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 | fix links for next css | a7741341cb805ff256583ee91a170daf0f47acd0 | <ide><path>readme.md
<ide> To use more sophisticated CSS-in-JS solutions, you typically have to implement s
<ide>
<ide> To support importing `.css` `.scss` or `.less` files you can use these modules, which configure sensible defaults for server rendered applications.
<ide>
<del>- 
<del>- 
<del>- 
<add>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css)
<add>- [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass)
<add>- [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less)
<ide>
<ide> ### Static file serving (e.g.: images)
<ide> | 1 |
Text | Text | fix broken examples/seq2seq/readme.md markdown | 23e87c27bedff55a2148ddd62452d6507648c64f | <ide><path>examples/seq2seq/README.md
<ide> python examples/seq2seq/run_seq2seq.py \
<ide> --predict_with_generate \
<ide> --max_train_samples 500 \
<ide> --max_val_samples 500
<del> ```
<add> ```
<ide>
<ide> Note, that depending on the used model additional language-specific command-line arguments are sometimes required. Specifically:
<ide> | 1 |
Python | Python | fix typo in data_adapter.py | c557822aa2caa7f9e81aae81bf8e6947ee5438cd | <ide><path>keras/engine/data_adapter.py
<ide> class DataAdapter(object, metaclass=abc.ABCMeta):
<ide> converted to `tf.data.Dataset` if possible.
<ide>
<ide> Note that since this class is mainly targeted for TF 2.0, it might have a lot
<del> of assumptions under the hood, eg eager context by default, distribution
<add> of assumptions under the hood, e.g. eager context by default, distribution
<ide> strategy, etc. In the meantime, some legacy feature support might be dropped,
<ide> eg, Iterator from dataset API in v1, etc.
<ide>
<ide> def __init__(self, x, y=None, **kwargs):
<ide> `distribution_strategy` is passed, the created dataset need to respect
<ide> the strategy.
<ide> DataAdapter might choose to ignore any keyword argument if it doesn't
<del> use it, or raise exception if any required argument is not provide.
<add> use it, or raise exception if any required argument is not provided.
<ide> """
<ide> if not self.can_handle(x, y):
<ide> raise ValueError("{} Cannot handle input {}, {}".format(
<ide> def get_dataset(self):
<ide>
<ide> Note that the dataset returned does not repeat for epoch, so caller might
<ide> need to create new iterator for the same dataset at the beginning of the
<del> epoch. This behavior might change in future.
<add> epoch. This behavior might change in the future.
<ide>
<ide> Returns:
<ide> An tf.dataset.Dataset. Caller might use the dataset in different
<del> context, eg iter(dataset) in eager to get the value directly, or in graph
<add> context, e.g. iter(dataset) in eager to get the value directly, or in graph
<ide> mode, provide the iterator tensor to Keras model function.
<ide> """
<ide> raise NotImplementedError
<ide> def get_size(self):
<ide> For certain type of the data input, the number of batches is known, eg for
<ide> Numpy data, the size is same as (number_of_element / batch_size). Whereas
<ide> for dataset or python generator, the size is unknown since it may or may not
<del> have a end state.
<add> have an end state.
<ide>
<ide> Returns:
<ide> int, the number of batches for the dataset, or None if it is unknown. The
<ide> def batch_size(self):
<ide> """Return the batch size of the dataset created.
<ide>
<ide> For certain type of the data input, the batch size is known, and even
<del> required, like numpy array. Where as for dataset, the batch is unknown
<add> required, like numpy array. Whereas for dataset, the batch is unknown
<ide> unless we take a peek.
<ide>
<ide> Returns:
<ide> def __init__(self,
<ide> dataset = dataset.shuffle(num_samples)
<ide>
<ide> # If batch_size is not passed but steps is, calculate from the input data.
<del> # Default to 32 for backwards compat.
<add> # Default to 32 for backwards compatibility.
<ide> if not batch_size:
<ide> batch_size = int(math.ceil(num_samples / steps)) if steps else 32
<ide>
<ide> def on_epoch_end(self):
<ide>
<ide>
<ide> def select_data_adapter(x, y):
<del> """Selects a data adapter than can handle a given x and y."""
<add> """Selects a data adapter that can handle a given x and y."""
<ide> adapter_cls = [cls for cls in ALL_ADAPTER_CLS if cls.can_handle(x, y)]
<ide> if not adapter_cls:
<ide> # TODO(scottzhu): This should be a less implementation-specific error. | 1 |
PHP | PHP | add unit test for mailable notification | 7b1916e1708b5a7fb31f5b42a4d6cd2f290998fc | <ide><path>tests/Notifications/NotificationMailChannelTest.php
<ide> public function testMessageWithToAddress()
<ide>
<ide> $channel->send($notifiable, $notification);
<ide> }
<add>
<add> public function testMessageWithMailableContract()
<add> {
<add> $notification = new NotificationMailChannelTestNotificationWithMailableContract;
<add> $notifiable = new NotificationMailChannelTestNotifiable;
<add>
<add> $channel = new Illuminate\Notifications\Channels\MailChannel(
<add> $mailer = Mockery::mock(Illuminate\Contracts\Mail\Mailer::class)
<add> );
<add>
<add> $mailer->shouldReceive('send')->once();
<add>
<add> $channel->send($notifiable, $notification);
<add> }
<ide> }
<ide>
<ide> class NotificationMailChannelTestNotifiable
<ide> public function toMail($notifiable)
<ide> ->to('jeffrey@laracasts.com');
<ide> }
<ide> }
<add>
<add>class NotificationMailChannelTestNotificationWithMailableContract extends Notification
<add>{
<add> public function toMail($notifiable)
<add> {
<add> $mock = Mockery::mock(Illuminate\Contracts\Mail\Mailable::class);
<add>
<add> $mock->shouldReceive('send')->once()->with(Mockery::on(function($mailer) {
<add> if (! ($mailer instanceof \Illuminate\Contracts\Mail\Mailer)) {
<add> return false;
<add> }
<add>
<add> $mailer->send('notifications::email-plain');
<add>
<add> return true;
<add> }));
<add>
<add> return $mock;
<add> }
<add>} | 1 |
Javascript | Javascript | fix linting issues | ae8ec39397cefa66f11432b50ad0632966943f31 | <ide><path>ContainerShip/scripts/run-android-ci-instrumentation-tests.js
<ide> const test_opts = {
<ide> PATH: argv.path || './ReactAndroid/src/androidTest/java/com/facebook/react/tests',
<ide> RETRIES: parseInt(argv.retries || 2, 10),
<ide>
<del> TEST_TIMEOUT: parseInt(argv['test-timeout'] || 1000 * 60 * 10),
<add> TEST_TIMEOUT: parseInt(argv['test-timeout'] || 1000 * 60 * 10, 10),
<ide>
<ide> OFFSET: argv.offset,
<ide> COUNT: argv.count,
<ide> testClasses = testClasses.map((clazz) => {
<ide>
<ide> // only process subset of the tests at corresponding offset and count if args provided
<ide> if (test_opts.COUNT != null && test_opts.OFFSET != null) {
<del> const testCount = testClasses.length;
<ide> const start = test_opts.COUNT * test_opts.OFFSET;
<ide> const end = start + test_opts.COUNT;
<ide>
<ide><path>Libraries/Animated/src/bezier.js
<ide> module.exports = function bezier(
<ide> mX2: number,
<ide> mY2: number,
<ide> ) {
<del> if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {
<add> if (!(mX1 >= 0 && mX1 <= 1 && mX2 >= 0 && mX2 <= 1)) {
<ide> throw new Error('bezier x values must be in [0, 1] range');
<ide> }
<ide>
<ide><path>Libraries/Animated/src/nodes/AnimatedValue.js
<ide> 'use strict';
<ide>
<ide> const AnimatedInterpolation = require('./AnimatedInterpolation');
<del>const AnimatedNode = require('./AnimatedNode');
<ide> const AnimatedWithChildren = require('./AnimatedWithChildren');
<ide> const InteractionManager = require('InteractionManager');
<ide> const NativeAnimatedHelper = require('../NativeAnimatedHelper');
<ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js
<ide> class KeyboardAvoidingView extends React.Component<Props, State> {
<ide> children,
<ide> contentContainerStyle,
<ide> enabled,
<del> keyboardVerticalOffset, // eslint-disable-line no-unused-vars
<add> keyboardVerticalOffset,
<ide> style,
<ide> ...props
<ide> } = this.props;
<ide><path>Libraries/Components/Touchable/TouchableOpacity.js
<ide> const TouchableOpacity = ((createReactClass({
<ide>
<ide> _getChildStyleOpacityWithDefault: function() {
<ide> const childStyle = flattenStyle(this.props.style) || {};
<del> return childStyle.opacity == undefined ? 1 : childStyle.opacity;
<add> return childStyle.opacity == null ? 1 : childStyle.opacity;
<ide> },
<ide>
<ide> render: function() {
<ide><path>Libraries/Components/WebView/WebView.ios.js
<ide> const Linking = require('Linking');
<ide> const PropTypes = require('prop-types');
<ide> const React = require('React');
<ide> const ReactNative = require('ReactNative');
<del>const ScrollView = require('ScrollView');
<ide> const StyleSheet = require('StyleSheet');
<ide> const Text = require('Text');
<ide> const UIManager = require('UIManager');
<ide><path>Libraries/Experimental/Incremental.js
<ide> export type Props = {
<ide> name: string,
<ide> children: React.Node,
<ide> };
<del>type DefaultProps = {
<del> name: string,
<del>};
<add>
<ide> type State = {
<ide> doIncrementalRender: boolean,
<ide> };
<add>
<ide> class Incremental extends React.Component<Props, State> {
<ide> props: Props;
<ide> state: State;
<ide><path>Libraries/Experimental/SwipeableRow/SwipeableFlatList.js
<ide> import type {Props as FlatListProps} from 'FlatList';
<ide> import type {renderItemType} from 'VirtualizedList';
<ide>
<del>const PropTypes = require('prop-types');
<ide> const React = require('React');
<ide> const SwipeableRow = require('SwipeableRow');
<ide> const FlatList = require('FlatList');
<ide><path>Libraries/Image/Image.android.js
<ide> const ImageViewNativeComponent = require('ImageViewNativeComponent');
<ide> const NativeModules = require('NativeModules');
<ide> const PropTypes = require('prop-types');
<ide> const React = require('React');
<del>const ReactNative = require('ReactNative');
<add>const ReactNative = require('ReactNative'); // eslint-disable-line no-unused-vars
<ide> const StyleSheet = require('StyleSheet');
<ide> const TextAncestor = require('TextAncestor');
<ide>
<ide><path>Libraries/Image/Image.ios.js
<ide> const DeprecatedImagePropType = require('DeprecatedImagePropType');
<ide> const NativeModules = require('NativeModules');
<ide> const React = require('React');
<del>const ReactNative = require('ReactNative');
<add>const ReactNative = require('ReactNative'); // eslint-disable-line no-unused-vars
<ide> const StyleSheet = require('StyleSheet');
<ide>
<ide> const flattenStyle = require('flattenStyle');
<ide><path>Libraries/Lists/VirtualizedList.js
<ide> class VirtualizedList extends React.PureComponent<Props, State> {
<ide> }
<ide>
<ide> static getDerivedStateFromProps(newProps: Props, prevState: State) {
<del> const {data, extraData, getItemCount, maxToRenderPerBatch} = newProps;
<add> const {data, getItemCount, maxToRenderPerBatch} = newProps;
<ide> // first and last could be stale (e.g. if a new, shorter items props is passed in), so we make
<ide> // sure we're rendering a reasonable range here.
<ide> return {
<ide><path>Libraries/Modal/Modal.js
<ide> const PropTypes = require('prop-types');
<ide> const StyleSheet = require('StyleSheet');
<ide> const View = require('View');
<ide>
<del>const deprecatedPropType = require('deprecatedPropType');
<ide> const requireNativeComponent = require('requireNativeComponent');
<ide>
<ide> const RCTModalHostView = requireNativeComponent('RCTModalHostView');
<ide><path>Libraries/ReactNative/UIManager.js
<ide> if (Platform.OS === 'ios') {
<ide> // we also tell Prepack that it has only partial knowledge of the UIManager,
<ide> // so that any accesses to unknown properties along the global code will fail
<ide> // when Prepack encounters them.
<del> if (global.__makePartial) global.__makePartial(UIManager);
<add> if (global.__makePartial) {
<add> global.__makePartial(UIManager);
<add> }
<ide> }
<ide>
<ide> if (__DEV__) {
<ide><path>Libraries/Utilities/setAndForwardRef.js
<ide>
<ide> 'use strict';
<ide>
<del>const invariant = require('fbjs/lib/invariant');
<del>
<ide> import type React from 'React';
<ide>
<ide> type Args = $ReadOnly<{|
<ide><path>Libraries/polyfills/babelHelpers.js
<ide> * @polyfill
<ide> */
<ide>
<add>/* eslint-disable no-func-assign, no-shadow, no-proto, no-void, no-undef-init */
<add>
<ide> 'use strict';
<ide>
<ide> var babelHelpers = (global.babelHelpers = {});
<ide><path>Libraries/polyfills/console.js
<ide> * @format
<ide> */
<ide>
<del>/* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void */
<add>/* eslint-disable no-shadow, eqeqeq, curly, no-unused-vars, no-void, no-control-regex */
<ide>
<ide> /**
<ide> * This pipes all of our console logging functions to native logging so that
<ide><path>RNTester/RNTesterUnitTests/RNTesterUnitTestsBundle.js
<ide>
<ide> 'use strict';
<ide>
<add>// eslint-disable-next-line no-unused-vars
<ide> const __fbBatchedBridge = {
<del> // eslint-disable-line no-unused-vars
<ide> flushedQueue: function() {
<ide> return null;
<ide> },
<ide><path>RNTester/e2e/sanity.test.js
<ide> describe('Sanity', () => {
<ide> beforeEach(async () => {
<ide> await device.reloadReactNative();
<del> await element(by.label(`<Button> Simple React Native button component.`)).tap();
<add> await element(by.label('<Button> Simple React Native button component.')).tap();
<ide> });
<ide>
<ide> afterEach(async () => {
<ide> describe('Sanity', () => {
<ide> await element(by.text('OK')).tap();
<ide> });
<ide>
<del> it(`Two buttons with JustifyContent:'space-between' should be tappable`, async () => {
<add> it("Two buttons with JustifyContent:'space-between' should be tappable", async () => {
<ide> await element(by.label('This looks great!')).tap();
<ide> await expect(element(by.text('Left has been pressed!'))).toBeVisible();
<ide> await element(by.text('OK')).tap();
<ide><path>RNTester/js/ARTExample.js
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<ide> const {ART, Platform, View} = ReactNative;
<ide>
<del>const {Surface, Path, Group, Transform, Shape} = ART;
<add>const {Surface, Path, Group, Shape} = ART;
<ide>
<ide> const scale = Platform.isTV ? 4 : 1;
<ide>
<ide><path>RNTester/js/AsyncStorageExample.js
<ide> class BasicStorageExample extends React.Component<{}, $FlowFixMeState> {
<ide> {'Selected: '}
<ide> <Text style={{color}}>{this.state.selectedValue}</Text>
<ide> </Text>
<del> <Text> </Text>
<add> <Text />
<ide> <Text onPress={this._removeStorage}>
<ide> Press here to remove from storage.
<ide> </Text>
<del> <Text> </Text>
<add> <Text />
<ide> <Text>Messages:</Text>
<ide> {this.state.messages.map(m => <Text key={m}>{m}</Text>)}
<ide> </View>
<ide><path>RNTester/js/XHRExampleFormData.js
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<ide> const {
<del> Alert,
<ide> CameraRoll,
<ide> Image,
<ide> ImageEditor,
<del> Linking,
<ide> Platform,
<ide> StyleSheet,
<ide> Text,
<ide><path>ReactAndroid/src/androidTest/js/TestIdTestModule.js
<ide> var Image = require('Image');
<ide> var React = require('React');
<ide> var StyleSheet = require('StyleSheet');
<del>var Switch = require('Switch');
<ide> var Text = require('Text');
<ide> var TextInput = require('TextInput');
<ide> var TouchableBounce = require('TouchableBounce');
<ide><path>bots/dangerfile.js
<ide>
<ide> 'use strict';
<ide>
<del>const fs = require('fs');
<ide> const includes = require('lodash.includes');
<del>const minimatch = require('minimatch');
<ide>
<del>const {danger, fail, markdown, message, warn} = require('danger');
<add>const {danger, fail, warn} = require('danger');
<ide>
<ide> // Fails if the description is too short.
<ide> if (!danger.github.pr.body || danger.github.pr.body.length < 10) {
<ide><path>local-cli/generator/promptSync.js
<ide> function create() {
<ide> return prompt;
<ide>
<ide> function prompt(ask, value, opts) {
<del> var insert = 0,
<del> savedinsert = 0,
<del> res,
<del> i,
<del> savedstr;
<add> var insert = 0;
<ide> opts = opts || {};
<ide>
<ide> if (Object(ask) === ask) {
<ide> function create() {
<ide> character,
<ide> read;
<ide>
<del> savedstr = '';
<del>
<ide> if (ask) {
<ide> process.stdout.write(ask);
<ide> }
<ide>
<del> var cycle = 0;
<del> var prevComplete;
<del>
<ide> while (true) {
<ide> read = fs.readSync(fd, buf, 0, 3);
<ide> if (read > 1) {
<ide> function create() {
<ide> character = buf[read - 1];
<ide>
<ide> // catch a ^C and return null
<del> if (character == 3) {
<add> if (character === 3) {
<ide> process.stdout.write('^C\n');
<ide> fs.closeSync(fd);
<ide> process.exit(130);
<ide> function create() {
<ide> }
<ide>
<ide> // catch the terminating character
<del> if (character == term) {
<add> if (character === term) {
<ide> fs.closeSync(fd);
<ide> break;
<ide> }
<ide>
<del> if (character == 127 || (process.platform == 'win32' && character == 8)) {
<add> if (
<add> character === 127 ||
<add> (process.platform === 'win32' && character === 8)
<add> ) {
<ide> //backspace
<ide> if (!insert) {
<ide> continue;
<ide> function create() {
<ide> );
<ide> } else {
<ide> process.stdout.write('\u001b[s');
<del> if (insert == str.length) {
<add> if (insert === str.length) {
<ide> process.stdout.write('\u001b[2K\u001b[0G' + ask + str);
<ide> } else {
<ide> if (ask) {
<ide><path>local-cli/link/__tests__/ios/writePlist.spec.js
<ide> describe('ios::writePlist', () => {
<ide>
<ide> it('should write a `.plist` file', () => {
<ide> plistPath = '/Basic/Info.plist';
<del> const result = writePlist(project, '/', plist);
<add> writePlist(project, '/', plist);
<ide> const infoPlist = readFileSync(infoPlistPath).toString();
<ide> expect(fs.writeFileSync).toHaveBeenCalledWith(plistPath, infoPlist);
<ide> });
<ide><path>local-cli/link/ios/copyAssets.js
<ide> const fs = require('fs-extra');
<ide> const path = require('path');
<ide> const xcode = require('xcode');
<del>const log = require('npmlog');
<ide> const groupFilesByType = require('../groupFilesByType');
<ide> const createGroupWithMessage = require('./createGroupWithMessage');
<ide> const getPlist = require('./getPlist');
<ide><path>local-cli/link/ios/unregisterNativeModule.js
<ide> const difference = require('lodash').difference;
<ide> const isEmpty = require('lodash').isEmpty;
<ide>
<ide> const getGroup = require('./getGroup');
<del>const getProducts = require('./getProducts');
<ide> const getTargets = require('./getTargets');
<ide> const getHeadersInFolder = require('./getHeadersInFolder');
<ide> const getHeaderSearchPath = require('./getHeaderSearchPath');
<ide><path>local-cli/templates/HelloWorld/__tests__/App.js
<ide> import App from '../App';
<ide> import renderer from 'react-test-renderer';
<ide>
<ide> it('renders correctly', () => {
<del> const tree = renderer.create(<App />);
<add> renderer.create(<App />);
<ide> });
<ide><path>local-cli/upgrade/upgrade.js
<ide> const chalk = require('chalk');
<ide> const copyProjectTemplateAndReplace = require('../generator/copyProjectTemplateAndReplace');
<ide> const fs = require('fs');
<ide> const path = require('path');
<del>const printRunInstructions = require('../generator/printRunInstructions');
<ide> const semver = require('semver');
<del>const yarn = require('../util/yarn');
<ide>
<ide> /**
<ide> * Migrate application to a new version of React Native.
<ide><path>scripts/try-n-times.js
<ide> * @format
<ide> */
<ide>
<del>/* globals echo:false */
<del>
<ide> 'use strict';
<ide>
<ide> /** | 30 |
Python | Python | add introspection support for binaryfield | c5a25c2771f0362a5775f81f9f4eb6b3c9caed62 | <ide><path>django/db/backends/oracle/introspection.py
<ide> class DatabaseIntrospection(BaseDatabaseIntrospection):
<ide> # Maps type objects to Django Field types.
<ide> data_types_reverse = {
<add> cx_Oracle.BLOB: 'BinaryField',
<ide> cx_Oracle.CLOB: 'TextField',
<ide> cx_Oracle.DATETIME: 'DateField',
<ide> cx_Oracle.FIXED_CHAR: 'CharField',
<ide><path>django/db/backends/postgresql_psycopg2/introspection.py
<ide> class DatabaseIntrospection(BaseDatabaseIntrospection):
<ide> # Maps type codes to Django Field types.
<ide> data_types_reverse = {
<ide> 16: 'BooleanField',
<add> 17: 'BinaryField',
<ide> 20: 'BigIntegerField',
<ide> 21: 'SmallIntegerField',
<ide> 23: 'IntegerField',
<ide><path>django/db/backends/sqlite3/introspection.py
<ide> class FlexibleFieldLookupDict(object):
<ide> 'real': 'FloatField',
<ide> 'text': 'TextField',
<ide> 'char': 'CharField',
<add> 'blob': 'BinaryField',
<ide> 'date': 'DateField',
<ide> 'datetime': 'DateTimeField',
<ide> 'time': 'TimeField',
<ide><path>tests/introspection/models.py
<ide> class Reporter(models.Model):
<ide> last_name = models.CharField(max_length=30)
<ide> email = models.EmailField()
<ide> facebook_user_id = models.BigIntegerField(null=True)
<add> raw_data = models.BinaryField(null=True)
<ide>
<ide> class Meta:
<ide> unique_together = ('first_name', 'last_name')
<ide><path>tests/introspection/tests.py
<ide> def test_get_table_description_names(self):
<ide> def test_get_table_description_types(self):
<ide> cursor = connection.cursor()
<ide> desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
<add> # The MySQL exception is due to the cursor.description returning the same constant for
<add> # text and blob columns. TODO: use information_schema database to retrieve the proper
<add> # field type on MySQL
<ide> self.assertEqual(
<ide> [datatype(r[1], r) for r in desc],
<del> ['IntegerField', 'CharField', 'CharField', 'CharField', 'BigIntegerField']
<add> ['IntegerField', 'CharField', 'CharField', 'CharField',
<add> 'BigIntegerField', 'BinaryField' if connection.vendor != 'mysql' else 'TextField']
<ide> )
<ide>
<ide> # The following test fails on Oracle due to #17202 (can't correctly
<ide> def test_get_table_description_nullable(self):
<ide> desc = connection.introspection.get_table_description(cursor, Reporter._meta.db_table)
<ide> self.assertEqual(
<ide> [r[6] for r in desc],
<del> [False, False, False, False, True]
<add> [False, False, False, False, True, True]
<ide> )
<ide>
<ide> # Regression test for #9991 - 'real' types in postgres | 5 |
Java | Java | add overflow visible kill switch (android) | bbdc12eda7dec135799b7f4c41fe678180970dd2 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.java
<ide> public class ReactViewGroup extends ViewGroup implements
<ide> ReactInterceptingViewGroup, ReactClippingViewGroup, ReactPointerEventsView, ReactHitSlopView,
<ide> ReactZIndexedViewGroup {
<ide>
<add> /**
<add> * Kill switch to make overflow hidden by default. This flag will eventually be removed.
<add> */
<add> public static boolean sDefaultOverflowHidden;
<add>
<ide> private static final int ARRAY_CAPACITY_INCREMENT = 12;
<ide> private static final int DEFAULT_BACKGROUND_COLOR = Color.TRANSPARENT;
<ide> private static final LayoutParams sDefaultLayoutParam = new ViewGroup.LayoutParams(0, 0);
<ide> public void onLayoutChange(
<ide>
<ide> public ReactViewGroup(Context context) {
<ide> super(context);
<del> setClipChildren(false);
<add> // TODO: Remove this check after a couple public releases.
<add> if (!sDefaultOverflowHidden) {
<add> setClipChildren(false);
<add> }
<ide> mDrawingOrderHelper = new ViewGroupDrawingOrderHelper(this);
<ide> }
<ide> | 1 |
Ruby | Ruby | upgrade virtualenv to 20.0.26 | 6dbcf83a21d36a0c03990a923cc07ef4a06e4e7f | <ide><path>Library/Homebrew/language/python_virtualenv_constants.rb
<ide> # frozen_string_literal: true
<ide>
<ide> PYTHON_VIRTUALENV_URL =
<del> "https://files.pythonhosted.org/packages/11/74" \
<del> "/2c151a13ef41ab9fb43b3c4ff9e788e0496ed7923b2078d42cab30622bdf" \
<del> "/virtualenv-16.7.4.tar.gz"
<add> "https://files.pythonhosted.org/packages/c4/1b" \
<add> "/09bb751c6e805bf4711bbaead5499c8d8caf92398ba8da92daa8bf19f60e" \
<add> "/virtualenv-20.0.26.tar.gz"
<ide> PYTHON_VIRTUALENV_SHA256 =
<del> "94a6898293d07f84a98add34c4df900f8ec64a570292279f6d91c781d37fd305"
<add> "e10cc66f40cbda459720dfe1d334c4dc15add0d80f09108224f171006a97a172"
<ide>
<ide> PYTHON_VIRTUALENV_URL_MOJAVE =
<ide> "https://files.pythonhosted.org/packages/b1/72" \ | 1 |
Ruby | Ruby | add initial tests | e8e6ee30b48a7f9df0bda5adc959fb0eaaaae13a | <ide><path>Library/Homebrew/cask/artifact/abstract_uninstall.rb
<ide> def uninstall_launchctl(*services, command: nil, **_)
<ide>
<ide> # if launchctl item contains a wildcard, find matching process(es)
<ide> services.each do |service|
<del> all_services << service
<add> all_services << service unless service.include?("*")
<ide> next unless service.include?("*")
<ide>
<ide> all_services += find_launchctl_with_wildcard(service)
<ide><path>Library/Homebrew/test/cask/artifact/shared_examples/uninstall_zap.rb
<ide> end
<ide> end
<ide>
<add> context "using launchctl with regex" do
<add> let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-launchctl-wildcard")) }
<add> let(:launchctl_list_cmd) { %w[/bin/launchctl list] }
<add>
<add> it "searches running launchctl items" do
<add> allow(fake_system_command).to receive(:run)
<add> .with("/bin/launchctl", args: ["list"], print_stderr: false, sudo: false)
<add> .and_return(instance_double(SystemCommand::Result))
<add>
<add> subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
<add> end
<add> end
<add>
<ide> context "using :pkgutil" do
<ide> let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-pkgutil")) }
<ide>
<ide> allow(User.current).to receive(:gui?).and_return false
<ide> allow(subject).to receive(:running?).with(bundle_id).and_return(true)
<ide>
<del> expect {
<add> expect do
<ide> subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
<del> }.to output(/Not logged into a GUI; skipping quitting application ID 'my.fancy.package.app'\./).to_stderr
<add> end.to output(/Not logged into a GUI; skipping quitting application ID 'my.fancy.package.app'\./).to_stderr
<ide> end
<ide>
<ide> it "quits a running application" do
<ide> .and_return(instance_double("SystemCommand::Result", success?: true))
<ide> expect(subject).to receive(:running?).with(bundle_id).ordered.and_return(false)
<ide>
<del> expect {
<add> expect do
<ide> subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
<del> }.to output(/Application 'my.fancy.package.app' quit successfully\./).to_stdout
<add> end.to output(/Application 'my.fancy.package.app' quit successfully\./).to_stdout
<ide> end
<ide>
<ide> it "tries to quit the application for 10 seconds" do
<ide> .and_return(instance_double("SystemCommand::Result", success?: false))
<ide>
<ide> time = Benchmark.measure do
<del> expect {
<add> expect do
<ide> subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
<del> }.to output(/Application 'my.fancy.package.app' did not quit\./).to_stderr
<add> end.to output(/Application 'my.fancy.package.app' did not quit\./).to_stderr
<ide> end
<ide>
<ide> expect(time.real).to be_within(3).of(10)
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-launchctl-wildcard.rb
<add>cask "with-uninstall-launchctl-wildcard" do
<add> version "1.2.3"
<add> sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
<add>
<add> url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyApp.zip"
<add> homepage "https://brew.sh/fancy"
<add>
<add> app "Fancy.app"
<add>
<add> uninstall launchctl: "my.fancy.package.service.*"
<add>end
<ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-zap-launchctl-wildcard.rb
<add>cask "with-zap-launchctl-wildcard" do
<add> version "1.2.3"
<add> sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
<add>
<add> url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyApp.zip"
<add> homepage "https://brew.sh/fancy"
<add>
<add> app "Fancy.app"
<add>
<add> zap launchctl: "my.fancy.package.service.*"
<add>end | 4 |
Ruby | Ruby | add spaces to deep_munge log message | 38594b35275a431ccf2fdc10be7219685aeed487 | <ide><path>actionpack/lib/action_controller/log_subscriber.rb
<ide> def unpermitted_parameters(event)
<ide> end
<ide>
<ide> def deep_munge(event)
<del> message = "Value for params[:#{event.payload[:keys].join('][:')}] was set"\
<del> "to nil, because it was one of [], [null] or [null, null, ...]."\
<del> "Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation"\
<add> message = "Value for params[:#{event.payload[:keys].join('][:')}] was set "\
<add> "to nil, because it was one of [], [null] or [null, null, ...]. "\
<add> "Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation "\
<ide> "for more information."\
<ide>
<ide> debug(message) | 1 |
Go | Go | implement imagedelete for containerd | 26c65447df6ad86dea98d65f679e3f428ab2ffd3 | <ide><path>api/server/router/image/backend.go
<ide> type Backend interface {
<ide> }
<ide>
<ide> type imageBackend interface {
<del> ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error)
<add> ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error)
<ide> ImageHistory(imageName string) ([]*image.HistoryResponseItem, error)
<ide> Images(ctx context.Context, opts types.ImageListOptions) ([]*types.ImageSummary, error)
<ide> GetImage(refOrID string, platform *specs.Platform) (retImg *dockerimage.Image, retErr error)
<ide><path>api/server/router/image/image_routes.go
<ide> func (s *imageRouter) deleteImages(ctx context.Context, w http.ResponseWriter, r
<ide> force := httputils.BoolValue(r, "force")
<ide> prune := !httputils.BoolValue(r, "noprune")
<ide>
<del> list, err := s.backend.ImageDelete(name, force, prune)
<add> list, err := s.backend.ImageDelete(ctx, name, force, prune)
<ide> if err != nil {
<ide> return err
<ide> }
<ide><path>daemon/containerd/image_delete.go
<ide> package containerd
<ide>
<del>import "github.com/docker/docker/api/types"
<add>import (
<add> "context"
<add>
<add> "github.com/containerd/containerd/images"
<add> "github.com/docker/distribution/reference"
<add> "github.com/docker/docker/api/types"
<add>)
<ide>
<ide> // ImageDelete deletes the image referenced by the given imageRef from this
<ide> // daemon. The given imageRef can be an image ID, ID prefix, or a repository
<ide> import "github.com/docker/docker/api/types"
<ide> // If prune is true, ancestor images will each attempt to be deleted quietly,
<ide> // meaning any delete conflicts will cause the image to not be deleted and the
<ide> // conflict will not be reported.
<del>func (i *ImageService) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
<del> panic("not implemented")
<add>//
<add>// TODO(thaJeztah): implement ImageDelete "force" options; see https://github.com/moby/moby/issues/43850
<add>// TODO(thaJeztah): implement ImageDelete "prune" options; see https://github.com/moby/moby/issues/43849
<add>// TODO(thaJeztah): add support for image delete using image (short)ID; see https://github.com/moby/moby/issues/43854
<add>// TODO(thaJeztah): mage delete should send image "untag" events and prometheus counters; see https://github.com/moby/moby/issues/43855
<add>func (i *ImageService) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
<add> parsedRef, err := reference.ParseNormalizedNamed(imageRef)
<add> if err != nil {
<add> return nil, err
<add> }
<add> ref := reference.TagNameOnly(parsedRef)
<add>
<add> err = i.client.ImageService().Delete(ctx, ref.String(), images.SynchronousDelete())
<add> if err != nil {
<add> return nil, err
<add> }
<add>
<add> return []types.ImageDeleteResponseItem{{Untagged: reference.FamiliarString(parsedRef)}}, nil
<ide> }
<ide><path>daemon/image_service.go
<ide> type ImageService interface {
<ide> PullImage(ctx context.Context, image, tag string, platform *v1.Platform, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error
<ide> PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error
<ide> CreateImage(config []byte, parent string) (builder.Image, error)
<del> ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error)
<add> ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error)
<ide> ExportImage(names []string, outStream io.Writer) error
<ide> LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error
<ide> Images(ctx context.Context, opts types.ImageListOptions) ([]*types.ImageSummary, error)
<ide><path>daemon/images/image_delete.go
<ide> package images // import "github.com/docker/docker/daemon/images"
<ide>
<ide> import (
<add> "context"
<ide> "fmt"
<ide> "strings"
<ide> "time"
<ide> const (
<ide> // If prune is true, ancestor images will each attempt to be deleted quietly,
<ide> // meaning any delete conflicts will cause the image to not be deleted and the
<ide> // conflict will not be reported.
<del>func (i *ImageService) ImageDelete(imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
<add>func (i *ImageService) ImageDelete(ctx context.Context, imageRef string, force, prune bool) ([]types.ImageDeleteResponseItem, error) {
<ide> start := time.Now()
<ide> records := []types.ImageDeleteResponseItem{}
<ide>
<ide><path>daemon/images/image_prune.go
<ide> deleteImagesLoop:
<ide>
<ide> if shouldDelete {
<ide> for _, ref := range refs {
<del> imgDel, err := i.ImageDelete(ref.String(), false, true)
<add> imgDel, err := i.ImageDelete(ctx, ref.String(), false, true)
<ide> if imageDeleteFailed(ref.String(), err) {
<ide> continue
<ide> }
<ide> deleteImagesLoop:
<ide> }
<ide> } else {
<ide> hex := id.Digest().Hex()
<del> imgDel, err := i.ImageDelete(hex, false, true)
<add> imgDel, err := i.ImageDelete(ctx, hex, false, true)
<ide> if imageDeleteFailed(hex, err) {
<ide> continue
<ide> }
<ide> func imageDeleteFailed(ref string, err error) bool {
<ide> switch {
<ide> case err == nil:
<ide> return false
<del> case errdefs.IsConflict(err):
<add> case errdefs.IsConflict(err), errors.Is(err, context.Canceled), errors.Is(err, context.DeadlineExceeded):
<ide> return true
<ide> default:
<ide> logrus.Warnf("failed to prune image %s: %v", ref, err) | 6 |
PHP | PHP | throw an exception if the behavior does not exist | 2733b8c33b263489613d943079c69068c2cdbadf | <ide><path>src/ORM/Table.php
<ide> public function behaviors()
<ide> *
<ide> * @param string $name The behavior alias to get from the registry.
<ide> * @return \Cake\ORM\Behavior
<add> * @throws \InvalidArgumentException If the behavior does not exist.
<ide> */
<ide> public function getBehavior($name)
<ide> {
<add> if ($this->hasBehavior($name) === false) {
<add> throw new InvalidArgumentException(sprintf(
<add> 'The %s behavior is not defined on %s.',
<add> $name,
<add> get_class($this)
<add> ));
<add> }
<add>
<ide> return $this->_behaviors->get($name);
<ide> }
<ide>
<ide><path>tests/TestCase/ORM/TableTest.php
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Validation\Validator;
<add>use InvalidArgumentException;
<ide>
<ide> /**
<ide> * Used to test correct class is instantiated when using TableRegistry::get();
<ide> public function testGetBehavior()
<ide> $this->assertSame($table->behaviors()->get('Sluggable'), $table->getBehavior('Sluggable'));
<ide> }
<ide>
<add> /**
<add> * Test that the getBehavior() method will throw an exception when you try to
<add> * get a behavior that does not exist.
<add> *
<add> * @return void
<add> */
<add> public function testGetBehaviorThrowsExceptionForMissingBehavior()
<add> {
<add> $table = new Table(['table' => 'comments']);
<add>
<add> $this->expectException(InvalidArgumentException::class);
<add> $this->expectExceptionMessage('The Sluggable behavior is not defined on ' . get_class($table) . '.');
<add>
<add> $this->assertFalse($table->hasBehavior('Sluggable'));
<add> $table->getBehavior('Sluggable');
<add> }
<add>
<ide> /**
<ide> * Ensure exceptions are raised on missing behaviors.
<ide> * | 2 |
Python | Python | add test for chararray.startswith | 763d2508c27487b5e1300d0298f3afdd48fbeef6 | <ide><path>numpy/core/tests/test_regression.py
<ide> def check_refcount_vdot(self, level=rlevel):
<ide> """Changeset #3443"""
<ide> assert_valid_refcount(N.vdot)
<ide>
<add> def check_startswith(self, level=rlevel):
<add> ca = N.char.array(['Hi','There'])
<add> assert_equal(ca.startswith('H'),[True,False])
<add>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
PHP | PHP | extend the container interface from app | 50578255e967c24c34fc02d49f07fa8012ccdf0a | <ide><path>src/Illuminate/Contracts/Foundation/Application.php
<ide> <?php namespace Illuminate\Contracts\Foundation;
<ide>
<del>interface Application {
<add>use Illuminate\Contracts\Container\Container;
<add>
<add>interface Application extends Container {
<ide>
<ide> /**
<ide> * Register a service provider with the application. | 1 |
Javascript | Javascript | add todo re. projection.stream(bound) | c0b5b08af9d26dbfee56ed5d3a846c80b1b9c1a4 | <ide><path>src/geo/bounds.js
<ide> function d3_geo_bounds(projection) {
<ide>
<ide> return function(feature) {
<ide> y1 = x1 = -(x0 = y0 = Infinity);
<del> d3.geo.stream(feature, bound);
<add> d3.geo.stream(feature, bound); // TODO projection.stream(bound)
<ide> return [[x0, y0], [x1, y1]];
<ide> };
<ide> } | 1 |
PHP | PHP | change delete() to remove() in the test | 0c97a25d23236438c7d8d65ce5e3f1022ae00997 | <ide><path>tests/TestCase/ORM/TableRegistryTest.php
<ide> public function testGenericInstances() {
<ide> }
<ide>
<ide> /**
<del> * Tests deleting an instance
<add> * Tests remove an instance
<ide> *
<ide> * @return void
<ide> */
<del> public function testDelete() {
<add> public function testRemove() {
<ide> Plugin::load('TestPlugin');
<ide>
<ide> $pluginTable = TableRegistry::get('TestPlugin.Comments');
<ide> public function testDelete() {
<ide> $this->assertTrue(TableRegistry::exists('Comments'));
<ide> $this->assertSame($pluginTable, $cachedTable);
<ide>
<del> TableRegistry::delete('Comments');
<add> TableRegistry::remove('Comments');
<ide> $this->assertFalse(TableRegistry::exists('Comments'));
<ide>
<ide> $appTable = TableRegistry::get('Comments'); | 1 |
Javascript | Javascript | convert `pdfdatarangetransport` to an es6 class | 5bb7f4b615a8ab1d7d43aaca94a2749498bc792d | <ide><path>src/display/api.js
<ide> var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
<ide>
<ide> /**
<ide> * Abstract class to support range requests file loading.
<del> * @class
<del> * @alias PDFDataRangeTransport
<ide> * @param {number} length
<ide> * @param {Uint8Array} initialData
<ide> */
<del>var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
<del> function PDFDataRangeTransport(length, initialData) {
<add>class PDFDataRangeTransport {
<add> constructor(length, initialData) {
<ide> this.length = length;
<ide> this.initialData = initialData;
<ide>
<ide> var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() {
<ide> this._progressiveReadListeners = [];
<ide> this._readyCapability = createPromiseCapability();
<ide> }
<del> PDFDataRangeTransport.prototype =
<del> /** @lends PDFDataRangeTransport.prototype */ {
<del> addRangeListener:
<del> function PDFDataRangeTransport_addRangeListener(listener) {
<del> this._rangeListeners.push(listener);
<del> },
<ide>
<del> addProgressListener:
<del> function PDFDataRangeTransport_addProgressListener(listener) {
<del> this._progressListeners.push(listener);
<del> },
<add> addRangeListener(listener) {
<add> this._rangeListeners.push(listener);
<add> }
<ide>
<del> addProgressiveReadListener:
<del> function PDFDataRangeTransport_addProgressiveReadListener(listener) {
<del> this._progressiveReadListeners.push(listener);
<del> },
<add> addProgressListener(listener) {
<add> this._progressListeners.push(listener);
<add> }
<ide>
<del> onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) {
<del> var listeners = this._rangeListeners;
<del> for (var i = 0, n = listeners.length; i < n; ++i) {
<del> listeners[i](begin, chunk);
<del> }
<del> },
<add> addProgressiveReadListener(listener) {
<add> this._progressiveReadListeners.push(listener);
<add> }
<ide>
<del> onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) {
<del> this._readyCapability.promise.then(() => {
<del> var listeners = this._progressListeners;
<del> for (var i = 0, n = listeners.length; i < n; ++i) {
<del> listeners[i](loaded);
<del> }
<del> });
<del> },
<add> onDataRange(begin, chunk) {
<add> for (const listener of this._rangeListeners) {
<add> listener(begin, chunk);
<add> }
<add> }
<ide>
<del> onDataProgressiveRead:
<del> function PDFDataRangeTransport_onDataProgress(chunk) {
<del> this._readyCapability.promise.then(() => {
<del> var listeners = this._progressiveReadListeners;
<del> for (var i = 0, n = listeners.length; i < n; ++i) {
<del> listeners[i](chunk);
<del> }
<del> });
<del> },
<add> onDataProgress(loaded) {
<add> this._readyCapability.promise.then(() => {
<add> for (const listener of this._progressListeners) {
<add> listener(loaded);
<add> }
<add> });
<add> }
<ide>
<del> transportReady: function PDFDataRangeTransport_transportReady() {
<del> this._readyCapability.resolve();
<del> },
<add> onDataProgressiveRead(chunk) {
<add> this._readyCapability.promise.then(() => {
<add> for (const listener of this._progressiveReadListeners) {
<add> listener(chunk);
<add> }
<add> });
<add> }
<ide>
<del> requestDataRange:
<del> function PDFDataRangeTransport_requestDataRange(begin, end) {
<del> unreachable('Abstract method PDFDataRangeTransport.requestDataRange');
<del> },
<add> transportReady() {
<add> this._readyCapability.resolve();
<add> }
<ide>
<del> abort: function PDFDataRangeTransport_abort() {
<del> },
<del> };
<del> return PDFDataRangeTransport;
<del>})();
<add> requestDataRange(begin, end) {
<add> unreachable('Abstract method PDFDataRangeTransport.requestDataRange');
<add> }
<add>
<add> abort() {}
<add>}
<ide>
<ide> /**
<ide> * Proxy to a PDFDocument in the worker thread. Also, contains commonly used
<ide><path>web/firefoxcom.js
<ide> class MozL10n {
<ide> }
<ide> })();
<ide>
<del>function FirefoxComDataRangeTransport(length, initialData) {
<del> PDFDataRangeTransport.call(this, length, initialData);
<add>class FirefoxComDataRangeTransport extends PDFDataRangeTransport {
<add> requestDataRange(begin, end) {
<add> FirefoxCom.request('requestDataRange', { begin, end, });
<add> }
<add>
<add> abort() {
<add> // Sync call to ensure abort is really started.
<add> FirefoxCom.requestSync('abortLoading', null);
<add> }
<ide> }
<del>FirefoxComDataRangeTransport.prototype =
<del> Object.create(PDFDataRangeTransport.prototype);
<del>FirefoxComDataRangeTransport.prototype.requestDataRange =
<del> function FirefoxComDataRangeTransport_requestDataRange(begin, end) {
<del> FirefoxCom.request('requestDataRange', { begin, end, });
<del>};
<del>FirefoxComDataRangeTransport.prototype.abort =
<del> function FirefoxComDataRangeTransport_abort() {
<del> // Sync call to ensure abort is really started.
<del> FirefoxCom.requestSync('abortLoading', null);
<del>};
<ide>
<ide> PDFViewerApplication.externalServices = {
<ide> updateFindControlState(data) { | 2 |
Java | Java | fix checkstyle violation | 4475c67ba86fa31b086704dff111d5970836bcf8 | <ide><path>spring-web/src/main/java/org/springframework/web/filter/reactive/ForwardedHeaderFilter.java
<ide> * where "Forwarded" and "X-Forwarded-*" headers are eliminated, and not used.
<ide> *
<ide> * @author Arjen Poutsma
<add> * @author Rossen Stoyanchev
<ide> * @since 5.0
<ide> * @see <a href="https://tools.ietf.org/html/rfc7239">https://tools.ietf.org/html/rfc7239</a>
<ide> */
<ide> public void setRemoveOnly(boolean removeOnly) {
<ide>
<ide> @Override
<ide> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<del>
<ide> ServerHttpRequest request = exchange.getRequest();
<ide> if (!hasForwardedHeaders(request)) {
<ide> return chain.filter(exchange);
<ide> private static String getForwardedPrefix(ServerHttpRequest request) {
<ide> int endIndex = prefix.length();
<ide> while (endIndex > 1 && prefix.charAt(endIndex - 1) == '/') {
<ide> endIndex--;
<del> };
<del> prefix = endIndex != prefix.length() ? prefix.substring(0, endIndex) : prefix;
<add> }
<add> prefix = (endIndex != prefix.length() ? prefix.substring(0, endIndex) : prefix);
<ide> }
<ide> return prefix;
<ide> } | 1 |
Javascript | Javascript | use isonlyinitial instead | 569de58ec71c57bba5e040f2160f145b77272274 | <ide><path>lib/JavascriptModulesPlugin.js
<ide> class JavascriptModulesPlugin {
<ide> let filenameTemplate;
<ide> if (chunk.filenameTemplate) {
<ide> filenameTemplate = chunk.filenameTemplate;
<del> } else if (chunk.hasEntryModule()) {
<add> } else if (chunk.isOnlyInitial()) {
<ide> filenameTemplate = outputOptions.filename;
<ide> } else {
<ide> filenameTemplate = outputOptions.chunkFilename; | 1 |
Ruby | Ruby | remove useless method | 6570ab7af8810d5415993310c80a550e32f6bc6d | <ide><path>actionpack/lib/action_controller/metal/rack_delegation.rb
<ide> def build_with_env(env = {}) #:nodoc:
<ide> end
<ide> end
<ide>
<del> def response_body=(body)
<del> response.body = body if response
<del> super
<del> end
<del>
<ide> def reset_session
<ide> @_request.reset_session
<ide> end | 1 |
Go | Go | fix convertion issues | 187646127fa80a5ba39a53619b410eb2a13f0ffd | <ide><path>container.go
<ide> type Config struct {
<ide> NetworkDisabled bool
<ide> }
<ide>
<add>func ContainerConfigFromJob(job *engine.Job) *Config {
<add> var config Config
<add> config.Hostname = job.Getenv("Hostname")
<add> config.Domainname = job.Getenv("Domainname")
<add> config.User = job.Getenv("User")
<add> config.Memory = job.GetenvInt64("Memory")
<add> config.MemorySwap = job.GetenvInt64("MemorySwap")
<add> config.CpuShares = job.GetenvInt64("CpuShares")
<add> config.AttachStdin = job.GetenvBool("AttachStdin")
<add> config.AttachStdout = job.GetenvBool("AttachStdout")
<add> config.AttachStderr = job.GetenvBool("AttachStderr")
<add> if PortSpecs := job.GetenvList("PortSpecs"); PortSpecs != nil {
<add> config.PortSpecs = PortSpecs
<add> }
<add> job.GetenvJson("ExposedPorts", &config.ExposedPorts)
<add> config.Tty = job.GetenvBool("Tty")
<add> config.OpenStdin = job.GetenvBool("OpenStdin")
<add> config.StdinOnce = job.GetenvBool("StdinOnce")
<add> if Env := job.GetenvList("Env"); Env != nil {
<add> config.Env = Env
<add> }
<add> if Cmd := job.GetenvList("Cmd"); Cmd != nil {
<add> config.Cmd = Cmd
<add> }
<add> if Dns := job.GetenvList("Dns"); Dns != nil {
<add> config.Dns = Dns
<add> }
<add> config.Image = job.Getenv("Image")
<add> job.GetenvJson("Volumes", &config.Volumes)
<add> config.VolumesFrom = job.Getenv("VolumesFrom")
<add> config.WorkingDir = job.Getenv("WorkingDir")
<add> if Entrypoint := job.GetenvList("Entrypoint"); Entrypoint != nil {
<add> config.Entrypoint = Entrypoint
<add> }
<add> config.NetworkDisabled = job.GetenvBool("NetworkDisabled")
<add> return &config
<add>}
<add>
<ide> type HostConfig struct {
<ide> Binds []string
<ide> ContainerIDFile string
<ide> type HostConfig struct {
<ide> PublishAllPorts bool
<ide> }
<ide>
<add>func ContainerHostConfigFromJob(job *engine.Job) *HostConfig {
<add> var hostConfig HostConfig
<add> if Binds := job.GetenvList("Binds"); Binds != nil {
<add> hostConfig.Binds = Binds
<add> }
<add> hostConfig.ContainerIDFile = job.Getenv("ContainerIDFile")
<add> job.GetenvJson("LxcConf", &hostConfig.LxcConf)
<add> hostConfig.Privileged = job.GetenvBool("Privileged")
<add> job.GetenvJson("PortBindings", &hostConfig.PortBindings)
<add> if Links := job.GetenvList("Links"); Links != nil {
<add> hostConfig.Links = Links
<add> }
<add> hostConfig.PublishAllPorts = job.GetenvBool("PublishAllPorts")
<add> return &hostConfig
<add>}
<add>
<ide> type BindMap struct {
<ide> SrcPath string
<ide> DstPath string
<ide><path>engine/env.go
<ide> func (env *Env) WriteTo(dst io.Writer) (n int64, err error) {
<ide> return 0, env.Encode(dst)
<ide> }
<ide>
<del>func (env *Env) Export(dst interface{}) (err error) {
<del> defer func() {
<del> if err != nil {
<del> err = fmt.Errorf("ExportEnv %s", err)
<del> }
<del> }()
<del> var buf bytes.Buffer
<del> // step 1: encode/marshal the env to an intermediary json representation
<del> if err := env.Encode(&buf); err != nil {
<del> return err
<del> }
<del> // step 2: decode/unmarshal the intermediary json into the destination object
<del> if err := json.NewDecoder(&buf).Decode(dst); err != nil {
<del> return err
<del> }
<del> return nil
<del>}
<del>
<ide> func (env *Env) Import(src interface{}) (err error) {
<ide> defer func() {
<ide> if err != nil {
<ide><path>engine/env_test.go
<ide> func TestSetenvList(t *testing.T) {
<ide> }
<ide> }
<ide>
<del>func TestImportEnv(t *testing.T) {
<del> type dummy struct {
<del> DummyInt int
<del> DummyStringArray []string
<del> }
<del>
<del> job := mkJob(t, "dummy")
<del> if err := job.ImportEnv(&dummy{42, []string{"foo", "bar"}}); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> dmy := dummy{}
<del> if err := job.ExportEnv(&dmy); err != nil {
<del> t.Fatal(err)
<del> }
<del>
<del> if dmy.DummyInt != 42 {
<del> t.Fatalf("Expected 42, got %d", dmy.DummyInt)
<del> }
<del>
<del> if len(dmy.DummyStringArray) != 2 || dmy.DummyStringArray[0] != "foo" || dmy.DummyStringArray[1] != "bar" {
<del> t.Fatalf("Expected {foo, bar}, got %v", dmy.DummyStringArray)
<del> }
<del>
<del>}
<del>
<ide> func TestEnviron(t *testing.T) {
<ide> job := mkJob(t, "dummy")
<ide> job.Setenv("foo", "bar")
<ide><path>engine/job.go
<ide> func (job *Job) EncodeEnv(dst io.Writer) error {
<ide> return job.env.Encode(dst)
<ide> }
<ide>
<del>func (job *Job) ExportEnv(dst interface{}) (err error) {
<del> return job.env.Export(dst)
<del>}
<del>
<ide> func (job *Job) ImportEnv(src interface{}) (err error) {
<ide> return job.env.Import(src)
<ide> }
<ide><path>server.go
<ide> func (srv *Server) ContainerCreate(job *engine.Job) engine.Status {
<ide> job.Printf("Usage: %s", job.Name)
<ide> return engine.StatusErr
<ide> }
<del> var config Config
<del> if err := job.ExportEnv(&config); err != nil {
<del> job.Error(err)
<del> return engine.StatusErr
<del> }
<add> config := ContainerConfigFromJob(job)
<ide> if config.Memory != 0 && config.Memory < 524288 {
<ide> job.Errorf("Minimum memory limit allowed is 512k")
<ide> return engine.StatusErr
<ide> func (srv *Server) ContainerCreate(job *engine.Job) engine.Status {
<ide> config.Dns = defaultDns
<ide> }
<ide>
<del> container, buildWarnings, err := srv.runtime.Create(&config, name)
<add> container, buildWarnings, err := srv.runtime.Create(config, name)
<ide> if err != nil {
<ide> if srv.runtime.graph.IsNotExist(err) {
<ide> _, tag := utils.ParseRepositoryTag(config.Image)
<ide> func (srv *Server) ContainerStart(job *engine.Job) engine.Status {
<ide> }
<ide> // If no environment was set, then no hostconfig was passed.
<ide> if len(job.Environ()) > 0 {
<del> var hostConfig HostConfig
<del> if err := job.ExportEnv(&hostConfig); err != nil {
<del> job.Error(err)
<del> return engine.StatusErr
<del> }
<add> hostConfig := ContainerHostConfigFromJob(job)
<ide> // Validate the HostConfig binds. Make sure that:
<ide> // 1) the source of a bind mount isn't /
<ide> // The bind mount "/:/foo" isn't allowed.
<ide> func (srv *Server) ContainerStart(job *engine.Job) engine.Status {
<ide> }
<ide> }
<ide> // Register any links from the host config before starting the container
<del> if err := srv.RegisterLinks(container, &hostConfig); err != nil {
<add> if err := srv.RegisterLinks(container, hostConfig); err != nil {
<ide> job.Error(err)
<ide> return engine.StatusErr
<ide> }
<del> container.hostConfig = &hostConfig
<add> container.hostConfig = hostConfig
<ide> container.ToDisk()
<ide> }
<ide> if err := container.Start(); err != nil { | 5 |
Text | Text | add 2 podcast suggestions | 2d14103da843b76b91367f35d629c1fe5c977870 | <ide><path>guide/english/working-in-tech/index.md
<ide> The field of computer security is growing at a rapid rate every year. A recent r
<ide> - [This week in Google](https://twit.tv/shows/this-week-in-google)
<ide> - [Programming Throwdown - Good overview of multiple languages and concepts](https://www.programmingthrowdown.com/)
<ide> - [Shop Talk: A Web Design and Development Podcast](https://shoptalkshow.com/)
<add>- [Command Line Heroes - Red Hat](https://www.redhat.com/en/command-line-heroes)
<add>- [Learn to Code With Me - Laurence Bradford](https://learntocodewith.me/podcast/) | 1 |
Text | Text | replace stub page with new hints | cf8a79c0af516255876cfe8272809c0891f37998 | <ide><path>guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/create-a-model/index.md
<ide> ---
<ide> title: Create a Model
<ide> ---
<del>## Create a Model
<ide>
<del>### Creating Schema
<add>There are 3 things to do in this challenge. You can click each item to see the code.
<add>
<add><details>
<add> <summary>Assign Mongoose Schema to a variable. This is not necessary but will make your code easier to read.</summary>
<add>
<add>```javascript
<add>const Schema = mongoose.Schema;
<add>```
<add></details>
<add>
<ide> See the [Mongoose docs](https://mongoosejs.com/docs/guide.html) first where is a lot of useful stuff.
<ide> When you are building schema you can use either of three options for name validation
<del>```javascript
<add>```js
<ide> name: String
<ide> name: {type: String}
<ide> name: {type: String, required: true} //preferred
<ide> ```
<del>For array of favoriteFoods here is the validation:
<add>
<add><details>
<add> <summary>Create Person schema.</summary>
<add>
<ide> ```javascript
<del>favoriteFoods: [{ type: String }]
<add>const personSchema = new Schema({
<add> name: { type: String, required: true },
<add> age: Number,
<add> favoriteFoods: [String]
<add>});
<ide> ```
<del>### Creating a Model
<del>Now that we have the schema of our model, we can actually create a model by:
<add>**Note**: If you choose to skip the first step, you have to use `mongoose.Schema` instead of `Schema`.
<add></details>
<add><details>
<add> <summary>Create Person model from the schema.</summary>
<add>
<ide> ```javascript
<del>var Model = mongoose.model('Model', modelSchema);
<add>const Person = mongoose.model('Person', personSchema);
<ide> ```
<del>
<del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<add></details> | 1 |
Python | Python | add lemmatizer data as variable on language data | 417d45f5d062078e1895f4521e868c5bece91a54 | <ide><path>spacy/lang/de/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class GermanDefaults(Language.Defaults):
<ide> tag_map = dict(TAG_MAP)
<ide> stop_words = set(STOP_WORDS)
<ide> syntax_iterators = dict(SYNTAX_ITERATORS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class German(Language):
<ide><path>spacy/lang/en/__init__.py
<ide> from .stop_words import STOP_WORDS
<ide> from .lex_attrs import LEX_ATTRS
<ide> from .morph_rules import MORPH_RULES
<del>from .lemmatizer import LEMMA_RULES, LEMMA_INDEX, LEMMA_EXC
<add>from .lemmatizer import LEMMA_RULES, LEMMA_INDEX, LEMMA_EXC, LOOKUP
<ide> from .syntax_iterators import SYNTAX_ITERATORS
<ide>
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> class EnglishDefaults(Language.Defaults):
<ide> lemma_rules = dict(LEMMA_RULES)
<ide> lemma_index = dict(LEMMA_INDEX)
<ide> lemma_exc = dict(LEMMA_EXC)
<add> lemma_lookup = dict(LOOKUP)
<ide> syntax_iterators = dict(SYNTAX_ITERATORS)
<ide>
<ide>
<ide><path>spacy/lang/es/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class SpanishDefaults(Language.Defaults):
<ide> tag_map = dict(TAG_MAP)
<ide> stop_words = set(STOP_WORDS)
<ide> sytax_iterators = dict(SYNTAX_ITERATORS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class Spanish(Language):
<ide><path>spacy/lang/fr/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class FrenchDefaults(Language.Defaults):
<ide> suffixes = tuple(TOKENIZER_SUFFIXES)
<ide> token_match = TOKEN_MATCH
<ide> syntax_iterators = dict(SYNTAX_ITERATORS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class French(Language):
<ide><path>spacy/lang/hu/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class HungarianDefaults(Language.Defaults):
<ide> suffixes = tuple(TOKENIZER_SUFFIXES)
<ide> infixes = tuple(TOKENIZER_INFIXES)
<ide> token_match = TOKEN_MATCH
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class Hungarian(Language):
<ide><path>spacy/lang/id/__init__.py
<ide>
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG
<ide> from ...util import update_exc
<ide>
<ide> class IndonesianDefaults(Language.Defaults):
<ide> suffixes = tuple(TOKENIZER_SUFFIXES)
<ide> infixes = tuple(TOKENIZER_INFIXES)
<ide> syntax_iterators = dict(SYNTAX_ITERATORS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class Indonesian(Language):
<ide><path>spacy/lang/it/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class ItalianDefaults(Language.Defaults):
<ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS)
<ide> stop_words = set(STOP_WORDS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class Italian(Language):
<ide><path>spacy/lang/pt/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class PortugueseDefaults(Language.Defaults):
<ide> lex_attr_getters.update(LEX_ATTRS)
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<ide> stop_words = set(STOP_WORDS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class Portuguese(Language):
<ide><path>spacy/lang/sv/__init__.py
<ide> from ..tokenizer_exceptions import BASE_EXCEPTIONS
<ide> from ..norm_exceptions import BASE_NORMS
<ide> from ...language import Language
<del>from ...lemmatizerlookup import Lemmatizer
<ide> from ...attrs import LANG, NORM
<ide> from ...util import update_exc, add_lookups
<ide>
<ide> class SwedishDefaults(Language.Defaults):
<ide> lex_attr_getters[NORM] = add_lookups(Language.Defaults.lex_attr_getters[NORM], BASE_NORMS)
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<ide> stop_words = set(STOP_WORDS)
<del>
<del> @classmethod
<del> def create_lemmatizer(cls, nlp=None):
<del> return Lemmatizer(LOOKUP)
<add> lemma_rules = dict(LEMMA_RULES)
<add> lemma_lookup = dict(LOOKUP)
<ide>
<ide>
<ide> class Swedish(Language): | 9 |
Python | Python | put mathlib checks in separate function | 23c84e5d50cb0bf720e5c01d4956708f9094f0c7 | <ide><path>numpy/core/setup.py
<ide> def sym2def(symbol):
<ide> define = symbol.replace(' ', '_')
<ide> return define.upper()
<ide>
<add>def check_mathlib(config_cmd):
<add> # Testing the C math library
<add> mathlibs = []
<add> tc = testcode_mathlib()
<add> mathlibs_choices = [[],['m'],['cpml']]
<add> mathlib = os.environ.get('MATHLIB')
<add> if mathlib:
<add> mathlibs_choices.insert(0,mathlib.split(','))
<add> for libs in mathlibs_choices:
<add> if config_cmd.try_run(tc,libraries=libs):
<add> mathlibs = libs
<add> break
<add> else:
<add> raise EnvironmentError("math library missing; rerun "
<add> "setup.py after setting the "
<add> "MATHLIB env variable")
<add> return mathlibs
<add>
<ide> def configuration(parent_package='',top_path=None):
<ide> from numpy.distutils.misc_util import Configuration,dot_join
<ide> from numpy.distutils.system_info import get_info, default_lib_dirs
<ide> def generate_config_h(ext, build_dir):
<ide>
<ide> moredefs, ignored = check_types(config, ext, build_dir)
<ide>
<del> # Testing the C math library
<del> mathlibs = []
<del> tc = testcode_mathlib()
<del> mathlibs_choices = [[],['m'],['cpml']]
<del> mathlib = os.environ.get('MATHLIB')
<del> if mathlib:
<del> mathlibs_choices.insert(0,mathlib.split(','))
<del> for libs in mathlibs_choices:
<del> if config_cmd.try_run(tc,libraries=libs):
<del> mathlibs = libs
<del> break
<del> else:
<del> raise EnvironmentError("math library missing; rerun "
<del> "setup.py after setting the "
<del> "MATHLIB env variable")
<del> ext.libraries.extend(mathlibs)
<add> mathlibs = check_mathlib(config_cmd)
<ide> moredefs.append(('MATHLIB',','.join(mathlibs)))
<ide>
<ide> check_math_capabilities(config_cmd, moredefs, mathlibs)
<ide> def generate_config_h(ext, build_dir):
<ide> mathlibs.extend(value.split(','))
<ide> target_f.close()
<ide>
<del> ext.libraries.extend(mathlibs)
<add> # Ugly: this can be called within a library and not an extension,
<add> # in which case there is no libraries attributes (and none is
<add> # needed).
<add> if hasattr(ext, 'libraries'):
<add> ext.libraries.extend(mathlibs)
<ide>
<ide> incl_dir = os.path.dirname(target)
<ide> if incl_dir not in config.numpy_include_dirs: | 1 |
Javascript | Javascript | add tabindex prop to view component | 621f4cf3b12979b62d2e1d49d63eaf85e0707026 | <ide><path>Libraries/Components/View/View.js
<ide> export type Props = ViewProps;
<ide> const View: React.AbstractComponent<
<ide> ViewProps,
<ide> React.ElementRef<typeof ViewNativeComponent>,
<del>> = React.forwardRef((props: ViewProps, forwardedRef) => {
<del> return (
<del> <TextAncestor.Provider value={false}>
<del> <ViewNativeComponent {...props} ref={forwardedRef} />
<del> </TextAncestor.Provider>
<del> );
<del>});
<add>> = React.forwardRef(
<add> ({tabIndex, focusable, ...otherProps}: ViewProps, forwardedRef) => {
<add> return (
<add> <TextAncestor.Provider value={false}>
<add> <ViewNativeComponent
<add> focusable={tabIndex !== undefined ? !tabIndex : focusable}
<add> {...otherProps}
<add> ref={forwardedRef}
<add> />
<add> </TextAncestor.Provider>
<add> );
<add> },
<add>);
<ide>
<ide> View.displayName = 'View';
<ide>
<ide><path>Libraries/Components/View/ViewPropTypes.js
<ide> type AndroidViewProps = $ReadOnly<{|
<ide> */
<ide> focusable?: boolean,
<ide>
<add> /**
<add> * Indicates whether this `View` should be focusable with a non-touch input device, eg. receive focus with a hardware keyboard.
<add> * See https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
<add> * for more details.
<add> *
<add> * Supports the following values:
<add> * - 0 (View is focusable)
<add> * - -1 (View is not focusable)
<add> *
<add> * @platform android
<add> */
<add> tabIndex?: 0 | -1,
<add>
<ide> /**
<ide> * The action to perform when this `View` is clicked on by a non-touch click, eg. enter key on a hardware keyboard.
<ide> * | 2 |
PHP | PHP | fix incorrect type on persistent connection | 055f9458193607471b118dbde2c4482fffd9e67b | <ide><path>src/Cache/Engine/MemcachedEngine.php
<ide> public function init(array $config = []): bool
<ide> $configuredServers = $this->_config['servers'];
<ide> sort($configuredServers);
<ide> if ($actualServers !== $configuredServers) {
<del> $message = "Invalid cache configuration. Multiple persistent cache configurations are detected" .
<del> " with different 'servers' values. 'servers' values for persistent cache configurations" .
<del> " must be the same when using the same persistence id.";
<add> $message = 'Invalid cache configuration. Multiple persistent cache configurations are detected' .
<add> ' with different `servers` values. `servers` values for persistent cache configurations' .
<add> ' must be the same when using the same persistence id.';
<ide> throw new InvalidArgumentException($message);
<ide> }
<ide> }
<ide><path>tests/TestCase/Cache/Engine/MemcachedEngineTest.php
<ide> public function testConfigDifferentPorts()
<ide> $config1 = [
<ide> 'className' => 'Memcached',
<ide> 'servers' => ['127.0.0.1:11211'],
<del> 'persistent' => true,
<add> 'persistent' => '123',
<ide> ];
<ide> $Memcached1->init($config1);
<ide>
<ide> $Memcached2 = new MemcachedEngine();
<ide> $config2 = [
<ide> 'className' => 'Memcached',
<ide> 'servers' => ['127.0.0.1:11212'],
<del> 'persistent' => true,
<add> 'persistent' => '123',
<ide> ];
<ide> $Memcached2->init($config2);
<ide> } | 2 |
Go | Go | remove job from pause/unpause | 5ccb1c764b04449811aa4d8095a9ee609b901cf7 | <ide><path>api/server/server.go
<ide> func postContainersPause(eng *engine.Engine, version version.Version, w http.Res
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<del> job := eng.Job("pause", vars["name"])
<del> if err := job.Run(); err != nil {
<add>
<add> name := vars["name"]
<add> d := getDaemon(eng)
<add> cont, err := d.Get(name)
<add> if err != nil {
<ide> return err
<ide> }
<add>
<add> if err := cont.Pause(); err != nil {
<add> return fmt.Errorf("Cannot pause container %s: %s", name, err)
<add> }
<add> cont.LogEvent("pause")
<add>
<ide> w.WriteHeader(http.StatusNoContent)
<add>
<ide> return nil
<ide> }
<ide>
<ide> func postContainersUnpause(eng *engine.Engine, version version.Version, w http.R
<ide> if err := parseForm(r); err != nil {
<ide> return err
<ide> }
<del> job := eng.Job("unpause", vars["name"])
<del> if err := job.Run(); err != nil {
<add>
<add> name := vars["name"]
<add> d := getDaemon(eng)
<add> cont, err := d.Get(name)
<add> if err != nil {
<ide> return err
<ide> }
<add>
<add> if err := cont.Unpause(); err != nil {
<add> return fmt.Errorf("Cannot unpause container %s: %s", name, err)
<add> }
<add> cont.LogEvent("unpause")
<add>
<ide> w.WriteHeader(http.StatusNoContent)
<add>
<ide> return nil
<ide> }
<ide>
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> "info": daemon.CmdInfo,
<ide> "kill": daemon.ContainerKill,
<ide> "logs": daemon.ContainerLogs,
<del> "pause": daemon.ContainerPause,
<ide> "resize": daemon.ContainerResize,
<ide> "restart": daemon.ContainerRestart,
<ide> "start": daemon.ContainerStart,
<ide> "stop": daemon.ContainerStop,
<ide> "top": daemon.ContainerTop,
<del> "unpause": daemon.ContainerUnpause,
<ide> "wait": daemon.ContainerWait,
<ide> "execCreate": daemon.ContainerExecCreate,
<ide> "execStart": daemon.ContainerExecStart,
<ide><path>daemon/pause.go
<del>package daemon
<del>
<del>import (
<del> "fmt"
<del>
<del> "github.com/docker/docker/engine"
<del>)
<del>
<del>func (daemon *Daemon) ContainerPause(job *engine.Job) error {
<del> if len(job.Args) != 1 {
<del> return fmt.Errorf("Usage: %s CONTAINER", job.Name)
<del> }
<del> name := job.Args[0]
<del> container, err := daemon.Get(name)
<del> if err != nil {
<del> return err
<del> }
<del> if err := container.Pause(); err != nil {
<del> return fmt.Errorf("Cannot pause container %s: %s", name, err)
<del> }
<del> container.LogEvent("pause")
<del> return nil
<del>}
<del>
<del>func (daemon *Daemon) ContainerUnpause(job *engine.Job) error {
<del> if n := len(job.Args); n < 1 || n > 2 {
<del> return fmt.Errorf("Usage: %s CONTAINER", job.Name)
<del> }
<del> name := job.Args[0]
<del> container, err := daemon.Get(name)
<del> if err != nil {
<del> return err
<del> }
<del> if err := container.Unpause(); err != nil {
<del> return fmt.Errorf("Cannot unpause container %s: %s", name, err)
<del> }
<del> container.LogEvent("unpause")
<del> return nil
<del>} | 3 |
Javascript | Javascript | add comment about serialization | 0d617c54b5a153d0a9c2c476c6d2760ac73b707f | <ide><path>lib/dependencies/CommonJsRequireContextDependency.js
<ide> class CommonJsRequireContextDependency extends ContextDependency {
<ide>
<ide> this.range = range;
<ide> this.valueRange = valueRange;
<add> // inShorthand must be serialized by subclasses that use it
<ide> this.inShorthand = inShorthand;
<ide> }
<ide> | 1 |
Javascript | Javascript | fix typeerror in with-graphql-hooks example | c4567a1a813c2b357e6c2857c80ac50d0d29c007 | <ide><path>examples/with-graphql-hooks/lib/with-graphql-client.js
<ide> export default App => {
<ide> return class GraphQLHooks extends React.Component {
<ide> static displayName = 'GraphQLHooks(App)'
<ide> static async getInitialProps(ctx) {
<del> const { Component, router } = ctx
<add> const { AppTree } = ctx
<ide>
<ide> let appProps = {}
<ide> if (App.getInitialProps) {
<ide> export default App => {
<ide> try {
<ide> // Run all GraphQL queries
<ide> graphQLState = await getInitialState({
<del> App: (
<del> <App
<del> {...appProps}
<del> Component={Component}
<del> router={router}
<del> graphQLClient={graphQLClient}
<del> />
<del> ),
<add> App: <AppTree {...appProps} graphQLClient={graphQLClient} />,
<ide> client: graphQLClient,
<ide> })
<ide> } catch (error) { | 1 |
PHP | PHP | remove requirement to have register method | af0080918dd53471916c38a87fcac0568a8deef2 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function register($provider, $options = [], $force = false)
<ide> $provider = $this->resolveProviderClass($provider);
<ide> }
<ide>
<del> $this->registerProvider($provider);
<add> if (method_exists($provider, 'register')) {
<add> $provider->register();
<add> }
<ide>
<ide> // Once we have registered the service we will iterate through the options
<ide> // and set each of them on the application so they will be available on
<ide> public function resolveProviderClass($provider)
<ide> return new $provider($this);
<ide> }
<ide>
<del> /**
<del> * Register the given service provider.
<del> *
<del> * @param \Illuminate\Support\ServiceProvider $provider
<del> * @return mixed
<del> */
<del> protected function registerProvider(ServiceProvider $provider)
<del> {
<del> if (method_exists($provider, 'register')) {
<del> return $this->call([$provider, 'register']);
<del> }
<del> }
<del>
<ide> /**
<ide> * Mark the given provider as registered.
<ide> *
<ide><path>tests/Foundation/FoundationApplicationTest.php
<ide> public function testSetLocaleSetsLocaleAndFiresLocaleChangedEvent()
<ide>
<ide> public function testServiceProvidersAreCorrectlyRegistered()
<ide> {
<del> $provider = m::mock('Illuminate\Support\ServiceProvider');
<add> $provider = m::mock('ApplicationBasicServiceProviderStub');
<ide> $class = get_class($provider);
<ide> $provider->shouldReceive('register')->once();
<ide> $app = new Application;
<ide> public function testServiceProvidersAreCorrectlyRegistered()
<ide> $this->assertTrue(in_array($class, $app->getLoadedProviders()));
<ide> }
<ide>
<add> public function testServiceProvidersAreCorrectlyRegisteredWhenRegisterMethodIsNotPresent()
<add> {
<add> $provider = m::mock('Illuminate\Support\ServiceProvider');
<add> $class = get_class($provider);
<add> $provider->shouldReceive('register')->never();
<add> $app = new Application;
<add> $app->register($provider);
<add>
<add> $this->assertTrue(in_array($class, $app->getLoadedProviders()));
<add> }
<add>
<ide> public function testDeferredServicesMarkedAsBound()
<ide> {
<ide> $app = new Application;
<ide> public function testAfterBootstrappingAddsClosure()
<ide> }
<ide> }
<ide>
<add>class ApplicationBasicServiceProviderStub extends Illuminate\Support\ServiceProvider
<add>{
<add> public function boot()
<add> {
<add> //
<add> }
<add>
<add> public function register()
<add> {
<add> //
<add> }
<add>}
<add>
<ide> class ApplicationDeferredSharedServiceProviderStub extends Illuminate\Support\ServiceProvider
<ide> {
<ide> protected $defer = true; | 2 |
Ruby | Ruby | convert formula name from pathname to string | 58b17a0cfc34adf2213e18b1f277c52a89407e64 | <ide><path>Library/Homebrew/utils.rb
<ide> def migrate_legacy_keg_symlinks_if_necessary
<ide>
<ide> HOMEBREW_LINKED_KEGS.mkpath unless legacy_linked_kegs.children.empty?
<ide> legacy_linked_kegs.children.each do |link|
<del> name = link.basename
<add> name = link.basename.to_s
<ide> src = begin
<ide> link.realpath
<ide> rescue Errno::ENOENT
<ide> def migrate_legacy_keg_symlinks_if_necessary
<ide>
<ide> HOMEBREW_PINNED_KEGS.mkpath unless legacy_pinned_kegs.children.empty?
<ide> legacy_pinned_kegs.children.each do |link|
<del> name = link.basename
<add> name = link.basename.to_s
<ide> src = link.realpath
<ide> dst = HOMEBREW_PINNED_KEGS/name
<ide> FileUtils.ln_sf(src.relative_path_from(dst.parent), dst) | 1 |
Go | Go | do actual rootfs.diffids copying in clone() | 3429e9993085520ac902fef2ef6aabd57080bd36 | <ide><path>image/rootfs.go
<ide> func (r *RootFS) Append(id layer.DiffID) {
<ide> func (r *RootFS) Clone() *RootFS {
<ide> newRoot := NewRootFS()
<ide> newRoot.Type = r.Type
<del> newRoot.DiffIDs = append(r.DiffIDs)
<add> newRoot.DiffIDs = make([]layer.DiffID, len(r.DiffIDs))
<add> copy(newRoot.DiffIDs, r.DiffIDs)
<ide> return newRoot
<ide> }
<ide> | 1 |
Ruby | Ruby | check all responses for protected cookies | 403a4d4a494643d0ecfd91f92812a6f5bfa9a9ff | <ide><path>Library/Homebrew/utils/curl.rb
<ide> def curl_output(*args, **options)
<ide> end
<ide>
<ide> # Check if a URL is protected by CloudFlare (e.g. badlion.net and jaxx.io).
<del> # @param details [Hash] Response information from
<del> # `#curl_http_content_headers_and_checksum`.
<add> # @param response [Hash] A response hash from `#parse_curl_response`.
<ide> # @return [true, false] Whether a response contains headers indicating that
<ide> # the URL is protected by Cloudflare.
<del> sig { params(details: T::Hash[Symbol, T.untyped]).returns(T::Boolean) }
<del> def url_protected_by_cloudflare?(details)
<del> return false if details[:headers].blank?
<del> return false unless [403, 503].include?(details[:status_code].to_i)
<add> sig { params(response: T::Hash[Symbol, T.untyped]).returns(T::Boolean) }
<add> def url_protected_by_cloudflare?(response)
<add> return false if response[:headers].blank?
<add> return false unless [403, 503].include?(response[:status_code].to_i)
<ide>
<del> set_cookie_header = Array(details[:headers]["set-cookie"])
<add> set_cookie_header = Array(response[:headers]["set-cookie"])
<ide> has_cloudflare_cookie_header = set_cookie_header.compact.any? do |cookie|
<ide> cookie.match?(/^(__cfduid|__cf_bm)=/i)
<ide> end
<ide>
<del> server_header = Array(details[:headers]["server"])
<add> server_header = Array(response[:headers]["server"])
<ide> has_cloudflare_server = server_header.compact.any? do |server|
<ide> server.match?(/^cloudflare/i)
<ide> end
<ide> def url_protected_by_cloudflare?(details)
<ide> end
<ide>
<ide> # Check if a URL is protected by Incapsula (e.g. corsair.com).
<del> # @param details [Hash] Response information from
<del> # `#curl_http_content_headers_and_checksum`.
<add> # @param response [Hash] A response hash from `#parse_curl_response`.
<ide> # @return [true, false] Whether a response contains headers indicating that
<ide> # the URL is protected by Incapsula.
<del> sig { params(details: T::Hash[Symbol, T.untyped]).returns(T::Boolean) }
<del> def url_protected_by_incapsula?(details)
<del> return false if details[:headers].blank?
<del> return false if details[:status_code].to_i != 403
<add> sig { params(response: T::Hash[Symbol, T.untyped]).returns(T::Boolean) }
<add> def url_protected_by_incapsula?(response)
<add> return false if response[:headers].blank?
<add> return false if response[:status_code].to_i != 403
<ide>
<del> set_cookie_header = Array(details[:headers]["set-cookie"])
<add> set_cookie_header = Array(response[:headers]["set-cookie"])
<ide> set_cookie_header.compact.any? { |cookie| cookie.match?(/^(visid_incap|incap_ses)_/i) }
<ide> end
<ide>
<ide> def curl_check_http_content(url, url_type, specs: {}, user_agents: [:default],
<ide> end
<ide>
<ide> unless http_status_ok?(details[:status_code])
<del> return if url_protected_by_cloudflare?(details) || url_protected_by_incapsula?(details)
<add> return if details[:responses].any? do |response|
<add> url_protected_by_cloudflare?(response) || url_protected_by_incapsula?(response)
<add> end
<ide>
<ide> return "The #{url_type} #{url} is not reachable (HTTP status code #{details[:status_code]})"
<ide> end
<ide> def curl_http_content_headers_and_checksum(
<ide> content_length: content_length,
<ide> file: file_contents,
<ide> file_hash: file_hash,
<add> responses: responses,
<ide> }
<ide> ensure
<ide> file.unlink | 1 |
Java | Java | move tests to packages where they belong | 8ab84481489c4357362984c16c14c2254c20e764 | <add><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/jetty/JettyWebSocketHandlerAdapterTests.java
<del><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/JettyWebSocketHandlerAdapterTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.web.socket.adapter;
<add>package org.springframework.web.socket.adapter.jetty;
<ide>
<ide> import org.eclipse.jetty.websocket.api.Session;
<ide> import org.junit.Before;
<add><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/ConvertingEncoderDecoderSupportTests.java
<del><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/ConvertingEncoderDecoderSupportTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.web.socket.adapter;
<add>package org.springframework.web.socket.adapter.standard;
<ide>
<ide> import java.nio.ByteBuffer;
<ide> import javax.websocket.DecodeException;
<add><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/standard/StandardWebSocketHandlerAdapterTests.java
<del><path>spring-websocket/src/test/java/org/springframework/web/socket/adapter/StandardWebSocketHandlerAdapterTests.java
<ide> * limitations under the License.
<ide> */
<ide>
<del>package org.springframework.web.socket.adapter;
<add>package org.springframework.web.socket.adapter.standard;
<ide>
<ide> import javax.websocket.CloseReason;
<ide> import javax.websocket.CloseReason.CloseCodes; | 3 |
Javascript | Javascript | fix _http_client.js after v0.10 merge | c898704db18fd3b8d7dd91bf7c1b74922c5de928 | <ide><path>lib/_http_client.js
<ide> ClientRequest.prototype._implicitHeader = function() {
<ide> };
<ide>
<ide> ClientRequest.prototype.abort = function() {
<del>// If we're aborting, we don't care about any more response data.
<add> // If we're aborting, we don't care about any more response data.
<ide> if (this.res)
<ide> this.res._dump();
<ide> else | 1 |
Python | Python | remove one of the last traces of south | d146b250aecd7adb13ad7b998cc60cc3a10fd0b6 | <ide><path>django/db/backends/schema.py
<ide> def _create_index_name(self, model, column_names, suffix=""):
<ide> '%s_%s' % (model._meta.db_table, BaseDatabaseCreation._digest(column_names[0])),
<ide> self.connection.ops.max_name_length()
<ide> )
<del> # Else generate the name for the index by South
<add> # Else generate the name for the index using a different algorithm
<ide> table_name = model._meta.db_table.replace('"', '').replace('.', '_')
<ide> index_unique_name = '_%x' % abs(hash((table_name, ','.join(column_names))))
<ide> # If the index name is too long, truncate it | 1 |
PHP | PHP | fix failing tests | 71320045917cc245b78f13cc79232ed917d226c2 | <ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php
<ide> public function setUp(): void
<ide> {
<ide> parent::setUp();
<ide>
<del> $salt = 'foo.bar';
<del> Security::setSalt($salt);
<ide> $this->Collection = $this->getMockBuilder(ComponentRegistry::class)->getMock();
<ide> $this->auth = new DigestAuthenticate($this->Collection, [
<ide> 'realm' => 'localhost',
<ide> 'nonce' => 123,
<ide> 'opaque' => '123abc',
<del> 'secret' => $salt,
<add> 'secret' => Security::getSalt(),
<ide> ]);
<ide>
<ide> $password = DigestAuthenticate::password('mariano', 'cake', 'localhost');
<ide><path>tests/TestCase/Auth/FormAuthenticateTest.php
<ide> use Cake\I18n\Time;
<ide> use Cake\ORM\Entity;
<ide> use Cake\TestSuite\TestCase;
<del>use Cake\Utility\Security;
<ide>
<ide> /**
<ide> * Test case for FormAuthentication
<ide> public function testPluginModel(): void
<ide> $PluginModel = $this->getTableLocator()->get('TestPlugin.AuthUsers');
<ide> $user['id'] = 1;
<ide> $user['username'] = 'gwoo';
<del> $user['password'] = password_hash(Security::getSalt() . 'cake', PASSWORD_BCRYPT);
<add> $user['password'] = password_hash('cake', PASSWORD_BCRYPT);
<ide> $PluginModel->save(new Entity($user));
<ide>
<ide> $this->auth->setConfig('userModel', 'TestPlugin.AuthUsers');
<ide><path>tests/bootstrap.php
<ide> use Cake\Core\Configure;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\Log\Log;
<add>use Cake\Utility\Security;
<ide>
<ide> if (is_file('vendor/autoload.php')) {
<ide> require_once 'vendor/autoload.php';
<ide> ]);
<ide>
<ide> Chronos::setTestNow(Chronos::now());
<add>Security::setSalt('a-long-but-not-random-value');;
<ide>
<ide> ini_set('intl.default_locale', 'en_US');
<ide> ini_set('session.gc_divisor', '1'); | 3 |
PHP | PHP | add setinput function to cakerequest | 6bf0b22195da5dd0a0f9fb219f9dd530373502a3 | <ide><path>lib/Cake/Network/CakeRequest.php
<ide> public function input($callback = null) {
<ide> return $input;
<ide> }
<ide>
<add>/**
<add> * Modify data originally from `php://input`. Useful for altering json/xml data
<add> * in middleware or DispatcherFilters before it gets to RequestHandlerComponent
<add> *
<add> * @param string $input A string to replace original parsed data from input()
<add> * @return void
<add> */
<add> public function setInput($input) {
<add> $this->_input = $input;
<add> }
<add>
<ide> /**
<ide> * Allow only certain HTTP request methods. If the request method does not match
<ide> * a 405 error will be shown and the required "Allow" response header will be set. | 1 |
Text | Text | remove keyword from the word "blue" | d95456648ee694f802370d1859e7173eb7154b9e | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-css-colors-by-building-a-set-of-colored-markers/61b315e76a63b3ecbbb11b75.md
<ide> dashedName: step-91
<ide>
<ide> Next, update the `color` value of the red marker's `box-shadow` property.
<ide>
<del>Replace the named color with the `rgba` function. Use the values `83` for red, `14` for green, `14` for `blue` and `0.8` for the alpha channel.
<add>Replace the named color with the `rgba` function. Use the values `83` for red, `14` for green, `14` for blue and `0.8` for the alpha channel.
<ide>
<ide> # --hints--
<ide> | 1 |
Javascript | Javascript | remove some useless var | 0a18434a2da3320737029cf19e7caac86b2826f0 | <ide><path>fonts.js
<ide> var Font = (function () {
<ide>
<ide> /** CMAP */
<ide> var charstrings = font.charstrings;
<del> cmap = createCMapTable(font.charstrings);
<add> cmap = createCMapTable(charstrings);
<ide> createTableEntry(otf, offsets, "cmap", cmap);
<ide>
<ide> /** HEAD */
<ide> CFF.prototype = {
<ide>
<ide> wrap: function wrap(name, charstrings, subrs, properties) {
<ide> // Starts the conversion of the Type1 charstrings to Type2
<del> var charstringsCount = 0;
<del> var charstringsDataLength = 0;
<del> var glyphs = [];
<del> for (var i = 0; i < charstrings.length; i++) {
<del> var charstring = charstrings[i].charstring;
<del> var glyph = charstrings[i].glyph;
<del>
<del> var flattened = this.flattenCharstring(glyph, charstring, subrs);
<del> glyphs.push(flattened);
<del> charstringsCount++;
<del> charstringsDataLength += flattened.length;
<add> var glyphs = charstrings.slice();
<add> var glyphsCount = glyphs.length;
<add> for (var i = 0; i < glyphs.length; i++) {
<add> var charstring = glyphs[i];
<add> glyphs[i] = this.flattenCharstring(charstring.glyph, charstring.charstring, subrs);
<ide> }
<ide>
<ide> // Create a CFF font data
<ide> CFF.prototype = {
<ide>
<ide> // Fill the charset header (first byte is the encoding)
<ide> var charset = [0x00];
<del> for (var i = 0; i < glyphs.length; i++) {
<add> for (var i = 0; i < glyphsCount; i++) {
<ide> var index = CFFStrings.indexOf(charstrings[i].glyph);
<ide> if (index == -1)
<del> index = CFFStrings.length + strings.indexOf(glyph);
<add> index = CFFStrings.length + strings.indexOf(charstrings[i].glyph);
<ide> var bytes = FontsUtils.integerToBytes(index, 2);
<ide> charset.push(bytes[0]);
<ide> charset.push(bytes[1]);
<ide> CFF.prototype = {
<ide>
<ide> topDictIndex = topDictIndex.concat([28, 0, 0, 16]) // Encoding
<ide>
<del> var charstringsOffset = charsetOffset + (charstringsCount * 2) + 1;
<add> var charstringsOffset = charsetOffset + (glyphsCount * 2) + 1;
<ide> topDictIndex = topDictIndex.concat(this.encodeNumber(charstringsOffset));
<ide> topDictIndex.push(17); // charstrings
<ide> | 1 |
Python | Python | add json output on sqltos3operator | 5276ef8ad9749b2aaf4878effda513ee378f4665 | <ide><path>airflow/providers/amazon/aws/transfers/sql_to_s3.py
<ide>
<ide> FILE_FORMAT = Enum(
<ide> "FILE_FORMAT",
<del> "CSV, PARQUET",
<add> "CSV, JSON, PARQUET",
<ide> )
<ide>
<del>FileOptions = namedtuple('FileOptions', ['mode', 'suffix'])
<add>FileOptions = namedtuple('FileOptions', ['mode', 'suffix', 'function'])
<ide>
<ide> FILE_OPTIONS_MAP = {
<del> FILE_FORMAT.CSV: FileOptions('r+', '.csv'),
<del> FILE_FORMAT.PARQUET: FileOptions('rb+', '.parquet'),
<add> FILE_FORMAT.CSV: FileOptions('r+', '.csv', 'to_csv'),
<add> FILE_FORMAT.JSON: FileOptions('r+', '.json', 'to_json'),
<add> FILE_FORMAT.PARQUET: FileOptions('rb+', '.parquet', 'to_parquet'),
<ide> }
<ide>
<ide>
<ide> class SqlToS3Operator(BaseOperator):
<ide> - ``path/to/cert/bundle.pem``: A filename of the CA cert bundle to uses.
<ide> You can specify this argument if you want to use a different
<ide> CA cert bundle than the one used by botocore.
<del> :param file_format: the destination file format, only string 'csv' or 'parquet' is accepted.
<del> :param pd_kwargs: arguments to include in ``DataFrame.to_parquet()`` or ``DataFrame.to_csv()``.
<add> :param file_format: the destination file format, only string 'csv', 'json' or 'parquet' is accepted.
<add> :param pd_kwargs: arguments to include in DataFrame ``.to_parquet()``, ``.to_json()`` or ``.to_csv()``.
<ide> """
<ide>
<ide> template_fields: Sequence[str] = (
<ide> class SqlToS3Operator(BaseOperator):
<ide> template_ext: Sequence[str] = ('.sql',)
<ide> template_fields_renderers = {
<ide> "query": "sql",
<del> "pd_csv_kwargs": "json",
<ide> "pd_kwargs": "json",
<ide> }
<ide>
<ide> def __init__(
<ide> replace: bool = False,
<ide> aws_conn_id: str = 'aws_default',
<ide> verify: Optional[Union[bool, str]] = None,
<del> file_format: Literal['csv', 'parquet'] = 'csv',
<add> file_format: Literal['csv', 'json', 'parquet'] = 'csv',
<ide> pd_kwargs: Optional[dict] = None,
<ide> **kwargs,
<ide> ) -> None:
<ide> def __init__(
<ide> self.pd_kwargs = pd_kwargs or {}
<ide> self.parameters = parameters
<ide>
<del> if file_format == "csv":
<del> self.file_format = FILE_FORMAT.CSV
<del> if "path_or_buf" in self.pd_kwargs:
<del> raise AirflowException('The argument path_or_buf is not allowed, please remove it')
<del> elif file_format == "parquet":
<del> self.file_format = FILE_FORMAT.PARQUET
<del> else:
<add> if "path_or_buf" in self.pd_kwargs:
<add> raise AirflowException('The argument path_or_buf is not allowed, please remove it')
<add>
<add> self.file_format = getattr(FILE_FORMAT, file_format.upper(), None)
<add>
<add> if self.file_format is None:
<ide> raise AirflowException(f"The argument file_format doesn't support {file_format} value.")
<ide>
<ide> @staticmethod
<ide> def execute(self, context: 'Context') -> None:
<ide>
<ide> with NamedTemporaryFile(mode=file_options.mode, suffix=file_options.suffix) as tmp_file:
<ide>
<del> if self.file_format == FILE_FORMAT.CSV:
<del> data_df.to_csv(tmp_file.name, **self.pd_kwargs)
<del> else:
<del> data_df.to_parquet(tmp_file.name, **self.pd_kwargs)
<add> self.log.info("Writing data to temp file")
<add> getattr(data_df, file_options.function)(tmp_file.name, **self.pd_kwargs)
<ide>
<add> self.log.info("Uploading data to S3")
<ide> s3_conn.load_file(
<ide> filename=tmp_file.name, key=self.s3_key, bucket_name=self.s3_bucket, replace=self.replace
<ide> )
<ide><path>tests/providers/amazon/aws/transfers/test_sql_to_s3.py
<ide> from unittest import mock
<ide>
<ide> import pandas as pd
<add>import pytest
<ide>
<add>from airflow.exceptions import AirflowException
<ide> from airflow.providers.amazon.aws.transfers.sql_to_s3 import SqlToS3Operator
<ide>
<ide>
<ide> def test_execute_parquet(self, mock_s3_hook, temp_mock):
<ide> filename=f.name, key=s3_key, bucket_name=s3_bucket, replace=False
<ide> )
<ide>
<add> @mock.patch("airflow.providers.amazon.aws.transfers.sql_to_s3.NamedTemporaryFile")
<add> @mock.patch("airflow.providers.amazon.aws.transfers.sql_to_s3.S3Hook")
<add> def test_execute_json(self, mock_s3_hook, temp_mock):
<add> query = "query"
<add> s3_bucket = "bucket"
<add> s3_key = "key"
<add>
<add> mock_dbapi_hook = mock.Mock()
<add> test_df = pd.DataFrame({'a': '1', 'b': '2'}, index=[0, 1])
<add> get_pandas_df_mock = mock_dbapi_hook.return_value.get_pandas_df
<add> get_pandas_df_mock.return_value = test_df
<add> with NamedTemporaryFile() as f:
<add> temp_mock.return_value.__enter__.return_value.name = f.name
<add>
<add> op = SqlToS3Operator(
<add> query=query,
<add> s3_bucket=s3_bucket,
<add> s3_key=s3_key,
<add> sql_conn_id="mysql_conn_id",
<add> aws_conn_id="aws_conn_id",
<add> task_id="task_id",
<add> file_format="json",
<add> replace=True,
<add> pd_kwargs={'date_format': "iso", 'lines': True, 'orient': "records"},
<add> dag=None,
<add> )
<add> op._get_hook = mock_dbapi_hook
<add> op.execute(None)
<add> mock_s3_hook.assert_called_once_with(aws_conn_id="aws_conn_id", verify=None)
<add>
<add> get_pandas_df_mock.assert_called_once_with(sql=query, parameters=None)
<add>
<add> temp_mock.assert_called_once_with(mode='r+', suffix=".json")
<add> mock_s3_hook.return_value.load_file.assert_called_once_with(
<add> filename=f.name,
<add> key=s3_key,
<add> bucket_name=s3_bucket,
<add> replace=True,
<add> )
<add>
<ide> def test_fix_int_dtypes(self):
<ide> op = SqlToS3Operator(
<ide> query="query",
<ide> def test_fix_int_dtypes(self):
<ide> dirty_df = pd.DataFrame({"strings": ["a", "b", "c"], "ints": [1, 2, None]})
<ide> op._fix_int_dtypes(df=dirty_df)
<ide> assert dirty_df["ints"].dtype.kind == "i"
<add>
<add> def test_invalid_file_format(self):
<add> with pytest.raises(AirflowException):
<add> SqlToS3Operator(
<add> query="query",
<add> s3_bucket="bucket",
<add> s3_key="key",
<add> sql_conn_id="mysql_conn_id",
<add> task_id="task_id",
<add> file_format="invalid_format",
<add> dag=None,
<add> ) | 2 |
Text | Text | add the missed volume filter | b1619766c0131a02774c7ec2b158c2fdf7206d05 | <ide><path>docs/reference/commandline/ps.md
<ide> parent = "smn_cli"
<ide> - before=(<container-name>|<container-id>)
<ide> - since=(<container-name>|<container-id>)
<ide> - ancestor=(<image-name>[:tag]|<image-id>|<image@digest>) - containers created from an image or a descendant.
<add> - volume=(<volume-name>|<mount-point>)
<ide> --format=[] Pretty-print containers using a Go template
<ide> --help Print usage
<ide> -l, --latest Show the latest created container (includes all states) | 1 |
Javascript | Javascript | add arrow functions to test-util-inspect | 7acc482432c7b961a52a4a081a87b05f882cf1dd | <ide><path>test/parallel/test-util-inspect.js
<ide> assert.strictEqual(util.inspect(false), 'false');
<ide> assert.strictEqual(util.inspect(''), "''");
<ide> assert.strictEqual(util.inspect('hello'), "'hello'");
<ide> assert.strictEqual(util.inspect(function() {}), '[Function]');
<add>assert.strictEqual(util.inspect(() => {}), '[Function]');
<ide> assert.strictEqual(util.inspect(async function() {}), '[AsyncFunction]');
<add>assert.strictEqual(util.inspect(async () => {}), '[AsyncFunction]');
<ide> assert.strictEqual(util.inspect(function*() {}), '[GeneratorFunction]');
<ide> assert.strictEqual(util.inspect(undefined), 'undefined');
<ide> assert.strictEqual(util.inspect(null), 'null');
<ide> assert.strictEqual(util.inspect([1, [2, 3]]), '[ 1, [ 2, 3 ] ]');
<ide> assert.strictEqual(util.inspect({}), '{}');
<ide> assert.strictEqual(util.inspect({a: 1}), '{ a: 1 }');
<ide> assert.strictEqual(util.inspect({a: function() {}}), '{ a: [Function: a] }');
<add>assert.strictEqual(util.inspect({a: () => {}}), '{ a: [Function: a] }');
<ide> assert.strictEqual(util.inspect({a: async function() {}}),
<ide> '{ a: [AsyncFunction: a] }');
<add>assert.strictEqual(util.inspect({a: async () => {}}),
<add> '{ a: [AsyncFunction: a] }');
<ide> assert.strictEqual(util.inspect({a: function*() {}}),
<ide> '{ a: [GeneratorFunction: a] }');
<ide> assert.strictEqual(util.inspect({a: 1, b: 2}), '{ a: 1, b: 2 }'); | 1 |
Javascript | Javascript | fix comment typos | 686cb4dbd020ec6c16450ad3fe422d9f917f0a48 | <ide><path>lib/internal/util/comparisons.js
<ide> function setHasEqualElement(set, val1, strict, memo) {
<ide> return false;
<ide> }
<ide>
<del>// Note: we val1ly run this multiple times for each loose key!
<add>// Note: we currently run this multiple times for each loose key!
<ide> // This is done to prevent slowing down the average case.
<ide> function setHasLoosePrim(a, b, val) {
<ide> const altValues = findLooseMatchingPrimitives(val);
<ide> function findLooseMatchingPrimitives(prim) {
<ide> }
<ide>
<ide> // This is a ugly but relatively fast way to determine if a loose equal entry
<del>// val1ly has a correspondent matching entry. Otherwise checking for such
<add>// currently has a correspondent matching entry. Otherwise checking for such
<ide> // values would be way more expensive (O(n^2)).
<del>// Note: we val1ly run this multiple times for each loose key!
<add>// Note: we currently run this multiple times for each loose key!
<ide> // This is done to prevent slowing down the average case.
<ide> function mapHasLoosePrim(a, b, key1, memo, item1, item2) {
<ide> const altKeys = findLooseMatchingPrimitives(key1); | 1 |
PHP | PHP | use config method in behaviors | da8de77d42d4c3ec6a6bde77707e0436073d0c3e | <ide><path>src/Model/Behavior/CounterCacheBehavior.php
<ide> public function afterDelete(Event $event, Entity $entity) {
<ide> * @return void
<ide> */
<ide> protected function _processAssociations(Event $event, Entity $entity) {
<del> foreach ($this->_config as $assoc => $settings) {
<add> foreach ($this->config() as $assoc => $settings) {
<ide> $assoc = $this->_table->association($assoc);
<ide> $this->_processAssociation($event, $entity, $assoc, $settings);
<ide> }
<ide><path>src/Model/Behavior/TimestampBehavior.php
<ide> class TimestampBehavior extends Behavior {
<ide> */
<ide> public function handleEvent(Event $event, Entity $entity) {
<ide> $eventName = $event->name();
<del> $config = $this->config();
<add> $events = $this->config('events');
<ide>
<ide> $new = $entity->isNew() !== false;
<add> $refresh = $this->config('refreshTimestamp');
<ide>
<del> foreach ($config['events'][$eventName] as $field => $when) {
<add> foreach ($events[$eventName] as $field => $when) {
<ide> if (!in_array($when, ['always', 'new', 'existing'])) {
<ide> throw new \UnexpectedValueException(
<ide> sprintf('When should be one of "always", "new" or "existing". The passed value "%s" is invalid', $when)
<ide> public function handleEvent(Event $event, Entity $entity) {
<ide> ($when === 'new' && $new) ||
<ide> ($when === 'existing' && !$new)
<ide> ) {
<del> $this->_updateField($entity, $field, $config['refreshTimestamp']);
<add> $this->_updateField($entity, $field, $refresh);
<ide> }
<ide> }
<ide>
<ide> public function timestamp(\DateTime $ts = null, $refreshTimestamp = false) {
<ide> * @return bool true if a field is updated, false if no action performed
<ide> */
<ide> public function touch(Entity $entity, $eventName = 'Model.beforeSave') {
<del> $config = $this->config();
<del> if (!isset($config['events'][$eventName])) {
<add> $events = $this->config('events');
<add> if (empty($events[$eventName])) {
<ide> return false;
<ide> }
<ide>
<ide> $return = false;
<add> $refresh = $this->config('refreshTimestamp');
<ide>
<del> foreach ($config['events'][$eventName] as $field => $when) {
<add> foreach ($events[$eventName] as $field => $when) {
<ide> if (in_array($when, ['always', 'existing'])) {
<ide> $return = true;
<ide> $entity->dirty($field, false);
<del> $this->_updateField($entity, $field, $config['refreshTimestamp']);
<add> $this->_updateField($entity, $field, $refresh);
<ide> }
<ide> }
<ide>
<ide><path>src/Model/Behavior/TranslateBehavior.php
<ide> public function beforeFind(Event $event, $query) {
<ide> };
<ide>
<ide> $contain = [];
<del> $fields = $this->config()['fields'];
<add> $fields = $this->config('fields');
<ide> $alias = $this->_table->alias();
<ide> foreach ($fields as $field) {
<ide> $contain[$alias . '_' . $field . '_translation'] = $conditions;
<ide> public function beforeFind(Event $event, $query) {
<ide> */
<ide> public function beforeSave(Event $event, Entity $entity, ArrayObject $options) {
<ide> $locale = $entity->get('_locale') ?: $this->locale();
<del> $table = $this->config()['translationTable'];
<add> $table = $this->config('translationTable');
<ide> $newOptions = [$table => ['validate' => false]];
<ide> $options['associated'] = $newOptions + $options['associated'];
<ide>
<ide> public function beforeSave(Event $event, Entity $entity, ArrayObject $options) {
<ide> return;
<ide> }
<ide>
<del> $values = $entity->extract($this->config()['fields'], true);
<add> $values = $entity->extract($this->config('fields'), true);
<ide> $fields = array_keys($values);
<ide> $primaryKey = (array)$this->_table->primaryKey();
<ide> $key = $entity->get(current($primaryKey));
<ide> public function locale($locale = null) {
<ide> */
<ide> public function findTranslations($query, $options) {
<ide> $locales = isset($options['locales']) ? $options['locales'] : [];
<del> $table = $this->config()['translationTable'];
<add> $table = $this->config('translationTable');
<ide> return $query
<ide> ->contain([$table => function($q) use ($locales, $table) {
<ide> if ($locales) {
<ide> protected function _rowMapper($results, $locale) {
<ide> return $results->map(function($row) use ($locale) {
<ide> $options = ['setter' => false, 'guard' => false];
<ide>
<del> foreach ($this->config()['fields'] as $field) {
<add> foreach ($this->config('fields') as $field) {
<ide> $name = $field . '_translation';
<ide> $translation = $row->get($name);
<ide>
<ide> protected function _bundleTranslatedFields($entity) {
<ide> return;
<ide> }
<ide>
<del> $fields = $this->config()['fields'];
<add> $fields = $this->config('fields');
<ide> $primaryKey = (array)$this->_table->primaryKey();
<ide> $key = $entity->get(current($primaryKey));
<ide> $find = [];
<ide> protected function _bundleTranslatedFields($entity) {
<ide> * @return array
<ide> */
<ide> protected function _findExistingTranslations($ruleSet) {
<del> $association = $this->_table->association($this->config()['translationTable']);
<add> $association = $this->_table->association($this->config('translationTable'));
<ide> $query = $association->find()
<ide> ->select(['id', 'num' => 0])
<ide> ->where(current($ruleSet))
<ide><path>src/ORM/Behavior.php
<ide> */
<ide> namespace Cake\ORM;
<ide>
<add>use Cake\Core\InstanceConfigTrait;
<ide> use Cake\Error\Exception;
<ide> use Cake\Event\EventListener;
<ide>
<ide> */
<ide> class Behavior implements EventListener {
<ide>
<add> use InstanceConfigTrait;
<add>
<ide> /**
<ide> * Reflection method cache for behaviors.
<ide> *
<ide> class Behavior implements EventListener {
<ide> */
<ide> protected $_defaultConfig = [];
<ide>
<del>/**
<del> * Contains configuration.
<del> *
<del> * @var array
<del> */
<del> protected $_config = [];
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide> class Behavior implements EventListener {
<ide> * @param array $config The config for this behavior.
<ide> */
<ide> public function __construct(Table $table, array $config = []) {
<del> $this->_config = $config + $this->_defaultConfig;
<del> }
<del>
<del>/**
<del> * Read the configuration being used.
<del> *
<del> * @return array
<del> */
<del> public function config() {
<del> return $this->_config;
<add> $this->config($config);
<ide> }
<ide>
<ide> /** | 4 |
Ruby | Ruby | fix instance_eval calls to association proxies | 49e943c4f0ac3459bd53023167aaa08fc8e46733 | <ide><path>activerecord/lib/active_record/associations/association_proxy.rb
<ide> def with_scope(*args, &block)
<ide>
<ide> private
<ide> # Forwards any missing method call to the \target.
<del> def method_missing(method, *args)
<add> def method_missing(method, *args, &block)
<ide> if load_target
<ide> unless @target.respond_to?(method)
<ide> message = "undefined method `#{method.to_s}' for \"#{@target}\":#{@target.class.to_s}"
<ide> raise NoMethodError, message
<ide> end
<ide>
<del> if block_given?
<del> @target.send(method, *args) { |*block_args| yield(*block_args) }
<del> else
<del> @target.send(method, *args)
<del> end
<add> @target.send(method, *args, &block)
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_creating_using_primary_key
<ide> client = firm.clients_using_primary_key.create!(:name => 'test')
<ide> assert_equal firm.name, client.firm_name
<ide> end
<add>
<add> def test_normal_method_call_in_association_proxy
<add> assert_equal 'Welcome to the weblog', Comment.all.map { |comment| comment.post }.first.title
<add> end
<add>
<add> def test_instance_eval_in_association_proxy
<add> assert_equal 'Welcome to the weblog', Comment.all.map { |comment| comment.post }.first.instance_eval{title}
<add> end
<ide> end
<ide> | 2 |
Text | Text | update multilingual passage rereanking model card | f5d69c75f7955f5f5d99b89494253957d0e5c5ce | <ide><path>model_cards/amberoad/bert-multilingual-passage-reranking-msmarco/README.md
<ide> It can be used as an improvement for Elasticsearch Results and boosts the releva
<ide>
<ide> **Architecture:** On top of BERT there is a Densly Connected NN which takes the 768 Dimensional [CLS] Token as input and provides the output ([Arxiv](https://arxiv.org/abs/1901.04085)).
<ide>
<del>**Output:** Just a single value between between 0-1
<add>**Output:** Just a single value between between -10 and 10. Better matching query,passage pairs tend to have a higher a score.
<ide>
<ide>
<ide>
<ide> ## Intended uses & limitations
<ide> Both query[1] and passage[2] have to fit in 512 Tokens.
<del>As you normally want to rerank the first dozens of search results keep in mind the inference time.
<add>As you normally want to rerank the first dozens of search results keep in mind the inference time of approximately 300 ms/query.
<ide>
<ide> #### How to use
<ide>
<ide> We see nearly similar performance than the English only Model in the English [Bi
<ide>
<ide> Fine-tuned Models | Dependency | Eval Set | Search Boost<a href='#benchmarks'> | Speed on GPU
<ide> ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------- | ----------------------------------
<del>**`amberoad/Multilingual-uncased-MSMARCO`** (This Model) | <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-blue"/> | <a href ='http://www.msmarco.org/'>bing queries</a> | **+61%** <sub><sup>(0.29 vs 0.18)</sup></sub> | - <a href='#footnotes'>
<add>**`amberoad/Multilingual-uncased-MSMARCO`** (This Model) | <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-blue"/> | <a href ='http://www.msmarco.org/'>bing queries</a> | **+61%** <sub><sup>(0.29 vs 0.18)</sup></sub> | ~300 ms/query <a href='#footnotes'>
<ide> `nboost/pt-tinybert-msmarco` | <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-red"/> | <a href ='http://www.msmarco.org/'>bing queries</a> | **+45%** <sub><sup>(0.26 vs 0.18)</sup></sub> | ~50ms/query <a href='#footnotes'>
<ide> `nboost/pt-bert-base-uncased-msmarco` | <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-red"/> | <a href ='http://www.msmarco.org/'>bing queries</a> | **+62%** <sub><sup>(0.29 vs 0.18)</sup></sub> | ~300 ms/query<a href='#footnotes'>
<ide> `nboost/pt-bert-large-msmarco` | <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-red"/> | <a href ='http://www.msmarco.org/'>bing queries</a> | **+77%** <sub><sup>(0.32 vs 0.18)</sup></sub> | - | 1 |
PHP | PHP | refactor the route class | 9cabf545306eb33c941d33f9a2ff428ef44dc41b | <ide><path>system/routing/route.php
<ide> public function call()
<ide> {
<ide> $response = isset($this->callback['before']) ? Filter::call($this->callback['before'], array(), true) : null;
<ide>
<del> if (is_null($response) and ! is_null($handler = $this->handler()))
<add> if (is_null($response) and ! is_null($handler = $this->find_route_function()))
<ide> {
<ide> $response = call_user_func_array($handler, $this->parameters);
<ide> }
<ide> public function call()
<ide> *
<ide> * @return Closure
<ide> */
<del> private function handler()
<add> private function find_route_function()
<ide> {
<ide> if (isset($this->callback['do'])) return $this->callback['do'];
<ide> | 1 |
Go | Go | add test for timeoutconn | 39320f9393b27dd6239a2356086abc8439c1614b | <ide><path>utils/timeoutconn_test.go
<add>package utils
<add>
<add>import (
<add> "bufio"
<add> "fmt"
<add> "net"
<add> "net/http"
<add> "net/http/httptest"
<add> "testing"
<add> "time"
<add>)
<add>
<add>func TestTimeoutConnRead(t *testing.T) {
<add> ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<add> fmt.Fprintln(w, "hello")
<add> }))
<add> defer ts.Close()
<add> conn, err := net.Dial("tcp", ts.URL[7:])
<add> if err != nil {
<add> t.Fatalf("failed to create connection to %q: %v", ts.URL, err)
<add> }
<add> tconn := NewTimeoutConn(conn, 1*time.Second)
<add>
<add> if _, err = bufio.NewReader(tconn).ReadString('\n'); err == nil {
<add> t.Fatalf("expected timeout error, got none")
<add> }
<add> if _, err := fmt.Fprintf(tconn, "GET / HTTP/1.0\r\n\r\n"); err != nil {
<add> t.Errorf("unexpected error: %v", err)
<add> }
<add> if _, err = bufio.NewReader(tconn).ReadString('\n'); err != nil {
<add> t.Errorf("unexpected error: %v", err)
<add> }
<add>} | 1 |
Javascript | Javascript | ignore event listeners on unmounted components | fd4ad6ca82676e4f63bad26eb0869981439ba106 | <ide><path>Libraries/Renderer/src/renderers/shared/shared/event/EventPluginHub.js
<ide> var EventPluginHub = {
<ide> // Text node, let it bubble through.
<ide> return null;
<ide> }
<add> if (!inst._rootNodeID) {
<add> // If the instance is already unmounted, we have no listeners.
<add> return null;
<add> }
<ide> const props = inst._currentElement.props;
<ide> listener = props[registrationName];
<ide> if (shouldPreventMouseEvent(registrationName, inst._currentElement.type, props)) { | 1 |
Ruby | Ruby | add assertions for lazy sync transaction state | 8188f10124f3e1824bd21b91b65ed31d7527589e | <ide><path>activerecord/test/cases/transactions_test.rb
<ide> def test_raise_after_destroy
<ide> end
<ide> }
<ide>
<del> assert @first.reload
<ide> assert_not_predicate @first, :frozen?
<ide> end
<ide>
<ide> def test_successful
<del> Topic.transaction do
<del> @first.approved = true
<del> @second.approved = false
<del> @first.save
<del> @second.save
<add> assert_not_called(@first, :committed!) do
<add> Topic.transaction do
<add> @first.approved = true
<add> @second.approved = false
<add> @first.save
<add> @second.save
<add> end
<ide> end
<ide>
<del> assert Topic.find(1).approved?, "First should have been approved"
<del> assert_not Topic.find(2).approved?, "Second should have been unapproved"
<add> assert_predicate Topic.find(1), :approved?, "First should have been approved"
<add> assert_not_predicate Topic.find(2), :approved?, "Second should have been unapproved"
<ide> end
<ide>
<ide> def transaction_with_return
<ide> def test_successful_with_return
<ide> end
<ide> end
<ide>
<del> transaction_with_return
<add> assert_not_called(@first, :committed!) do
<add> transaction_with_return
<add> end
<ide> assert committed
<ide>
<del> assert Topic.find(1).approved?, "First should have been approved"
<del> assert_not Topic.find(2).approved?, "Second should have been unapproved"
<add> assert_predicate Topic.find(1), :approved?, "First should have been approved"
<add> assert_not_predicate Topic.find(2), :approved?, "Second should have been unapproved"
<ide> ensure
<ide> Topic.connection.class_eval do
<ide> remove_method :commit_db_transaction
<ide> def test_number_of_transactions_in_commit
<ide> end
<ide> end
<ide>
<del> Topic.transaction do
<del> @first.approved = true
<del> @first.save!
<add> assert_not_called(@first, :committed!) do
<add> Topic.transaction do
<add> @first.approved = true
<add> @first.save!
<add> end
<ide> end
<ide>
<ide> assert_equal 0, num
<ide> def test_number_of_transactions_in_commit
<ide> end
<ide>
<ide> def test_successful_with_instance_method
<del> @first.transaction do
<del> @first.approved = true
<del> @second.approved = false
<del> @first.save
<del> @second.save
<add> assert_not_called(@first, :committed!) do
<add> @first.transaction do
<add> @first.approved = true
<add> @second.approved = false
<add> @first.save
<add> @second.save
<add> end
<ide> end
<ide>
<del> assert Topic.find(1).approved?, "First should have been approved"
<del> assert_not Topic.find(2).approved?, "Second should have been unapproved"
<add> assert_predicate Topic.find(1), :approved?, "First should have been approved"
<add> assert_not_predicate Topic.find(2), :approved?, "Second should have been unapproved"
<ide> end
<ide>
<ide> def test_failing_on_exception
<del> begin
<add> assert_not_called(@first, :rolledback!) do
<ide> Topic.transaction do
<ide> @first.approved = true
<ide> @second.approved = false
<ide> def test_failing_on_exception
<ide> # caught it
<ide> end
<ide>
<del> assert @first.approved?, "First should still be changed in the objects"
<del> assert_not @second.approved?, "Second should still be changed in the objects"
<add> assert_predicate @first, :approved?, "First should still be changed in the objects"
<add> assert_not_predicate @second, :approved?, "Second should still be changed in the objects"
<ide>
<del> assert_not Topic.find(1).approved?, "First shouldn't have been approved"
<del> assert Topic.find(2).approved?, "Second should still be approved"
<add> assert_not_predicate Topic.find(1), :approved?, "First shouldn't have been approved"
<add> assert_predicate Topic.find(2), :approved?, "Second should still be approved"
<ide> end
<ide>
<ide> def test_raising_exception_in_callback_rollbacks_in_save
<ide> def @first.after_save_for_transaction
<ide> end
<ide>
<ide> @first.approved = true
<del> e = assert_raises(RuntimeError) { @first.save }
<del> assert_equal "Make the transaction rollback", e.message
<add> assert_not_called(@first, :rolledback!) do
<add> e = assert_raises(RuntimeError) { @first.save }
<add> assert_equal "Make the transaction rollback", e.message
<add> end
<ide> assert_not_predicate Topic.find(1), :approved?
<ide> end
<ide>
<ide> def test_rolling_back_in_a_callback_rollbacks_before_save
<ide> def @first.before_save_for_transaction
<ide> raise ActiveRecord::Rollback
<ide> end
<del> assert_not @first.approved
<add> assert_not_predicate @first, :approved?
<ide>
<del> Topic.transaction do
<del> @first.approved = true
<del> @first.save!
<add> assert_not_called(@first, :rolledback!) do
<add> Topic.transaction do
<add> @first.approved = true
<add> @first.save!
<add> end
<ide> end
<del> assert_not Topic.find(@first.id).approved?, "Should not commit the approved flag"
<add> assert_not_predicate Topic.find(@first.id), :approved?, "Should not commit the approved flag"
<ide> end
<ide>
<ide> def test_raising_exception_in_nested_transaction_restore_state_in_save
<ide> def topic.after_save_for_transaction
<ide> raise "Make the transaction rollback"
<ide> end
<ide>
<del> assert_raises(RuntimeError) do
<del> Topic.transaction { topic.save }
<add> assert_not_called(topic, :rolledback!) do
<add> assert_raises(RuntimeError) do
<add> Topic.transaction { topic.save }
<add> end
<ide> end
<ide>
<del> assert topic.new_record?, "#{topic.inspect} should be new record"
<add> assert_predicate topic, :new_record?, "#{topic.inspect} should be new record"
<ide> end
<ide>
<ide> def test_transaction_state_is_cleared_when_record_is_persisted | 1 |
Javascript | Javascript | remove deprecated jsnext option | a3aa378a5b64848e12da08ed4edc78f4b38c0711 | <ide><path>rollup.config.js
<ide> export default [
<ide> input: 'src/index.js',
<ide> output: { file: 'es/redux.mjs', format: 'es', indent: false },
<ide> plugins: [
<del> nodeResolve({
<del> jsnext: true
<del> }),
<add> nodeResolve(),
<ide> replace({
<ide> 'process.env.NODE_ENV': JSON.stringify('production')
<ide> }),
<ide> export default [
<ide> indent: false
<ide> },
<ide> plugins: [
<del> nodeResolve({
<del> jsnext: true
<del> }),
<add> nodeResolve(),
<ide> babel({
<ide> exclude: 'node_modules/**'
<ide> }),
<ide> export default [
<ide> indent: false
<ide> },
<ide> plugins: [
<del> nodeResolve({
<del> jsnext: true
<del> }),
<add> nodeResolve(),
<ide> babel({
<ide> exclude: 'node_modules/**'
<ide> }), | 1 |
Ruby | Ruby | remove unreached default value | 88a1800526855edfc42209d4960b48550212fd8f | <ide><path>actionpack/lib/action_dispatch/journey/route.rb
<ide> def self.verb_matcher(verb)
<ide> end
<ide>
<ide> def self.build(name, app, path, constraints, required_defaults, defaults)
<del> request_method_match = verb_matcher(constraints.delete(:request_method)) || []
<add> request_method_match = verb_matcher(constraints.delete(:request_method))
<ide> new name, app, path, constraints, required_defaults, defaults, request_method_match
<ide> end
<ide> | 1 |
Text | Text | add guide for action mailer previews | 8657fb77751fd4f916c997932373aaf1966636db | <ide><path>guides/source/action_mailer_basics.md
<ide> end
<ide> Will render the HTML part using the `my_layout.html.erb` file and the text part
<ide> with the usual `user_mailer.text.erb` file if it exists.
<ide>
<add>### Previewing Emails
<add>
<add>Action Mailer previews provide a way to see how emails look by visiting a
<add>special URL that renders them. In the above example, the preview class for
<add>`UserMailer` should be named `UserMailerPreview` and located in
<add>`test/mailers/previews/user_mailer_preview.rb`. To see the preview of
<add>`welcome_email`, implement a method that has the same name and call
<add>`UserMailer.welcome_email`:
<add>
<add>```ruby
<add>class UserMailerPreview < ActionMailer::Preview
<add> def welcome_email
<add> UserMailer.welcome_email(User.first)
<add> end
<add>end
<add>```
<add>
<add>Then the preview will be available in <http://localhost:3000/rails/mailers/user_mailer/welcome_email>.
<add>
<add>If you change something in `app/views/user_mailer/welcome_email.html.erb`
<add>or the mailer itself, it'll automatically reload and render it so you can
<add>visually see the new style instantly. A list of previews are also available
<add>in <http://localhost:3000/rails/mailers>.
<add>
<add>By default, these preview classes live in `test/mailers/previews`.
<add>This can be configured using the `preview_path` option. For example, if you
<add>want to change it to `lib/mailer_previews`, you can configure it in
<add>`config/application.rb`:
<add>
<add>```ruby
<add>config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews"
<add>```
<add>
<ide> ### Generating URLs in Action Mailer Views
<ide>
<ide> Unlike controllers, the mailer instance doesn't have any context about the | 1 |
Python | Python | expose memusage for nt os | 14d5854b76e423cbaf0622b206d7b3b69e513a83 | <ide><path>numpy/testing/utils.py
<ide> def GetPerformanceAttributes(object, counter, instance = None,
<ide> finally:
<ide> win32pdh.CloseQuery(hq)
<ide>
<del> def memusage(processName="python", instance=0):
<del> # from win32pdhutil, part of the win32all package
<del> import win32pdh
<del> return GetPerformanceAttributes("Process", "Virtual Bytes",
<del> processName, instance,
<del> win32pdh.PDH_FMT_LONG, None)
<add> def memusage(processName="python", instance=0):
<add> # from win32pdhutil, part of the win32all package
<add> import win32pdh
<add> return GetPerformanceAttributes("Process", "Virtual Bytes",
<add> processName, instance,
<add> win32pdh.PDH_FMT_LONG, None)
<ide>
<ide> def build_err_msg(arrays, err_msg, header='Items are not equal:',
<ide> verbose=True, | 1 |
PHP | PHP | fix bugs in env | 375f2d82861b03f02220cc8b87409acde8d9d27b | <ide><path>src/Illuminate/Foundation/Console/EnvironmentCommand.php
<ide>
<ide> use Illuminate\Console\Command;
<ide>
<del>class ChangesCommand extends Command {
<add>class EnvironmentCommand extends Command {
<ide>
<ide> /**
<ide> * The console command name.
<ide> class ChangesCommand extends Command {
<ide> */
<ide> public function fire()
<ide> {
<del> $this->line('<info>Current application environment:</info> <comment>'.$this->app['env'].'</comment>');
<add> $this->line('<info>Current application environment:</info> <comment>'.$this->laravel['env'].'</comment>');
<ide> }
<ide>
<ide> }
<ide>\ No newline at end of file | 1 |
Python | Python | serialize vocab last | 8716ffe57d71cd0cd8d1e34b0417006e588ae478 | <ide><path>spacy/language.py
<ide> def to_disk(self, path, disable=tuple()):
<ide> """
<ide> path = util.ensure_path(path)
<ide> serializers = OrderedDict((
<del> ('vocab', lambda p: self.vocab.to_disk(p)),
<ide> ('tokenizer', lambda p: self.tokenizer.to_disk(p, vocab=False)),
<ide> ('meta.json', lambda p: p.open('w').write(json_dumps(self.meta)))
<ide> ))
<ide> def to_disk(self, path, disable=tuple()):
<ide> if not hasattr(proc, 'to_disk'):
<ide> continue
<ide> serializers[proc.name] = lambda p, proc=proc: proc.to_disk(p, vocab=False)
<add> serializers['vocab'] = lambda p: self.vocab.to_disk(p)
<ide> util.to_disk(path, serializers, {p: False for p in disable})
<ide>
<ide> def from_disk(self, path, disable=tuple()): | 1 |
PHP | PHP | add "splice" method to collection | 2d351b39bf32ddb4d3ca1ea542183391b4240460 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function slice($offset, $length = null, $preserveKeys = false)
<ide> return new static(array_slice($this->items, $offset, $length, $preserveKeys));
<ide> }
<ide>
<add> /**
<add> * Splice portion of the underlying collection array.
<add> *
<add> * @param int $offset
<add> * @param int $length
<add> * @param mixed $replacement
<add> * @return \Illuminate\Support\Collection
<add> */
<add> public function splice($offset, $length = 0, $replacement = array())
<add> {
<add> array_splice($this->items, $offset, $length, $replacement);
<add> }
<add>
<ide> /**
<ide> * Get an array with the values of a given key.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testMakeMethod()
<ide> $this->assertEquals(array('foo'), $collection->all());
<ide> }
<ide>
<add> public function testSplice()
<add> {
<add> $data = new Collection(array('foo', 'baz'));
<add> $data->splice(1, 0, 'bar');
<add> $this->assertEquals(array('foo', 'bar', 'baz'), array_values($data->all()));
<add>
<add> $data = new Collection(array('foo', 'baz'));
<add> $data->splice(1, 1);
<add> $this->assertEquals(array('foo'), array_values($data->all()));
<add>
<add> $data = new Collection(array('foo', 'baz'));
<add> $data->splice(1, 1, 'bar');
<add> $this->assertEquals(array('foo', 'bar'), array_values($data->all()));
<add> }
<add>
<ide> } | 2 |
Javascript | Javascript | remove "copy" function override | 6ccec8f4154279b575255d17c3c729fcbb439ec3 | <ide><path>examples/jsm/lines/LineGeometry.js
<ide> class LineGeometry extends LineSegmentsGeometry {
<ide>
<ide> }
<ide>
<del> copy( /* source */ ) {
<del>
<del> // todo
<del>
<del> return this;
<del>
<del> }
<del>
<ide> }
<ide>
<ide> LineGeometry.prototype.isLineGeometry = true; | 1 |
Javascript | Javascript | check node, yarn and grunt-cli versions | f04fcdfe9f9260f18d1ac79e3a9584aa28073d4c | <ide><path>Gruntfile.js
<ide> var path = require('path');
<ide> var e2e = require('./test/e2e/tools');
<ide>
<ide> var semver = require('semver');
<del>var fs = require('fs');
<add>var exec = require('shelljs').exec;
<add>var pkg = require(__dirname + '/package.json');
<ide>
<del>var useNodeVersion = fs.readFileSync('.nvmrc', 'utf8');
<del>if (!semver.satisfies(process.version, useNodeVersion)) {
<del> throw new Error('Invalid node version; please use node v' + useNodeVersion);
<add>// Node.js version checks
<add>if (!semver.satisfies(process.version, pkg.engines.node)) {
<add> reportOrFail('Invalid node version (' + process.version + '). ' +
<add> 'Please use a version that satisfies ' + pkg.engines.node);
<ide> }
<ide>
<add>// Yarn version checks
<add>var expectedYarnVersion = pkg.engines.yarn;
<add>var currentYarnVersion = exec('yarn --version', {silent: true}).stdout.trim();
<add>if (!semver.satisfies(currentYarnVersion, expectedYarnVersion)) {
<add> reportOrFail('Invalid yarn version (' + currentYarnVersion + '). ' +
<add> 'Please use a version that satisfies ' + expectedYarnVersion);
<add>}
<add>
<add>// Grunt CLI version checks
<add>var expectedGruntVersion = pkg.engines.grunt;
<add>var currentGruntVersions = exec('grunt --version', {silent: true}).stdout;
<add>var match = /^grunt-cli v(.+)$/m.exec(currentGruntVersions);
<add>if (!match) {
<add> reportOrFail('Unable to compute the current grunt-cli version. We found:\n' +
<add> currentGruntVersions);
<add>} else {
<add> if (!semver.satisfies(match[1], expectedGruntVersion)) {
<add> reportOrFail('Invalid grunt-cli version (' + match[1] + '). ' +
<add> 'Please use a version that satisfies ' + expectedGruntVersion);
<add> }
<add>}
<add>
<add>// Ensure Node.js dependencies have been installed
<add>if (!process.env.TRAVIS && !process.env.JENKINS_HOME) {
<add> var yarnOutput = exec('yarn install');
<add> if (yarnOutput.code !== 0) {
<add> throw new Error('Yarn install failed: ' + yarnOutput.stderr);
<add> }
<add>}
<add>
<add>
<ide> module.exports = function(grunt) {
<del> //grunt plugins
<add>
<add> // this loads all the node_modules that start with `grunt-` as plugins
<ide> require('load-grunt-tasks')(grunt);
<ide>
<add> // load additional grunt tasks
<ide> grunt.loadTasks('lib/grunt');
<ide> grunt.loadNpmTasks('angular-benchpress');
<ide>
<add> // compute version related info for this build
<ide> var NG_VERSION = versionInfo.currentVersion;
<ide> NG_VERSION.cdn = versionInfo.cdnVersion;
<ide> var dist = 'angular-' + NG_VERSION.full;
<ide>
<ide> if (versionInfo.cdnVersion == null) {
<del> throw new Error('Unable to read CDN version, are you offline or has the CDN not been properly pushed?');
<add> throw new Error('Unable to read CDN version, are you offline or has the CDN not been properly pushed?\n' +
<add> 'Perhaps you want to set the NG1_BUILD_NO_REMOTE_VERSION_REQUESTS environment variable?');
<ide> }
<ide>
<ide> //config
<ide> module.exports = function(grunt) {
<ide> }
<ide> });
<ide>
<del> if (!process.env.TRAVIS) {
<del> grunt.task.run('shell:install-node-dependencies');
<del> }
<del>
<ide> //alias tasks
<ide> grunt.registerTask('test', 'Run unit, docs and e2e tests with Karma', ['eslint', 'package', 'test:unit', 'test:promises-aplus', 'tests:docs', 'test:protractor']);
<ide> grunt.registerTask('test:jqlite', 'Run the unit tests with Karma' , ['tests:jqlite']);
<ide> module.exports = function(grunt) {
<ide> grunt.registerTask('ci-checks', ['ddescribe-iit', 'merge-conflict', 'eslint']);
<ide> grunt.registerTask('default', ['package']);
<ide> };
<add>
<add>
<add>function reportOrFail(message) {
<add> if (process.env.TRAVIS || process.env.JENKINS_HOME) {
<add> throw new Error(message);
<add> } else {
<add> console.log('===============================================================================');
<add> console.log(message);
<add> console.log('===============================================================================');
<add> }
<add>} | 1 |
Javascript | Javascript | remove unused imports in ember.textarea | 2d501df08085018bcab80148ce941ce4410a6c03 | <ide><path>packages/ember-views/lib/views/text_area.js
<ide> @module ember
<ide> @submodule ember-views
<ide> */
<del>import { get } from "ember-metal/property_get";
<ide> import Component from "ember-views/views/component";
<ide> import TextSupport from "ember-views/mixins/text_support";
<del>import { observer } from "ember-metal/mixin";
<ide>
<ide> /**
<ide> The internal class used to create textarea element when the `{{textarea}}` | 1 |
Text | Text | fix tensorrt test output and add int8 result. | f7f2bf4f416addb6b5c1f7df67bfff13eb48ddd5 | <ide><path>research/tensorrt/README.md
<ide> Here we provide a sample script that can:
<ide> 1. Convert a TensorFlow SavedModel to a Frozen Graph.
<ide> 2. Load a Frozen Graph for inference.
<ide> 3. Time inference loops using the native TensorFlow graph.
<del>4. Time inference loops using FP32, FP16, or INT8<sup>1</sup> precision modes from TensorRT.
<add>4. Time inference loops using FP32, FP16, or INT8 precision modes from TensorRT.
<ide>
<ide> We provide some results below, as well as instructions for running this script.
<ide>
<del><sup>1</sup> INT8 mode is a work in progress; please see [INT8 Mode is the Bleeding Edge](#int8-mode-is-the-bleeding-edge) below.
<del>
<ide> ## How to Run This Script
<ide>
<ide> ### Step 1: Install Prerequisites
<ide> you would run:
<ide>
<ide> ```
<ide> python tensorrt.py --frozen_graph=resnetv2_imagenet_frozen_graph.pb \
<del> --image_file=image.jpg --native --fp32 --fp16 --output_dir=/my/output
<add> --image_file=image.jpg --native --fp32 --fp16 --int8 --output_dir=/my/output
<ide> ```
<ide>
<ide> This will print the predictions for each of the precision modes that were run
<ide> (native, which is the native precision of the model passed in, as well
<del>as the TensorRT version of the graph at precisions of fp32 and fp16):
<add>as the TensorRT version of the graph at precisions of fp32, fp16 and int8):
<ide>
<ide> ```
<ide> INFO:tensorflow:Starting timing.
<ide> INFO:tensorflow:Timing loop done!
<ide> Predictions:
<ide> Precision: native [u'seashore, coast, seacoast, sea-coast', u'promontory, headland, head, foreland', u'breakwater, groin, groyne, mole, bulwark, seawall, jetty', u'lakeside, lakeshore', u'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus']
<ide> Precision: FP32 [u'seashore, coast, seacoast, sea-coast', u'promontory, headland, head, foreland', u'breakwater, groin, groyne, mole, bulwark, seawall, jetty', u'lakeside, lakeshore', u'sandbar, sand bar']
<del>Precision: FP16 [u'seashore, coast, seacoast, sea-coast', u'promontory, headland, head, foreland', u'lakeside, lakeshore', u'sandbar, sand bar', u'breakwater, groin, groyne, mole, bulwark, seawall, jetty']
<add>Precision: FP16 [u'seashore, coast, seacoast, sea-coast', u'promontory, headland, head, foreland', u'breakwater, groin, groyne, mole, bulwark, seawall, jetty', u'lakeside, lakeshore', u'sandbar, sand bar']
<add>Precision: INT8 [u'seashore, coast, seacoast, sea-coast', u'promontory, headland, head, foreland', u'breakwater, groin, groyne, mole, bulwark, seawall, jetty', u'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus', u'lakeside, lakeshore']
<ide> ```
<ide>
<ide> The script will generate or append to a file in the output_dir, `log.txt`,
<ide> which includes the timing information for each of the models:
<ide>
<ide> ```
<ide> ==========================
<del>network: native_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<del> fps median: 1041.4, mean: 1056.6, uncertainty: 2.8, jitter: 6.1
<del> latency median: 0.12292, mean: 0.12123, 99th_p: 0.13151, 99th_uncertainty: 0.00024
<add>network: native_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<add> fps median: 468.2, mean: 469.0, uncertainty: 0.3, jitter: 1.6
<add> latency median: 0.27336, mean: 0.27290, 99th_p: 0.27475, 99th_uncertainty: 0.00027
<ide>
<ide> ==========================
<del>network: tftrt_fp32_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<del> fps median: 1253.0, mean: 1250.8, uncertainty: 3.4, jitter: 17.3
<del> latency median: 0.10215, mean: 0.10241, 99th_p: 0.11482, 99th_uncertainty: 0.01109
<add>network: tftrt_fp32_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<add> fps median: 627.7, mean: 628.9, uncertainty: 0.5, jitter: 3.6
<add> latency median: 0.20392, mean: 0.20354, 99th_p: 0.20608, 99th_uncertainty: 0.00083
<ide>
<ide> ==========================
<del>network: tftrt_fp16_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<del> fps median: 2280.2, mean: 2312.8, uncertainty: 10.3, jitter: 100.1
<del> latency median: 0.05614, mean: 0.05546, 99th_p: 0.06103, 99th_uncertainty: 0.00781
<add>network: tftrt_fp16_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<add> fps median: 626.8, mean: 628.8, uncertainty: 0.5, jitter: 3.1
<add> latency median: 0.20421, mean: 0.20359, 99th_p: 0.20555, 99th_uncertainty: 0.00019
<ide>
<add>==========================
<add>network: tftrt_int8_resnetv2_imagenet_frozen_graph.pb, batchsize 128, steps 100
<add> fps median: 1362.4, mean: 1368.1, uncertainty: 2.2, jitter: 14.4
<add> latency median: 0.09396, mean: 0.09359, 99th_p: 0.09546, 99th_uncertainty: 0.00021
<ide> ```
<ide>
<ide> The script will also output the GraphDefs used for each of the modes run,
<ide> for future use and inspection:
<ide> ```
<ide> ls /my/output
<ide> log.txt
<del>tftrt_fp16_imagenet_frozen_graph.pb
<del>tftrt_fp32_imagenet_frozen_graph.pb
<add>tftrt_fp16_resnetv2_imagenet_frozen_graph.pb
<add>tftrt_fp32_resnetv2_imagenet_frozen_graph.pb
<add>tftrt_int8_calib_resnetv2_imagenet_frozen_graph.pb
<add>tftrt_int8_resnetv2_imagenet_frozen_graph.pb
<ide> ```
<ide>
<ide> ## Troubleshooting and Notes
<ide>
<del>### INT8 Mode is the Bleeding Edge
<del>
<del>Note that currently, INT8 mode results in a segfault using the models provided.
<del>We are working on it.
<del>
<del>```
<del>E tensorflow/contrib/tensorrt/log/trt_logger.cc:38] DefaultLogger Parameter check failed at: Network.cpp::addScale::118, condition: shift.count == 0 || shift.count == weightCount
<del>Segmentation fault (core dumped)
<del>```
<del>
<ide> ### GPU/Precision Compatibility
<ide>
<ide> Not all GPUs support the ops required for all precisions. For example, P100s | 1 |
Text | Text | use inline code style for directory names | b02ab963cdd414486751bb6ba39ec6b6dea9d750 | <ide><path>object_detection/g3doc/running_pets.md
<ide> dataset for Oxford-IIIT Pets lives
<ide> [here](http://www.robots.ox.ac.uk/~vgg/data/pets/). You will need to download
<ide> both the image dataset [`images.tar.gz`](http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz)
<ide> and the groundtruth data [`annotations.tar.gz`](http://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz)
<del>to the tensorflow/models directory. This may take some time. After downloading
<del>the tarballs, your object_detection directory should appear as follows:
<add>to the `tensorflow/models` directory. This may take some time. After downloading
<add>the tarballs, your `object_detection` directory should appear as follows:
<ide>
<ide> ```lang-none
<ide> + object_detection/
<ide> the tarballs, your object_detection directory should appear as follows:
<ide> The Tensorflow Object Detection API expects data to be in the TFRecord format,
<ide> so we'll now run the `create_pet_tf_record` script to convert from the raw
<ide> Oxford-IIIT Pet dataset into TFRecords. Run the following commands from the
<del>object_detection directory:
<add>`object_detection` directory:
<ide>
<ide> ``` bash
<ide> # From tensorflow/models/
<ide> Note: It is normal to see some warnings when running this script. You may ignore
<ide> them.
<ide>
<ide> Two TFRecord files named `pet_train.record` and `pet_val.record` should be generated
<del>in the object_detection/ directory.
<add>in the `object_detection` directory.
<ide>
<ide> Now that the data has been generated, we'll need to upload it to Google Cloud
<ide> Storage so the data can be accessed by ML Engine. Run the following command to
<ide> In the Tensorflow Object Detection API, the model parameters, training
<ide> parameters and eval parameters are all defined by a config file. More details
<ide> can be found [here](configuring_jobs.md). For this tutorial, we will use some
<ide> predefined templates provided with the source code. In the
<del>object_detection/samples/configs folder, there are skeleton object_detection
<add>`object_detection/samples/configs` folder, there are skeleton object_detection
<ide> configuration files. We will use `faster_rcnn_resnet101_pets.config` as a
<ide> starting point for configuring the pipeline. Open the file with your favourite
<ide> text editor.
<ide> Before we can start a job on Google Cloud ML Engine, we must:
<ide> 2. Write a cluster configuration for our Google Cloud ML job.
<ide>
<ide> To package the Tensorflow Object Detection code, run the following commands from
<del>the tensorflow/models/ directory:
<add>the `tensorflow/models/` directory:
<ide>
<ide> ``` bash
<ide> # From tensorflow/models/
<ide> For running the training Cloud ML job, we'll configure the cluster to use 10
<ide> training jobs (1 master + 9 workers) and three parameters servers. The
<ide> configuration file can be found at `object_detection/samples/cloud/cloud.yml`.
<ide>
<del>To start training, execute the following command from the tensorflow/models/
<add>To start training, execute the following command from the `tensorflow/models/`
<ide> directory:
<ide>
<ide> ``` bash
<ide> Browser](https://console.cloud.google.com/storage/browser). The file should be
<ide> stored under `${YOUR_GCS_BUCKET}/train`. The checkpoint will typically consist of
<ide> three files:
<ide>
<del>* model.ckpt-${CHECKPOINT_NUMBER}.data-00000-of-00001,
<del>* model.ckpt-${CHECKPOINT_NUMBER}.index
<del>* model.ckpt-${CHECKPOINT_NUMBER}.meta
<add>* `model.ckpt-${CHECKPOINT_NUMBER}.data-00000-of-00001`
<add>* `model.ckpt-${CHECKPOINT_NUMBER}.index`
<add>* `model.ckpt-${CHECKPOINT_NUMBER}.meta`
<ide>
<ide> After you've identified a candidate checkpoint to export, run the following
<del>command from tensorflow/models/object_detection:
<add>command from `tensorflow/models/object_detection`:
<ide>
<ide> ``` bash
<ide> # From tensorflow/models | 1 |
Java | Java | add snaptoalignment to reactscrollviewmanager | c6e5640e87e7cb5b514ded2c8d4cbb039bd02c5f | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java
<ide>
<ide> package com.facebook.react.views.scroll;
<ide>
<add>import static com.facebook.react.views.scroll.ReactScrollViewHelper.SNAP_ALIGNMENT_DISABLED;
<add>
<ide> import android.animation.Animator;
<ide> import android.animation.ObjectAnimator;
<ide> import android.animation.PropertyValuesHolder;
<ide> public class ReactScrollView extends ScrollView
<ide> private @Nullable List<Integer> mSnapOffsets;
<ide> private boolean mSnapToStart = true;
<ide> private boolean mSnapToEnd = true;
<add> private int mSnapToAlignment = SNAP_ALIGNMENT_DISABLED;
<ide> private @Nullable View mContentView;
<ide> private ReactViewBackgroundManager mReactBackgroundManager;
<ide> private int pendingContentOffsetX = UNSET_CONTENT_OFFSET;
<ide> public void setSnapToEnd(boolean snapToEnd) {
<ide> mSnapToEnd = snapToEnd;
<ide> }
<ide>
<add> public void setSnapToAlignment(int snapToAlignment) {
<add> mSnapToAlignment = snapToAlignment;
<add> }
<add>
<ide> public void flashScrollIndicators() {
<ide> awakenScrollBars();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollViewManager.java
<ide> public void setSnapToOffsets(ReactScrollView view, @Nullable ReadableArray snapT
<ide> view.setSnapOffsets(offsets);
<ide> }
<ide>
<add> @ReactProp(name = "snapToAlignment")
<add> public void setSnapToAlignment(ReactScrollView view, String alignment) {
<add> view.setSnapToAlignment(ReactScrollViewHelper.parseSnapToAlignment(alignment));
<add> }
<add>
<ide> @ReactProp(name = "snapToStart")
<ide> public void setSnapToStart(ReactScrollView view, boolean snapToStart) {
<ide> view.setSnapToStart(snapToStart); | 2 |
Ruby | Ruby | add line break to action text installation outputs | 95e00befbc2fe46aafb15046ac229884688f677d | <ide><path>actiontext/lib/templates/installer.rb
<ide> line = %[require("#{name}")]
<ide> unless APPLICATION_PACK_PATH.read.include? line
<ide> say "Adding #{name} to #{APPLICATION_PACK_PATH}"
<del> append_to_file APPLICATION_PACK_PATH, "#{line}\n"
<add> append_to_file APPLICATION_PACK_PATH, "\n#{line}"
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | support configurable labels for custom hooks | edb1f595649b013a59a18f43c03a57035ddea19e | <ide><path>packages/react-debug-tools/src/ReactDebugHooks.js
<ide> function getPrimitiveStackCache(): Map<string, Array<any>> {
<ide> Dispatcher.useLayoutEffect(() => {});
<ide> Dispatcher.useEffect(() => {});
<ide> Dispatcher.useImperativeHandle(undefined, () => null);
<add> Dispatcher.useDebugValue(null);
<ide> Dispatcher.useCallback(() => {});
<ide> Dispatcher.useMemo(() => null);
<ide> } finally {
<ide> function useImperativeHandle<T>(
<ide> });
<ide> }
<ide>
<add>function useDebugValue(value: any, formatterFn: ?(value: any) => any) {
<add> hookLog.push({
<add> primitive: 'DebugValue',
<add> stackError: new Error(),
<add> value: typeof formatterFn === 'function' ? formatterFn(value) : value,
<add> });
<add>}
<add>
<ide> function useCallback<T>(callback: T, inputs: Array<mixed> | void | null): T {
<ide> let hook = nextHook();
<ide> hookLog.push({
<ide> const Dispatcher = {
<ide> useContext,
<ide> useEffect,
<ide> useImperativeHandle,
<add> useDebugValue,
<ide> useLayoutEffect,
<ide> useMemo,
<ide> useReducer,
<ide> function buildTree(rootStack, readHookLog): HooksTree {
<ide> let children = [];
<ide> levelChildren.push({
<ide> name: parseCustomHookName(stack[j - 1].functionName),
<del> value: undefined, // TODO: Support custom inspectable values.
<add> value: undefined,
<ide> subHooks: children,
<ide> });
<ide> stackOfChildren.push(levelChildren);
<ide> function buildTree(rootStack, readHookLog): HooksTree {
<ide> subHooks: [],
<ide> });
<ide> }
<add>
<add> // Associate custom hook values (useDebugValue() hook entries) with the correct hooks.
<add> processDebugValues(rootChildren, null);
<add>
<ide> return rootChildren;
<ide> }
<ide>
<add>// Custom hooks support user-configurable labels (via the special useDebugValue() hook).
<add>// That hook adds user-provided values to the hooks tree,
<add>// but these values aren't intended to appear alongside of the other hooks.
<add>// Instead they should be attributed to their parent custom hook.
<add>// This method walks the tree and assigns debug values to their custom hook owners.
<add>function processDebugValues(
<add> hooksTree: HooksTree,
<add> parentHooksNode: HooksNode | null,
<add>): void {
<add> let debugValueHooksNodes: Array<HooksNode> = [];
<add>
<add> for (let i = 0; i < hooksTree.length; i++) {
<add> const hooksNode = hooksTree[i];
<add> if (hooksNode.name === 'DebugValue' && hooksNode.subHooks.length === 0) {
<add> hooksTree.splice(i, 1);
<add> i--;
<add> debugValueHooksNodes.push(hooksNode);
<add> } else {
<add> processDebugValues(hooksNode.subHooks, hooksNode);
<add> }
<add> }
<add>
<add> // Bubble debug value labels to their custom hook owner.
<add> // If there is no parent hook, just ignore them for now.
<add> // (We may warn about this in the future.)
<add> if (parentHooksNode !== null) {
<add> if (debugValueHooksNodes.length === 1) {
<add> parentHooksNode.value = debugValueHooksNodes[0].value;
<add> } else if (debugValueHooksNodes.length > 1) {
<add> parentHooksNode.value = debugValueHooksNodes.map(({value}) => value);
<add> }
<add> }
<add>}
<add>
<ide> export function inspectHooks<Props>(
<ide> renderFunction: Props => React$Node,
<ide> props: Props,
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspection-test.internal.js
<ide> describe('ReactHooksInspection', () => {
<ide> it('should inspect a simple custom hook', () => {
<ide> function useCustom(value) {
<ide> let [state] = React.useState(value);
<add> React.useDebugValue('custom hook label');
<ide> return state;
<ide> }
<ide> function Foo(props) {
<ide> describe('ReactHooksInspection', () => {
<ide> expect(tree).toEqual([
<ide> {
<ide> name: 'Custom',
<del> value: undefined,
<add> value: __DEV__ ? 'custom hook label' : undefined,
<ide> subHooks: [
<ide> {
<ide> name: 'State',
<ide> describe('ReactHooksInspection', () => {
<ide> expect(setterCalls[0]).not.toBe(initial);
<ide> expect(setterCalls[1]).toBe(initial);
<ide> });
<add>
<add> describe('useDebugValue', () => {
<add> it('should be ignored when called outside of a custom hook', () => {
<add> function Foo(props) {
<add> React.useDebugValue('this is invalid');
<add> return null;
<add> }
<add> let tree = ReactDebugTools.inspectHooks(Foo, {});
<add> expect(tree).toHaveLength(0);
<add> });
<add>
<add> it('should support an optional formatter function param', () => {
<add> function useCustom() {
<add> React.useDebugValue({bar: 123}, object => `bar:${object.bar}`);
<add> React.useState(0);
<add> }
<add> function Foo(props) {
<add> useCustom();
<add> return null;
<add> }
<add> let tree = ReactDebugTools.inspectHooks(Foo, {});
<add> expect(tree).toEqual([
<add> {
<add> name: 'Custom',
<add> value: __DEV__ ? 'bar:123' : undefined,
<add> subHooks: [{name: 'State', subHooks: [], value: 0}],
<add> },
<add> ]);
<add> });
<add> });
<ide> });
<ide><path>packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.internal.js
<ide> describe('ReactHooksInspectionIntergration', () => {
<ide> ]);
<ide> });
<ide>
<add> describe('useDebugValue', () => {
<add> it('should support inspectable values for multiple custom hooks', () => {
<add> function useLabeledValue(label) {
<add> let [value] = React.useState(label);
<add> React.useDebugValue(`custom label ${label}`);
<add> return value;
<add> }
<add> function useAnonymous(label) {
<add> let [value] = React.useState(label);
<add> return value;
<add> }
<add> function Example() {
<add> useLabeledValue('a');
<add> React.useState('b');
<add> useAnonymous('c');
<add> useLabeledValue('d');
<add> return null;
<add> }
<add> let renderer = ReactTestRenderer.create(<Example />);
<add> let childFiber = renderer.root.findByType(Example)._currentFiber();
<add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<add> expect(tree).toEqual([
<add> {
<add> name: 'LabeledValue',
<add> value: __DEV__ ? 'custom label a' : undefined,
<add> subHooks: [{name: 'State', value: 'a', subHooks: []}],
<add> },
<add> {
<add> name: 'State',
<add> value: 'b',
<add> subHooks: [],
<add> },
<add> {
<add> name: 'Anonymous',
<add> value: undefined,
<add> subHooks: [{name: 'State', value: 'c', subHooks: []}],
<add> },
<add> {
<add> name: 'LabeledValue',
<add> value: __DEV__ ? 'custom label d' : undefined,
<add> subHooks: [{name: 'State', value: 'd', subHooks: []}],
<add> },
<add> ]);
<add> });
<add>
<add> it('should support inspectable values for nested custom hooks', () => {
<add> function useInner() {
<add> React.useDebugValue('inner');
<add> React.useState(0);
<add> }
<add> function useOuter() {
<add> React.useDebugValue('outer');
<add> useInner();
<add> }
<add> function Example() {
<add> useOuter();
<add> return null;
<add> }
<add> let renderer = ReactTestRenderer.create(<Example />);
<add> let childFiber = renderer.root.findByType(Example)._currentFiber();
<add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<add> expect(tree).toEqual([
<add> {
<add> name: 'Outer',
<add> value: __DEV__ ? 'outer' : undefined,
<add> subHooks: [
<add> {
<add> name: 'Inner',
<add> value: __DEV__ ? 'inner' : undefined,
<add> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> },
<add> ],
<add> },
<add> ]);
<add> });
<add>
<add> it('should support multiple inspectable values per custom hooks', () => {
<add> function useMultiLabelCustom() {
<add> React.useDebugValue('one');
<add> React.useDebugValue('two');
<add> React.useDebugValue('three');
<add> React.useState(0);
<add> }
<add> function useSingleLabelCustom(value) {
<add> React.useDebugValue(`single ${value}`);
<add> React.useState(0);
<add> }
<add> function Example() {
<add> useSingleLabelCustom('one');
<add> useMultiLabelCustom();
<add> useSingleLabelCustom('two');
<add> return null;
<add> }
<add> let renderer = ReactTestRenderer.create(<Example />);
<add> let childFiber = renderer.root.findByType(Example)._currentFiber();
<add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<add> expect(tree).toEqual([
<add> {
<add> name: 'SingleLabelCustom',
<add> value: __DEV__ ? 'single one' : undefined,
<add> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> },
<add> {
<add> name: 'MultiLabelCustom',
<add> value: __DEV__ ? ['one', 'two', 'three'] : undefined,
<add> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> },
<add> {
<add> name: 'SingleLabelCustom',
<add> value: __DEV__ ? 'single two' : undefined,
<add> subHooks: [{name: 'State', value: 0, subHooks: []}],
<add> },
<add> ]);
<add> });
<add>
<add> it('should ignore useDebugValue() made outside of a custom hook', () => {
<add> function Example() {
<add> React.useDebugValue('this is invalid');
<add> return null;
<add> }
<add> let renderer = ReactTestRenderer.create(<Example />);
<add> let childFiber = renderer.root.findByType(Example)._currentFiber();
<add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<add> expect(tree).toHaveLength(0);
<add> });
<add>
<add> it('should support an optional formatter function param', () => {
<add> function useCustom() {
<add> React.useDebugValue({bar: 123}, object => `bar:${object.bar}`);
<add> React.useState(0);
<add> }
<add> function Example() {
<add> useCustom();
<add> return null;
<add> }
<add> let renderer = ReactTestRenderer.create(<Example />);
<add> let childFiber = renderer.root.findByType(Example)._currentFiber();
<add> let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
<add> expect(tree).toEqual([
<add> {
<add> name: 'Custom',
<add> value: __DEV__ ? 'bar:123' : undefined,
<add> subHooks: [{name: 'State', subHooks: [], value: 0}],
<add> },
<add> ]);
<add> });
<add> });
<add>
<ide> it('should support defaultProps and lazy', async () => {
<ide> let Suspense = React.Suspense;
<ide>
<ide><path>packages/react-reconciler/src/ReactFiberDispatcher.js
<ide> import {
<ide> useContext,
<ide> useEffect,
<ide> useImperativeHandle,
<add> useDebugValue,
<ide> useLayoutEffect,
<ide> useMemo,
<ide> useReducer,
<ide> export const Dispatcher = {
<ide> useContext,
<ide> useEffect,
<ide> useImperativeHandle,
<add> useDebugValue,
<ide> useLayoutEffect,
<ide> useMemo,
<ide> useReducer,
<ide><path>packages/react-reconciler/src/ReactFiberHooks.js
<ide> export function useImperativeHandle<T>(
<ide> }, nextInputs);
<ide> }
<ide>
<add>export function useDebugValue(
<add> value: any,
<add> formatterFn: ?(value: any) => any,
<add>): void {
<add> // This hook is normally a no-op.
<add> // The react-debug-hooks package injects its own implementation
<add> // so that e.g. DevTools can display custom hook values.
<add>}
<add>
<ide> export function useCallback<T>(
<ide> callback: T,
<ide> inputs: Array<mixed> | void | null,
<ide><path>packages/react/src/React.js
<ide> import {
<ide> useContext,
<ide> useEffect,
<ide> useImperativeHandle,
<add> useDebugValue,
<ide> useLayoutEffect,
<ide> useMemo,
<ide> useReducer,
<ide> if (enableHooks) {
<ide> React.useContext = useContext;
<ide> React.useEffect = useEffect;
<ide> React.useImperativeHandle = useImperativeHandle;
<add> React.useDebugValue = useDebugValue;
<ide> React.useLayoutEffect = useLayoutEffect;
<ide> React.useMemo = useMemo;
<ide> React.useReducer = useReducer;
<ide><path>packages/react/src/ReactHooks.js
<ide> export function useImperativeHandle<T>(
<ide> const dispatcher = resolveDispatcher();
<ide> return dispatcher.useImperativeHandle(ref, create, inputs);
<ide> }
<add>
<add>export function useDebugValue(value: any, formatterFn: ?(value: any) => any) {
<add> if (__DEV__) {
<add> const dispatcher = resolveDispatcher();
<add> return dispatcher.useDebugValue(value, formatterFn);
<add> }
<add>} | 7 |
Java | Java | fix getters to match setters in rmha | 62e23363cb78bfb106d0dc499c8c2c18ec2a3719 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java
<ide> import org.springframework.web.context.request.NativeWebRequest;
<ide> import org.springframework.web.context.request.ServletWebRequest;
<ide> import org.springframework.web.context.request.WebRequest;
<del>import org.springframework.web.context.request.async.WebAsyncTask;
<ide> import org.springframework.web.context.request.async.AsyncWebRequest;
<ide> import org.springframework.web.context.request.async.CallableProcessingInterceptor;
<ide> import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor;
<ide> import org.springframework.web.context.request.async.WebAsyncManager;
<add>import org.springframework.web.context.request.async.WebAsyncTask;
<ide> import org.springframework.web.context.request.async.WebAsyncUtils;
<ide> import org.springframework.web.method.ControllerAdviceBean;
<ide> import org.springframework.web.method.HandlerMethod;
<ide> public void setArgumentResolvers(List<HandlerMethodArgumentResolver> argumentRes
<ide> * Return the configured argument resolvers, or possibly {@code null} if
<ide> * not initialized yet via {@link #afterPropertiesSet()}.
<ide> */
<del> public HandlerMethodArgumentResolverComposite getArgumentResolvers() {
<del> return this.argumentResolvers;
<add> public List<HandlerMethodArgumentResolver> getArgumentResolvers() {
<add> return this.argumentResolvers.getResolvers();
<ide> }
<ide>
<ide> /**
<ide> public void setInitBinderArgumentResolvers(List<HandlerMethodArgumentResolver> a
<ide> * Return the argument resolvers for {@code @InitBinder} methods, or possibly
<ide> * {@code null} if not initialized yet via {@link #afterPropertiesSet()}.
<ide> */
<del> public HandlerMethodArgumentResolverComposite getInitBinderArgumentResolvers() {
<del> return this.initBinderArgumentResolvers;
<add> public List<HandlerMethodArgumentResolver> getInitBinderArgumentResolvers() {
<add> return this.initBinderArgumentResolvers.getResolvers();
<ide> }
<ide>
<ide> /**
<ide> public void setReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnV
<ide> * Return the configured handlers, or possibly {@code null} if not
<ide> * initialized yet via {@link #afterPropertiesSet()}.
<ide> */
<del> public HandlerMethodReturnValueHandlerComposite getReturnValueHandlers() {
<del> return this.returnValueHandlers;
<add> public List<HandlerMethodReturnValueHandler> getReturnValueHandlers() {
<add> return this.returnValueHandlers.getHandlers();
<ide> }
<ide>
<ide> /**
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java
<ide>
<ide> package org.springframework.web.servlet.mvc.method.annotation;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertTrue;
<del>
<ide> import java.lang.reflect.Method;
<ide> import java.util.Arrays;
<ide>
<ide> import org.springframework.web.servlet.FlashMap;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide>
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * Unit tests for {@link RequestMappingHandlerAdapter}.
<ide> *
<ide> public static void setupOnce() {
<ide> adapter.setApplicationContext(new StaticWebApplicationContext());
<ide> adapter.afterPropertiesSet();
<ide>
<del> RESOLVER_COUNT = adapter.getArgumentResolvers().getResolvers().size();
<del> INIT_BINDER_RESOLVER_COUNT = adapter.getInitBinderArgumentResolvers().getResolvers().size();
<del> HANDLER_COUNT = adapter.getReturnValueHandlers().getHandlers().size();
<add> RESOLVER_COUNT = adapter.getArgumentResolvers().size();
<add> INIT_BINDER_RESOLVER_COUNT = adapter.getInitBinderArgumentResolvers().size();
<add> HANDLER_COUNT = adapter.getReturnValueHandlers().size();
<ide> }
<ide>
<ide> @Before
<ide> public void setCustomArgumentResolvers() throws Exception {
<ide> this.handlerAdapter.setCustomArgumentResolvers(Arrays.asList(resolver));
<ide> this.handlerAdapter.afterPropertiesSet();
<ide>
<del> assertTrue(this.handlerAdapter.getArgumentResolvers().getResolvers().contains(resolver));
<add> assertTrue(this.handlerAdapter.getArgumentResolvers().contains(resolver));
<ide> assertMethodProcessorCount(RESOLVER_COUNT + 1, INIT_BINDER_RESOLVER_COUNT + 1, HANDLER_COUNT);
<ide> }
<ide>
<ide> public void setCustomReturnValueHandlers() {
<ide> this.handlerAdapter.setCustomReturnValueHandlers(Arrays.asList(handler));
<ide> this.handlerAdapter.afterPropertiesSet();
<ide>
<del> assertTrue(this.handlerAdapter.getReturnValueHandlers().getHandlers().contains(handler));
<add> assertTrue(this.handlerAdapter.getReturnValueHandlers().contains(handler));
<ide> assertMethodProcessorCount(RESOLVER_COUNT, INIT_BINDER_RESOLVER_COUNT, HANDLER_COUNT + 1);
<ide> }
<ide>
<ide> private HandlerMethod handlerMethod(Object handler, String methodName, Class<?>.
<ide> }
<ide>
<ide> private void assertMethodProcessorCount(int resolverCount, int initBinderResolverCount, int handlerCount) {
<del> assertEquals(resolverCount, this.handlerAdapter.getArgumentResolvers().getResolvers().size());
<del> assertEquals(initBinderResolverCount, this.handlerAdapter.getInitBinderArgumentResolvers().getResolvers().size());
<del> assertEquals(handlerCount, this.handlerAdapter.getReturnValueHandlers().getHandlers().size());
<add> assertEquals(resolverCount, this.handlerAdapter.getArgumentResolvers().size());
<add> assertEquals(initBinderResolverCount, this.handlerAdapter.getInitBinderArgumentResolvers().size());
<add> assertEquals(handlerCount, this.handlerAdapter.getReturnValueHandlers().size());
<ide> }
<ide>
<ide> | 2 |
Python | Python | use _umath_linalg for solve() | 04ad33ed7b6b6a0eee2a0a6e98fc8d598db487ad | <ide><path>numpy/linalg/linalg.py
<ide> def solve(a, b):
<ide>
<ide> Parameters
<ide> ----------
<del> a : (M, M) array_like
<add> a : (..., M, M) array_like
<ide> Coefficient matrix.
<del> b : {(M,), (M, N)}, array_like
<add> b : {(..., M,), (..., M, K)}, array_like
<ide> Ordinate or "dependent variable" values.
<ide>
<ide> Returns
<ide> -------
<del> x : {(M,), (M, N)} ndarray
<add> x : {(..., M,), (..., M, K)} ndarray
<ide> Solution to the system a x = b. Returned shape is identical to `b`.
<ide>
<ide> Raises
<ide> def solve(a, b):
<ide>
<ide> Notes
<ide> -----
<del> `solve` is a wrapper for the LAPACK routines `dgesv`_ and
<del> `zgesv`_, the former being used if `a` is real-valued, the latter if
<del> it is complex-valued. The solution to the system of linear equations
<del> is computed using an LU decomposition [1]_ with partial pivoting and
<del> row interchanges.
<del>
<del> .. _dgesv: http://www.netlib.org/lapack/double/dgesv.f
<add> Broadcasting rules apply, see the `numpy.linalg` documentation for
<add> details.
<ide>
<del> .. _zgesv: http://www.netlib.org/lapack/complex16/zgesv.f
<add> The solutions are computed using LAPACK routine _gesv
<ide>
<ide> `a` must be square and of full-rank, i.e., all rows (or, equivalently,
<ide> columns) must be linearly independent; if either is not true, use
<ide> def solve(a, b):
<ide>
<ide> """
<ide> a, _ = _makearray(a)
<add> _assertNonEmpty(a)
<add> _assertRankAtLeast2(a)
<add> _assertNdSquareness(a)
<ide> b, wrap = _makearray(b)
<del> one_eq = len(b.shape) == 1
<del> if one_eq:
<del> b = b[:, newaxis]
<del> _assertRank2(a, b)
<del> _assertSquareness(a)
<del> n_eq = a.shape[0]
<del> n_rhs = b.shape[1]
<del> if n_eq != b.shape[0]:
<del> raise LinAlgError('Incompatible dimensions')
<ide> t, result_t = _commonType(a, b)
<del># lapack_routine = _findLapackRoutine('gesv', t)
<del> if isComplexType(t):
<del> lapack_routine = lapack_lite.zgesv
<del> else:
<del> lapack_routine = lapack_lite.dgesv
<del> a, b = _fastCopyAndTranspose(t, a, b)
<del> a, b = _to_native_byte_order(a, b)
<del> pivots = zeros(n_eq, fortran_int)
<del> results = lapack_routine(n_eq, n_rhs, a, n_eq, pivots, b, n_eq, 0)
<del> if results['info'] > 0:
<del> raise LinAlgError('Singular matrix')
<del> if one_eq:
<del> return wrap(b.ravel().astype(result_t))
<add>
<add> if len(b.shape) == len(a.shape) - 1:
<add> gufunc = _umath_linalg.solve1
<ide> else:
<del> return wrap(b.transpose().astype(result_t))
<add> gufunc = _umath_linalg.solve
<add>
<add> extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
<add> r = gufunc(a.astype(t), b.astype(t), extobj=extobj)
<add>
<add> return wrap(r.astype(result_t))
<ide>
<ide>
<ide> def tensorinv(a, ind=2): | 1 |
Python | Python | fix py3 compatibility | f9325e8fe5fe002f9720b7cb1c6d3614948a10ea | <ide><path>keras/models.py
<ide> def generator_task():
<ide> while not _stop.is_set():
<ide> try:
<ide> if generator_queue.qsize() < max_queue_size:
<del> generator_output = generator.next()
<add> generator_output = next(generator)
<ide> generator_queue.put(generator_output)
<ide> i += 1
<ide> else:
<ide> def generator_task():
<ide> while not _stop.is_set():
<ide> try:
<ide> if generator_queue.qsize() < max_queue_size:
<del> generator_output = generator.next()
<add> generator_output = next(generator)
<ide> generator_queue.put(generator_output)
<ide> i += 1
<ide> else:
<ide> def generator_task():
<ide> data, sample_weight = input_validation(generator_output)
<ide>
<ide> batch_logs = {}
<del> batch_size = len(data[data.keys()[0]])
<add> batch_size = len(data[list(data.keys())[0]])
<ide> batch_logs['batch'] = batch_index
<ide> batch_logs['size'] = batch_size
<ide> callbacks.on_batch_begin(batch_index, batch_logs) | 1 |
Javascript | Javascript | fix lint warnings | 481f242b5a3acfb0ac0935a12600839bab3e2d4c | <ide><path>fonts.js
<ide> var FontLoader = {
<ide> // loaded in a subdocument. It's expected that the load of |rules|
<ide> // has already started in this (outer) document, so that they should
<ide> // be ordered before the load in the subdocument.
<del> prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, names, objs) {
<add> prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, names,
<add> objs) {
<ide> /** Hack begin */
<ide> // There's no event when a font has finished downloading so the
<ide> // following code is a dirty hack to 'guess' when a font is
<ide> var Type2CFF = (function type2CFF() {
<ide>
<ide> // sort the array by the unicode value
<ide> charstrings.sort(function type2CFFGetCharStringsSort(a, b) {
<del> return a.unicode - b.unicode
<add> return a.unicode - b.unicode;
<ide> });
<ide> return charstrings;
<ide> }, | 1 |
Ruby | Ruby | remove useless instance variable | 10058ea2805e2347fe070b937c62c878269d1b1d | <ide><path>activerecord/lib/active_record/transactions.rb
<ide> def has_transactional_callbacks? # :nodoc:
<ide> # method recursively goes through the parent of the TransactionState and
<ide> # checks if the ActiveRecord object reflects the state of the object.
<ide> def sync_with_transaction_state
<del> update_attributes_from_transaction_state(@transaction_state, 0)
<add> update_attributes_from_transaction_state(@transaction_state)
<ide> end
<ide>
<del> def update_attributes_from_transaction_state(transaction_state, depth)
<del> @reflects_state = [false] if depth == 0
<del>
<add> def update_attributes_from_transaction_state(transaction_state)
<ide> if transaction_state && transaction_state.finalized? && !has_transactional_callbacks?
<del> unless @reflects_state[depth]
<del> restore_transaction_record_state if transaction_state.rolledback?
<del> clear_transaction_record_state
<del> @reflects_state[depth] = true
<del> end
<add> restore_transaction_record_state if transaction_state.rolledback?
<add> clear_transaction_record_state
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | remove intermediate variable | efec6811b667b6cf362d648bc599b667eebffce0 | <ide><path>lib/readline.js
<ide> function Interface(input, output, completer, terminal) {
<ide> terminal = input.terminal;
<ide> historySize = input.historySize;
<ide> if (input.tabSize !== undefined) {
<del> const positive = true;
<del> validateUint32(input.tabSize, 'tabSize', positive);
<add> validateUint32(input.tabSize, 'tabSize', true);
<ide> this.tabSize = input.tabSize;
<ide> }
<ide> removeHistoryDuplicates = input.removeHistoryDuplicates; | 1 |
PHP | PHP | add test for previous commit | d668bc1e536b5a64f3e16d02fad9a19a9defd6e9 | <ide><path>tests/TestCase/Form/FormTest.php
<ide>
<ide> use Cake\Form\Form;
<ide> use Cake\TestSuite\TestCase;
<add>use TestApp\Form\AppForm;
<add>use TestApp\Form\FormSchema;
<ide>
<ide> /**
<ide> * Form test case.
<ide> public function testSchema()
<ide> $schema = $this->getMockBuilder('Cake\Form\Schema')->getMock();
<ide> $this->assertSame($schema, $form->schema($schema));
<ide> $this->assertSame($schema, $form->schema());
<add>
<add> $form = new AppForm();
<add> $this->assertInstanceOf(FormSchema::class, $form->schema());
<ide> }
<ide>
<ide> /**
<ide><path>tests/test_app/TestApp/Form/AppForm.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 3.5.13
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace TestApp\Form;
<add>
<add>use Cake\Form\Form;
<add>
<add>class AppForm extends Form
<add>{
<add> protected $_schemaClass = FormSchema::class;
<add>}
<ide><path>tests/test_app/TestApp/Form/FormSchema.php
<add><?php
<add>/**
<add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP(tm) Project
<add> * @since 3.5.13
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace TestApp\Form;
<add>
<add>use Cake\Form\Schema;
<add>
<add>/**
<add> * Contains the schema information for Form instances.
<add> */
<add>class FormSchema extends Schema
<add>{
<add>} | 3 |
Text | Text | create model card | 243e687be6cd701722cce050005a2181e78a08a8 | <ide><path>model_cards/mrm8488/gpt2-imdb-neg/README.md
<add># GPT2-IMDB-neg (LM + RL) 🎞😡✍
<add>
<add>All credits to [@lvwerra](https://twitter.com/lvwerra)
<add>
<add>## What is it?
<add>A small GPT2 (`lvwerra/gpt2-imdb`) language model fine-tuned to produce **negative** movie reviews based the [IMDB dataset](https://www.kaggle.com/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews). The model is trained with rewards from a BERT sentiment classifier (`lvwerra/gpt2-imdb`) via **PPO**.
<add>
<add>## Why?
<add>I wanted to reproduce the experiment [lvwerra/gpt2-imdb-pos](https://huggingface.co/lvwerra/gpt2-imdb-pos) but for generating **negative** movie reviews.
<add>
<add>## Training setting
<add>The model was trained for `100` optimisation steps with a batch size of `256` which corresponds to `25600` training samples. The full experiment setup (for positive samples) in [trl repo](https://lvwerra.github.io/trl/04-gpt2-sentiment-ppo-training/).
<add>
<add>## Examples
<add>A few examples of the model response to a query before and after optimisation:
<add>
<add>| query | response (before) | response (after) | rewards (before) | rewards (after) |
<add>|-------|-------------------|------------------|------------------|-----------------|
<add>|This movie is a fine | attempt as far as live action is concerned, n...|example of how bad Hollywood in theatrics pla...| 2.118391 | -3.31625|
<add>|I have watched 3 episodes |with this guy and he is such a talented actor...| but the show is just plain awful and there ne...| 2.681171| -4.512792|
<add>|We know that firefighters and| police officers are forced to become populari...| other chains have going to get this disaster ...| 1.367811| -3.34017|
<add>
<add>
<add>
<add>> Created by [Manuel Romero/@mrm8488](https://twitter.com/mrm8488)
<add>
<add>> Made with <span style="color: #e25555;">♥</span> in Spain | 1 |
Ruby | Ruby | add commit in the encryptedcookiejar | 94b313db8d672a57ad5deb63203e334fe1184b84 | <ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> def [](name)
<ide> end
<ide> end
<ide>
<del> class EncryptedCookieJar #:nodoc:
<del> include ChainedCookieJars
<add> class EncryptedCookieJar < AbstractCookieJar # :nodoc:
<ide> include SerializedCookieJars
<ide>
<ide> def initialize(parent_jar)
<del> @parent_jar = parent_jar
<add> super
<ide>
<ide> if ActiveSupport::LegacyKeyGenerator === key_generator
<ide> raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " +
<ide> def [](name)
<ide> end
<ide> end
<ide>
<del> # Encrypts and sets the cookie named +name+. The second argument may be the cookie's
<del> # value or a hash of options as documented above.
<del> def []=(name, options)
<del> if options.is_a?(Hash)
<del> options.symbolize_keys!
<del> else
<del> options = { :value => options }
<del> end
<del>
<del> options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value]))
<add> private
<add> def commit(options)
<add> options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value]))
<ide>
<del> raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
<del> @parent_jar[name] = options
<del> end
<add> raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE
<add> end
<ide>
<del> private
<ide> def decrypt_and_verify(encrypted_message)
<ide> @encryptor.decrypt_and_verify(encrypted_message)
<ide> rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage | 1 |
Javascript | Javascript | add unit test for bahasa melayu | f4cede705fdf291157631824b9e5c179eb782640 | <ide><path>test/lang/ms-my.js
<add>var moment = require("../../moment");
<add>
<add>
<add> /**************************************************
<add> English
<add> *************************************************/
<add>
<add>exports["lang:ms-my"] = {
<add> setUp : function (cb) {
<add> moment.lang('ms-my');
<add> cb();
<add> },
<add>
<add> tearDown : function (cb) {
<add> moment.lang('en');
<add> cb();
<add> },
<add>
<add> "parse" : function(test) {
<add> test.expect(96);
<add>
<add> var i,
<add> tests = 'Januari Jan_Februari Feb_Mac Mac_April Apr_Mei Mei_Jun Jun_Julai Jul_Ogos Ogs_September Sep_Oktober Okt_November Nov_Disember Dis'.split("_");
<add>
<add> function equalTest(input, mmm, i) {
<add> test.equal(moment(input, mmm).month(), i, input + ' sepatutnya bulan ' + (i + 1));
<add> }
<add>
<add> for (i = 0; i < 12; i++) {
<add> tests[i] = tests[i].split(' ');
<add> equalTest(tests[i][0], 'MMM', i);
<add> equalTest(tests[i][1], 'MMM', i);
<add> equalTest(tests[i][0], 'MMMM', i);
<add> equalTest(tests[i][1], 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
<add> equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
<add> equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
<add> }
<add>
<add> test.done();
<add> },
<add>
<add> "format" : function(test) {
<add> test.expect(22);
<add>
<add> var a = [
<add> ['dddd, MMMM Do YYYY, h:mm:ss a', 'Ahad, Februari 14th 2010, 3:25:50 pm'],
<add> ['ddd, hA', 'Ahd, 3PM'],
<add> ['M Mo MM MMMM MMM', '2 2nd 02 Februari Feb'],
<add> ['YYYY YY', '2010 10'],
<add> ['D Do DD', '14 14th 14'],
<add> ['d do dddd ddd dd', '0 0th Ahad Ahd Ah'],
<add> ['DDD DDDo DDDD', '45 45th 045'],
<add> ['w wo ww', '8 8th 08'],
<add> ['h hh', '3 03'],
<add> ['H HH', '15 15'],
<add> ['m mm', '25 25'],
<add> ['s ss', '50 50'],
<add> ['a A', 'pm PM'],
<add> ['t\\he DDDo \\d\\ay of t\\he ye\\ar', 'hari ke 45 tahun ini'],
<add> ['L', '02/14/2010'],
<add> ['LL', 'Februari 14 2010'],
<add> ['LLL', 'Februari 14 2010 3:25 PM'],
<add> ['LLLL', 'Ahad, Februari 14 2010 3:25 PM'],
<add> ['l', '2/14/2010'],
<add> ['ll', 'Feb 14 2010'],
<add> ['lll', 'Feb 14 2010 3:25 PM'],
<add> ['llll', 'Ahd, Feb 14 2010 3:25 PM']
<add> ],
<add> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)),
<add> i;
<add>
<add> for (i = 0; i < a.length; i++) {
<add> test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]);
<add> }
<add>
<add> test.done();
<add> },
<add>
<add> "format ordinal" : function(test) {
<add> test.expect(31);
<add>
<add> test.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st');
<add> test.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd');
<add> test.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd');
<add> test.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th');
<add> test.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th');
<add> test.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th');
<add> test.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th');
<add> test.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th');
<add> test.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th');
<add> test.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th');
<add>
<add> test.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th');
<add> test.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th');
<add> test.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th');
<add> test.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th');
<add> test.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th');
<add> test.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th');
<add> test.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th');
<add> test.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th');
<add> test.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th');
<add> test.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th');
<add>
<add> test.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st');
<add> test.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd');
<add> test.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd');
<add> test.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th');
<add> test.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th');
<add> test.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th');
<add> test.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th');
<add> test.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th');
<add> test.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th');
<add> test.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th');
<add>
<add> test.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st');
<add> test.done();
<add> },
<add>
<add> "format month" : function(test) {
<add> test.expect(12);
<add>
<add> var i,
<add> expected = 'Januari Jan_Februari Feb_Mac Mac_April Apr_Mei Mei_Jun Jun_Julai Jul_Ogos Ogs_September Sep_Oktober Okt_November Nov_Disember Dis'.split("_");
<add>
<add> for (i = 0; i < expected.length; i++) {
<add> test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]);
<add> }
<add> test.done();
<add> },
<add>
<add> "format week" : function(test) {
<add> test.expect(7);
<add>
<add> var i,
<add> expected = 'Ahad Ahd Ah_Isnin Isn Is_Selasa Sel Sl_Rabu Rab Rb_Khamis Kha Kh_Jumaat Jum Jm_Sabtu Sab Sb'.split("_");
<add>
<add> for (i = 0; i < expected.length; i++) {
<add> test.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]);
<add> }
<add>
<add> test.done();
<add> },
<add>
<add> "from" : function(test) {
<add> test.expect(30);
<add>
<add> var start = moment([2007, 1, 28]);
<add>
<add> test.equal(start.from(moment([2007, 1, 28]).add({s:44}), true), "beberapa saat", "44 saat = beberapa saat");
<add> test.equal(start.from(moment([2007, 1, 28]).add({s:45}), true), "seminit", "45 saat = seminit");
<add> test.equal(start.from(moment([2007, 1, 28]).add({s:89}), true), "seminit", "89 saat = seminit");
<add> test.equal(start.from(moment([2007, 1, 28]).add({s:90}), true), "2 minit", "90 saat = 2 minit");
<add> test.equal(start.from(moment([2007, 1, 28]).add({m:44}), true), "44 minit", "44 minit = 44 minit");
<add> test.equal(start.from(moment([2007, 1, 28]).add({m:45}), true), "sejam", "45 minit = sejam");
<add> test.equal(start.from(moment([2007, 1, 28]).add({m:89}), true), "sejam", "89 minit = sejam");
<add> test.equal(start.from(moment([2007, 1, 28]).add({m:90}), true), "2 jam", "90 minit = 2 jam");
<add> test.equal(start.from(moment([2007, 1, 28]).add({h:5}), true), "5 jam", "5 jam = 5 jam");
<add> test.equal(start.from(moment([2007, 1, 28]).add({h:21}), true), "21 jam", "21 jam = 21 jam");
<add> test.equal(start.from(moment([2007, 1, 28]).add({h:22}), true), "sehari", "22 jam = sehari");
<add> test.equal(start.from(moment([2007, 1, 28]).add({h:35}), true), "sehari", "35 jam = sehari");
<add> test.equal(start.from(moment([2007, 1, 28]).add({h:36}), true), "2 hari", "36 jam = 2 hari");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:1}), true), "sehari", "1 hari = sehari");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:5}), true), "5 hari", "5 hari = 5 hari");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:25}), true), "25 hari", "25 hari = 25 hari");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:26}), true), "sebulan", "26 hari = sebulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:30}), true), "sebulan", "30 hari = sebulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:45}), true), "sebulan", "45 hari = sebulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:46}), true), "2 bulan", "46 hari = 2 bulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:74}), true), "2 bulan", "75 hari = 2 bulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:76}), true), "3 bulan", "76 hari = 3 bulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({M:1}), true), "sebulan", "1 bulan = sebulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({M:5}), true), "5 bulan", "5 bulan = 5 bulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:344}), true), "11 bulan", "344 hari = 11 bulan");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:345}), true), "setahun", "345 hari = setahun");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:547}), true), "setahun", "547 hari = setahun");
<add> test.equal(start.from(moment([2007, 1, 28]).add({d:548}), true), "2 tahun", "548 hari = 2 tahun");
<add> test.equal(start.from(moment([2007, 1, 28]).add({y:1}), true), "setahun", "1 tahun = setahun");
<add> test.equal(start.from(moment([2007, 1, 28]).add({y:5}), true), "5 tahun", "5 tahun = 5 tahun");
<add>
<add> test.done();
<add> },
<add>
<add> "suffix" : function(test) {
<add> test.expect(2);
<add>
<add> test.equal(moment(30000).from(0), "dalam beberapa saat", "prefix");
<add> test.equal(moment(0).from(30000), "beberapa saat yang lepas", "suffix");
<add>
<add> test.done();
<add> },
<add>
<add> "now from now" : function(test) {
<add> test.expect(1);
<add>
<add> test.equal(moment().fromNow(), "beberapa saat yang lepas", "waktu sekarang dari sekarang sepatutnya menunjukkan sebagai telah lepas");
<add>
<add> test.done();
<add> },
<add>
<add> "fromNow" : function(test) {
<add> test.expect(2);
<add>
<add> test.equal(moment().add({s:30}).fromNow(), "dalam beberapa saat", "dalam beberapa saat");
<add> test.equal(moment().add({d:5}).fromNow(), "dalam 5 hari", "dalam 5 hari");
<add>
<add> test.done();
<add> },
<add>
<add> "calendar day" : function(test) {
<add> test.expect(6);
<add>
<add> var a = moment().hours(2).minutes(0).seconds(0);
<add>
<add> test.equal(moment(a).calendar(), "Hari ini pada pukul 2:00 AM", "hari ini pada waktu yang sama");
<add> test.equal(moment(a).add({ m: 25 }).calendar(), "Hari ini pada pukul 2:25 AM", "Sekarang tambah 25 minit");
<add> test.equal(moment(a).add({ h: 1 }).calendar(), "Hari ini pada pukul 3:00 AM", "Sekarang tambah 1 jam");
<add> test.equal(moment(a).add({ d: 1 }).calendar(), "Esok pada pukul 2:00 AM", "esok pada waktu yang sama");
<add> test.equal(moment(a).subtract({ h: 1 }).calendar(), "Hari ini pada pukul 1:00 AM", "Sekarang tolak 1 jam");
<add> test.equal(moment(a).subtract({ d: 1 }).calendar(), "Semalam pada pukul 2:00 AM", "semalam pada waktu yang sama");
<add>
<add> test.done();
<add> },
<add>
<add> "calendar next week" : function(test) {
<add> test.expect(15);
<add>
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().add({ d: i });
<add> test.equal(m.calendar(), m.format('dddd [at] LT'), "Hari ini + " + i + " hari waktu sekarang");
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> test.equal(m.calendar(), m.format('dddd [at] LT'), "Hari ini + " + i + " hari permulaan hari");
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> test.equal(m.calendar(), m.format('dddd [at] LT'), "Hari ini + " + i + " hari tamat hari");
<add> }
<add> test.done();
<add> },
<add>
<add> "calendar last week" : function(test) {
<add> test.expect(15);
<add>
<add> var i, m;
<add>
<add> for (i = 2; i < 7; i++) {
<add> m = moment().subtract({ d: i });
<add> test.equal(m.calendar(), m.format('[last] dddd [at] LT'), "Hari ini - " + i + " hari waktu sekarang");
<add> m.hours(0).minutes(0).seconds(0).milliseconds(0);
<add> test.equal(m.calendar(), m.format('[last] dddd [at] LT'), "Hari ini - " + i + " hari permulaan hari");
<add> m.hours(23).minutes(59).seconds(59).milliseconds(999);
<add> test.equal(m.calendar(), m.format('[last] dddd [at] LT'), "Hari ini - " + i + " hari tamat hari");
<add> }
<add> test.done();
<add> },
<add>
<add> "calendar all else" : function(test) {
<add> test.expect(4);
<add>
<add> var weeksAgo = moment().subtract({ w: 1 }),
<add> weeksFromNow = moment().add({ w: 1 });
<add>
<add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 minggu lalu");
<add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "dalam 1 minggu");
<add>
<add> weeksAgo = moment().subtract({ w: 2 });
<add> weeksFromNow = moment().add({ w: 2 });
<add>
<add> test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 minggu lepas");
<add> test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "dalam 2 minggu");
<add>
<add> test.done();
<add> },
<add>
<add> // Sunday is the first day of the week.
<add> // The week that contains Jan 1st is the first week of the year.
<add>
<add> "weeks year starting sunday" : function(test) {
<add> test.expect(5);
<add>
<add> test.equal(moment([2012, 0, 1]).week(), 1, "Jan 1 2012 sepatutnya minggu 1");
<add> test.equal(moment([2012, 0, 7]).week(), 1, "Jan 7 2012 sepatutnya minggu 1");
<add> test.equal(moment([2012, 0, 8]).week(), 2, "Jan 8 2012 sepatutnya minggu 2");
<add> test.equal(moment([2012, 0, 14]).week(), 2, "Jan 14 2012 sepatutnya minggu 2");
<add> test.equal(moment([2012, 0, 15]).week(), 3, "Jan 15 2012 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting monday" : function(test) {
<add> test.expect(6);
<add>
<add> test.equal(moment([2006, 11, 31]).week(), 1, "Dec 31 2006 sepatutnya minggu 1");
<add> test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 sepatutnya minggu 1");
<add> test.equal(moment([2007, 0, 6]).week(), 1, "Jan 6 2007 sepatutnya minggu 1");
<add> test.equal(moment([2007, 0, 7]).week(), 2, "Jan 7 2007 sepatutnya minggu 2");
<add> test.equal(moment([2007, 0, 13]).week(), 2, "Jan 13 2007 sepatutnya minggu 2");
<add> test.equal(moment([2007, 0, 14]).week(), 3, "Jan 14 2007 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting tuesday" : function(test) {
<add> test.expect(6);
<add>
<add> test.equal(moment([2007, 11, 30]).week(), 1, "Dec 30 2007 sepatutnya minggu 1");
<add> test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 sepatutnya minggu 1");
<add> test.equal(moment([2008, 0, 5]).week(), 1, "Jan 5 2008 sepatutnya minggu 1");
<add> test.equal(moment([2008, 0, 6]).week(), 2, "Jan 6 2008 sepatutnya minggu 2");
<add> test.equal(moment([2008, 0, 12]).week(), 2, "Jan 12 2008 sepatutnya minggu 2");
<add> test.equal(moment([2008, 0, 13]).week(), 3, "Jan 13 2008 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting wednesday" : function(test) {
<add> test.expect(6);
<add>
<add> test.equal(moment([2002, 11, 29]).week(), 1, "Dec 29 2002 sepatutnya minggu 1");
<add> test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 sepatutnya minggu 1");
<add> test.equal(moment([2003, 0, 4]).week(), 1, "Jan 4 2003 sepatutnya minggu 1");
<add> test.equal(moment([2003, 0, 5]).week(), 2, "Jan 5 2003 sepatutnya minggu 2");
<add> test.equal(moment([2003, 0, 11]).week(), 2, "Jan 11 2003 sepatutnya minggu 2");
<add> test.equal(moment([2003, 0, 12]).week(), 3, "Jan 12 2003 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting thursday" : function(test) {
<add> test.expect(6);
<add>
<add> test.equal(moment([2008, 11, 28]).week(), 1, "Dec 28 2008 sepatutnya minggu 1");
<add> test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 sepatutnya minggu 1");
<add> test.equal(moment([2009, 0, 3]).week(), 1, "Jan 3 2009 sepatutnya minggu 1");
<add> test.equal(moment([2009, 0, 4]).week(), 2, "Jan 4 2009 sepatutnya minggu 2");
<add> test.equal(moment([2009, 0, 10]).week(), 2, "Jan 10 2009 sepatutnya minggu 2");
<add> test.equal(moment([2009, 0, 11]).week(), 3, "Jan 11 2009 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting friday" : function(test) {
<add> test.expect(6);
<add>
<add> test.equal(moment([2009, 11, 27]).week(), 1, "Dec 27 2009 sepatutnya minggu 1");
<add> test.equal(moment([2010, 0, 1]).week(), 1, "Jan 1 2010 sepatutnya minggu 1");
<add> test.equal(moment([2010, 0, 2]).week(), 1, "Jan 2 2010 sepatutnya minggu 1");
<add> test.equal(moment([2010, 0, 3]).week(), 2, "Jan 3 2010 sepatutnya minggu 2");
<add> test.equal(moment([2010, 0, 9]).week(), 2, "Jan 9 2010 sepatutnya minggu 2");
<add> test.equal(moment([2010, 0, 10]).week(), 3, "Jan 10 2010 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting saturday" : function(test) {
<add> test.expect(5);
<add>
<add> test.equal(moment([2010, 11, 26]).week(), 1, "Dec 26 2010 sepatutnya minggu 1");
<add> test.equal(moment([2011, 0, 1]).week(), 1, "Jan 1 2011 sepatutnya minggu 1");
<add> test.equal(moment([2011, 0, 2]).week(), 2, "Jan 2 2011 sepatutnya minggu 2");
<add> test.equal(moment([2011, 0, 8]).week(), 2, "Jan 8 2011 sepatutnya minggu 2");
<add> test.equal(moment([2011, 0, 9]).week(), 3, "Jan 9 2011 sepatutnya minggu 3");
<add>
<add> test.done();
<add> },
<add>
<add> "weeks year starting sunday format" : function(test) {
<add> test.expect(5);
<add>
<add> test.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1st', "Jan 1 2012 sepatutnya minggu 1");
<add> test.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1st', "Jan 7 2012 sepatutnya minggu 1");
<add> test.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2nd', "Jan 8 2012 sepatutnya minggu 2");
<add> test.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2nd', "Jan 14 2012 sepatutnya minggu 2");
<add> test.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', "Jan 15 2012 sepatutnya minggu 3");
<add>
<add> test.done();
<add> }
<add>}; | 1 |
Javascript | Javascript | fix wrong comment for getrange function | d7f45bab89790fe84f8fcc162df2b9e2ff6d265b | <ide><path>src/js/utils/time-ranges.js
<ide> function rangeCheck(fnName, index, maxIndex) {
<ide> }
<ide>
<ide> /**
<del> * Check if any of the time ranges are over the maximum index.
<add> * Get the time for the specified index at the start or end
<add> * of a TimeRange object.
<ide> *
<ide> * @param {string} fnName
<ide> * The function name to use for logging | 1 |
Javascript | Javascript | remove set bookkeeping for root events | e9f5ad2584ddb0d42a96045c9b23d0b4d9311331 | <ide><path>packages/react-dom/src/__tests__/ReactDOMEventListener-test.js
<ide> describe('ReactDOMEventListener', () => {
<ide> </div>,
<ide> container,
<ide> );
<add>
<add> // Update to attach.
<ide> ReactDOM.render(
<ide> <div
<ide> className="grand"
<del> onScroll={onScroll}
<del> onScrollCapture={onScrollCapture}>
<add> onScroll={e => onScroll(e)}
<add> onScrollCapture={e => onScrollCapture(e)}>
<ide> <div
<ide> className="parent"
<del> onScroll={onScroll}
<del> onScrollCapture={onScrollCapture}>
<add> onScroll={e => onScroll(e)}
<add> onScrollCapture={e => onScrollCapture(e)}>
<ide> <div
<ide> className="child"
<del> onScroll={onScroll}
<del> onScrollCapture={onScrollCapture}
<add> onScroll={e => onScroll(e)}
<add> onScrollCapture={e => onScrollCapture(e)}
<ide> ref={ref}
<ide> />
<ide> </div>
<ide> describe('ReactDOMEventListener', () => {
<ide> ['capture', 'child'],
<ide> ['bubble', 'child'],
<ide> ]);
<add>
<add> // Update to verify deduplication.
<add> log.length = 0;
<add> ReactDOM.render(
<add> <div
<add> className="grand"
<add> // Note: these are intentionally inline functions so that
<add> // we hit the reattachment codepath instead of bailing out.
<add> onScroll={e => onScroll(e)}
<add> onScrollCapture={e => onScrollCapture(e)}>
<add> <div
<add> className="parent"
<add> onScroll={e => onScroll(e)}
<add> onScrollCapture={e => onScrollCapture(e)}>
<add> <div
<add> className="child"
<add> onScroll={e => onScroll(e)}
<add> onScrollCapture={e => onScrollCapture(e)}
<add> ref={ref}
<add> />
<add> </div>
<add> </div>,
<add> container,
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('scroll', {
<add> bubbles: false,
<add> }),
<add> );
<add> expect(log).toEqual([
<add> ['capture', 'grand'],
<add> ['capture', 'parent'],
<add> ['capture', 'child'],
<add> ['bubble', 'child'],
<add> ]);
<add>
<add> // Update to detach.
<add> log.length = 0;
<add> ReactDOM.render(
<add> <div>
<add> <div>
<add> <div ref={ref} />
<add> </div>
<add> </div>,
<add> container,
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('scroll', {
<add> bubbles: false,
<add> }),
<add> );
<add> expect(log).toEqual([]);
<ide> } finally {
<ide> document.body.removeChild(container);
<ide> }
<ide> describe('ReactDOMEventListener', () => {
<ide> ['capture', 'child'],
<ide> ['bubble', 'child'],
<ide> ]);
<add>
<add> log.length = 0;
<add> ReactDOM.render(
<add> <div>
<add> <div>
<add> <div ref={ref} />
<add> </div>
<add> </div>,
<add> container,
<add> );
<add> ref.current.dispatchEvent(
<add> new Event('scroll', {
<add> bubbles: false,
<add> }),
<add> );
<add> expect(log).toEqual([]);
<ide> } finally {
<ide> document.body.removeChild(container);
<ide> }
<ide> });
<add>
<add> it('should not subscribe to selectionchange twice', () => {
<add> const log = [];
<add>
<add> const originalDocAddEventListener = document.addEventListener;
<add> document.addEventListener = function(type, fn, options) {
<add> switch (type) {
<add> case 'selectionchange':
<add> log.push(options);
<add> break;
<add> default:
<add> throw new Error(
<add> `Did not expect to add a document-level listener for the "${type}" event.`,
<add> );
<add> }
<add> };
<add> try {
<add> ReactDOM.render(<input />, document.createElement('div'));
<add> ReactDOM.render(<input />, document.createElement('div'));
<add> } finally {
<add> document.addEventListener = originalDocAddEventListener;
<add> }
<add>
<add> expect(log).toEqual([false]);
<add> });
<ide> });
<ide><path>packages/react-dom/src/client/ReactDOMEventHandle.js
<ide> import {
<ide> addEventHandleToTarget,
<ide> } from './ReactDOMComponentTree';
<ide> import {ELEMENT_NODE} from '../shared/HTMLNodeType';
<del>import {listenToNativeEvent} from '../events/DOMPluginEventSystem';
<del>
<del>import {IS_EVENT_HANDLE_NON_MANAGED_NODE} from '../events/EventSystemFlags';
<add>import {listenToNativeEventForNonManagedEventTarget} from '../events/DOMPluginEventSystem';
<ide>
<ide> import {
<ide> enableScopeAPI,
<ide> function registerReactDOMEvent(
<ide> const eventTarget = ((target: any): EventTarget);
<ide> // These are valid event targets, but they are also
<ide> // non-managed React nodes.
<del> listenToNativeEvent(
<add> listenToNativeEventForNonManagedEventTarget(
<ide> domEventName,
<ide> isCapturePhaseListener,
<ide> eventTarget,
<del> null,
<del> IS_EVENT_HANDLE_NON_MANAGED_NODE,
<ide> );
<ide> } else {
<ide> invariant(
<ide><path>packages/react-dom/src/events/DOMPluginEventSystem.js
<ide> export function listenToNonDelegatedEvent(
<ide> domEventName: DOMEventName,
<ide> targetElement: Element,
<ide> ): void {
<add> if (__DEV__) {
<add> if (!nonDelegatedEvents.has(domEventName)) {
<add> console.error(
<add> 'Did not expect a listenToNonDelegatedEvent() call for "%s". ' +
<add> 'This is a bug in React. Please file an issue.',
<add> domEventName,
<add> );
<add> }
<add> }
<ide> const isCapturePhaseListener = false;
<ide> const listenerSet = getEventListenerSet(targetElement);
<ide> const listenerSetKey = getListenerSetKey(
<ide> export function listenToNonDelegatedEvent(
<ide> }
<ide> }
<ide>
<del>const listeningMarker =
<del> '_reactListening' +
<del> Math.random()
<del> .toString(36)
<del> .slice(2);
<del>
<del>export function listenToAllSupportedEvents(rootContainerElement: EventTarget) {
<del> if ((rootContainerElement: any)[listeningMarker]) {
<del> // Performance optimization: don't iterate through events
<del> // for the same portal container or root node more than once.
<del> // TODO: once we remove the flag, we may be able to also
<del> // remove some of the bookkeeping maps used for laziness.
<del> return;
<del> }
<del> (rootContainerElement: any)[listeningMarker] = true;
<del> allNativeEvents.forEach(domEventName => {
<del> if (!nonDelegatedEvents.has(domEventName)) {
<del> listenToNativeEvent(
<add>export function listenToNativeEvent(
<add> domEventName: DOMEventName,
<add> isCapturePhaseListener: boolean,
<add> target: EventTarget,
<add>): void {
<add> if (__DEV__) {
<add> if (nonDelegatedEvents.has(domEventName) && !isCapturePhaseListener) {
<add> console.error(
<add> 'Did not expect a listenToNativeEvent() call for "%s" in the bubble phase. ' +
<add> 'This is a bug in React. Please file an issue.',
<ide> domEventName,
<del> false,
<del> ((rootContainerElement: any): Element),
<del> null,
<ide> );
<ide> }
<del> listenToNativeEvent(
<del> domEventName,
<del> true,
<del> ((rootContainerElement: any): Element),
<del> null,
<del> );
<del> });
<add> }
<add>
<add> let eventSystemFlags = 0;
<add> if (isCapturePhaseListener) {
<add> eventSystemFlags |= IS_CAPTURE_PHASE;
<add> }
<add> addTrappedEventListener(
<add> target,
<add> domEventName,
<add> eventSystemFlags,
<add> isCapturePhaseListener,
<add> );
<ide> }
<ide>
<del>export function listenToNativeEvent(
<add>// This is only used by createEventHandle when the
<add>// target is not a DOM element. E.g. window.
<add>export function listenToNativeEventForNonManagedEventTarget(
<ide> domEventName: DOMEventName,
<ide> isCapturePhaseListener: boolean,
<del> rootContainerElement: EventTarget,
<del> targetElement: Element | null,
<del> eventSystemFlags?: EventSystemFlags = 0,
<add> target: EventTarget,
<ide> ): void {
<del> let target = rootContainerElement;
<del>
<del> // selectionchange needs to be attached to the document
<del> // otherwise it won't capture incoming events that are only
<del> // triggered on the document directly.
<del> if (
<del> domEventName === 'selectionchange' &&
<del> (rootContainerElement: any).nodeType !== DOCUMENT_NODE
<del> ) {
<del> target = (rootContainerElement: any).ownerDocument;
<del> }
<del> // If the event can be delegated (or is capture phase), we can
<del> // register it to the root container. Otherwise, we should
<del> // register the event to the target element and mark it as
<del> // a non-delegated event.
<del> if (
<del> targetElement !== null &&
<del> !isCapturePhaseListener &&
<del> nonDelegatedEvents.has(domEventName)
<del> ) {
<del> // For all non-delegated events, apart from scroll, we attach
<del> // their event listeners to the respective elements that their
<del> // events fire on. That means we can skip this step, as event
<del> // listener has already been added previously. However, we
<del> // special case the scroll event because the reality is that any
<del> // element can scroll.
<del> // TODO: ideally, we'd eventually apply the same logic to all
<del> // events from the nonDelegatedEvents list. Then we can remove
<del> // this special case and use the same logic for all events.
<del> if (domEventName !== 'scroll') {
<del> return;
<del> }
<del> eventSystemFlags |= IS_NON_DELEGATED;
<del> target = targetElement;
<del> }
<add> let eventSystemFlags = IS_EVENT_HANDLE_NON_MANAGED_NODE;
<ide> const listenerSet = getEventListenerSet(target);
<ide> const listenerSetKey = getListenerSetKey(
<ide> domEventName,
<ide> isCapturePhaseListener,
<ide> );
<del> // If the listener entry is empty or we should upgrade, then
<del> // we need to trap an event listener onto the target.
<ide> if (!listenerSet.has(listenerSetKey)) {
<ide> if (isCapturePhaseListener) {
<ide> eventSystemFlags |= IS_CAPTURE_PHASE;
<ide> export function listenToNativeEvent(
<ide> }
<ide> }
<ide>
<add>const listeningMarker =
<add> '_reactListening' +
<add> Math.random()
<add> .toString(36)
<add> .slice(2);
<add>
<add>export function listenToAllSupportedEvents(rootContainerElement: EventTarget) {
<add> if (!(rootContainerElement: any)[listeningMarker]) {
<add> (rootContainerElement: any)[listeningMarker] = true;
<add> allNativeEvents.forEach(domEventName => {
<add> // We handle selectionchange separately because it
<add> // doesn't bubble and needs to be on the document.
<add> if (domEventName !== 'selectionchange') {
<add> if (!nonDelegatedEvents.has(domEventName)) {
<add> listenToNativeEvent(domEventName, false, rootContainerElement);
<add> }
<add> listenToNativeEvent(domEventName, true, rootContainerElement);
<add> }
<add> });
<add> const ownerDocument =
<add> (rootContainerElement: any).nodeType === DOCUMENT_NODE
<add> ? rootContainerElement
<add> : (rootContainerElement: any).ownerDocument;
<add> if (ownerDocument !== null) {
<add> // The selectionchange event also needs deduplication
<add> // but it is attached to the document.
<add> if (!(ownerDocument: any)[listeningMarker]) {
<add> (ownerDocument: any)[listeningMarker] = true;
<add> listenToNativeEvent('selectionchange', false, ownerDocument);
<add> }
<add> }
<add> }
<add>}
<add>
<ide> function addTrappedEventListener(
<ide> targetContainer: EventTarget,
<ide> domEventName: DOMEventName, | 3 |
Javascript | Javascript | fix jshint issues | 6ac773f350a3eacb5f4b3ab83bc06e3568ac8005 | <ide><path>src/ngResource/resource.js
<ide> function shallowClearAndCopy(src, dst) {
<ide> * @example
<ide> * # Creating a custom 'PUT' request
<ide> * In this example we create a custom method on our resource to make a PUT request
<del> <pre>
<del> var app = angular.module('app', ['ngResource', 'ngRoute']);
<del>
<del> // Some APIs expect a PUT request in the format URL/object/ID
<del> // Here we are creating an 'update' method
<del> app.factory('Notes', ['$resource', function($resource) {
<del> return $resource('/notes/:id', null,
<del> {
<del> 'update': { method:'PUT' }
<del> });
<del> }]);
<del>
<del> // In our controller we get the ID from the URL using ngRoute and $routeParams
<del> // We pass in $routeParams and our Notes factory along with $scope
<del> app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', function($scope, $routeParams, Notes) {
<del> // First get a note object from the factory
<del> var note = Notes.get({ id:$routeParams.id });
<del> $id = note.id;
<del>
<del> // Now call update passing in the ID first then the object you are updating
<del> Notes.update({ id:$id }, note);
<del>
<del> // This will PUT /notes/ID with the note object in the request payload
<del> }]);
<del> </pre>
<add> * <pre>
<add> * var app = angular.module('app', ['ngResource', 'ngRoute']);
<add> *
<add> * // Some APIs expect a PUT request in the format URL/object/ID
<add> * // Here we are creating an 'update' method
<add> * app.factory('Notes', ['$resource', function($resource) {
<add> * return $resource('/notes/:id', null,
<add> * {
<add> * 'update': { method:'PUT' }
<add> * });
<add> * }]);
<add> *
<add> * // In our controller we get the ID from the URL using ngRoute and $routeParams
<add> * // We pass in $routeParams and our Notes factory along with $scope
<add> * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
<add> function($scope, $routeParams, Notes) {
<add> * // First get a note object from the factory
<add> * var note = Notes.get({ id:$routeParams.id });
<add> * $id = note.id;
<add> *
<add> * // Now call update passing in the ID first then the object you are updating
<add> * Notes.update({ id:$id }, note);
<add> *
<add> * // This will PUT /notes/ID with the note object in the request payload
<add> * }]);
<add> * </pre>
<ide> */
<ide> angular.module('ngResource', ['ng']).
<ide> factory('$resource', ['$http', '$q', function($http, $q) { | 1 |
Python | Python | prefer consistent casing | 7077fb14526a59705b8313323a3f73e9e32d4383 | <ide><path>airflow/models/baseoperator.py
<ide> class derived from this one results in the creation of a task object,
<ide> has not succeeded yet.
<ide> The scheduler pays special attention for jobs with an SLA and
<ide> sends alert
<del> emails for sla misses. SLA misses are also recorded in the database
<add> emails for SLA misses. SLA misses are also recorded in the database
<ide> for future reference. All tasks that share the same SLA time
<ide> get bundled in a single email, sent soon after that time. SLA
<ide> notification are sent once and only once for each task instance. | 1 |
PHP | PHP | make tree recovery much, much simpler | 8ea021226537205bba4283218241f6da25b41292 | <ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> public function recover(Model $Model, $mode = 'parent', $missingParentAction = n
<ide> $Model->updateAll(array($Model->escapeField($parent) => $missingParentAction), array($Model->escapeField($Model->primaryKey) => array_flip($missingParents)));
<ide> }
<ide> }
<del> $count = 1;
<del> foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey), 'order' => $left)) as $array) {
<del> $lft = $count++;
<del> $rght = $count++;
<del> $Model->create(false);
<del> $Model->id = $array[$Model->alias][$Model->primaryKey];
<del> $Model->save(array($left => $lft, $right => $rght), array('callbacks' => false, 'validate' => false));
<del> }
<del> foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
<del> $Model->create(false);
<del> $Model->id = $array[$Model->alias][$Model->primaryKey];
<del> $this->_setParent($Model, $array[$Model->alias][$parent]);
<del> }
<add>
<add> $this->_recoverByParentId($Model);
<ide> } else {
<ide> $db = ConnectionManager::getDataSource($Model->useDbConfig);
<ide> foreach ($Model->find('all', array('conditions' => $scope, 'fields' => array($Model->primaryKey, $parent), 'order' => $left)) as $array) {
<ide> public function recover(Model $Model, $mode = 'parent', $missingParentAction = n
<ide> return true;
<ide> }
<ide>
<add>/**
<add> * _recoverByParentId
<add> *
<add> * Recursive helper function used by recover
<add> *
<add> * @param Model $Model
<add> * @param integer $counter
<add> * @param mixed $parentId
<add> * @return integer $counter
<add> */
<add> protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = null) {
<add> if (!is_null($parentId)) {
<add> $Model->updateAll(
<add> array($this->settings[$Model->alias]['left'] => $counter),
<add> array($Model->escapeField() => $parentId)
<add> );
<add> $counter++;
<add> }
<add>
<add> $params = array(
<add> 'conditions' => array(
<add> $this->settings[$Model->alias]['parent'] => $parentId
<add> ),
<add> 'fields' => array($Model->primaryKey),
<add> 'page' => 1,
<add> 'limit' => 100,
<add> 'order' => array($Model->primaryKey)
<add> );
<add>
<add> $scope = $this->settings[$Model->alias]['scope'];
<add> if ($scope && ($scope !== '1 = 1' && $scope !== true)) {
<add> $conditions[] = $scope;
<add> }
<add>
<add> while ($rows = $Model->find('all', $params)) {
<add> foreach ($rows as $row) {
<add> $counter = $this->_recoverByParentId($Model, $counter, $row[$Model->alias][$Model->primaryKey]);
<add> }
<add> $params['page']++;
<add> if (count($rows) !== $params['limit']) {
<add> break;
<add> }
<add> }
<add>
<add> if (!is_null($parentId)) {
<add> $Model->updateAll(
<add> array($this->settings[$Model->alias]['right'] => $counter),
<add> array($Model->escapeField() => $parentId)
<add> );
<add> $counter++;
<add> }
<add>
<add> return $counter;
<add> }
<add>
<ide> /**
<ide> * Reorder method.
<ide> * | 1 |
Javascript | Javascript | remove touch() method | 716dd5f3f90f853713706aa3b404822fef18ef93 | <ide><path>src/directive/input.js
<ide> function isEmpty(value) {
<ide>
<ide> function textInputType(scope, element, attr, ctrl) {
<ide> element.bind('blur', function() {
<del> var touched = ctrl.touch(),
<del> value = trim(element.val());
<del>
<del> if (ctrl.viewValue !== value) {
<del> scope.$apply(function() {
<del> ctrl.setViewValue(value);
<del> });
<del> } else if (touched) {
<del> scope.$apply();
<del> }
<add> scope.$apply(function() {
<add> ctrl.setViewValue(trim(element.val()));
<add> });
<ide> });
<ide>
<ide> ctrl.render = function() {
<ide> function radioInputType(scope, element, attr, ctrl) {
<ide> element.bind('click', function() {
<ide> if (element[0].checked) {
<ide> scope.$apply(function() {
<del> ctrl.touch();
<ide> ctrl.setViewValue(attr.value);
<ide> });
<ide> };
<ide> function checkboxInputType(scope, element, attr, ctrl) {
<ide>
<ide> element.bind('click', function() {
<ide> scope.$apply(function() {
<del> ctrl.touch();
<ide> ctrl.setViewValue(element[0].checked);
<ide> });
<ide> });
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel',
<ide> this.widgetId = $attr.name;
<ide>
<ide>
<del> /**
<del> * @ngdoc function
<del> * @name angular.module.ng.$compileProvider.directive.ng-model.NgModelController#touch
<del> * @methodOf angular.module.ng.$compileProvider.directive.ng-model.NgModelController
<del> *
<del> * @return {boolean} Whether it did change state.
<del> *
<del> * @description
<del> * This method should be called from within a DOM event handler.
<del> * For example {@link angular.module.ng.$compileProvider.directive.input input} or
<del> * {@link angular.module.ng.$compileProvider.directive.select select} directives call it.
<del> *
<del> * It changes state to `dirty` and emits `$viewTouch` event if the state was `pristine` before.
<del> */
<del> this.touch = function() {
<del> if (this.dirty) return false;
<del>
<del> this.dirty = true;
<del> this.pristine = false;
<del> try {
<del> $scope.$emit('$viewTouch');
<del> } catch (e) {
<del> $exceptionHandler(e);
<del> }
<del> return true;
<del> };
<del>
<del>
<ide> /**
<ide> * @ngdoc function
<ide> * @name angular.module.ng.$compileProvider.directive.ng-model.NgModelController#setValidity
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', 'ngModel',
<ide> this.setViewValue = function(value) {
<ide> this.viewValue = value;
<ide>
<add> // change to dirty
<add> if (this.pristine) {
<add> this.dirty = true;
<add> this.pristine = false;
<add> $scope.$emit('$viewTouch', this);
<add> }
<add>
<ide> forEach(this.parsers, function(fn) {
<ide> value = fn(value);
<ide> });
<ide> var ngModelInstantDirective = ['$browser', function($browser) {
<ide> require: 'ngModel',
<ide> link: function(scope, element, attr, ctrl) {
<ide> var handler = function() {
<del> var touched = ctrl.touch(),
<del> value = trim(element.val());
<del>
<del> if (ctrl.viewValue !== value) {
<del> scope.$apply(function() {
<del> ctrl.setViewValue(value);
<del> });
<del> } else if (touched) {
<del> scope.$apply();
<del> }
<add> scope.$apply(function() {
<add> ctrl.setViewValue(trim(element.val()));
<add> });
<ide> };
<ide>
<ide> var timeout;
<ide><path>src/directive/select.js
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide>
<ide> selectElement.bind('change', function() {
<ide> scope.$apply(function() {
<del> ctrl.touch();
<ide> ctrl.setViewValue(selectElement.val());
<ide> });
<ide> });
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> array.push(option.value);
<ide> }
<ide> });
<del> ctrl.touch();
<ide> ctrl.setViewValue(array);
<ide> });
<ide> });
<ide> var selectDirective = ['$compile', '$parse', function($compile, $parse) {
<ide> value = valueFn(scope, locals);
<ide> }
<ide> }
<del> ctrl.touch();
<del>
<del> if (ctrl.viewValue !== value) {
<del> ctrl.setViewValue(value);
<del> }
<add> ctrl.setViewValue(value);
<ide> });
<ide> });
<ide>
<ide><path>test/directive/formSpec.js
<ide> describe('form', function() {
<ide> it('should have ng-pristine/ng-dirty css class', function() {
<ide> expect(doc).toBePristine();
<ide>
<del> widget.touch();
<add> widget.setViewValue('');
<ide> scope.$apply();
<ide> expect(doc).toBeDirty();
<ide> });
<ide><path>test/directive/inputSpec.js
<ide> describe('NgModelController', function() {
<ide> });
<ide>
<ide>
<del> describe('touch', function() {
<del> it('should only fire $viewTouch when pristine', function() {
<del> var spy = jasmine.createSpy('$viewTouch');
<del> scope.$on('$viewTouch', spy);
<del>
<del> ctrl.touch();
<del> expect(ctrl.pristine).toBe(false);
<del> expect(ctrl.dirty).toBe(true);
<del> expect(spy).toHaveBeenCalledOnce();
<del>
<del> spy.reset();
<del> ctrl.touch();
<del> expect(ctrl.pristine).toBe(false);
<del> expect(ctrl.dirty).toBe(true);
<del> expect(spy).not.toHaveBeenCalled();
<del> });
<del> });
<del>
<del>
<ide> describe('setValidity', function() {
<ide>
<ide> it('should emit $invalid only when $valid', function() {
<ide> describe('NgModelController', function() {
<ide> ctrl.setViewValue('val');
<ide> expect(spy).not.toHaveBeenCalled();
<ide> });
<add>
<add>
<add> it('should only fire $viewTouch when pristine', function() {
<add> var spy = jasmine.createSpy('$viewTouch');
<add> scope.$on('$viewTouch', spy);
<add>
<add> ctrl.setViewValue('');
<add> expect(ctrl.pristine).toBe(false);
<add> expect(ctrl.dirty).toBe(true);
<add> expect(spy).toHaveBeenCalledOnce();
<add>
<add> spy.reset();
<add> ctrl.setViewValue('');
<add> expect(ctrl.pristine).toBe(false);
<add> expect(ctrl.dirty).toBe(true);
<add> expect(spy).not.toHaveBeenCalled();
<add> });
<ide> });
<ide>
<ide> | 4 |
Python | Python | add comment to 'at' method unit test | 56d74a4687b8b01ed328896f91b5e42962923122 | <ide><path>numpy/core/tests/test_ufunc.py
<ide> def __rmul__(self, other):
<ide> assert_(MyThing.getitem_count <= 2, MyThing.getitem_count)
<ide>
<ide> def test_inplace_fancy_indexing(self):
<del> # 'at' method is equivalent to a[:,idx] += b
<ide>
<ide> a = np.arange(10)
<ide> indices = np.array([2,5,2]) | 1 |
Text | Text | add additional fix in hydration error document | 1bbd2642164098ceb9cebfb36deba9aed7e8a53b | <ide><path>errors/react-hydration-error.md
<ide> function MyComponent() {
<ide> }
<ide> ```
<ide>
<add>Another example:
<add>
<add>Invalid HTML may cause hydration mismatch such as div inside p.
<add>
<add>```jsx
<add>export const IncorrectComponent = () => {
<add> return (
<add> <p>
<add> <div>
<add> This is not correct and should never be done because the p tag has been
<add> abused
<add> </div>
<add> <Image src="/vercel.svg" alt="" width="30" height="30" />
<add> </p>
<add> )
<add>}
<add>```
<add>
<add>How to fix it:
<add>
<add>```jsx
<add>export const CorrectComponent = () => {
<add> return (
<add> <div>
<add> <div>
<add> This is correct and should work because a div is really good for this
<add> task.
<add> </div>
<add> <Image src="/vercel.svg" alt="" width="30" height="30" />
<add> </div>
<add> )
<add>}
<add>```
<add>
<ide> Common causes with css-in-js libraries:
<ide>
<ide> - When using Styled Components / Emotion | 1 |
Python | Python | use print function in py2.7 to print to stderr | 280156e5e62e23c0ec7e305986b6dcc8bf76c0aa | <ide><path>libcloud/test/compute/test_vcloud.py
<ide> # See the License for the specific language governing permissions and
<ide> # limitations under the License.
<ide>
<add>from __future__ import print_function
<ide> import datetime
<ide> import re
<ide> import sys | 1 |
Python | Python | fix typo in tokenization_auto.py | 0d00c08da0aaa03dc00e2b6dce9574aee3402967 | <ide><path>src/transformers/models/auto/tokenization_auto.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs):
<ide> if type(config.decoder) is not type(config.encoder): # noqa: E721
<ide> logger.warning(
<ide> f"The encoder model config class: {config.encoder.__class__} is different from the decoder model "
<del> f"config class: {config.decoder.__class}. It is not recommended to use the "
<add> f"config class: {config.decoder.__class__}. It is not recommended to use the "
<ide> "`AutoTokenizer.from_pretrained()` method in this case. Please use the encoder and decoder "
<ide> "specific tokenizer classes."
<ide> ) | 1 |
Javascript | Javascript | clarify issue with isolated scope directive | f12c61e984e2fa7f6b225f3567d497f4ad36436d | <ide><path>src/ng/directive/input.js
<ide> var VALID_CLASS = 'ng-valid',
<ide> * purposefully does not contain any logic which deals with DOM rendering or listening to
<ide> * DOM events. Such DOM related logic should be provided by other directives which make use of
<ide> * `NgModelController` for data-binding.
<del> * Note that you cannot use `NgModelController` in a directive with an isolated scope,
<del> * as, in that case, the `ng-model` value gets put into the isolated scope and does not get
<del> * propagated to the parent scope.
<del> *
<ide> *
<add> * ## Custom Control Example
<ide> * This example shows how to use `NgModelController` with a custom control to achieve
<ide> * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
<ide> * collaborate together to achieve the desired result.
<ide> var VALID_CLASS = 'ng-valid',
<ide> </file>
<ide> * </example>
<ide> *
<add> * ## Isolated Scope Pitfall
<add> *
<add> * Note that if you have a directive with an isolated scope, you cannot require `ngModel`
<add> * since the model value will be looked up on the isolated scope rather than the outer scope.
<add> * When the directive updates the model value, calling `ngModel.$setViewValue()` the property
<add> * on the outer scope will not be updated.
<add> *
<add> * Here is an example of this situation. You'll notice that even though both 'input' and 'div'
<add> * seem to be attached to the same model, they are not kept in synch.
<add> *
<add> * <example module="badIsolatedDirective">
<add> <file name="script.js">
<add> angular.module('badIsolatedDirective', []).directive('bad', function() {
<add> return {
<add> require: 'ngModel',
<add> scope: { },
<add> template: '<input ng-model="innerModel">',
<add> link: function(scope, element, attrs, ngModel) {
<add> scope.$watch('innerModel', function(value) {
<add> console.log(value);
<add> ngModel.$setViewValue(value);
<add> });
<add> }
<add> };
<add> });
<add> </file>
<add> <file name="index.html">
<add> <input ng-model="someModel">
<add> <div bad ng-model="someModel"></div>
<add> </file>
<add> * </example>
<add> *
<add> *
<ide> */
<ide> var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
<ide> function($scope, $exceptionHandler, $attr, $element, $parse) { | 1 |
Javascript | Javascript | expose entryplugin creation | 907795fed02cc10b2446f4b4627868c96fbeff3e | <ide><path>lib/EntryOptionPlugin.js
<ide> class EntryOptionPlugin {
<ide> * @returns {void}
<ide> */
<ide> apply(compiler) {
<del> compiler.hooks.entryOption.tap("EntryOptionPlugin", (context, entry) => {
<add> compiler.hooks.entryOption.tap(
<add> "EntryOptionPlugin",
<add> EntryOptionPlugin.newEntryPlugins(compiler)
<add> );
<add> }
<add>
<add> /**
<add> * @param {Compiler} compiler the compiler
<add> * @returns {(context, entry) => Boolean} returns a function for adding EntryPlugins to the target compiler
<add> */
<add> static newEntryPlugins(compiler) {
<add> return function (context, entry) {
<ide> if (typeof entry === "function") {
<ide> const DynamicEntryPlugin = require("./DynamicEntryPlugin");
<ide> new DynamicEntryPlugin(context, entry).apply(compiler);
<ide> class EntryOptionPlugin {
<ide> }
<ide> }
<ide> return true;
<del> });
<add> };
<ide> }
<ide>
<ide> /** | 1 |
Go | Go | add security info to `docker info` | eee20b564ffae0b8c8043115c959f0f9d1869fed | <ide><path>api/client/info.go
<ide> func (cli *DockerCli) CmdInfo(args ...string) error {
<ide> fmt.Fprintf(cli.out, "Default Runtime: %s\n", info.DefaultRuntime)
<ide> }
<ide>
<add> fmt.Fprintf(cli.out, "Security Options:")
<add> ioutils.FprintfIfNotEmpty(cli.out, " %s", strings.Join(info.SecurityOptions, " "))
<add> fmt.Fprintf(cli.out, "\n")
<add>
<ide> ioutils.FprintfIfNotEmpty(cli.out, "Kernel Version: %s\n", info.KernelVersion)
<ide> ioutils.FprintfIfNotEmpty(cli.out, "Operating System: %s\n", info.OperatingSystem)
<ide> ioutils.FprintfIfNotEmpty(cli.out, "OSType: %s\n", info.OSType)
<ide><path>integration-cli/docker_cli_info_test.go
<ide> func (s *DockerSuite) TestInfoEnsureSucceeds(c *check.C) {
<ide> "Storage Driver:",
<ide> "Volume:",
<ide> "Network:",
<add> "Security Options:",
<ide> }
<ide>
<ide> if DaemonIsLinux.Condition() {
<ide><path>integration-cli/docker_cli_info_unix_test.go
<add>// +build !windows
<add>
<add>package main
<add>
<add>import (
<add> "github.com/docker/docker/pkg/integration/checker"
<add> "github.com/go-check/check"
<add>)
<add>
<add>func (s *DockerSuite) TestInfoSecurityOptions(c *check.C) {
<add> testRequires(c, SameHostDaemon, seccompEnabled, Apparmor, DaemonIsLinux)
<add>
<add> out, _ := dockerCmd(c, "info")
<add> c.Assert(out, checker.Contains, "Security Options: apparmor seccomp")
<add>} | 3 |
Text | Text | improve the clarity on a challenge sentence | 2c1280af65199eb41bc9b2df1e0e2a61ce4ab32f | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/passing-values-to-functions-with-arguments.md
<ide> function testFun(param1, param2) {
<ide> }
<ide> ```
<ide>
<del>Then we can call `testFun`: `testFun("Hello", "World");` We have passed two arguments, `"Hello"` and `"World"`. Inside the function, `param1` will equal "Hello" and `param2` will equal "World". Note that you could call `testFun` again with different arguments and the parameters would take on the value of the new arguments.
<add>Then we can call `testFun` like this: `testFun("Hello", "World");`. We have passed two string arguments, `Hello` and `World`. Inside the function, `param1` will equal the string `Hello` and `param2` will equal the string `World`. Note that you could call `testFun` again with different arguments and the parameters would take on the value of the new arguments.
<ide>
<ide> # --instructions--
<ide> | 1 |
Ruby | Ruby | add timeout to test_async_stream | 28348e068151cd144da28a87d63853a328e393e7 | <ide><path>actionpack/test/controller/live_stream_test.rb
<ide> def test_async_stream
<ide>
<ide> @controller.process :blocking_stream
<ide>
<del> assert t.join
<add> assert t.join(3), 'timeout expired before the thread terminated'
<ide> end
<ide>
<ide> def test_thread_locals_get_copied | 1 |
Go | Go | remove redundant filepath.base() | 73f0b01da18a53be2d86dce540d680a226d77946 | <ide><path>volume/local/local.go
<ide> func New(scope string, rootIdentity idtools.Identity) (*Root, error) {
<ide> continue
<ide> }
<ide>
<del> name := filepath.Base(d.Name())
<add> name := d.Name()
<ide> v := &localVolume{
<ide> driverName: r.Name(),
<ide> name: name, | 1 |
Python | Python | handle subarrays in descr_to_dtype | 666d92ac85a6adf0fec7361c3340fc6ab12c8330 | <ide><path>numpy/lib/format.py
<ide> def dtype_to_descr(dtype):
<ide> def descr_to_dtype(descr):
<ide> '''
<ide> descr may be stored as dtype.descr, which is a list of
<del> (name, format, [shape]) tuples. Offsets are not explicitly saved, rather
<del> empty fields with name,format == '', '|Vn' are added as padding.
<add> (name, format, [shape]) tuples where format may be a str or a tuple.
<add> Offsets are not explicitly saved, rather empty fields with
<add> name, format == '', '|Vn' are added as padding.
<ide>
<ide> This function reverses the process, eliminating the empty padding fields.
<ide> '''
<del> if isinstance(descr, (str, dict)):
<add> if isinstance(descr, (str, dict, tuple)):
<ide> # No padding removal needed
<ide> return numpy.dtype(descr)
<ide>
<ide><path>numpy/lib/tests/test_format.py
<ide> def teardown_module():
<ide> np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')),
<ide> np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')),
<ide> np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')),
<add> np.zeros(1, dtype=[('c', ('<f8', (5,)), (2,))])
<ide> ]
<ide>
<ide> | 2 |
Ruby | Ruby | remove some test warnings | ff86da4f930c290942bfcf1896eaee24fec0377b | <ide><path>test/test_insert_manager.rb
<ide> module Arel
<ide>
<ide> describe 'insert' do
<ide> it 'can create a Values node' do
<del> table = Table.new(:users)
<ide> manager = Arel::InsertManager.new Table.engine
<ide> values = manager.create_values %w{ a b }, %w{ c d }
<ide>
<ide> module Arel
<ide> end
<ide>
<ide> it 'allows sql literals' do
<del> table = Table.new(:users)
<ide> manager = Arel::InsertManager.new Table.engine
<ide> manager.values = manager.create_values [Arel.sql('*')], %w{ a }
<ide> manager.to_sql.must_be_like %{
<ide><path>test/test_select_manager.rb
<ide> def test_join_sources
<ide> end
<ide>
<ide> it 'returns string join sql' do
<del> table = Table.new :users
<ide> manager = Arel::SelectManager.new Table.engine
<ide> manager.from Nodes::StringJoin.new('hello')
<ide> manager.join_sql.must_be_like %{ 'hello' }
<ide> def test_join_sources
<ide>
<ide> describe 'source' do
<ide> it 'returns the join source of the select core' do
<del> table = Table.new :users
<ide> manager = Arel::SelectManager.new Table.engine
<ide> manager.source.must_equal manager.ast.cores.last.source
<ide> end
<ide> end
<ide>
<ide> describe 'distinct' do
<ide> it 'sets the quantifier' do
<del> table = Table.new :users
<ide> manager = Arel::SelectManager.new Table.engine
<ide>
<ide> manager.distinct | 2 |
PHP | PHP | fix auth | b65cf424d6bf8f820a9ab97c02551e56dde769ff | <ide><path>src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php
<ide> public function actingAs(UserContract $user, $driver = null)
<ide> */
<ide> public function be(UserContract $user, $driver = null)
<ide> {
<add> if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) {
<add> $user->wasRecentlyCreated = false;
<add> }
<add>
<ide> $this->app['auth']->guard($driver)->setUser($user);
<ide>
<ide> $this->app['auth']->shouldUse($driver); | 1 |
Javascript | Javascript | clarify inline template | 5d7763ebf999abd95eaedc83b081ff023008261b | <ide><path>src/ng/cacheFactory.js
<ide> function $CacheFactoryProvider() {
<ide> * ```
<ide> *
<ide> * **Note:** the `script` tag containing the template does not need to be included in the `head` of
<del> * the document, but it must be below the `ng-app` definition.
<add> * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
<add> * element with ng-app attribute), otherwise the template will be ignored.
<ide> *
<ide> * Adding via the $templateCache service:
<ide> * | 1 |
Python | Python | change httplib name for python 3.4 - issue #419 | 57569b23f326647f567a8668a910148f8239457c | <ide><path>glances/core/glances_client.py
<ide> import sys
<ide> try:
<ide> from xmlrpc.client import Transport, ServerProxy, ProtocolError, Fault
<del>except ImportError: # Python 2
<add>except ImportError:
<add> # Python 2
<ide> from xmlrpclib import Transport, ServerProxy, ProtocolError, Fault
<del>import httplib
<add>try:
<add> import http.client as httplib
<add>except:
<add> # Python 2
<add> import httplib
<ide>
<ide> # Import Glances libs
<ide> from glances.core.glances_globals import version, logger | 1 |
Java | Java | introduce tests for @nested tests in junit jupiter | e574820dc92d44cbeff18e1041e1575c8ee0ff54 | <ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/NestedTestsWithSpringAndJUnitJupiterTestCase.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.test.context.junit.jupiter.nested;
<add>
<add>import org.junit.jupiter.api.Nested;
<add>import org.junit.jupiter.api.Test;
<add>
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.test.context.junit.jupiter.SpringExtension;
<add>import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
<add>import org.springframework.test.context.junit.jupiter.nested.NestedTestsWithSpringAndJUnitJupiterTestCase.TopLevelConfig;
<add>
<add>import static org.junit.jupiter.api.Assertions.assertEquals;
<add>
<add>/**
<add> * Integration tests that verify support for {@code @Nested} test classes
<add> * in conjunction with the {@link SpringExtension} in a JUnit 5 (Jupiter)
<add> * environment.
<add> *
<add> * @author Sam Brannen
<add> * @since 5.0
<add> * @see org.springframework.test.context.junit4.nested.NestedTestsWithSpringRulesTests
<add> */
<add>@SpringJUnitConfig(TopLevelConfig.class)
<add>class NestedTestsWithSpringAndJUnitJupiterTestCase {
<add>
<add> @Autowired
<add> String foo;
<add>
<add>
<add> @Test
<add> void topLevelTest() {
<add> assertEquals("foo", foo);
<add> }
<add>
<add>
<add> @Nested
<add> @SpringJUnitConfig(NestedConfig.class)
<add> class NestedTestCase {
<add>
<add> @Autowired
<add> String bar;
<add>
<add>
<add> @Test
<add> void nestedTest() throws Exception {
<add> // In contrast to nested test classes running in JUnit 4, the foo
<add> // field in the outer instance should have been injected from the
<add> // test ApplicationContext for the outer instance.
<add> assertEquals("foo", foo);
<add> assertEquals("bar", bar);
<add> }
<add> }
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @Configuration
<add> public static class TopLevelConfig {
<add>
<add> @Bean
<add> String foo() {
<add> return "foo";
<add> }
<add> }
<add>
<add> @Configuration
<add> static class NestedConfig {
<add>
<add> @Bean
<add> String bar() {
<add> return "bar";
<add> }
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit4/nested/NestedTestsWithSpringRulesTests.java
<ide> *
<ide> * @author Sam Brannen
<ide> * @since 5.0
<add> * @see org.springframework.test.context.junit.jupiter.nested.NestedTestsWithSpringAndJUnitJupiterTestCase
<ide> */
<ide> @RunWith(HierarchicalContextRunner.class)
<ide> @ContextConfiguration(classes = TopLevelConfig.class) | 2 |
Javascript | Javascript | fix error diff | e4ec4f2656f14d3992da154c46f6c0c44025f30d | <ide><path>lib/internal/assert/assertion_error.js
<ide> function inspectValue(val) {
<ide> maxArrayLength: Infinity,
<ide> // Assert compares only enumerable properties (with a few exceptions).
<ide> showHidden: false,
<del> // Having a long line as error is better than wrapping the line for
<del> // comparison for now.
<del> // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we
<del> // have meta information about the inspected properties (i.e., know where
<del> // in what line the property starts and ends).
<del> breakLength: Infinity,
<ide> // Assert does not detect proxies currently.
<ide> showProxy: false,
<ide> sorted: true,
<ide> // Inspect getters as we also check them when comparing entries.
<del> getters: true
<add> getters: true,
<ide> }
<ide> );
<ide> }
<ide>
<ide> function createErrDiff(actual, expected, operator) {
<ide> let other = '';
<ide> let res = '';
<del> let lastPos = 0;
<ide> let end = '';
<ide> let skipped = false;
<ide> const actualInspected = inspectValue(actual);
<ide> function createErrDiff(actual, expected, operator) {
<ide> }
<ide>
<ide> let printedLines = 0;
<add> let identical = 0;
<ide> const msg = kReadableOperator[operator] +
<ide> `\n${green}+ actual${white} ${red}- expected${white}`;
<ide> const skippedMsg = ` ${blue}...${white} Lines skipped`;
<ide>
<ide> for (i = 0; i < maxLines; i++) {
<del> // Only extra expected lines exist
<del> const cur = i - lastPos;
<ide> if (actualLines.length < i + 1) {
<del> // If the last diverging line is more than one line above and the
<del> // current line is at least line three, add some of the former lines and
<del> // also add dots to indicate skipped entries.
<del> if (cur > 1 && i > 2) {
<del> if (cur > 4) {
<add> // If more than one former line is identical, print that. Collapse those
<add> // in case more than three lines before were identical.
<add> if (identical > 1) {
<add> if (identical > 3) {
<ide> res += `\n${blue}...${white}`;
<ide> skipped = true;
<del> } else if (cur > 3) {
<add> } else if (identical > 2) {
<ide> res += `\n ${expectedLines[i - 2]}`;
<ide> printedLines++;
<ide> }
<ide> res += `\n ${expectedLines[i - 1]}`;
<ide> printedLines++;
<ide> }
<del> // Mark the current line as the last diverging one.
<del> lastPos = i;
<add> // No identical lines before.
<add> identical = 0;
<ide> // Add the expected line to the cache.
<ide> other += `\n${red}-${white} ${expectedLines[i]}`;
<ide> printedLines++;
<ide> // Only extra actual lines exist
<ide> } else if (expectedLines.length < i + 1) {
<del> // If the last diverging line is more than one line above and the
<del> // current line is at least line three, add some of the former lines and
<del> // also add dots to indicate skipped entries.
<del> if (cur > 1 && i > 2) {
<del> if (cur > 4) {
<add> // If more than one former line is identical, print that. Collapse those
<add> // in case more than three lines before were identical.
<add> if (identical > 1) {
<add> if (identical > 3) {
<ide> res += `\n${blue}...${white}`;
<ide> skipped = true;
<del> } else if (cur > 3) {
<add> } else if (identical > 2) {
<ide> res += `\n ${actualLines[i - 2]}`;
<ide> printedLines++;
<ide> }
<ide> res += `\n ${actualLines[i - 1]}`;
<ide> printedLines++;
<ide> }
<del> // Mark the current line as the last diverging one.
<del> lastPos = i;
<add> // No identical lines before.
<add> identical = 0;
<ide> // Add the actual line to the result.
<ide> res += `\n${green}+${white} ${actualLines[i]}`;
<ide> printedLines++;
<ide> function createErrDiff(actual, expected, operator) {
<ide> actualLine += ',';
<ide> }
<ide> if (divergingLines) {
<del> // If the last diverging line is more than one line above and the
<del> // current line is at least line three, add some of the former lines and
<del> // also add dots to indicate skipped entries.
<del> if (cur > 1 && i > 2) {
<del> if (cur > 4) {
<add> // If more than one former line is identical, print that. Collapse those
<add> // in case more than three lines before were identical.
<add> if (identical > 1) {
<add> if (identical > 3) {
<ide> res += `\n${blue}...${white}`;
<ide> skipped = true;
<del> } else if (cur > 3) {
<add> } else if (identical > 2) {
<ide> res += `\n ${actualLines[i - 2]}`;
<ide> printedLines++;
<ide> }
<ide> res += `\n ${actualLines[i - 1]}`;
<ide> printedLines++;
<ide> }
<del> // Mark the current line as the last diverging one.
<del> lastPos = i;
<add> // No identical lines before.
<add> identical = 0;
<ide> // Add the actual line to the result and cache the expected diverging
<ide> // line so consecutive diverging lines show up as +++--- and not +-+-+-.
<ide> res += `\n${green}+${white} ${actualLine}`;
<ide> function createErrDiff(actual, expected, operator) {
<ide> // and reset the cache.
<ide> res += other;
<ide> other = '';
<del> // If the last diverging line is exactly one line above or if it is the
<del> // very first line, add the line to the result.
<del> if (cur === 1 || i === 0) {
<add> identical++;
<add> // The very first identical line since the last diverging line is be
<add> // added to the result.
<add> if (identical === 1) {
<ide> res += `\n ${actualLine}`;
<ide> printedLines++;
<ide> }
<ide> class AssertionError extends Error {
<ide> if (process.stderr.isTTY) {
<ide> // Reset on each call to make sure we handle dynamically set environment
<ide> // variables correct.
<del> if (process.stderr.getColorDepth() !== 1) {
<add> if (process.stderr.hasColors()) {
<ide> blue = '\u001b[34m';
<ide> green = '\u001b[32m';
<ide> white = '\u001b[39m';
<ide><path>test/parallel/test-assert-deep.js
<ide> assert.deepEqual(arr, buf);
<ide> code: 'ERR_ASSERTION',
<ide> message: `${defaultMsgStartFull} ... Lines skipped\n\n` +
<ide> ' Buffer [Uint8Array] [\n' +
<del> ' 120,\n' +
<ide> '...\n' +
<ide> ' 10,\n' +
<ide> '+ prop: 1\n' +
<ide> assert.deepEqual(arr, buf);
<ide> code: 'ERR_ASSERTION',
<ide> message: `${defaultMsgStartFull} ... Lines skipped\n\n` +
<ide> ' Uint8Array [\n' +
<del> ' 120,\n' +
<ide> '...\n' +
<ide> ' 10,\n' +
<ide> '- prop: 5\n' +
<ide> assert.deepStrictEqual(obj1, obj2);
<ide> const a = new TypeError('foo');
<ide> const b = new TypeError('foo');
<ide> a.foo = 'bar';
<del> b.foo = 'baz';
<add> b.foo = 'baz.';
<ide>
<ide> assert.throws(
<del> () => assert.deepStrictEqual(a, b),
<add> () => assert.throws(
<add> () => assert.deepStrictEqual(a, b),
<add> {
<add> operator: 'throws',
<add> message: `${defaultMsgStartFull}\n\n` +
<add> ' [TypeError: foo] {\n+ foo: \'bar\'\n- foo: \'baz\'\n }',
<add> }
<add> ),
<ide> {
<del> message: `${defaultMsgStartFull}\n\n` +
<del> ' [TypeError: foo] {\n+ foo: \'bar\'\n- foo: \'baz\'\n }'
<add> message: 'Expected values to be strictly deep-equal:\n' +
<add> '+ actual - expected ... Lines skipped\n' +
<add> '\n' +
<add> ' Comparison {\n' +
<add> '...\n' +
<add> " \"+ foo: 'bar'\\n\" +\n" +
<add> "+ \"- foo: 'baz.'\\n\" +\n" +
<add> "- \"- foo: 'baz'\\n\" +\n" +
<add> " ' }',\n" +
<add> "+ operator: 'deepStrictEqual'\n" +
<add> "- operator: 'throws'\n" +
<add> ' }'
<ide> }
<ide> );
<ide> } | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.