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 |
|---|---|---|---|---|---|
Ruby | Ruby | remove warning from integer ext test | 90f3c28820fa126ccab4635868c9b69cc9ef2cef | <ide><path>activesupport/test/core_ext/integer_ext_test.rb
<ide> def test_ordinal
<ide> def test_positive
<ide> assert 1.positive?
<ide> assert_not 0.positive?
<del> assert_not -1.positive?
<add> assert_not(-1.positive?)
<ide> end
<ide>
<ide> def test_negative
<del> assert -1.negative?
<add> assert(-1.negative?)
<ide> assert_not 0.negative?
<ide> assert_not 1.negative?
<ide> end | 1 |
Mixed | Ruby | remove deprecation warning from attribute_missing | 0d4075fb47db388f1365ce4784401fa4454a2499 | <ide><path>activerecord/CHANGELOG.md
<add>* Remove deprecation warning from `attribute_missing` for attributes that are columns.
<add>
<add> *Arun Agrawal*
<add>
<ide> * Remove extra decrement of transaction deep level.
<ide>
<ide> Fixes: #4566
<ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def method_missing(method, *args, &block) # :nodoc:
<ide> end
<ide> end
<ide>
<del> def attribute_missing(match, *args, &block) # :nodoc:
<del> if self.class.columns_hash[match.attr_name]
<del> ActiveSupport::Deprecation.warn(
<del> "The method `#{match.method_name}', matching the attribute `#{match.attr_name}' has " \
<del> "dispatched through method_missing. This shouldn't happen, because `#{match.attr_name}' " \
<del> "is a column of the table. If this error has happened through normal usage of Active " \
<del> "Record (rather than through your own code or external libraries), please report it as " \
<del> "a bug."
<del> )
<del> end
<del>
<del> super
<del> end
<del>
<ide> # A Person object with a name attribute can ask <tt>person.respond_to?(:name)</tt>,
<ide> # <tt>person.respond_to?(:name=)</tt>, and <tt>person.respond_to?(:name?)</tt>
<ide> # which will all return +true+. It also define the attribute methods if they have
<ide><path>activerecord/test/cases/attribute_methods_test.rb
<ide> def test_instance_method_should_be_defined_on_the_base_class
<ide> assert subklass.method_defined?(:id), "subklass is missing id method"
<ide> end
<ide>
<del> def test_dispatching_column_attributes_through_method_missing_deprecated
<del> Topic.define_attribute_methods
<del>
<del> topic = Topic.new(:id => 5)
<del> topic.id = 5
<del>
<del> topic.method(:id).owner.send(:undef_method, :id)
<del>
<del> assert_deprecated do
<del> assert_equal 5, topic.id
<del> end
<del> ensure
<del> Topic.undefine_attribute_methods
<del> end
<del>
<ide> def test_read_attribute_with_nil_should_not_asplode
<ide> assert_equal nil, Topic.new.read_attribute(nil)
<ide> end | 3 |
Javascript | Javascript | use module.exports = {} on internal/readline | 392a8987c62f0c54de9036659853467b48f113cd | <ide><path>lib/internal/readline.js
<ide> const ansi =
<ide> /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g;
<ide>
<del>
<del>module.exports = {
<del> emitKeys,
<del> stripVTControlCharacters
<del>};
<add>var getStringWidth;
<add>var isFullWidthCodePoint;
<ide>
<ide> if (process.binding('config').hasIntl) {
<ide> const icu = process.binding('icu');
<del> module.exports.getStringWidth = function getStringWidth(str, options) {
<add> getStringWidth = function getStringWidth(str, options) {
<ide> options = options || {};
<ide> if (!Number.isInteger(str))
<ide> str = stripVTControlCharacters(String(str));
<ide> return icu.getStringWidth(str,
<ide> Boolean(options.ambiguousAsFullWidth),
<ide> Boolean(options.expandEmojiSequence));
<ide> };
<del> module.exports.isFullWidthCodePoint =
<add> isFullWidthCodePoint =
<ide> function isFullWidthCodePoint(code, options) {
<ide> if (typeof code !== 'number')
<ide> return false;
<ide> if (process.binding('config').hasIntl) {
<ide> /**
<ide> * Returns the number of columns required to display the given string.
<ide> */
<del> module.exports.getStringWidth = function getStringWidth(str) {
<add> getStringWidth = function getStringWidth(str) {
<ide> if (Number.isInteger(str))
<del> return module.exports.isFullWidthCodePoint(str) ? 2 : 1;
<add> return isFullWidthCodePoint(str) ? 2 : 1;
<ide>
<ide> let width = 0;
<ide>
<ide> if (process.binding('config').hasIntl) {
<ide> i++;
<ide> }
<ide>
<del> if (module.exports.isFullWidthCodePoint(code)) {
<add> if (isFullWidthCodePoint(code)) {
<ide> width += 2;
<ide> } else {
<ide> width++;
<ide> if (process.binding('config').hasIntl) {
<ide> * Returns true if the character represented by a given
<ide> * Unicode code point is full-width. Otherwise returns false.
<ide> */
<del> module.exports.isFullWidthCodePoint = function isFullWidthCodePoint(code) {
<add> isFullWidthCodePoint = function isFullWidthCodePoint(code) {
<ide> if (!Number.isInteger(code)) {
<ide> return false;
<ide> }
<ide> function* emitKeys(stream) {
<ide> /* Unrecognized or broken escape sequence, don't emit anything */
<ide> }
<ide> }
<add>
<add>module.exports = {
<add> emitKeys,
<add> getStringWidth,
<add> isFullWidthCodePoint,
<add> stripVTControlCharacters
<add>}; | 1 |
PHP | PHP | apply fixes from styleci | 315baf73daac7fb005d2135f37dc4bbf96e1062c | <ide><path>src/Illuminate/View/Factory.php
<ide> public function first(array $views, $data = [], $mergeData = [])
<ide> });
<ide>
<ide> if (! $view) {
<del> throw new InvalidArgumentException("None of the views in the given array exist.");
<add> throw new InvalidArgumentException('None of the views in the given array exist.');
<ide> }
<ide>
<ide> return $this->make($view, $data, $mergeData); | 1 |
PHP | PHP | fix path to cafile.pem | 751b8def11796e8e5a5b735f24a1a3755b2b9e55 | <ide><path>src/Network/Socket.php
<ide> protected function _setSslContext($host)
<ide> }
<ide> }
<ide> if (empty($this->_config['context']['ssl']['cafile'])) {
<del> $dir = dirname(__DIR__);
<add> $dir = dirname(dirname(__DIR__));
<ide> $this->_config['context']['ssl']['cafile'] = $dir . DIRECTORY_SEPARATOR .
<ide> 'config' . DIRECTORY_SEPARATOR . 'cacert.pem';
<ide> } | 1 |
Ruby | Ruby | add tests for symbols passed to polymorphic_url | bfcbd6fd4cf5f60d8de3824355e0348b0fc91637 | <ide><path>actionview/test/activerecord/polymorphic_routes_test.rb
<ide> def test_string_with_options
<ide> end
<ide> end
<ide>
<add> def test_symbol
<add> with_test_routes do
<add> assert_equal "http://example.com/projects", polymorphic_url(:projects)
<add> end
<add> end
<add>
<add> def test_symbol_with_options
<add> with_test_routes do
<add> assert_equal "http://example.com/projects?id=10", polymorphic_url(:projects, :id => 10)
<add> end
<add> end
<add>
<ide> def test_passing_routes_proxy
<ide> with_namespaced_routes(:blog) do
<ide> proxy = ActionDispatch::Routing::RoutesProxy.new(_routes, self) | 1 |
Text | Text | add angular logo | b688afcf7d23b6fe29822bbd6f2c69c2c2f733c1 | <ide><path>guide/english/angular/index.md
<ide> title: Angular
<ide>
<ide>
<ide> ## Angular
<add>
<ide>
<ide> AngularJS (versions 1.x) is a JavaScript based open source Framework. It is cross platform and used to develop Single Page Web Application (SPWA). AngularJS implements the MVC pattern to separate the logic , presentation and data components. It also uses dependency injection to make use of server-side services in client side applications.
<ide> | 1 |
Ruby | Ruby | drop pointless string split | dae83fc89586938ca6bebcf22c1c38022bb91303 | <ide><path>Library/Homebrew/exceptions.rb
<ide> def dump
<ide> puts
<ide> puts "#{Tty.red}READ THIS#{Tty.reset}: #{Tty.em}#{ISSUES_URL}#{Tty.reset}"
<ide> if formula.tap?
<del> user, repo = formula.tap.split '/'
<del> tap_issues_url = "https://github.com/#{user}/#{repo}/issues"
<add> tap_issues_url = "https://github.com/#{f.tap}/issues"
<ide> puts "If reporting this issue please do so at (not Homebrew/homebrew):"
<ide> puts " #{tap_issues_url}"
<ide> end | 1 |
Python | Python | add test for multilevel | 3f3135bb5c2413a6b2207e58d523f1f9c44e1849 | <ide><path>research/object_detection/meta_architectures/faster_rcnn_meta_arch_test_lib.py
<ide> def get_box_classifier_feature_extractor_model(self, name):
<ide> 3, kernel_size=1, padding='SAME', name=name + '_layer2')])
<ide>
<ide>
<add>class FakeFasterRCNNKerasMultilevelFeatureExtractor(
<add> faster_rcnn_meta_arch.FasterRCNNKerasFeatureExtractor):
<add> """Fake feature extractor to use in tests."""
<add>
<add> def __init__(self):
<add> super(FakeFasterRCNNKerasMultilevelFeatureExtractor, self).__init__(
<add> is_training=False,
<add> first_stage_features_stride=32,
<add> weight_decay=0.0)
<add>
<add> def preprocess(self, resized_inputs):
<add> return tf.identity(resized_inputs)
<add>
<add> def get_proposal_feature_extractor_model(self, name):
<add>
<add> class ProposalFeatureExtractor(tf.keras.Model):
<add> """Dummy proposal feature extraction."""
<add>
<add> def __init__(self, name):
<add> super(ProposalFeatureExtractor, self).__init__(name=name)
<add> self.conv = None
<add>
<add> def build(self, input_shape):
<add> self.conv = tf.keras.layers.Conv2D(
<add> 3, kernel_size=3, name='layer1')
<add> self.conv_1 = tf.keras.layers.Conv2D(
<add> 3, kernel_size=3, name='layer1')
<add>
<add> def call(self, inputs):
<add> output_1 = self.conv(inputs)
<add> output_2 = self.conv_1(output_1)
<add> return [output_1, output_2]
<add>
<add> return ProposalFeatureExtractor(name=name)
<add>
<add>
<ide> class FasterRCNNMetaArchTestBase(test_case.TestCase, parameterized.TestCase):
<ide> """Base class to test Faster R-CNN and R-FCN meta architectures."""
<ide>
<ide> def _build_model(self,
<ide> calibration_mapping_value=None,
<ide> share_box_across_classes=False,
<ide> return_raw_detections_during_predict=False,
<del> output_final_box_features=False):
<add> output_final_box_features=False,
<add> multi_level=False):
<ide> use_keras = tf_version.is_tf2()
<ide> def image_resizer_fn(image, masks=None):
<ide> """Fake image resizer function."""
<ide> def image_resizer_fn(image, masks=None):
<ide> use_matmul_gather=use_matmul_gather_in_matcher)
<ide>
<ide> if use_keras:
<del> fake_feature_extractor = FakeFasterRCNNKerasFeatureExtractor()
<add> if multi_level:
<add> fake_feature_extractor = FakeFasterRCNNKerasMultilevelFeatureExtractor()
<add> else:
<add> fake_feature_extractor = FakeFasterRCNNKerasFeatureExtractor()
<ide> else:
<ide> fake_feature_extractor = FakeFasterRCNNFeatureExtractor()
<ide>
<ide> def graph_fn(images):
<ide> self.assertTrue(np.all(np.less_equal(anchors[:, 2], height)))
<ide> self.assertTrue(np.all(np.less_equal(anchors[:, 3], width)))
<ide>
<add> def test_predict_shape_in_inference_mode_first_stage_only_multi_level(
<add> self, use_static_shapes=False):
<add> batch_size = 2
<add> height = 10
<add> width = 12
<add> input_image_shape = (batch_size, height, width, 3)
<add>
<add> with test_utils.GraphContextOrNone() as g:
<add> model = self._build_model(
<add> is_training=False,
<add> number_of_stages=1,
<add> second_stage_batch_size=2,
<add> clip_anchors_to_image=use_static_shapes,
<add> use_static_shapes=use_static_shapes,
<add> multi_level=True)
<add> def graph_fn(images):
<add> """Function to construct tf graph for the test."""
<add>
<add> preprocessed_inputs, true_image_shapes = model.preprocess(images)
<add> prediction_dict = model.predict(preprocessed_inputs, true_image_shapes)
<add> return (prediction_dict['rpn_box_predictor_features'][0],
<add> prediction_dict['rpn_box_predictor_features'][1],
<add> prediction_dict['rpn_features_to_crop'][0],
<add> prediction_dict['rpn_features_to_crop'][1],
<add> prediction_dict['image_shape'],
<add> prediction_dict['rpn_box_encodings'],
<add> prediction_dict['rpn_objectness_predictions_with_background'],
<add> prediction_dict['anchors'])
<add>
<add> images = np.zeros(input_image_shape, dtype=np.float32)
<add>
<add> # In inference mode, anchors are clipped to the image window, but not
<add> # pruned. Since MockFasterRCNN.extract_proposal_features returns a
<add> # tensor with the same shape as its input, the expected number of anchors
<add> # is height * width * the number of anchors per location (i.e. 3x3).
<add> expected_num_anchors = height * width * 3 * 3
<add> expected_output_shapes = {
<add> 'rpn_box_predictor_features_0': (batch_size, height-2, width-2, 512),
<add> 'rpn_box_predictor_features_1': (batch_size, height-4, width-4, 512),
<add> 'rpn_features_to_crop_0': (batch_size, height-2, width-2, 3),
<add> 'rpn_features_to_crop_1': (batch_size, height-4, width-4, 3),
<add> 'rpn_box_encodings': (batch_size, expected_num_anchors, 4),
<add> 'rpn_objectness_predictions_with_background':
<add> (batch_size, expected_num_anchors, 2),
<add> 'anchors': (expected_num_anchors, 4)
<add> }
<add> print(expected_output_shapes)
<add>
<add> if use_static_shapes:
<add> results = self.execute(graph_fn, [images], graph=g)
<add> else:
<add> results = self.execute_cpu(graph_fn, [images], graph=g)
<add> print(results)
<add> self.assertAllEqual(0, 1)
<add>
<add> self.assertAllEqual(results[0].shape,
<add> expected_output_shapes['rpn_box_predictor_features_0'])
<add> self.assertAllEqual(results[1].shape,
<add> expected_output_shapes['rpn_box_predictor_features_1'])
<add> self.assertAllEqual(results[2].shape,
<add> expected_output_shapes['rpn_features_to_crop_0'])
<add> self.assertAllEqual(results[3].shape,
<add> expected_output_shapes['rpn_features_to_crop_1'])
<add> self.assertAllEqual(results[4],
<add> input_image_shape)
<add> self.assertAllEqual(results[5].shape,
<add> expected_output_shapes['rpn_box_encodings'])
<add> self.assertAllEqual(
<add> results[6].shape,
<add> expected_output_shapes['rpn_objectness_predictions_with_background'])
<add> self.assertAllEqual(results[7].shape,
<add> expected_output_shapes['anchors'])
<add>
<add> # Check that anchors are clipped to window.
<add> anchors = results[5]
<add> self.assertTrue(np.all(np.greater_equal(anchors, 0)))
<add> self.assertTrue(np.all(np.less_equal(anchors[:, 0], height)))
<add> self.assertTrue(np.all(np.less_equal(anchors[:, 1], width)))
<add> self.assertTrue(np.all(np.less_equal(anchors[:, 2], height)))
<add> self.assertTrue(np.all(np.less_equal(anchors[:, 3], width)))
<add>
<ide> def test_regularization_losses(self):
<ide> with test_utils.GraphContextOrNone() as g:
<ide> model = self._build_model( | 1 |
Go | Go | add test for cgroup parent flag for build | f40dd69c97a5a3797f07d52fe5f76e296ef629dc | <ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
<ide> }
<ide>
<ide> }
<add>
<add>func TestBuildContainerWithCgroupParent(t *testing.T) {
<add> testRequires(t, NativeExecDriver)
<add> defer deleteImages()
<add>
<add> cgroupParent := "test"
<add> data, err := ioutil.ReadFile("/proc/self/cgroup")
<add> if err != nil {
<add> t.Fatalf("failed to read '/proc/self/cgroup - %v", err)
<add> }
<add> selfCgroupPaths := parseCgroupPaths(string(data))
<add> _, found := selfCgroupPaths["memory"]
<add> if !found {
<add> t.Fatalf("unable to find self cpu cgroup path. CgroupsPath: %v", selfCgroupPaths)
<add> }
<add> cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent , "-")
<add> cmd.Stdin = strings.NewReader(`
<add>FROM busybox
<add>RUN cat /proc/self/cgroup
<add>`)
<add>
<add> out, _, err := runCommandWithOutput(cmd)
<add> if err != nil {
<add> t.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
<add> }
<add> logDone("build - cgroup parent")
<add>} | 1 |
PHP | PHP | allow mocking protected methods on facades | 8a2a2d5d9102ecab0cd4a69ffc073f09f03760e1 | <ide><path>src/Illuminate/Support/Facades/Facade.php
<ide> protected static function createFreshMockInstance($name)
<ide> {
<ide> static::$resolvedInstance[$name] = $mock = static::createMockByName($name);
<ide>
<add> $mock->shouldAllowMockingProtectedMethods();
<add>
<ide> if (isset(static::$app)) {
<ide> static::$app->instance($name, $mock);
<ide> } | 1 |
Text | Text | provide example for media query | 9a95f232e1e5d698342d07fad095f0560541da32 | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-responsive-web-design-by-building-a-piano/612ec19d5268da7074941f84.md
<ide> dashedName: step-32
<ide>
<ide> # --description--
<ide>
<del>Add another `@media` rule to apply if the browser window is bigger than `769px` but smaller than `1199px`.
<add>Logical operators can be used to construct more complex media queries. The `and` logical operator is used to query two media conditions.
<add>
<add>For example, a media query that targets a display width between 500px and 1000px would be:
<add>
<add>```
<add>@media (min-width: 500px) and (max-width: 1000px){
<add>
<add>}
<add>```
<add>
<add>Add another `@media` rule to apply if the browser window is wider than `769px` but smaller than `1199px`.
<ide>
<ide> # --hints--
<ide> | 1 |
Python | Python | fix issues with target assigner for pr | de3a34b1a0213cc8d6d6dc0931b0f9924cdc5456 | <ide><path>research/object_detection/core/region_similarity_calculator.py
<ide> def _compare(self, boxlist1, boxlist2):
<ide> """
<ide> groundtruth_labels = boxlist1.get_field(fields.BoxListFields.classes)
<ide> predicted_labels = boxlist2.get_field(fields.BoxListFields.classes)
<add> # Currently supporting only softmax
<ide> classification_scores = tf.matmul(groundtruth_labels,
<del> tf.nn.softmax(predicted_labels), transpose_b=True)
<add> predicted_labels,
<add> transpose_b=True)
<ide> return -self.l1_weight * box_list_ops.l1(
<ide> boxlist1, boxlist2) + self.giou_weight * box_list_ops.giou(
<del> boxlist1, boxlist2) + classification_scores
<add> boxlist1, boxlist2) + classification_scores
<ide>
<ide>
<ide> class NegSqDistSimilarity(RegionSimilarityCalculator):
<ide><path>research/object_detection/core/target_assigner.py
<ide> def __init__(self):
<ide> self._matcher = hungarian_matcher.HungarianBipartiteMatcher()
<ide>
<ide> def batch_assign(self,
<del> pred_boxes_batch,
<add> pred_box_batch,
<ide> gt_box_batch,
<del> class_predictions,
<add> pred_class_batch,
<ide> gt_class_targets_batch,
<ide> gt_weights_batch=None):
<del>
<add>
<ide> """Batched assignment of classification and regression targets.
<ide>
<ide> Args:
<del> pred_boxes_batch: list of BoxList objects with length batch_size
<del> representing predicted box sets.
<del> gt_box_batch: a list of BoxList objects with length batch_size
<del> representing groundtruth boxes for each image in the batch
<del> class_predictions: A list of tensors with length batch_size, where each
<del> each tensor has shape [max_num_boxes, num_classes] to be used
<add> pred_box_batch: a tensor of shape [batch_size, num_queries, 4]
<add> representing predicted bounding boxes.
<add> gt_box_batch: a tensor of shape [batch_size, num_queries, 4]
<add> representing groundtruth bounding boxes.
<add> pred_class_batch: A list of tensors with length batch_size, where each
<add> each tensor has shape [num_queries, num_classes] to be used
<ide> by certain similarity calculators.
<ide> gt_class_targets_batch: a list of tensors with length batch_size, where
<ide> each tensor has shape [num_gt_boxes_i, num_classes] and
<ide> def batch_assign(self,
<ide> box_code_dimension]
<ide> batch_reg_weights: a tensor with shape [batch_size, num_pred_boxes].
<ide> """
<add> pred_box_batch = [
<add> box_list.BoxList(pred_box)
<add> for pred_box in tf.unstack(pred_box_batch)]
<add> gt_box_batch = [
<add> box_list.BoxList(gt_box)
<add> for gt_box in tf.unstack(gt_box_batch)]
<add>
<ide> cls_targets_list = []
<ide> cls_weights_list = []
<ide> reg_targets_list = []
<ide> reg_weights_list = []
<ide> if gt_weights_batch is None:
<ide> gt_weights_batch = [None] * len(gt_class_targets_batch)
<del> class_predictions = tf.unstack(class_predictions)
<del> for pred_boxes, gt_boxes, class_preds, gt_class_targets, gt_weights in zip(
<del> pred_boxes_batch, gt_box_batch, class_predictions,
<del> gt_class_targets_batch, gt_weights_batch):
<add> pred_class_batch = tf.unstack(pred_class_batch)
<add> for (pred_boxes, gt_boxes, pred_class_batch,
<add> gt_class_targets, gt_weights) in zip(
<add> pred_box_batch, gt_box_batch, pred_class_batch,
<add> gt_class_targets_batch, gt_weights_batch):
<ide> (cls_targets, cls_weights,
<del> reg_targets, reg_weights) = self.assign(
<del> pred_boxes, gt_boxes, class_preds, gt_class_targets, gt_weights)
<add> reg_targets, reg_weights) = self.assign(
<add> pred_boxes, gt_boxes, pred_class_batch, gt_class_targets, gt_weights)
<ide> cls_targets_list.append(cls_targets)
<ide> cls_weights_list.append(cls_weights)
<ide> reg_targets_list.append(reg_targets)
<ide> def batch_assign(self,
<ide> def assign(self,
<ide> box_preds,
<ide> groundtruth_boxes,
<del> class_predictions,
<add> pred_class_batch,
<ide> groundtruth_labels,
<ide> groundtruth_weights=None):
<ide> """Assign classification and regression targets to each box_pred.
<ide> def assign(self,
<ide> Args:
<ide> box_preds: a BoxList representing N box_preds
<ide> groundtruth_boxes: a BoxList representing M groundtruth boxes
<del> class_predictions: A tensor with shape [max_num_boxes, num_classes]
<add> pred_class_batch: A tensor with shape [max_num_boxes, num_classes]
<ide> to be used by certain similarity calculators.
<ide> groundtruth_labels: a tensor of shape [M, num_classes]
<ide> with labels for each of the ground_truth boxes. The subshape
<ide> [num_classes] can be empty (corresponding to scalar inputs). When set
<ide> to None, groundtruth_labels assumes a binary problem where all
<ide> ground_truth boxes get a positive label (of 1).
<ide> groundtruth_weights: a float tensor of shape [M] indicating the weight to
<del> assign to all box_preds match to a particular groundtruth box. The weights
<del> must be in [0., 1.]. If None, all weights are set to 1. Generally no
<del> groundtruth boxes with zero weight match to any box_preds as matchers are
<del> aware of groundtruth weights. Additionally, `cls_weights` and
<del> `reg_weights` are calculated using groundtruth weights as an added
<del> safety.
<add> assign to all box_preds match to a particular groundtruth box. The
<add> weights must be in [0., 1.]. If None, all weights are set to 1.
<add> Generally no groundtruth boxes with zero weight match to any box_preds
<add> as matchers are aware of groundtruth weights. Additionally,
<add> `cls_weights` and `reg_weights` are calculated using groundtruth
<add> weights as an added safety.
<ide>
<ide> Returns:
<ide> cls_targets: a float32 tensor with shape [num_box_preds, num_classes],
<ide> where the subshape [num_classes] is compatible with groundtruth_labels
<ide> which has shape [num_gt_boxes, num_classes].
<ide> cls_weights: a float32 tensor with shape [num_box_preds, num_classes],
<ide> representing weights for each element in cls_targets.
<del> reg_targets: a float32 tensor with shape [num_box_preds, box_code_dimension]
<add> reg_targets: a float32 tensor with shape [num_box_preds,
<add> box_code_dimension]
<ide> reg_weights: a float32 tensor with shape [num_box_preds]
<ide>
<ide> """
<del> unmatched_class_label = tf.constant([1] + [0] * (groundtruth_labels.shape[1] - 1), tf.float32)
<add> unmatched_class_label = tf.constant(
<add> [1] + [0] * (groundtruth_labels.shape[1] - 1), tf.float32)
<ide>
<ide> if groundtruth_weights is None:
<ide> num_gt_boxes = groundtruth_boxes.num_boxes_static()
<ide> if not num_gt_boxes:
<ide> num_gt_boxes = groundtruth_boxes.num_boxes()
<ide> groundtruth_weights = tf.ones([num_gt_boxes], dtype=tf.float32)
<ide>
<del> groundtruth_boxes.add_field(fields.BoxListFields.classes, groundtruth_labels)
<del> box_preds.add_field(fields.BoxListFields.classes, class_predictions)
<add> groundtruth_boxes.add_field(fields.BoxListFields.classes,
<add> groundtruth_labels)
<add> box_preds.add_field(fields.BoxListFields.classes, pred_class_batch)
<ide>
<ide> match_quality_matrix = self._similarity_calc.compare(
<ide> groundtruth_boxes,
<ide><path>research/object_detection/core/target_assigner_test.py
<ide> def _get_target_assigner(self):
<ide> return targetassigner.TargetAssigner(similarity_calc, matcher, box_coder)
<ide>
<ide> def test_batch_assign_targets(self):
<add>
<ide> def graph_fn(anchor_means, groundtruth_boxlist1, groundtruth_boxlist2):
<ide> box_list1 = box_list.BoxList(groundtruth_boxlist1)
<ide> box_list2 = box_list.BoxList(groundtruth_boxlist2)
<ide> def graph_fn():
<ide> np.testing.assert_array_almost_equal(
<ide> expected_seg_target, segmentation_target)
<ide>
<add>
<ide> class CenterNetDensePoseTargetAssignerTest(test_case.TestCase):
<ide>
<ide> def test_assign_part_and_coordinate_targets(self):
<ide> def graph_fn(pred_corners, groundtruth_box_corners,
<ide> dtype=np.float32)
<ide> groundtruth_labels = np.array([[0.0, 1.0], [0.0, 1.0]],
<ide> dtype=np.float32)
<del>
<add>
<ide> exp_cls_targets = [[0, 1], [0, 1], [1, 0]]
<ide> exp_cls_weights = [[1, 1], [1, 1], [1, 1]]
<ide> exp_reg_targets = [[0.25, 0.25, 0.5, 0.5],
<ide> def graph_fn(pred_corners, groundtruth_box_corners,
<ide>
<ide> def test_batch_assign_detr(self):
<ide> def graph_fn(pred_corners, groundtruth_box_corners,
<del> groundtruth_labels, predicted_labels):
<add> groundtruth_labels, predicted_labels):
<ide> detr_target_assigner = targetassigner.DETRTargetAssigner()
<del> pred_boxlist = [box_list.BoxList(pred_corners)]
<del> groundtruth_boxlist = [box_list.BoxList(groundtruth_box_corners)]
<ide> result = detr_target_assigner.batch_assign(
<del> pred_boxlist, groundtruth_boxlist,
<add> pred_corners, groundtruth_box_corners,
<ide> [predicted_labels], [groundtruth_labels])
<ide> (cls_targets, cls_weights, reg_targets, reg_weights) = result
<ide> return (cls_targets, cls_weights, reg_targets, reg_weights)
<ide>
<del> pred_corners = np.array([[0.25, 0.25, 0.4, 0.2],
<del> [0.5, 0.8, 1.0, 0.8],
<del> [0.9, 0.5, 0.1, 1.0]], dtype=np.float32)
<del> groundtruth_box_corners = np.array([[0.0, 0.0, 0.5, 0.5],
<del> [0.5, 0.5, 0.9, 0.9]],
<del> dtype=np.float32)
<add> pred_corners = np.array([[[0.25, 0.25, 0.4, 0.2],
<add> [0.5, 0.8, 1.0, 0.8],
<add> [0.9, 0.5, 0.1, 1.0]]], dtype=np.float32)
<add> groundtruth_box_corners = np.array([[[0.0, 0.0, 0.5, 0.5],
<add> [0.5, 0.5, 0.9, 0.9]]],
<add> dtype=np.float32)
<ide> predicted_labels = np.array([[-3.0, 3.0], [2.0, 9.4], [5.0, 1.0]],
<ide> dtype=np.float32)
<ide> groundtruth_labels = np.array([[0.0, 1.0], [0.0, 1.0]],
<ide> dtype=np.float32)
<del>
<add>
<ide> exp_cls_targets = [[[0, 1], [0, 1], [1, 0]]]
<ide> exp_cls_weights = [[[1, 1], [1, 1], [1, 1]]]
<ide> exp_reg_targets = [[[0.25, 0.25, 0.5, 0.5],
<del> [0.7, 0.7, 0.4, 0.4],
<del> [0, 0, 0, 0]]]
<add> [0.7, 0.7, 0.4, 0.4],
<add> [0, 0, 0, 0]]]
<ide> exp_reg_weights = [[1, 1, 0]]
<ide>
<ide> (cls_targets_out,
<del> cls_weights_out, reg_targets_out, reg_weights_out) = self.execute(
<del> graph_fn, [pred_corners, groundtruth_box_corners,
<add> cls_weights_out, reg_targets_out, reg_weights_out) = self.execute(
<add> graph_fn, [pred_corners, groundtruth_box_corners,
<ide> groundtruth_labels, predicted_labels])
<ide>
<ide> self.assertAllClose(cls_targets_out, exp_cls_targets)
<ide> def graph_fn(pred_corners, groundtruth_box_corners,
<ide> self.assertEqual(reg_weights_out.dtype, np.float32)
<ide>
<ide> if __name__ == '__main__':
<del> tf.test.main()
<ide>\ No newline at end of file
<add> tf.test.main() | 3 |
Ruby | Ruby | add missing monkey-patch | d4a2006f0404de6696876e0e252ebc707ce419ee | <ide><path>Library/Homebrew/dev-cmd/extract.rb
<ide> def respond_to_missing?(*)
<ide> end
<ide> end
<ide>
<add>class Resource
<add> def method_missing(*); end
<add>
<add> def respond_to_missing?(*)
<add> true
<add> end
<add>end
<add>
<ide> class DependencyCollector
<ide> def parse_symbol_spec(*); end
<ide> | 1 |
Python | Python | restrict pymorphy2 requirement to pymorphy2 mode | f4008bdb13e262c389e3d0c7017a634605f6e706 | <ide><path>spacy/lang/ru/lemmatizer.py
<ide> def __init__(
<ide> mode: str = "pymorphy2",
<ide> overwrite: bool = False,
<ide> ) -> None:
<del> try:
<del> from pymorphy2 import MorphAnalyzer
<del> except ImportError:
<del> raise ImportError(
<del> "The Russian lemmatizer requires the pymorphy2 library: "
<del> 'try to fix it with "pip install pymorphy2"'
<del> ) from None
<del> if RussianLemmatizer._morph is None:
<del> RussianLemmatizer._morph = MorphAnalyzer()
<add> if mode == "pymorphy2":
<add> try:
<add> from pymorphy2 import MorphAnalyzer
<add> except ImportError:
<add> raise ImportError(
<add> "The Russian lemmatizer mode 'pymorphy2' requires the "
<add> "pymorphy2 library. Install it with: pip install pymorphy2"
<add> ) from None
<add> if RussianLemmatizer._morph is None:
<add> RussianLemmatizer._morph = MorphAnalyzer()
<ide> super().__init__(vocab, model, name, mode=mode, overwrite=overwrite)
<ide>
<ide> def pymorphy2_lemmatize(self, token: Token) -> List[str]:
<ide><path>spacy/lang/uk/lemmatizer.py
<ide> def __init__(
<ide> mode: str = "pymorphy2",
<ide> overwrite: bool = False,
<ide> ) -> None:
<del> try:
<del> from pymorphy2 import MorphAnalyzer
<del> except ImportError:
<del> raise ImportError(
<del> "The Ukrainian lemmatizer requires the pymorphy2 library and "
<del> "dictionaries: try to fix it with "
<del> '"pip install pymorphy2 pymorphy2-dicts-uk"'
<del> ) from None
<del> if UkrainianLemmatizer._morph is None:
<del> UkrainianLemmatizer._morph = MorphAnalyzer(lang="uk")
<add> if mode == "pymorphy2":
<add> try:
<add> from pymorphy2 import MorphAnalyzer
<add> except ImportError:
<add> raise ImportError(
<add> "The Ukrainian lemmatizer mode 'pymorphy2' requires the "
<add> "pymorphy2 library and dictionaries. Install them with: "
<add> "pip install pymorphy2 pymorphy2-dicts-uk"
<add> ) from None
<add> if UkrainianLemmatizer._morph is None:
<add> UkrainianLemmatizer._morph = MorphAnalyzer(lang="uk")
<ide> super().__init__(vocab, model, name, mode=mode, overwrite=overwrite)
<ide><path>spacy/tests/conftest.py
<ide> def uk_tokenizer():
<ide> return get_lang_class("uk")().tokenizer
<ide>
<ide>
<add>@pytest.fixture
<add>def uk_lemmatizer():
<add> pytest.importorskip("pymorphy2")
<add> pytest.importorskip("pymorphy2_dicts_uk")
<add> return get_lang_class("uk")().add_pipe("lemmatizer")
<add>
<add>
<ide> @pytest.fixture(scope="session")
<ide> def ur_tokenizer():
<ide> return get_lang_class("ur")().tokenizer
<ide><path>spacy/tests/lang/uk/test_lemmatizer.py
<add>import pytest
<add>from spacy.tokens import Doc
<add>
<add>
<add>def test_uk_lemmatizer(uk_lemmatizer):
<add> """Check that the default uk lemmatizer runs."""
<add> doc = Doc(uk_lemmatizer.vocab, words=["a", "b", "c"])
<add> uk_lemmatizer(doc) | 4 |
Javascript | Javascript | add spec for animatedmodule | 116ac65feade4e4cfb7b91b6a90ecdfb8fd137f5 | <ide><path>Libraries/Animated/src/NativeAnimatedHelper.js
<ide> * This source code is licensed under the MIT license found in the
<ide> * LICENSE file in the root directory of this source tree.
<ide> *
<del> * @flow
<add> * @flow strict-local
<ide> * @format
<ide> */
<ide> 'use strict';
<ide>
<del>const NativeAnimatedModule = require('../../BatchedBridge/NativeModules')
<del> .NativeAnimatedModule;
<del>const NativeEventEmitter = require('../../EventEmitter/NativeEventEmitter');
<add>import NativeEventEmitter from '../../EventEmitter/NativeEventEmitter';
<add>import type {
<add> EventMapping,
<add> AnimatedNodeConfig,
<add> AnimatingNodeConfig,
<add>} from './NativeAnimatedModule';
<add>import NativeAnimatedModule from './NativeAnimatedModule';
<add>import invariant from 'invariant';
<ide>
<del>const invariant = require('invariant');
<del>
<del>import type {AnimationConfig} from './animations/Animation';
<add>import type {AnimationConfig, EndCallback} from './animations/Animation';
<add>import type {InterpolationConfigType} from './nodes/AnimatedInterpolation';
<ide> import type {EventConfig} from './AnimatedEvent';
<ide>
<ide> let __nativeAnimatedNodeTagCount = 1; /* used for animated nodes */
<ide> let __nativeAnimationIdCount = 1; /* used for started animations */
<ide>
<del>type EndResult = {finished: boolean};
<del>type EndCallback = (result: EndResult) => void;
<del>type EventMapping = {
<del> nativeEventPath: Array<string>,
<del> animatedValueTag: ?number,
<del>};
<del>
<ide> let nativeEventEmitter;
<ide>
<ide> /**
<ide> * Simple wrappers around NativeAnimatedModule to provide flow and autocmplete support for
<ide> * the native module methods
<ide> */
<ide> const API = {
<del> createAnimatedNode: function(tag: ?number, config: Object): void {
<del> assertNativeAnimatedModule();
<add> createAnimatedNode: function(tag: ?number, config: AnimatedNodeConfig): void {
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.createAnimatedNode(tag, config);
<ide> },
<ide> startListeningToAnimatedNodeValue: function(tag: ?number) {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.startListeningToAnimatedNodeValue(tag);
<ide> },
<ide> stopListeningToAnimatedNodeValue: function(tag: ?number) {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.stopListeningToAnimatedNodeValue(tag);
<ide> },
<ide> connectAnimatedNodes: function(parentTag: ?number, childTag: ?number): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.connectAnimatedNodes(parentTag, childTag);
<ide> },
<ide> disconnectAnimatedNodes: function(
<ide> parentTag: ?number,
<ide> childTag: ?number,
<ide> ): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.disconnectAnimatedNodes(parentTag, childTag);
<ide> },
<ide> startAnimatingNode: function(
<ide> animationId: ?number,
<ide> nodeTag: ?number,
<del> config: Object,
<add> config: AnimatingNodeConfig,
<ide> endCallback: EndCallback,
<ide> ): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.startAnimatingNode(
<ide> animationId,
<ide> nodeTag,
<ide> const API = {
<ide> );
<ide> },
<ide> stopAnimation: function(animationId: ?number) {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.stopAnimation(animationId);
<ide> },
<ide> setAnimatedNodeValue: function(nodeTag: ?number, value: ?number): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.setAnimatedNodeValue(nodeTag, value);
<ide> },
<ide> setAnimatedNodeOffset: function(nodeTag: ?number, offset: ?number): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.setAnimatedNodeOffset(nodeTag, offset);
<ide> },
<ide> flattenAnimatedNodeOffset: function(nodeTag: ?number): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.flattenAnimatedNodeOffset(nodeTag);
<ide> },
<ide> extractAnimatedNodeOffset: function(nodeTag: ?number): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.extractAnimatedNodeOffset(nodeTag);
<ide> },
<ide> connectAnimatedNodeToView: function(
<ide> nodeTag: ?number,
<ide> viewTag: ?number,
<ide> ): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.connectAnimatedNodeToView(nodeTag, viewTag);
<ide> },
<ide> disconnectAnimatedNodeFromView: function(
<ide> nodeTag: ?number,
<ide> viewTag: ?number,
<ide> ): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.disconnectAnimatedNodeFromView(nodeTag, viewTag);
<ide> },
<ide> dropAnimatedNode: function(tag: ?number): void {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.dropAnimatedNode(tag);
<ide> },
<ide> addAnimatedEventToView: function(
<ide> viewTag: ?number,
<ide> eventName: string,
<ide> eventMapping: EventMapping,
<ide> ) {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.addAnimatedEventToView(
<ide> viewTag,
<ide> eventName,
<ide> const API = {
<ide> eventName: string,
<ide> animatedNodeTag: ?number,
<ide> ) {
<del> assertNativeAnimatedModule();
<add> invariant(NativeAnimatedModule, 'Native animated module is not available');
<ide> NativeAnimatedModule.removeAnimatedEventFromView(
<ide> viewTag,
<ide> eventName,
<ide> function addWhitelistedInterpolationParam(param: string): void {
<ide> SUPPORTED_INTERPOLATION_PARAMS[param] = true;
<ide> }
<ide>
<del>function validateTransform(configs: Array<Object>): void {
<add>function validateTransform(
<add> configs: Array<
<add> | {type: 'animated', property: string, nodeTag: ?number}
<add> | {type: 'static', property: string, value: number},
<add> >,
<add>): void {
<ide> configs.forEach(config => {
<ide> if (!TRANSFORM_WHITELIST.hasOwnProperty(config.property)) {
<ide> throw new Error(
<ide> function validateTransform(configs: Array<Object>): void {
<ide> });
<ide> }
<ide>
<del>function validateStyles(styles: Object): void {
<add>function validateStyles(styles: {[key: string]: ?number}): void {
<ide> for (const key in styles) {
<ide> if (!STYLES_WHITELIST.hasOwnProperty(key)) {
<ide> throw new Error(
<ide> function validateStyles(styles: Object): void {
<ide> }
<ide> }
<ide>
<del>function validateInterpolation(config: Object): void {
<add>function validateInterpolation(config: InterpolationConfigType): void {
<ide> for (const key in config) {
<ide> if (!SUPPORTED_INTERPOLATION_PARAMS.hasOwnProperty(key)) {
<ide> throw new Error(
<ide> function assertNativeAnimatedModule(): void {
<ide> let _warnedMissingNativeAnimated = false;
<ide>
<ide> function shouldUseNativeDriver(config: AnimationConfig | EventConfig): boolean {
<del> if (config.useNativeDriver && !NativeAnimatedModule) {
<add> if (config.useNativeDriver === true && !NativeAnimatedModule) {
<ide> if (!_warnedMissingNativeAnimated) {
<ide> console.warn(
<ide> 'Animated: `useNativeDriver` is not supported because the native ' +
<ide> function shouldUseNativeDriver(config: AnimationConfig | EventConfig): boolean {
<ide> return config.useNativeDriver || false;
<ide> }
<ide>
<del>function transformDataType(value: any): number {
<add>function transformDataType(value: number | string): number {
<ide> // Change the string type to number type so we can reuse the same logic in
<ide> // iOS and Android platform
<ide> if (typeof value !== 'string') {
<ide> module.exports = {
<ide> assertNativeAnimatedModule,
<ide> shouldUseNativeDriver,
<ide> transformDataType,
<add> // $FlowExpectedError - unsafe getter lint suppresion
<ide> get nativeEventEmitter() {
<ide> if (!nativeEventEmitter) {
<ide> nativeEventEmitter = new NativeEventEmitter(NativeAnimatedModule);
<ide><path>Libraries/Animated/src/NativeAnimatedModule.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>type EndResult = {finished: boolean};
<add>type EndCallback = (result: EndResult) => void;
<add>
<add>export type EventMapping = {|
<add> nativeEventPath: Array<string>,
<add> animatedValueTag: ?number,
<add>|};
<add>
<add>export type AnimatedNodeConfig = {|
<add> // TODO: Type this with better enums.
<add> type: string,
<add>|};
<add>
<add>export type AnimatingNodeConfig = {|
<add> // TODO: Type this with better enums.
<add> type: string,
<add>|};
<add>
<add>export interface Spec extends TurboModule {
<add> +createAnimatedNode: (tag: ?number, config: AnimatedNodeConfig) => void;
<add> +startListeningToAnimatedNodeValue: (tag: ?number) => void;
<add> +stopListeningToAnimatedNodeValue: (tag: ?number) => void;
<add> +connectAnimatedNodes: (parentTag: ?number, childTag: ?number) => void;
<add> +disconnectAnimatedNodes: (parentTag: ?number, childTag: ?number) => void;
<add> +startAnimatingNode: (
<add> animationId: ?number,
<add> nodeTag: ?number,
<add> config: AnimatingNodeConfig,
<add> endCallback: EndCallback,
<add> ) => void;
<add> +stopAnimation: (animationId: ?number) => void;
<add> +setAnimatedNodeValue: (nodeTag: ?number, value: ?number) => void;
<add> +setAnimatedNodeOffset: (nodeTag: ?number, offset: ?number) => void;
<add> +flattenAnimatedNodeOffset: (nodeTag: ?number) => void;
<add> +extractAnimatedNodeOffset: (nodeTag: ?number) => void;
<add> +connectAnimatedNodeToView: (nodeTag: ?number, viewTag: ?number) => void;
<add> +disconnectAnimatedNodeFromView: (nodeTag: ?number, viewTag: ?number) => void;
<add> +dropAnimatedNode: (tag: ?number) => void;
<add> +addAnimatedEventToView: (
<add> viewTag: ?number,
<add> eventName: string,
<add> eventMapping: EventMapping,
<add> ) => void;
<add> +removeAnimatedEventFromView: (
<add> viewTag: ?number,
<add> eventName: string,
<add> animatedNodeTag: ?number,
<add> ) => void;
<add>
<add> // Events
<add> +addListener: (eventName: string) => void;
<add> +removeListeners: (count: number) => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('NativeAnimatedModule');
<ide><path>Libraries/Animated/src/__tests__/Animated-test.js
<ide>
<ide> 'use strict';
<ide>
<add>jest.mock('../../../BatchedBridge/NativeModules', () => ({
<add> NativeAnimatedModule: {},
<add>}));
<add>
<ide> let Animated = require('../Animated');
<ide> describe('Animated tests', () => {
<ide> beforeEach(() => {
<ide><path>Libraries/Animated/src/__tests__/AnimatedNative-test.js
<ide> jest
<ide> .setMock('../../../Lists/FlatList', ClassComponentMock)
<ide> .setMock('../../../Lists/SectionList', ClassComponentMock)
<ide> .setMock('react', {Component: class {}})
<del> .setMock('../../../BatchedBridge/NativeModules', {
<add> .mock('../../../BatchedBridge/NativeModules', () => ({
<ide> NativeAnimatedModule: {},
<del> })
<add> }))
<add> .mock('../NativeAnimatedModule')
<ide> .mock('../../../EventEmitter/NativeEventEmitter')
<ide> // findNodeHandle is imported from ReactNative so mock that whole module.
<ide> .setMock('../../../Renderer/shims/ReactNative', {findNodeHandle: () => 1});
<ide> function createAndMountComponent(ComponentClass, props) {
<ide> }
<ide>
<ide> describe('Native Animated', () => {
<del> const nativeAnimatedModule = require('../../../BatchedBridge/NativeModules')
<del> .NativeAnimatedModule;
<add> const nativeAnimatedModule = require('../NativeAnimatedModule').default;
<ide>
<ide> beforeEach(() => {
<ide> nativeAnimatedModule.addAnimatedEventToView = jest.fn(); | 4 |
Ruby | Ruby | do proper adapter check | 18b9595814057095084f508b6837ad3c7331079f | <ide><path>activerecord/test/cases/finder_test.rb
<ide> def test_exists
<ide> def test_exists_fails_when_parameter_has_invalid_type
<ide> begin
<ide> assert_equal false, Topic.exists?(("9"*53).to_i) # number that's bigger than int
<del> flunk if defined? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter and Topic.connection.is_a? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter # PostgreSQL does raise here
<add> flunk if current_adapter?(:PostgreSQLAdapter) # PostgreSQL does raise here
<ide> rescue ActiveRecord::StatementInvalid
<ide> # PostgreSQL complains that it can't coerce a numeric that's bigger than int into int
<ide> rescue Exception
<ide> def test_exists_fails_when_parameter_has_invalid_type
<ide>
<ide> begin
<ide> assert_equal false, Topic.exists?("foo")
<del> flunk if defined? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter and Topic.connection.is_a? ActiveRecord::ConnectionAdapters::PostgreSQLAdapter # PostgreSQL does raise here
<add> flunk if current_adapter?(:PostgreSQLAdapter) # PostgreSQL does raise here
<ide> rescue ActiveRecord::StatementInvalid
<ide> # PostgreSQL complains about string comparison with integer field
<ide> rescue Exception | 1 |
PHP | PHP | fix pivot table losing its connection | 172ebcb00d60400060b7fa5028a4558e0233b193 | <ide><path>laravel/database/eloquent/pivot.php
<ide> class Pivot extends Model {
<ide> *
<ide> * @var string
<ide> */
<del> public $pivot_table;
<add> protected $pivot_table;
<add>
<add> /**
<add> * The database connection used for this model.
<add> *
<add> * @var Laravel\Database\Connection
<add> */
<add> protected $pivot_connection;
<ide>
<ide> /**
<ide> * Indicates if the model has update and creation timestamps.
<ide> class Pivot extends Model {
<ide> public function __construct($table, $connection = null)
<ide> {
<ide> $this->pivot_table = $table;
<del> static::$connection = $connection;
<add> $this->pivot_connection = $connection;
<ide>
<ide> parent::__construct(array(), true);
<ide> }
<ide> public function table()
<ide> return $this->pivot_table;
<ide> }
<ide>
<add> /**
<add> * Get the connection used by the pivot table.
<add> *
<add> * @return string
<add> */
<add> public function connection()
<add> {
<add> return $this->pivot_connection;
<add> }
<add>
<ide> }
<ide>\ No newline at end of file | 1 |
Python | Python | move most new loadtxt tests to its own file | 90c71f0a8a84d9f17243e28e01527b5fd1ecdbb9 | <ide><path>numpy/lib/tests/test_io.py
<ide> def test_load_refcount():
<ide> with assert_no_gc_cycles():
<ide> x = np.loadtxt(TextIO("0 1 2 3"), dtype=dt)
<ide> assert_equal(x, np.array([((0, 1), (2, 3))], dtype=dt))
<del>
<del>
<del>def test_loadtxt_scientific_notation():
<del> """Test that both 'e' and 'E' are parsed correctly."""
<del> data = TextIO(
<del> (
<del> "1.0e-1,2.0E1,3.0\n"
<del> "4.0e-2,5.0E-1,6.0\n"
<del> "7.0e-3,8.0E1,9.0\n"
<del> "0.0e-4,1.0E-1,2.0"
<del> )
<del> )
<del> expected = np.array(
<del> [[0.1, 20., 3.0], [0.04, 0.5, 6], [0.007, 80., 9], [0, 0.1, 2]]
<del> )
<del> assert_array_equal(np.loadtxt(data, delimiter=","), expected)
<del>
<del>
<del>@pytest.mark.parametrize("comment", ["..", "//", "@-", "this is a comment:"])
<del>def test_loadtxt_comment_multiple_chars(comment):
<del> content = "# IGNORE\n1.5, 2.5# ABC\n3.0,4.0# XXX\n5.5,6.0\n"
<del> txt = TextIO(content.replace("#", comment))
<del> a = np.loadtxt(txt, delimiter=",", comments=comment)
<del> assert_equal(a, [[1.5, 2.5], [3.0, 4.0], [5.5, 6.0]])
<del>
<del>
<del>@pytest.fixture
<del>def mixed_types_structured():
<del> """
<del> Fixture providing hetergeneous input data with a structured dtype, along
<del> with the associated structured array.
<del> """
<del> data = TextIO(
<del> (
<del> "1000;2.4;alpha;-34\n"
<del> "2000;3.1;beta;29\n"
<del> "3500;9.9;gamma;120\n"
<del> "4090;8.1;delta;0\n"
<del> "5001;4.4;epsilon;-99\n"
<del> "6543;7.8;omega;-1\n"
<del> )
<del> )
<del> dtype = np.dtype(
<del> [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
<del> )
<del> expected = np.array(
<del> [
<del> (1000, 2.4, "alpha", -34),
<del> (2000, 3.1, "beta", 29),
<del> (3500, 9.9, "gamma", 120),
<del> (4090, 8.1, "delta", 0),
<del> (5001, 4.4, "epsilon", -99),
<del> (6543, 7.8, "omega", -1)
<del> ],
<del> dtype=dtype
<del> )
<del> return data, dtype, expected
<del>
<del>
<del>@pytest.mark.parametrize('skiprows', [0, 1, 2, 3])
<del>def test_loadtxt_structured_dtype_and_skiprows_no_empty_lines(
<del> skiprows, mixed_types_structured
<del> ):
<del> data, dtype, expected = mixed_types_structured
<del> a = np.loadtxt(data, dtype=dtype, delimiter=";", skiprows=skiprows)
<del> assert_array_equal(a, expected[skiprows:])
<del>
<del>
<del>def test_loadtxt_unpack_structured(mixed_types_structured):
<del> data, dtype, expected = mixed_types_structured
<del>
<del> a, b, c, d = np.loadtxt(data, dtype=dtype, delimiter=";", unpack=True)
<del> assert_array_equal(a, expected["f0"])
<del> assert_array_equal(b, expected["f1"])
<del> assert_array_equal(c, expected["f2"])
<del> assert_array_equal(d, expected["f3"])
<del>
<del>
<del>def test_loadtxt_structured_dtype_with_shape():
<del> dtype = np.dtype([("a", "u1", 2), ("b", "u1", 2)])
<del> data = TextIO("0,1,2,3\n6,7,8,9\n")
<del> expected = np.array([((0, 1), (2, 3)), ((6, 7), (8, 9))], dtype=dtype)
<del> assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dtype), expected)
<del>
<del>
<del>def test_loadtxt_structured_dtype_with_multi_shape():
<del> dtype = np.dtype([("a", "u1", (2, 2))])
<del> data = TextIO("0 1 2 3\n")
<del> expected = np.array([(((0, 1), (2, 3)),)], dtype=dtype)
<del> assert_array_equal(np.loadtxt(data, dtype=dtype), expected)
<del>
<del>
<del>def test_loadtxt_nested_structured_subarray():
<del> # Test from gh-16678
<del> point = np.dtype([('x', float), ('y', float)])
<del> dt = np.dtype([('code', int), ('points', point, (2,))])
<del> data = TextIO("100,1,2,3,4\n200,5,6,7,8\n")
<del> expected = np.array(
<del> [
<del> (100, [(1., 2.), (3., 4.)]),
<del> (200, [(5., 6.), (7., 8.)]),
<del> ],
<del> dtype=dt
<del> )
<del> assert_array_equal(np.loadtxt(data, dtype=dt, delimiter=","), expected)
<del>
<del>
<del>def test_loadtxt_structured_dtype_offsets():
<del> # An aligned structured dtype will have additional padding
<del> dt = np.dtype("i1, i4, i1, i4, i1, i4", align=True)
<del> data = TextIO("1,2,3,4,5,6\n7,8,9,10,11,12\n")
<del> expected = np.array([(1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12)], dtype=dt)
<del> assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dt), expected)
<del>
<del>
<del>@pytest.mark.parametrize("param", ("skiprows", "max_rows"))
<del>def test_loadtxt_exception_negative_row_limits(param):
<del> """skiprows and max_rows should raise for negative parameters."""
<del> with pytest.raises(ValueError, match="argument must be nonnegative"):
<del> np.loadtxt("foo.bar", **{param: -3})
<del>
<del>
<del>@pytest.mark.parametrize("param", ("skiprows", "max_rows"))
<del>def test_loadtxt_exception_noninteger_row_limits(param):
<del> with pytest.raises(TypeError, match="argument must be an integer"):
<del> np.loadtxt("foo.bar", **{param: 1.0})
<del>
<del>
<del>@pytest.mark.parametrize(
<del> "data, shape",
<del> [
<del> ("1 2 3 4 5\n", (1, 5)), # Single row
<del> ("1\n2\n3\n4\n5\n", (5, 1)), # Single column
<del> ]
<del>)
<del>def test_loadtxt_ndmin_single_row_or_col(data, shape):
<del> arr = np.array([1, 2, 3, 4, 5])
<del> arr2d = arr.reshape(shape)
<del>
<del> assert_array_equal(np.loadtxt(TextIO(data), dtype=int), arr)
<del> assert_array_equal(np.loadtxt(TextIO(data), dtype=int, ndmin=0), arr)
<del> assert_array_equal(np.loadtxt(TextIO(data), dtype=int, ndmin=1), arr)
<del> assert_array_equal(np.loadtxt(TextIO(data), dtype=int, ndmin=2), arr2d)
<del>
<del>
<del>@pytest.mark.parametrize("badval", [-1, 3, None, "plate of shrimp"])
<del>def test_loadtxt_bad_ndmin(badval):
<del> with pytest.raises(ValueError, match="Illegal value of ndmin keyword"):
<del> np.loadtxt("foo.bar", ndmin=badval)
<del>
<del>
<del>@pytest.mark.parametrize(
<del> "ws",
<del> (
<del> "\t", # tab
<del> "\u2003", # em
<del> "\u00A0", # non-break
<del> "\u3000", # ideographic space
<del> )
<del>)
<del>def test_loadtxt_blank_lines_spaces_delimit(ws):
<del> txt = StringIO(
<del> f"1 2{ws}30\n\n4 5 60\n {ws} \n7 8 {ws} 90\n # comment\n3 2 1"
<del> )
<del> # NOTE: It is unclear that the ` # comment` should succeed. Except
<del> # for delimiter=None, which should use any whitespace (and maybe
<del> # should just be implemented closer to Python
<del> expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
<del> assert_equal(
<del> np.loadtxt(txt, dtype=int, delimiter=None, comments="#"), expected
<del> )
<del>
<del>
<del>def test_loadtxt_blank_lines_normal_delimiter():
<del> txt = StringIO('1,2,30\n\n4,5,60\n\n7,8,90\n# comment\n3,2,1')
<del> expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
<del> assert_equal(
<del> np.loadtxt(txt, dtype=int, delimiter=',', comments="#"), expected
<del> )
<del>
<del>
<del>@pytest.mark.parametrize("dtype", (float, object))
<del>def test_loadtxt_maxrows_no_blank_lines(dtype):
<del> txt = TextIO("1.5,2.5\n3.0,4.0\n5.5,6.0")
<del> res = np.loadtxt(txt, dtype=dtype, delimiter=",", max_rows=2)
<del> assert_equal(res.dtype, dtype)
<del> assert_equal(res, np.array([["1.5", "2.5"], ["3.0", "4.0"]], dtype=dtype))
<del>
<del>
<del>@pytest.mark.parametrize("dtype", (np.dtype("f8"), np.dtype("i2")))
<del>def test_loadtxt_exception_message_bad_values(dtype):
<del> txt = TextIO("1,2\n3,XXX\n5,6")
<del> msg = f"could not convert string 'XXX' to {dtype} at row 1, column 2"
<del> with pytest.raises(ValueError, match=msg):
<del> np.loadtxt(txt, dtype=dtype, delimiter=",")
<del>
<del>
<del>def test_loadtxt_converters_negative_indices():
<del> txt = TextIO('1.5,2.5\n3.0,XXX\n5.5,6.0')
<del> conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
<del> expected = np.array([[1.5, 2.5], [3.0, np.nan], [5.5, 6.0]])
<del> res = np.loadtxt(
<del> txt, dtype=np.float64, delimiter=",", converters=conv, encoding=None
<del> )
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_converters_negative_indices_with_usecols():
<del> txt = TextIO('1.5,2.5,3.5\n3.0,4.0,XXX\n5.5,6.0,7.5\n')
<del> conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
<del> expected = np.array([[1.5, 3.5], [3.0, np.nan], [5.5, 7.5]])
<del> res = np.loadtxt(
<del> txt,
<del> dtype=np.float64,
<del> delimiter=",",
<del> converters=conv,
<del> usecols=[0, -1],
<del> encoding=None,
<del> )
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_ragged_usecols():
<del> # usecols, and negative ones, work even with varying number of columns.
<del> txt = TextIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
<del> expected = np.array([[0, 0], [0, 0], [0, 0]])
<del> res = np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_empty_usecols():
<del> txt = TextIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
<del> res = np.loadtxt(txt, dtype=np.dtype([]), delimiter=",", usecols=[])
<del> assert res.shape == (3,)
<del> assert res.dtype == np.dtype([])
<del>
<del>
<del>@pytest.mark.parametrize("c1", ["a", "の", "🫕"])
<del>@pytest.mark.parametrize("c2", ["a", "の", "🫕"])
<del>def test_loadtxt_large_unicode_characters(c1, c2):
<del> # c1 and c2 span ascii, 16bit and 32bit range.
<del> txt = StringIO(f"a,{c1},c,1.0\ne,{c2},2.0,g")
<del> res = np.loadtxt(txt, dtype=np.dtype('U12'), delimiter=",")
<del> expected = np.array(
<del> [f"a,{c1},c,1.0".split(","), f"e,{c2},2.0,g".split(",")],
<del> dtype=np.dtype('U12')
<del> )
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_unicode_with_converter():
<del> txt = StringIO("cat,dog\nαβγ,δεζ\nabc,def\n")
<del> conv = {0: lambda s: s.upper()}
<del> res = np.loadtxt(
<del> txt,
<del> dtype=np.dtype("U12"),
<del> converters=conv,
<del> delimiter=",",
<del> encoding=None
<del> )
<del> expected = np.array([['CAT', 'dog'], ['ΑΒΓ', 'δεζ'], ['ABC', 'def']])
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_converter_with_structured_dtype():
<del> txt = TextIO('1.5,2.5,Abc\n3.0,4.0,dEf\n5.5,6.0,ghI\n')
<del> dt = np.dtype([('m', np.int32), ('r', np.float32), ('code', 'U8')])
<del> conv = {0: lambda s: int(10*float(s)), -1: lambda s: s.upper()}
<del> res = np.loadtxt(txt, dtype=dt, delimiter=",", converters=conv)
<del> expected = np.array(
<del> [(15, 2.5, 'ABC'), (30, 4.0, 'DEF'), (55, 6.0, 'GHI')], dtype=dt
<del> )
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_converter_with_unicode_dtype():
<del> """
<del> With the default 'bytes' encoding, tokens are encoded prior to being passed
<del> to the converter. This means that the output of the converter may be bytes
<del> instead of unicode as expected by `read_rows`.
<del>
<del> This test checks that outputs from the above scenario are properly decoded
<del> prior to parsing by `read_rows`.
<del> """
<del> txt = StringIO('abc,def\nrst,xyz')
<del> conv = bytes.upper
<del> res = np.loadtxt(txt, dtype=np.dtype("U3"), converters=conv, delimiter=",")
<del> expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']])
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_read_huge_row():
<del> row = "1.5, 2.5," * 50000
<del> row = row[:-1] + "\n"
<del> txt = TextIO(row * 2)
<del> res = np.loadtxt(txt, delimiter=",", dtype=float)
<del> assert_equal(res, np.tile([1.5, 2.5], (2, 50000)))
<del>
<del>
<del>@pytest.mark.parametrize("dtype", "edfgFDG")
<del>def test_loadtxt_huge_float(dtype):
<del> # Covers a non-optimized path that is rarely taken:
<del> field = "0" * 1000 + ".123456789"
<del> dtype = np.dtype(dtype)
<del> value = np.loadtxt([field], dtype=dtype)[()]
<del> assert value == dtype.type("0.123456789")
<del>
<del>
<del>@pytest.mark.parametrize(
<del> ("given_dtype", "expected_dtype"),
<del> [
<del> ("S", np.dtype("S5")),
<del> ("U", np.dtype("U5")),
<del> ],
<del>)
<del>def test_loadtxt_string_no_length_given(given_dtype, expected_dtype):
<del> """
<del> The given dtype is just 'S' or 'U' with no length. In these cases, the
<del> length of the resulting dtype is determined by the longest string found
<del> in the file.
<del> """
<del> txt = TextIO("AAA,5-1\nBBBBB,0-3\nC,4-9\n")
<del> res = np.loadtxt(txt, dtype=given_dtype, delimiter=",")
<del> expected = np.array(
<del> [['AAA', '5-1'], ['BBBBB', '0-3'], ['C', '4-9']], dtype=expected_dtype
<del> )
<del> assert_equal(res, expected)
<del> assert_equal(res.dtype, expected_dtype)
<del>
<del>
<del>def test_loadtxt_float_conversion():
<del> """
<del> Some tests that the conversion to float64 works as accurately as the Python
<del> built-in `float` function. In a naive version of the float parser, these
<del> strings resulted in values that were off by an ULP or two.
<del> """
<del> strings = [
<del> '0.9999999999999999',
<del> '9876543210.123456',
<del> '5.43215432154321e+300',
<del> '0.901',
<del> '0.333',
<del> ]
<del> txt = TextIO('\n'.join(strings))
<del> res = np.loadtxt(txt)
<del> expected = np.array([float(s) for s in strings])
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_bool():
<del> # Simple test for bool via integer
<del> txt = TextIO("1, 0\n10, -1")
<del> res = np.loadtxt(txt, dtype=bool, delimiter=",")
<del> assert res.dtype == bool
<del> assert_array_equal(res, [[True, False], [True, True]])
<del> # Make sure we use only 1 and 0 on the byte level:
<del> assert_array_equal(res.view(np.uint8), [[1, 0], [1, 1]])
<del>
<del>
<del>@pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
<del>def test_loadtxt_integer_signs(dtype):
<del> dtype = np.dtype(dtype)
<del> assert np.loadtxt(["+2"], dtype=dtype) == 2
<del> if dtype.kind == "u":
<del> with pytest.raises(ValueError):
<del> np.loadtxt(["-1\n"], dtype=dtype)
<del> else:
<del> assert np.loadtxt(["-2\n"], dtype=dtype) == -2
<del>
<del> for sign in ["++", "+-", "--", "-+"]:
<del> with pytest.raises(ValueError):
<del> np.loadtxt([f"{sign}2\n"], dtype=dtype)
<del>
<del>
<del>@pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
<del>def test_loadtxt_implicit_cast_float_to_int_fails(dtype):
<del> txt = TextIO("1.0, 2.1, 3.7\n4, 5, 6")
<del> with pytest.raises(ValueError):
<del> np.loadtxt(txt, dtype=dtype, delimiter=",")
<del>
<del>@pytest.mark.parametrize("dtype", (np.complex64, np.complex128))
<del>@pytest.mark.parametrize("with_parens", (False, True))
<del>def test_loadtxt_complex_parsing(dtype, with_parens):
<del> s = "(1.0-2.5j),3.75,(7+-5.0j)\n(4),(-19e2j),(0)"
<del> if not with_parens:
<del> s = s.replace("(", "").replace(")", "")
<del>
<del> res = np.loadtxt(TextIO(s), dtype=dtype, delimiter=",")
<del> expected = np.array(
<del> [[1.0-2.5j, 3.75, 7-5j], [4.0, -1900j, 0]], dtype=dtype
<del> )
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_read_from_generator():
<del> def gen():
<del> for i in range(4):
<del> yield f"{i},{2*i},{i**2}"
<del>
<del> res = np.loadtxt(gen(), dtype=int, delimiter=",")
<del> expected = np.array([[0, 0, 0], [1, 2, 1], [2, 4, 4], [3, 6, 9]])
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_read_from_generator_multitype():
<del> def gen():
<del> for i in range(3):
<del> yield f"{i} {i / 4}"
<del>
<del> res = np.loadtxt(gen(), dtype="i, d", delimiter=" ")
<del> expected = np.array([(0, 0.0), (1, 0.25), (2, 0.5)], dtype="i, d")
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_read_from_bad_generator():
<del> def gen():
<del> for entry in ["1,2", b"3, 5", 12738]:
<del> yield entry
<del>
<del> with pytest.raises(
<del> TypeError, match=r"non-string returned while reading data"
<del> ):
<del> np.loadtxt(gen(), dtype="i, i", delimiter=",")
<del>
<del>
<del>@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
<del>def test_loadtxt_object_cleanup_on_read_error():
<del> sentinel = object()
<del>
<del> already_read = 0
<del> def conv(x):
<del> nonlocal already_read
<del> if already_read > 4999:
<del> raise ValueError("failed half-way through!")
<del> already_read += 1
<del> return sentinel
<del>
<del> txt = TextIO("x\n" * 10000)
<del>
<del> with pytest.raises(ValueError, match="at row 5000, column 1"):
<del> np.loadtxt(txt, dtype=object, converters={0: conv})
<del>
<del> assert sys.getrefcount(sentinel) == 2
<del>
<del>
<del>def test_loadtxt_character_not_bytes_compatible():
<del> """Test exception when a character cannot be encoded as 'S'."""
<del> data = StringIO("–") # == \u2013
<del> with pytest.raises(ValueError):
<del> np.loadtxt(data, dtype="S5")
<del>
<del>
<del>@pytest.mark.parametrize("conv", (0, [float], ""))
<del>def test_loadtxt_invalid_converter(conv):
<del> msg = (
<del> "converters must be a dictionary mapping columns to converter "
<del> "functions or a single callable."
<del> )
<del> with pytest.raises(TypeError, match=msg):
<del> np.loadtxt(TextIO("1 2\n3 4"), converters=conv)
<del>
<del>
<del>def test_loadtxt_converters_dict_raises_non_integer_key():
<del> with pytest.raises(TypeError, match="keys of the converters dict"):
<del> np.loadtxt(TextIO("1 2\n3 4"), converters={"a": int})
<del> with pytest.raises(TypeError, match="keys of the converters dict"):
<del> np.loadtxt(TextIO("1 2\n3 4"), converters={"a": int}, usecols=0)
<del>
<del>
<del>@pytest.mark.parametrize("bad_col_ind", (3, -3))
<del>def test_loadtxt_converters_dict_raises_non_col_key(bad_col_ind):
<del> data = TextIO("1 2\n3 4")
<del> with pytest.raises(ValueError, match="converter specified for column"):
<del> np.loadtxt(data, converters={bad_col_ind: int})
<del>
<del>
<del>def test_loadtxt_converters_dict_raises_val_not_callable():
<del> with pytest.raises(
<del> TypeError, match="values of the converters dictionary must be callable"
<del> ):
<del> np.loadtxt(StringIO("1 2\n3 4"), converters={0: 1})
<del>
<del>
<del>@pytest.mark.parametrize("q", ('"', "'", "`"))
<del>def test_loadtxt_quoted_field(q):
<del> txt = TextIO(
<del> f"{q}alpha, x{q}, 2.5\n{q}beta, y{q}, 4.5\n{q}gamma, z{q}, 5.0\n"
<del> )
<del> dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])
<del> expected = np.array(
<del> [("alpha, x", 2.5), ("beta, y", 4.5), ("gamma, z", 5.0)], dtype=dtype
<del> )
<del>
<del> res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar=q)
<del> assert_array_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_quote_support_default():
<del> """Support for quoted fields is disabled by default."""
<del> txt = TextIO('"lat,long", 45, 30\n')
<del> dtype = np.dtype([('f0', 'U24'), ('f1', np.float64), ('f2', np.float64)])
<del>
<del> with pytest.raises(ValueError, match="the number of columns changed"):
<del> np.loadtxt(txt, dtype=dtype, delimiter=",")
<del>
<del> # Enable quoting support with non-None value for quotechar param
<del> txt.seek(0)
<del> expected = np.array([("lat,long", 45., 30.)], dtype=dtype)
<del>
<del> res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
<del> assert_array_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_quotechar_multichar_error():
<del> txt = StringIO("1,2\n3,4")
<del> msg = r".*must be a single unicode character or None"
<del> with pytest.raises(TypeError, match=msg):
<del> np.loadtxt(txt, delimiter=",", quotechar="''")
<del>
<del>
<del>def test_loadtxt_comment_multichar_error_with_quote():
<del> txt = StringIO("1,2\n3,4")
<del> msg = (
<del> "when multiple comments or a multi-character comment is given, "
<del> "quotes are not supported."
<del> )
<del> with pytest.raises(ValueError, match=msg):
<del> np.loadtxt(txt, delimiter=",", comments="123", quotechar='"')
<del> with pytest.raises(ValueError, match=msg):
<del> np.loadtxt(txt, delimiter=",", comments=["#", "%"], quotechar='"')
<del>
<del> # A single character string in a tuple is unpacked though:
<del> res = np.loadtxt(txt, delimiter=",", comments=("#",), quotechar="'")
<del> assert_equal(res, [[1, 2], [3, 4]])
<del>
<del>
<del>def test_loadtxt_structured_dtype_with_quotes():
<del> data = TextIO(
<del> (
<del> "1000;2.4;'alpha';-34\n"
<del> "2000;3.1;'beta';29\n"
<del> "3500;9.9;'gamma';120\n"
<del> "4090;8.1;'delta';0\n"
<del> "5001;4.4;'epsilon';-99\n"
<del> "6543;7.8;'omega';-1\n"
<del> )
<del> )
<del> dtype = np.dtype(
<del> [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
<del> )
<del> expected = np.array(
<del> [
<del> (1000, 2.4, "alpha", -34),
<del> (2000, 3.1, "beta", 29),
<del> (3500, 9.9, "gamma", 120),
<del> (4090, 8.1, "delta", 0),
<del> (5001, 4.4, "epsilon", -99),
<del> (6543, 7.8, "omega", -1)
<del> ],
<del> dtype=dtype
<del> )
<del> res = np.loadtxt(data, dtype=dtype, delimiter=";", quotechar="'")
<del> assert_array_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_quoted_field_is_not_empty():
<del> txt = StringIO('1\n\n"4"\n""')
<del> expected = np.array(["1", "4", ""], dtype="U1")
<del> res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
<del> assert_equal(res, expected)
<del>
<del>
<del>def test_loadtxt_consecutive_quotechar_escaped():
<del> txt = TextIO('"Hello, my name is ""Monty""!"')
<del> expected = np.array('Hello, my name is "Monty"!', dtype="U40")
<del> res = np.loadtxt(txt, dtype="U40", delimiter=",", quotechar='"')
<del> assert_equal(res, expected)
<del>
<del>
<del>@pytest.mark.parametrize("data", ("", "\n\n\n", "# 1 2 3\n# 4 5 6\n"))
<del>@pytest.mark.parametrize("ndmin", (0, 1, 2))
<del>@pytest.mark.parametrize("usecols", [None, (1, 2, 3)])
<del>def test_loadtxt_warn_on_no_data(data, ndmin, usecols):
<del> """Check that a UserWarning is emitted when no data is read from input."""
<del> if usecols is not None:
<del> expected_shape = (0, 3)
<del> elif ndmin == 2:
<del> expected_shape = (0, 1) # guess a single column?!
<del> else:
<del> expected_shape = (0,)
<del>
<del> txt = TextIO(data)
<del> with pytest.warns(UserWarning, match="input contained no data"):
<del> res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
<del> assert res.shape == expected_shape
<del>
<del> with NamedTemporaryFile(mode="w") as fh:
<del> fh.write(data)
<del> fh.seek(0)
<del> with pytest.warns(UserWarning, match="input contained no data"):
<del> res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
<del> assert res.shape == expected_shape
<del>
<del>@pytest.mark.parametrize("skiprows", (2, 3))
<del>def test_loadtxt_warn_on_skipped_data(skiprows):
<del> data = "1 2 3\n4 5 6"
<del> txt = TextIO(data)
<del> with pytest.warns(UserWarning, match="input contained no data"):
<del> np.loadtxt(txt, skiprows=skiprows)
<del>
<del>@pytest.mark.parametrize("dtype",
<del> list(np.typecodes["AllInteger"] + np.typecodes["AllFloat"]) + ["U2"])
<del>@pytest.mark.parametrize("swap", [True, False])
<del>def test_loadtxt_byteswapping_and_unaligned(dtype, swap):
<del> data = ["x,1\n"] # no need for complicated data
<del> dtype = np.dtype(dtype)
<del> if swap:
<del> dtype = dtype.newbyteorder()
<del> full_dt = np.dtype([("a", "S1"), ("b", dtype)], align=False)
<del> # The above ensures that the interesting "b" field is unaligned:
<del> assert full_dt.fields["b"][1] == 1
<del> res = np.loadtxt(data, dtype=full_dt, delimiter=",")
<del> assert res["b"] == dtype.type(1)
<del>
<del>@pytest.mark.parametrize("dtype",
<del> np.typecodes["AllInteger"] + "efdFD" + "?")
<del>def test_loadtxt_unicode_whitespace_stripping(dtype):
<del> # Test that all numeric types (and bool) strip whitespace correctly
<del> # \u202F is a narrow no-break space, `\n` is just a whitespace if quoted.
<del> # Currently, skip float128 as it did not always support this and has no
<del> # "custom" parsing:
<del> txt = StringIO(' 3 ,"\u202F2\n"')
<del> res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
<del> assert_array_equal(res, np.array([3, 2]).astype(dtype))
<del>
<del>@pytest.mark.parametrize("dtype", "FD")
<del>def test_loadtxt_unicode_whitespace_stripping_complex(dtype):
<del> # Complex has a few extra cases since it has two components and parentheses
<del> line = " 1 , 2+3j , ( 4+5j ), ( 6+-7j ) , 8j , ( 9j ) \n"
<del> data = [line, line.replace(" ", "\u202F")]
<del> res = np.loadtxt(data, dtype=dtype, delimiter=',')
<del> assert_array_equal(res, np.array([[1, 2+3j, 4+5j, 6-7j, 8j, 9j]] * 2))
<del>
<del>@pytest.mark.parametrize("dtype", "FD")
<del>@pytest.mark.parametrize("field",
<del> ["1 +2j", "1+ 2j", "1+2 j", "1+-+3", "(1j", "(1", "(1+2j", "1+2j)"])
<del>def test_loadtxt_bad_complex(dtype, field):
<del> with pytest.raises(ValueError):
<del> np.loadtxt([field + "\n"], dtype=dtype, delimiter=",")
<del>
<del>
<del>@pytest.mark.parametrize("data", [
<del> ["1,2\n", "2\n,3\n"],
<del> ["1,2\n", "2\r,3\n"]])
<del>def test_loadtxt_bad_newline_in_iterator(data):
<del> # In NumPy <=1.22 this was accepted, because newlines were completely
<del> # ignored when the input was an iterable. This could be changed, but right
<del> # now, we raise an error.
<del> with pytest.raises(ValueError,
<del> match="Found an unquoted embedded newline within a single line"):
<del> np.loadtxt(data, delimiter=",")
<del>
<del>@pytest.mark.parametrize("data", [
<del> ["1,2\n", "2,3\r\n"], # a universal newline
<del> ["1,2\n", "'2\n',3\n"], # a quoted newline
<del> ["1,2\n", "'2\r',3\n"],
<del> ["1,2\n", "'2\r\n',3\n"],
<del>])
<del>def test_loadtxt_good_newline_in_iterator(data):
<del> # The quoted newlines will be untransformed here, but are just whitespace.
<del> res = np.loadtxt(data, delimiter=",", quotechar="'")
<del> assert_array_equal(res, [[1., 2.], [2., 3.]])
<del>
<del>
<del>@pytest.mark.parametrize("newline", ["\n", "\r", "\r\n"])
<del>def test_unviersal_newlines_quoted(newline):
<del> # Check that universal newline support within the tokenizer is not applied
<del> # to quoted fields. (note that lines must end in newline or quoted
<del> # fields will not include a newline at all)
<del> data = ['1,"2\n"\n', '3,"4\n', '1"\n']
<del> data = [row.replace("\n", newline) for row in data]
<del> res = np.loadtxt(data, dtype=object, delimiter=",", quotechar='"')
<del> assert_array_equal(res, [['1', f'2{newline}'], ['3', f'4{newline}1']])
<del>
<del>
<del>def test_loadtxt_iterator_fails_getting_next_line():
<del> class BadSequence:
<del> def __len__(self):
<del> return 100
<del>
<del> def __getitem__(self, item):
<del> if item == 50:
<del> raise RuntimeError("Bad things happened!")
<del> return f"{item}, {item+1}"
<del>
<del> with pytest.raises(RuntimeError, match="Bad things happened!"):
<del> np.loadtxt(BadSequence(), dtype=int, delimiter=",")
<del>
<del>
<del>class TestCReaderUnitTests:
<del> # These are internal tests for path that should not be possible to hit
<del> # unless things go very very wrong somewhere.
<del> def test_not_an_filelike(self):
<del> with pytest.raises(AttributeError, match=".*read"):
<del> np.core._multiarray_umath._load_from_filelike(
<del> object(), dtype=np.dtype("i"), filelike=True)
<del>
<del> def test_filelike_read_fails(self):
<del> # Can only be reached if loadtxt opens the file, so it is hard to do
<del> # via the public interface (although maybe not impossible considering
<del> # the current "DataClass" backing).
<del> class BadFileLike:
<del> counter = 0
<del> def read(self, size):
<del> self.counter += 1
<del> if self.counter > 20:
<del> raise RuntimeError("Bad bad bad!")
<del> return "1,2,3\n"
<del>
<del> with pytest.raises(RuntimeError, match="Bad bad bad!"):
<del> np.core._multiarray_umath._load_from_filelike(
<del> BadFileLike(), dtype=np.dtype("i"), filelike=True)
<del>
<del> def test_filelike_bad_read(self):
<del> # Can only be reached if loadtxt opens the file, so it is hard to do
<del> # via the public interface (although maybe not impossible considering
<del> # the current "DataClass" backing).
<del> class BadFileLike:
<del> counter = 0
<del> def read(self, size):
<del> return 1234 # not a string!
<del>
<del> with pytest.raises(TypeError,
<del> match="non-string returned while reading data"):
<del> np.core._multiarray_umath._load_from_filelike(
<del> BadFileLike(), dtype=np.dtype("i"), filelike=True)
<del>
<del> def test_not_an_iter(self):
<del> with pytest.raises(TypeError,
<del> match="error reading from object, expected an iterable"):
<del> np.core._multiarray_umath._load_from_filelike(
<del> object(), dtype=np.dtype("i"), filelike=False)
<del>
<del> def test_bad_type(self):
<del> with pytest.raises(TypeError, match="internal error: dtype must"):
<del> np.core._multiarray_umath._load_from_filelike(
<del> object(), dtype="i", filelike=False)
<del>
<del> def test_bad_encoding(self):
<del> with pytest.raises(TypeError, match="encoding must be a unicode"):
<del> np.core._multiarray_umath._load_from_filelike(
<del> object(), dtype=np.dtype("i"), filelike=False, encoding=123)
<del>
<del> @pytest.mark.parametrize("newline", ["\r", "\n", "\r\n"])
<del> def test_manual_universal_newlines(self, newline):
<del> # This is currently not available to users, because we should always
<del> # open files with universal newlines enabled `newlines=None`.
<del> # (And reading from an iterator uses slightly different code paths.)
<del> # We have no real support for `newline="\r"` or `newline="\n" as the
<del> # user cannot specify those options.
<del> data = StringIO('0\n1\n"2\n"\n3\n4 #\n'.replace("\n", newline),
<del> newline="")
<del>
<del> res = np.core._multiarray_umath._load_from_filelike(
<del> data, dtype=np.dtype("U10"), filelike=True,
<del> quote='"', comment="#", skiplines=1)
<del> assert_array_equal(res[:, 0], ["1", f"2{newline}", "3", "4 "])
<ide><path>numpy/lib/tests/test_loadtxt.py
<add>"""
<add>Tests specific to `np.loadtxt` added during the move of loadtxt to be backed
<add>by C code.
<add>These tests complement those found in `test_io.py`.
<add>"""
<add>
<add>import sys
<add>import pytest
<add>from tempfile import NamedTemporaryFile
<add>from io import StringIO
<add>
<add>import numpy as np
<add>from numpy.ma.testutils import assert_equal
<add>from numpy.testing import assert_array_equal, HAS_REFCOUNT
<add>
<add>
<add>def test_scientific_notation():
<add> """Test that both 'e' and 'E' are parsed correctly."""
<add> data = StringIO(
<add> (
<add> "1.0e-1,2.0E1,3.0\n"
<add> "4.0e-2,5.0E-1,6.0\n"
<add> "7.0e-3,8.0E1,9.0\n"
<add> "0.0e-4,1.0E-1,2.0"
<add> )
<add> )
<add> expected = np.array(
<add> [[0.1, 20., 3.0], [0.04, 0.5, 6], [0.007, 80., 9], [0, 0.1, 2]]
<add> )
<add> assert_array_equal(np.loadtxt(data, delimiter=","), expected)
<add>
<add>
<add>@pytest.mark.parametrize("comment", ["..", "//", "@-", "this is a comment:"])
<add>def test_comment_multiple_chars(comment):
<add> content = "# IGNORE\n1.5, 2.5# ABC\n3.0,4.0# XXX\n5.5,6.0\n"
<add> txt = StringIO(content.replace("#", comment))
<add> a = np.loadtxt(txt, delimiter=",", comments=comment)
<add> assert_equal(a, [[1.5, 2.5], [3.0, 4.0], [5.5, 6.0]])
<add>
<add>
<add>@pytest.fixture
<add>def mixed_types_structured():
<add> """
<add> Fixture providing hetergeneous input data with a structured dtype, along
<add> with the associated structured array.
<add> """
<add> data = StringIO(
<add> (
<add> "1000;2.4;alpha;-34\n"
<add> "2000;3.1;beta;29\n"
<add> "3500;9.9;gamma;120\n"
<add> "4090;8.1;delta;0\n"
<add> "5001;4.4;epsilon;-99\n"
<add> "6543;7.8;omega;-1\n"
<add> )
<add> )
<add> dtype = np.dtype(
<add> [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
<add> )
<add> expected = np.array(
<add> [
<add> (1000, 2.4, "alpha", -34),
<add> (2000, 3.1, "beta", 29),
<add> (3500, 9.9, "gamma", 120),
<add> (4090, 8.1, "delta", 0),
<add> (5001, 4.4, "epsilon", -99),
<add> (6543, 7.8, "omega", -1)
<add> ],
<add> dtype=dtype
<add> )
<add> return data, dtype, expected
<add>
<add>
<add>@pytest.mark.parametrize('skiprows', [0, 1, 2, 3])
<add>def test_structured_dtype_and_skiprows_no_empty_lines(
<add> skiprows, mixed_types_structured):
<add> data, dtype, expected = mixed_types_structured
<add> a = np.loadtxt(data, dtype=dtype, delimiter=";", skiprows=skiprows)
<add> assert_array_equal(a, expected[skiprows:])
<add>
<add>
<add>def test_unpack_structured(mixed_types_structured):
<add> data, dtype, expected = mixed_types_structured
<add>
<add> a, b, c, d = np.loadtxt(data, dtype=dtype, delimiter=";", unpack=True)
<add> assert_array_equal(a, expected["f0"])
<add> assert_array_equal(b, expected["f1"])
<add> assert_array_equal(c, expected["f2"])
<add> assert_array_equal(d, expected["f3"])
<add>
<add>
<add>def test_structured_dtype_with_shape():
<add> dtype = np.dtype([("a", "u1", 2), ("b", "u1", 2)])
<add> data = StringIO("0,1,2,3\n6,7,8,9\n")
<add> expected = np.array([((0, 1), (2, 3)), ((6, 7), (8, 9))], dtype=dtype)
<add> assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dtype), expected)
<add>
<add>
<add>def test_structured_dtype_with_multi_shape():
<add> dtype = np.dtype([("a", "u1", (2, 2))])
<add> data = StringIO("0 1 2 3\n")
<add> expected = np.array([(((0, 1), (2, 3)),)], dtype=dtype)
<add> assert_array_equal(np.loadtxt(data, dtype=dtype), expected)
<add>
<add>
<add>def test_nested_structured_subarray():
<add> # Test from gh-16678
<add> point = np.dtype([('x', float), ('y', float)])
<add> dt = np.dtype([('code', int), ('points', point, (2,))])
<add> data = StringIO("100,1,2,3,4\n200,5,6,7,8\n")
<add> expected = np.array(
<add> [
<add> (100, [(1., 2.), (3., 4.)]),
<add> (200, [(5., 6.), (7., 8.)]),
<add> ],
<add> dtype=dt
<add> )
<add> assert_array_equal(np.loadtxt(data, dtype=dt, delimiter=","), expected)
<add>
<add>
<add>def test_structured_dtype_offsets():
<add> # An aligned structured dtype will have additional padding
<add> dt = np.dtype("i1, i4, i1, i4, i1, i4", align=True)
<add> data = StringIO("1,2,3,4,5,6\n7,8,9,10,11,12\n")
<add> expected = np.array([(1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12)], dtype=dt)
<add> assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dt), expected)
<add>
<add>
<add>@pytest.mark.parametrize("param", ("skiprows", "max_rows"))
<add>def test_exception_negative_row_limits(param):
<add> """skiprows and max_rows should raise for negative parameters."""
<add> with pytest.raises(ValueError, match="argument must be nonnegative"):
<add> np.loadtxt("foo.bar", **{param: -3})
<add>
<add>
<add>@pytest.mark.parametrize("param", ("skiprows", "max_rows"))
<add>def test_exception_noninteger_row_limits(param):
<add> with pytest.raises(TypeError, match="argument must be an integer"):
<add> np.loadtxt("foo.bar", **{param: 1.0})
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "data, shape",
<add> [
<add> ("1 2 3 4 5\n", (1, 5)), # Single row
<add> ("1\n2\n3\n4\n5\n", (5, 1)), # Single column
<add> ]
<add>)
<add>def test_ndmin_single_row_or_col(data, shape):
<add> arr = np.array([1, 2, 3, 4, 5])
<add> arr2d = arr.reshape(shape)
<add>
<add> assert_array_equal(np.loadtxt(StringIO(data), dtype=int), arr)
<add> assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=0), arr)
<add> assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=1), arr)
<add> assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=2), arr2d)
<add>
<add>
<add>@pytest.mark.parametrize("badval", [-1, 3, None, "plate of shrimp"])
<add>def test_bad_ndmin(badval):
<add> with pytest.raises(ValueError, match="Illegal value of ndmin keyword"):
<add> np.loadtxt("foo.bar", ndmin=badval)
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "ws",
<add> (
<add> "\t", # tab
<add> "\u2003", # em
<add> "\u00A0", # non-break
<add> "\u3000", # ideographic space
<add> )
<add>)
<add>def test_blank_lines_spaces_delimit(ws):
<add> txt = StringIO(
<add> f"1 2{ws}30\n\n4 5 60\n {ws} \n7 8 {ws} 90\n # comment\n3 2 1"
<add> )
<add> # NOTE: It is unclear that the ` # comment` should succeed. Except
<add> # for delimiter=None, which should use any whitespace (and maybe
<add> # should just be implemented closer to Python
<add> expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
<add> assert_equal(
<add> np.loadtxt(txt, dtype=int, delimiter=None, comments="#"), expected
<add> )
<add>
<add>
<add>def test_blank_lines_normal_delimiter():
<add> txt = StringIO('1,2,30\n\n4,5,60\n\n7,8,90\n# comment\n3,2,1')
<add> expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
<add> assert_equal(
<add> np.loadtxt(txt, dtype=int, delimiter=',', comments="#"), expected
<add> )
<add>
<add>
<add>@pytest.mark.parametrize("dtype", (float, object))
<add>def test_maxrows_no_blank_lines(dtype):
<add> txt = StringIO("1.5,2.5\n3.0,4.0\n5.5,6.0")
<add> res = np.loadtxt(txt, dtype=dtype, delimiter=",", max_rows=2)
<add> assert_equal(res.dtype, dtype)
<add> assert_equal(res, np.array([["1.5", "2.5"], ["3.0", "4.0"]], dtype=dtype))
<add>
<add>
<add>@pytest.mark.parametrize("dtype", (np.dtype("f8"), np.dtype("i2")))
<add>def test_exception_message_bad_values(dtype):
<add> txt = StringIO("1,2\n3,XXX\n5,6")
<add> msg = f"could not convert string 'XXX' to {dtype} at row 1, column 2"
<add> with pytest.raises(ValueError, match=msg):
<add> np.loadtxt(txt, dtype=dtype, delimiter=",")
<add>
<add>
<add>def test_converters_negative_indices():
<add> txt = StringIO('1.5,2.5\n3.0,XXX\n5.5,6.0')
<add> conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
<add> expected = np.array([[1.5, 2.5], [3.0, np.nan], [5.5, 6.0]])
<add> res = np.loadtxt(
<add> txt, dtype=np.float64, delimiter=",", converters=conv, encoding=None
<add> )
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_converters_negative_indices_with_usecols():
<add> txt = StringIO('1.5,2.5,3.5\n3.0,4.0,XXX\n5.5,6.0,7.5\n')
<add> conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
<add> expected = np.array([[1.5, 3.5], [3.0, np.nan], [5.5, 7.5]])
<add> res = np.loadtxt(
<add> txt,
<add> dtype=np.float64,
<add> delimiter=",",
<add> converters=conv,
<add> usecols=[0, -1],
<add> encoding=None,
<add> )
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_ragged_usecols():
<add> # usecols, and negative ones, work even with varying number of columns.
<add> txt = StringIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
<add> expected = np.array([[0, 0], [0, 0], [0, 0]])
<add> res = np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
<add> assert_equal(res, expected)
<add>
<add> txt = StringIO("0,0,XXX\n0\n0,XXX,XXX,0,XXX\n")
<add> with pytest.raises(ValueError,
<add> match="invalid column index -2 at row 1 with 2 columns"):
<add> # There is no -2 column in the second row:
<add> np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
<add>
<add>
<add>def test_empty_usecols():
<add> txt = StringIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
<add> res = np.loadtxt(txt, dtype=np.dtype([]), delimiter=",", usecols=[])
<add> assert res.shape == (3,)
<add> assert res.dtype == np.dtype([])
<add>
<add>
<add>@pytest.mark.parametrize("c1", ["a", "の", "🫕"])
<add>@pytest.mark.parametrize("c2", ["a", "の", "🫕"])
<add>def test_large_unicode_characters(c1, c2):
<add> # c1 and c2 span ascii, 16bit and 32bit range.
<add> txt = StringIO(f"a,{c1},c,1.0\ne,{c2},2.0,g")
<add> res = np.loadtxt(txt, dtype=np.dtype('U12'), delimiter=",")
<add> expected = np.array(
<add> [f"a,{c1},c,1.0".split(","), f"e,{c2},2.0,g".split(",")],
<add> dtype=np.dtype('U12')
<add> )
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_unicode_with_converter():
<add> txt = StringIO("cat,dog\nαβγ,δεζ\nabc,def\n")
<add> conv = {0: lambda s: s.upper()}
<add> res = np.loadtxt(
<add> txt,
<add> dtype=np.dtype("U12"),
<add> converters=conv,
<add> delimiter=",",
<add> encoding=None
<add> )
<add> expected = np.array([['CAT', 'dog'], ['ΑΒΓ', 'δεζ'], ['ABC', 'def']])
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_converter_with_structured_dtype():
<add> txt = StringIO('1.5,2.5,Abc\n3.0,4.0,dEf\n5.5,6.0,ghI\n')
<add> dt = np.dtype([('m', np.int32), ('r', np.float32), ('code', 'U8')])
<add> conv = {0: lambda s: int(10*float(s)), -1: lambda s: s.upper()}
<add> res = np.loadtxt(txt, dtype=dt, delimiter=",", converters=conv)
<add> expected = np.array(
<add> [(15, 2.5, 'ABC'), (30, 4.0, 'DEF'), (55, 6.0, 'GHI')], dtype=dt
<add> )
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_converter_with_unicode_dtype():
<add> """
<add> With the default 'bytes' encoding, tokens are encoded prior to being passed
<add> to the converter. This means that the output of the converter may be bytes
<add> instead of unicode as expected by `read_rows`.
<add>
<add> This test checks that outputs from the above scenario are properly decoded
<add> prior to parsing by `read_rows`.
<add> """
<add> txt = StringIO('abc,def\nrst,xyz')
<add> conv = bytes.upper
<add> res = np.loadtxt(txt, dtype=np.dtype("U3"), converters=conv, delimiter=",")
<add> expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']])
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_read_huge_row():
<add> row = "1.5, 2.5," * 50000
<add> row = row[:-1] + "\n"
<add> txt = StringIO(row * 2)
<add> res = np.loadtxt(txt, delimiter=",", dtype=float)
<add> assert_equal(res, np.tile([1.5, 2.5], (2, 50000)))
<add>
<add>
<add>@pytest.mark.parametrize("dtype", "edfgFDG")
<add>def test_huge_float(dtype):
<add> # Covers a non-optimized path that is rarely taken:
<add> field = "0" * 1000 + ".123456789"
<add> dtype = np.dtype(dtype)
<add> value = np.loadtxt([field], dtype=dtype)[()]
<add> assert value == dtype.type("0.123456789")
<add>
<add>
<add>@pytest.mark.parametrize(
<add> ("given_dtype", "expected_dtype"),
<add> [
<add> ("S", np.dtype("S5")),
<add> ("U", np.dtype("U5")),
<add> ],
<add>)
<add>def test_string_no_length_given(given_dtype, expected_dtype):
<add> """
<add> The given dtype is just 'S' or 'U' with no length. In these cases, the
<add> length of the resulting dtype is determined by the longest string found
<add> in the file.
<add> """
<add> txt = StringIO("AAA,5-1\nBBBBB,0-3\nC,4-9\n")
<add> res = np.loadtxt(txt, dtype=given_dtype, delimiter=",")
<add> expected = np.array(
<add> [['AAA', '5-1'], ['BBBBB', '0-3'], ['C', '4-9']], dtype=expected_dtype
<add> )
<add> assert_equal(res, expected)
<add> assert_equal(res.dtype, expected_dtype)
<add>
<add>
<add>def test_float_conversion():
<add> """
<add> Some tests that the conversion to float64 works as accurately as the Python
<add> built-in `float` function. In a naive version of the float parser, these
<add> strings resulted in values that were off by an ULP or two.
<add> """
<add> strings = [
<add> '0.9999999999999999',
<add> '9876543210.123456',
<add> '5.43215432154321e+300',
<add> '0.901',
<add> '0.333',
<add> ]
<add> txt = StringIO('\n'.join(strings))
<add> res = np.loadtxt(txt)
<add> expected = np.array([float(s) for s in strings])
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_bool():
<add> # Simple test for bool via integer
<add> txt = StringIO("1, 0\n10, -1")
<add> res = np.loadtxt(txt, dtype=bool, delimiter=",")
<add> assert res.dtype == bool
<add> assert_array_equal(res, [[True, False], [True, True]])
<add> # Make sure we use only 1 and 0 on the byte level:
<add> assert_array_equal(res.view(np.uint8), [[1, 0], [1, 1]])
<add>
<add>
<add>@pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
<add>def test_integer_signs(dtype):
<add> dtype = np.dtype(dtype)
<add> assert np.loadtxt(["+2"], dtype=dtype) == 2
<add> if dtype.kind == "u":
<add> with pytest.raises(ValueError):
<add> np.loadtxt(["-1\n"], dtype=dtype)
<add> else:
<add> assert np.loadtxt(["-2\n"], dtype=dtype) == -2
<add>
<add> for sign in ["++", "+-", "--", "-+"]:
<add> with pytest.raises(ValueError):
<add> np.loadtxt([f"{sign}2\n"], dtype=dtype)
<add>
<add>
<add>@pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
<add>def test_implicit_cast_float_to_int_fails(dtype):
<add> txt = StringIO("1.0, 2.1, 3.7\n4, 5, 6")
<add> with pytest.raises(ValueError):
<add> np.loadtxt(txt, dtype=dtype, delimiter=",")
<add>
<add>@pytest.mark.parametrize("dtype", (np.complex64, np.complex128))
<add>@pytest.mark.parametrize("with_parens", (False, True))
<add>def test_complex_parsing(dtype, with_parens):
<add> s = "(1.0-2.5j),3.75,(7+-5.0j)\n(4),(-19e2j),(0)"
<add> if not with_parens:
<add> s = s.replace("(", "").replace(")", "")
<add>
<add> res = np.loadtxt(StringIO(s), dtype=dtype, delimiter=",")
<add> expected = np.array(
<add> [[1.0-2.5j, 3.75, 7-5j], [4.0, -1900j, 0]], dtype=dtype
<add> )
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_read_from_generator():
<add> def gen():
<add> for i in range(4):
<add> yield f"{i},{2*i},{i**2}"
<add>
<add> res = np.loadtxt(gen(), dtype=int, delimiter=",")
<add> expected = np.array([[0, 0, 0], [1, 2, 1], [2, 4, 4], [3, 6, 9]])
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_read_from_generator_multitype():
<add> def gen():
<add> for i in range(3):
<add> yield f"{i} {i / 4}"
<add>
<add> res = np.loadtxt(gen(), dtype="i, d", delimiter=" ")
<add> expected = np.array([(0, 0.0), (1, 0.25), (2, 0.5)], dtype="i, d")
<add> assert_equal(res, expected)
<add>
<add>
<add>def test_read_from_bad_generator():
<add> def gen():
<add> for entry in ["1,2", b"3, 5", 12738]:
<add> yield entry
<add>
<add> with pytest.raises(
<add> TypeError, match=r"non-string returned while reading data"
<add> ):
<add> np.loadtxt(gen(), dtype="i, i", delimiter=",")
<add>
<add>
<add>@pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
<add>def test_object_cleanup_on_read_error():
<add> sentinel = object()
<add>
<add> already_read = 0
<add> def conv(x):
<add> nonlocal already_read
<add> if already_read > 4999:
<add> raise ValueError("failed half-way through!")
<add> already_read += 1
<add> return sentinel
<add>
<add> txt = StringIO("x\n" * 10000)
<add>
<add> with pytest.raises(ValueError, match="at row 5000, column 1"):
<add> np.loadtxt(txt, dtype=object, converters={0: conv})
<add>
<add> assert sys.getrefcount(sentinel) == 2
<add>
<add>
<add>def test_character_not_bytes_compatible():
<add> """Test exception when a character cannot be encoded as 'S'."""
<add> data = StringIO("–") # == \u2013
<add> with pytest.raises(ValueError):
<add> np.loadtxt(data, dtype="S5")
<add>
<add>
<add>@pytest.mark.parametrize("conv", (0, [float], ""))
<add>def test_invalid_converter(conv):
<add> msg = (
<add> "converters must be a dictionary mapping columns to converter "
<add> "functions or a single callable."
<add> )
<add> with pytest.raises(TypeError, match=msg):
<add> np.loadtxt(StringIO("1 2\n3 4"), converters=conv)
<add>
<add>
<add>def test_converters_dict_raises_non_integer_key():
<add> with pytest.raises(TypeError, match="keys of the converters dict"):
<add> np.loadtxt(StringIO("1 2\n3 4"), converters={"a": int})
<add> with pytest.raises(TypeError, match="keys of the converters dict"):
<add> np.loadtxt(StringIO("1 2\n3 4"), converters={"a": int}, usecols=0)
<add>
<add>
<add>@pytest.mark.parametrize("bad_col_ind", (3, -3))
<add>def test_converters_dict_raises_non_col_key(bad_col_ind):
<add> data = StringIO("1 2\n3 4")
<add> with pytest.raises(ValueError, match="converter specified for column"):
<add> np.loadtxt(data, converters={bad_col_ind: int})
<add>
<add>
<add>def test_converters_dict_raises_val_not_callable():
<add> with pytest.raises(
<add> TypeError, match="values of the converters dictionary must be callable"
<add> ):
<add> np.loadtxt(StringIO("1 2\n3 4"), converters={0: 1})
<add>
<add>
<add>@pytest.mark.parametrize("q", ('"', "'", "`"))
<add>def test_quoted_field(q):
<add> txt = StringIO(
<add> f"{q}alpha, x{q}, 2.5\n{q}beta, y{q}, 4.5\n{q}gamma, z{q}, 5.0\n"
<add> )
<add> dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])
<add> expected = np.array(
<add> [("alpha, x", 2.5), ("beta, y", 4.5), ("gamma, z", 5.0)], dtype=dtype
<add> )
<add>
<add> res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar=q)
<add> assert_array_equal(res, expected)
<add>
<add>
<add>def test_quote_support_default():
<add> """Support for quoted fields is disabled by default."""
<add> txt = StringIO('"lat,long", 45, 30\n')
<add> dtype = np.dtype([('f0', 'U24'), ('f1', np.float64), ('f2', np.float64)])
<add>
<add> with pytest.raises(ValueError, match="the number of columns changed"):
<add> np.loadtxt(txt, dtype=dtype, delimiter=",")
<add>
<add> # Enable quoting support with non-None value for quotechar param
<add> txt.seek(0)
<add> expected = np.array([("lat,long", 45., 30.)], dtype=dtype)
<add>
<add> res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
<add> assert_array_equal(res, expected)
<add>
<add>
<add>def test_quotechar_multichar_error():
<add> txt = StringIO("1,2\n3,4")
<add> msg = r".*must be a single unicode character or None"
<add> with pytest.raises(TypeError, match=msg):
<add> np.loadtxt(txt, delimiter=",", quotechar="''")
<add>
<add>
<add>def test_comment_multichar_error_with_quote():
<add> txt = StringIO("1,2\n3,4")
<add> msg = (
<add> "when multiple comments or a multi-character comment is given, "
<add> "quotes are not supported."
<add> )
<add> with pytest.raises(ValueError, match=msg):
<add> np.loadtxt(txt, delimiter=",", comments="123", quotechar='"')
<add> with pytest.raises(ValueError, match=msg):
<add> np.loadtxt(txt, delimiter=",", comments=["#", "%"], quotechar='"')
<add>
<add> # A single character string in a tuple is unpacked though:
<add> res = np.loadtxt(txt, delimiter=",", comments=("#",), quotechar="'")
<add> assert_equal(res, [[1, 2], [3, 4]])
<add>
<add>
<add>def test_structured_dtype_with_quotes():
<add> data = StringIO(
<add> (
<add> "1000;2.4;'alpha';-34\n"
<add> "2000;3.1;'beta';29\n"
<add> "3500;9.9;'gamma';120\n"
<add> "4090;8.1;'delta';0\n"
<add> "5001;4.4;'epsilon';-99\n"
<add> "6543;7.8;'omega';-1\n"
<add> )
<add> )
<add> dtype = np.dtype(
<add> [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
<add> )
<add> expected = np.array(
<add> [
<add> (1000, 2.4, "alpha", -34),
<add> (2000, 3.1, "beta", 29),
<add> (3500, 9.9, "gamma", 120),
<add> (4090, 8.1, "delta", 0),
<add> (5001, 4.4, "epsilon", -99),
<add> (6543, 7.8, "omega", -1)
<add> ],
<add> dtype=dtype
<add> )
<add> res = np.loadtxt(data, dtype=dtype, delimiter=";", quotechar="'")
<add> assert_array_equal(res, expected)
<add>
<add>
<add>def test_quoted_field_is_not_empty():
<add> txt = StringIO('1\n\n"4"\n""')
<add> expected = np.array(["1", "4", ""], dtype="U1")
<add> res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
<add> assert_equal(res, expected)
<add>
<add>def test_quoted_field_is_not_empty_nonstrict():
<add> # Same as test_quoted_field_is_not_empty but check that we are not strict
<add> # about missing closing quote (this is the `csv.reader` default also)
<add> txt = StringIO('1\n\n"4"\n"')
<add> expected = np.array(["1", "4", ""], dtype="U1")
<add> res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
<add> assert_equal(res, expected)
<add>
<add>def test_consecutive_quotechar_escaped():
<add> txt = StringIO('"Hello, my name is ""Monty""!"')
<add> expected = np.array('Hello, my name is "Monty"!', dtype="U40")
<add> res = np.loadtxt(txt, dtype="U40", delimiter=",", quotechar='"')
<add> assert_equal(res, expected)
<add>
<add>
<add>@pytest.mark.parametrize("data", ("", "\n\n\n", "# 1 2 3\n# 4 5 6\n"))
<add>@pytest.mark.parametrize("ndmin", (0, 1, 2))
<add>@pytest.mark.parametrize("usecols", [None, (1, 2, 3)])
<add>def test_warn_on_no_data(data, ndmin, usecols):
<add> """Check that a UserWarning is emitted when no data is read from input."""
<add> if usecols is not None:
<add> expected_shape = (0, 3)
<add> elif ndmin == 2:
<add> expected_shape = (0, 1) # guess a single column?!
<add> else:
<add> expected_shape = (0,)
<add>
<add> txt = StringIO(data)
<add> with pytest.warns(UserWarning, match="input contained no data"):
<add> res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
<add> assert res.shape == expected_shape
<add>
<add> with NamedTemporaryFile(mode="w") as fh:
<add> fh.write(data)
<add> fh.seek(0)
<add> with pytest.warns(UserWarning, match="input contained no data"):
<add> res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
<add> assert res.shape == expected_shape
<add>
<add>@pytest.mark.parametrize("skiprows", (2, 3))
<add>def test_warn_on_skipped_data(skiprows):
<add> data = "1 2 3\n4 5 6"
<add> txt = StringIO(data)
<add> with pytest.warns(UserWarning, match="input contained no data"):
<add> np.loadtxt(txt, skiprows=skiprows)
<add>
<add>
<add>@pytest.mark.parametrize("dtype",
<add> list(np.typecodes["AllInteger"] + np.typecodes["AllFloat"]) + ["U2"])
<add>@pytest.mark.parametrize("swap", [True, False])
<add>def test_byteswapping_and_unaligned(dtype, swap):
<add> data = ["x,1\n"] # no need for complicated data
<add> dtype = np.dtype(dtype)
<add> if swap:
<add> dtype = dtype.newbyteorder()
<add> full_dt = np.dtype([("a", "S1"), ("b", dtype)], align=False)
<add> # The above ensures that the interesting "b" field is unaligned:
<add> assert full_dt.fields["b"][1] == 1
<add> res = np.loadtxt(data, dtype=full_dt, delimiter=",")
<add> assert res["b"] == dtype.type(1)
<add>
<add>
<add>@pytest.mark.parametrize("dtype",
<add> np.typecodes["AllInteger"] + "efdFD" + "?")
<add>def test_unicode_whitespace_stripping(dtype):
<add> # Test that all numeric types (and bool) strip whitespace correctly
<add> # \u202F is a narrow no-break space, `\n` is just a whitespace if quoted.
<add> # Currently, skip float128 as it did not always support this and has no
<add> # "custom" parsing:
<add> txt = StringIO(' 3 ,"\u202F2\n"')
<add> res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
<add> assert_array_equal(res, np.array([3, 2]).astype(dtype))
<add>
<add>
<add>@pytest.mark.parametrize("dtype", "FD")
<add>def test_unicode_whitespace_stripping_complex(dtype):
<add> # Complex has a few extra cases since it has two components and parentheses
<add> line = " 1 , 2+3j , ( 4+5j ), ( 6+-7j ) , 8j , ( 9j ) \n"
<add> data = [line, line.replace(" ", "\u202F")]
<add> res = np.loadtxt(data, dtype=dtype, delimiter=',')
<add> assert_array_equal(res, np.array([[1, 2+3j, 4+5j, 6-7j, 8j, 9j]] * 2))
<add>
<add>
<add>@pytest.mark.parametrize("dtype", "FD")
<add>@pytest.mark.parametrize("field",
<add> ["1 +2j", "1+ 2j", "1+2 j", "1+-+3", "(1j", "(1", "(1+2j", "1+2j)"])
<add>def test_bad_complex(dtype, field):
<add> with pytest.raises(ValueError):
<add> np.loadtxt([field + "\n"], dtype=dtype, delimiter=",")
<add>
<add>
<add>@pytest.mark.parametrize("dtype",
<add> np.typecodes["AllInteger"] + "efgdFDG" + "?")
<add>def test_nul_character_error(dtype):
<add> # Test that a \0 character is correctly recognized as an error even if
<add> # what comes before is valid (not everything gets parsed internally).
<add> if dtype.lower() == "g":
<add> pytest.xfail("longdouble/clongdouble assignment may misbehave.")
<add> with pytest.raises(ValueError):
<add> np.loadtxt(["1\000"], dtype=dtype, delimiter=",", quotechar='"')
<add>
<add>
<add>@pytest.mark.parametrize("dtype",
<add> np.typecodes["AllInteger"] + "efgdFDG" + "?")
<add>def test_no_thousands_support(dtype):
<add> # Mainly to document behaviour, Python supports thousands like 1_1.
<add> # (e and G may end up using different conversion and support it, this is
<add> # a bug but happens...)
<add> if dtype == "e":
<add> pytest.skip("half assignment currently uses Python float converter")
<add> if dtype in "eG":
<add> pytest.xfail("clongdouble assignment is buggy (uses `complex` always).")
<add>
<add> assert int("1_1") == float("1_1") == complex("1_1") == 11
<add> with pytest.raises(ValueError):
<add> np.loadtxt(["1_1\n"], dtype=dtype)
<add>
<add>
<add>@pytest.mark.parametrize("data", [
<add> ["1,2\n", "2\n,3\n"],
<add> ["1,2\n", "2\r,3\n"]])
<add>def test_bad_newline_in_iterator(data):
<add> # In NumPy <=1.22 this was accepted, because newlines were completely
<add> # ignored when the input was an iterable. This could be changed, but right
<add> # now, we raise an error.
<add> with pytest.raises(ValueError,
<add> match="Found an unquoted embedded newline within a single line"):
<add> np.loadtxt(data, delimiter=",")
<add>
<add>
<add>@pytest.mark.parametrize("data", [
<add> ["1,2\n", "2,3\r\n"], # a universal newline
<add> ["1,2\n", "'2\n',3\n"], # a quoted newline
<add> ["1,2\n", "'2\r',3\n"],
<add> ["1,2\n", "'2\r\n',3\n"],
<add>])
<add>def test_good_newline_in_iterator(data):
<add> # The quoted newlines will be untransformed here, but are just whitespace.
<add> res = np.loadtxt(data, delimiter=",", quotechar="'")
<add> assert_array_equal(res, [[1., 2.], [2., 3.]])
<add>
<add>
<add>@pytest.mark.parametrize("newline", ["\n", "\r", "\r\n"])
<add>def test_universal_newlines_quoted(newline):
<add> # Check that universal newline support within the tokenizer is not applied
<add> # to quoted fields. (note that lines must end in newline or quoted
<add> # fields will not include a newline at all)
<add> data = ['1,"2\n"\n', '3,"4\n', '1"\n']
<add> data = [row.replace("\n", newline) for row in data]
<add> res = np.loadtxt(data, dtype=object, delimiter=",", quotechar='"')
<add> assert_array_equal(res, [['1', f'2{newline}'], ['3', f'4{newline}1']])
<add>
<add>
<add>def test_null_character():
<add> # Basic tests to check that the NUL character is not special:
<add> res = np.loadtxt(["1\0002\0003\n", "4\0005\0006"], delimiter="\000")
<add> assert_array_equal(res, [[1, 2, 3], [4, 5, 6]])
<add>
<add> # Also not as part of a field (avoid unicode/arrays as unicode strips \0)
<add> res = np.loadtxt(["1\000,2\000,3\n", "4\000,5\000,6"],
<add> delimiter=",", dtype=object)
<add> assert res.tolist() == [["1\000", "2\000", "3"], ["4\000", "5\000", "6"]]
<add>
<add>
<add>def test_iterator_fails_getting_next_line():
<add> class BadSequence:
<add> def __len__(self):
<add> return 100
<add>
<add> def __getitem__(self, item):
<add> if item == 50:
<add> raise RuntimeError("Bad things happened!")
<add> return f"{item}, {item+1}"
<add>
<add> with pytest.raises(RuntimeError, match="Bad things happened!"):
<add> np.loadtxt(BadSequence(), dtype=int, delimiter=",")
<add>
<add>
<add>class TestCReaderUnitTests:
<add> # These are internal tests for path that should not be possible to hit
<add> # unless things go very very wrong somewhere.
<add> def test_not_an_filelike(self):
<add> with pytest.raises(AttributeError, match=".*read"):
<add> np.core._multiarray_umath._load_from_filelike(
<add> object(), dtype=np.dtype("i"), filelike=True)
<add>
<add> def test_filelike_read_fails(self):
<add> # Can only be reached if loadtxt opens the file, so it is hard to do
<add> # via the public interface (although maybe not impossible considering
<add> # the current "DataClass" backing).
<add> class BadFileLike:
<add> counter = 0
<add> def read(self, size):
<add> self.counter += 1
<add> if self.counter > 20:
<add> raise RuntimeError("Bad bad bad!")
<add> return "1,2,3\n"
<add>
<add> with pytest.raises(RuntimeError, match="Bad bad bad!"):
<add> np.core._multiarray_umath._load_from_filelike(
<add> BadFileLike(), dtype=np.dtype("i"), filelike=True)
<add>
<add> def test_filelike_bad_read(self):
<add> # Can only be reached if loadtxt opens the file, so it is hard to do
<add> # via the public interface (although maybe not impossible considering
<add> # the current "DataClass" backing).
<add> class BadFileLike:
<add> counter = 0
<add> def read(self, size):
<add> return 1234 # not a string!
<add>
<add> with pytest.raises(TypeError,
<add> match="non-string returned while reading data"):
<add> np.core._multiarray_umath._load_from_filelike(
<add> BadFileLike(), dtype=np.dtype("i"), filelike=True)
<add>
<add> def test_not_an_iter(self):
<add> with pytest.raises(TypeError,
<add> match="error reading from object, expected an iterable"):
<add> np.core._multiarray_umath._load_from_filelike(
<add> object(), dtype=np.dtype("i"), filelike=False)
<add>
<add> def test_bad_type(self):
<add> with pytest.raises(TypeError, match="internal error: dtype must"):
<add> np.core._multiarray_umath._load_from_filelike(
<add> object(), dtype="i", filelike=False)
<add>
<add> def test_bad_encoding(self):
<add> with pytest.raises(TypeError, match="encoding must be a unicode"):
<add> np.core._multiarray_umath._load_from_filelike(
<add> object(), dtype=np.dtype("i"), filelike=False, encoding=123)
<add>
<add> @pytest.mark.parametrize("newline", ["\r", "\n", "\r\n"])
<add> def test_manual_universal_newlines(self, newline):
<add> # This is currently not available to users, because we should always
<add> # open files with universal newlines enabled `newlines=None`.
<add> # (And reading from an iterator uses slightly different code paths.)
<add> # We have no real support for `newline="\r"` or `newline="\n" as the
<add> # user cannot specify those options.
<add> data = StringIO('0\n1\n"2\n"\n3\n4 #\n'.replace("\n", newline),
<add> newline="")
<add>
<add> res = np.core._multiarray_umath._load_from_filelike(
<add> data, dtype=np.dtype("U10"), filelike=True,
<add> quote='"', comment="#", skiplines=1)
<add> assert_array_equal(res[:, 0], ["1", f"2{newline}", "3", "4 "]) | 2 |
Python | Python | replace xrange by range | 190f7df6dff4f06b5d61e04ab375185089fc91dd | <ide><path>numpy/core/tests/test_nditer.py
<ide> def test_iter_buffered_reduce_reuse():
<ide> op_dtypes = [np.float, a.dtype]
<ide>
<ide> def get_params():
<del> for xs in xrange(-3**2, 3**2 + 1):
<del> for ys in xrange(xs, 3**2 + 1):
<add> for xs in range(-3**2, 3**2 + 1):
<add> for ys in range(xs, 3**2 + 1):
<ide> for op_axes in op_axes_list:
<ide> # last stride is reduced and because of that not
<ide> # important for this test, as it is the inner stride.
<ide> strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize)
<ide> arr = np.lib.stride_tricks.as_strided(a, (3,3,3), strides)
<del>
<add>
<ide> for skip in [0, 1]:
<ide> yield arr, op_axes, skip
<del>
<add>
<ide> for arr, op_axes, skip in get_params():
<ide> nditer2 = np.nditer([arr.copy(), None],
<ide> op_axes=op_axes, flags=flags, op_flags=op_flags,
<ide> op_dtypes=op_dtypes)
<ide> nditer2.operands[-1][...] = 0
<ide> nditer2.reset()
<del> nditer2.iterindex = skip
<add> nditer2.iterindex = skip
<ide>
<ide> for (a2_in, b2_in) in nditer2:
<ide> b2_in += a2_in.astype(np.int_)
<ide>
<ide> comp_res = nditer2.operands[-1]
<ide>
<del> for bufsize in xrange(0, 3**3):
<add> for bufsize in range(0, 3**3):
<ide> nditer1 = np.nditer([arr, None],
<ide> op_axes=op_axes, flags=flags, op_flags=op_flags,
<ide> buffersize=bufsize, op_dtypes=op_dtypes)
<ide> nditer1.operands[-1][...] = 0
<ide> nditer1.reset()
<ide> nditer1.iterindex = skip
<del>
<add>
<ide> for (a1_in, b1_in) in nditer1:
<ide> b1_in += a1_in.astype(np.int_)
<ide> | 1 |
Python | Python | improve test coverage of snshook | 63d38b82a93595021dfdb438eadb6e8ef2ded7af | <ide><path>tests/providers/amazon/aws/hooks/test_sns.py
<ide> def test_publish_to_target_plain(self):
<ide> response = hook.publish_to_target(target, message)
<ide>
<ide> assert 'MessageId' in response
<add>
<add> @mock_sns
<add> def test_publish_to_target_error(self):
<add> hook = SnsHook(aws_conn_id='aws_default')
<add>
<add> message = "Hello world"
<add> topic_name = "test-topic"
<add> target = hook.get_conn().create_topic(Name=topic_name).get('TopicArn')
<add>
<add> with self.assertRaises(TypeError) as ctx:
<add> hook.publish_to_target(
<add> target,
<add> message,
<add> message_attributes={
<add> 'test-non-iterable': object(),
<add> },
<add> )
<add>
<add> self.assertEqual(
<add> "Values in MessageAttributes must be one of bytes, str, int, float, "
<add> "or iterable; got <class 'object'>",
<add> str(ctx.exception),
<add> ) | 1 |
Ruby | Ruby | improve manpage output | 0fff6e0c09f2d1bdf9d1486b193840f0b1bc356e | <ide><path>Library/Homebrew/dev-cmd/man.rb
<ide> require "erb"
<ide> require "ostruct"
<ide> require "cli_parser"
<del>require "dev-cmd/audit"
<del>require "dev-cmd/bottle"
<del>require "dev-cmd/bump-formula-pr"
<del>require "dev-cmd/create"
<del>require "dev-cmd/edit"
<del>require "dev-cmd/extract"
<del>require "dev-cmd/formula"
<del>require "dev-cmd/irb"
<del>require "dev-cmd/linkage"
<del>require "dev-cmd/mirror"
<del>require "dev-cmd/prof"
<del>require "dev-cmd/pull"
<del>require "dev-cmd/release-notes"
<del>require "dev-cmd/ruby"
<del>require "dev-cmd/tap-new"
<del>require "dev-cmd/test"
<del>require "dev-cmd/tests"
<del>require "dev-cmd/update-test"
<add># Require all commands
<add>Dir.glob("#{HOMEBREW_LIBRARY_PATH}/{dev-,}cmd/*.rb").each { |cmd| require cmd }
<ide>
<ide> module Homebrew
<ide> module_function
<ide> def regenerate_man_pages
<ide> convert_man_page(cask_markup, TARGET_MAN_PATH/"brew-cask.1")
<ide> end
<ide>
<del> def path_glob_commands(glob)
<del> Pathname.glob(glob)
<del> .sort_by { |source_file| sort_key_for_path(source_file) }
<del> .map(&:read).map(&:lines)
<del> .map { |lines| lines.grep(/^#:/).map { |line| line.slice(2..-1) }.join }
<del> .reject { |s| s.strip.empty? || s.include?("@hide_from_man_page") }
<del> end
<del>
<ide> def build_man_page
<ide> template = (SOURCE_PATH/"brew.1.md.erb").read
<ide> variables = OpenStruct.new
<ide>
<del> variables[:commands] = path_glob_commands("#{HOMEBREW_LIBRARY_PATH}/cmd/*.{rb,sh}")
<add> variables[:commands] = generate_cmd_manpages("#{HOMEBREW_LIBRARY_PATH}/cmd/*.{rb,sh}")
<add> variables[:developer_commands] = generate_cmd_manpages("#{HOMEBREW_LIBRARY_PATH}/dev-cmd/{*.rb,sh}")
<add> variables[:global_options] = global_options_manpage
<ide>
<del> variables[:developer_commands] = generate_cmd_manpages("#{HOMEBREW_LIBRARY_PATH}/dev-cmd/*.{rb,sh}")
<del> variables[:global_options] = global_options_manpage_lines
<ide> readme = HOMEBREW_REPOSITORY/"README.md"
<ide> variables[:lead_maintainer] =
<ide> readme.read[/(Homebrew's lead maintainer .*\.)/, 1]
<ide> def build_man_page
<ide> readme.read[/(Former maintainers .*\.)/, 1]
<ide> .gsub(/\[([^\]]+)\]\([^)]+\)/, '\1')
<ide>
<del> variables[:homebrew_bundle] = help_output(:bundle)
<del> variables[:homebrew_services] = help_output(:services)
<del>
<ide> ERB.new(template, nil, ">").result(variables.instance_eval { binding })
<ide> end
<ide>
<ide> def convert_man_page(markup, target)
<ide> odie "Got no output from ronn!" unless ronn_output
<ide> if format_flag == "--markdown"
<ide> ronn_output = ronn_output.gsub(%r{<var>(.*?)</var>}, "*`\\1`*")
<add> .gsub(/\n\n\n+/, "\n\n")
<ide> elsif format_flag == "--roff"
<ide> ronn_output = ronn_output.gsub(%r{<code>(.*?)</code>}, "\\fB\\1\\fR")
<ide> .gsub(%r{<var>(.*?)</var>}, "\\fI\\1\\fR")
<ide> def convert_man_page(markup, target)
<ide> end
<ide> end
<ide>
<del> def help_output(command)
<del> tap = Tap.fetch("Homebrew/homebrew-#{command}")
<del> tap.install unless tap.installed?
<del> command_help_lines(which("brew-#{command}.rb", Tap.cmd_directories))
<del> end
<del>
<ide> def target_path_to_format(target)
<ide> case target.basename
<ide> when /\.md$/ then ["--markdown", "markdown"]
<ide> def generate_cmd_manpages(glob)
<ide> cmd_paths = Pathname.glob(glob).sort
<ide> man_page_lines = []
<ide> man_args = Homebrew.args
<del> cmd_paths.each do |cmd_path|
<del> begin
<del> cmd_parser = Homebrew.send(cmd_arg_parser(cmd_path))
<del> man_page_lines << cmd_manpage_lines(cmd_parser).join
<del> rescue NoMethodError
<del> man_page_lines << path_glob_commands(cmd_path.to_s).first
<add> # preserve existing manpage order
<add> cmd_paths.sort_by(&method(:sort_key_for_path))
<add> .each do |cmd_path|
<add> cmd_args_method_name = cmd_arg_parser(cmd_path)
<add>
<add> cmd_man_page_lines = begin
<add> cmd_parser = Homebrew.send(cmd_args_method_name)
<add> next if cmd_parser.hide_from_man_page
<add> cmd_parser_manpage_lines(cmd_parser).join
<add> rescue NoMethodError => e
<add> raise if e.name != cmd_args_method_name
<add> nil
<ide> end
<add> cmd_man_page_lines ||= cmd_comment_manpage_lines(cmd_path)
<add>
<add> man_page_lines << cmd_man_page_lines
<ide> end
<ide> Homebrew.args = man_args
<del> man_page_lines
<add> man_page_lines.compact.join("\n")
<ide> end
<ide>
<ide> def cmd_arg_parser(cmd_path)
<ide> "#{cmd_path.basename.to_s.gsub(".rb", "").tr("-", "_")}_args".to_sym
<ide> end
<ide>
<del> def cmd_manpage_lines(cmd_parser)
<add> def cmd_parser_manpage_lines(cmd_parser)
<ide> lines = [format_usage_banner(cmd_parser.usage_banner_text)]
<ide> lines += cmd_parser.processed_options.map do |short, long, _, desc|
<ide> next if !long.nil? && cmd_parser.global_option?(cmd_parser.option_to_name(long))
<ide> generate_option_doc(short, long, desc)
<add> end.reject(&:blank?)
<add> lines
<add> end
<add>
<add> def cmd_comment_manpage_lines(cmd_path)
<add> comment_lines = cmd_path.read.lines.grep(/^#:/)
<add> return if comment_lines.empty?
<add> return if comment_lines.first.include?("@hide_from_man_page")
<add> lines = [format_usage_banner(comment_lines.first).chomp]
<add> comment_lines.slice(1..-1)
<add> .each do |line|
<add> line = line.slice(4..-1)
<add> next unless line
<add> lines << line.gsub(/^ +(-+[a-z-]+) */, "* `\\1`:\n ")
<ide> end
<ide> lines
<ide> end
<ide>
<del> def global_options_manpage_lines
<add> def global_options_manpage
<ide> lines = ["These options are applicable across all sub-commands.\n"]
<ide> lines += Homebrew::CLI::Parser.global_options.values.map do |names, _, desc|
<ide> short, long = names
<ide> generate_option_doc(short, long, desc)
<ide> end
<del> lines
<add> lines.join("\n")
<ide> end
<ide>
<ide> def generate_option_doc(short, long, desc)
<ide> def format_long_opt(opt)
<ide> end
<ide>
<ide> def format_usage_banner(usage_banner)
<del> usage_banner.sub(/^/, "### ")
<add> usage_banner&.sub(/^(#: *\* )?/, "### ")
<ide> end
<ide> end | 1 |
PHP | PHP | update doc blocks | 2a8242141209a4912d00ee8be596dd7b33f2487f | <ide><path>src/Core/Plugin.php
<ide> <?php
<ide> /**
<del> * PHP 5
<del> *
<ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<ide> *
<ide> *
<ide> * It also can retrieve plugin paths and load their bootstrap and routes files.
<ide> *
<del> * @link http://book.cakephp.org/2.0/en/plugins.html
<add> * @link http://book.cakephp.org/3.0/en/plugins.html
<ide> */
<ide> class Plugin {
<ide> | 1 |
Python | Python | add test for openapi schemagenerator url argument | 30a21a98dc4b3f85746315c974bd2e007a3e5393 | <ide><path>tests/schemas/test_openapi.py
<ide> def test_prefixed_paths_construction(self):
<ide> assert '/v1/example/' in paths
<ide> assert '/v1/example/{id}/' in paths
<ide>
<add> def test_mount_url_prefixed_to_paths(self):
<add> patterns = [
<add> url(r'^example/?$', views.ExampleListView.as_view()),
<add> url(r'^example/{pk}/?$', views.ExampleDetailView.as_view()),
<add> ]
<add> generator = SchemaGenerator(patterns=patterns, url='/api/')
<add> generator._initialise_endpoints()
<add>
<add> paths = generator.get_paths()
<add>
<add> assert '/api/example/' in paths
<add> assert '/api/example/{id}/' in paths
<add>
<ide> def test_schema_construction(self):
<ide> """Construction of the top level dictionary."""
<ide> patterns = [ | 1 |
Ruby | Ruby | remove default arguments that aren't used | b3d73e789cc8616fad30621e96f872bfd86ee099 | <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb
<ide> def empty?
<ide> routes.empty?
<ide> end
<ide>
<del> def add_route(app, conditions = {}, requirements = {}, defaults = {}, name = nil, anchor = true)
<add> def add_route(app, conditions, requirements, defaults, name, anchor)
<ide> raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i)
<ide>
<ide> if name && named_routes[name] | 1 |
Text | Text | add changelog message for pr | 141a0859f8162002fefd38c8b46bc28f6f688f60 | <ide><path>actionview/CHANGELOG.md
<add>* Improve error messages when file does not exist at filepath.
<add>
<add> *Ted Whang*
<add>
<ide> * Add `:country_code` option to `sms_to` for consistency with `phone_to`.
<ide>
<ide> *Jonathan Hefner* | 1 |
Text | Text | add instructions to fetch the dataset | fe25eefc1589a0362e1b60c30734f88f666aff5b | <ide><path>examples/README.md
<ide> similar API between the different models.
<ide> | [GLUE](#glue) | Examples running BERT/XLM/XLNet/RoBERTa on the 9 GLUE tasks. Examples feature distributed training as well as half-precision. |
<ide> | [SQuAD](#squad) | Using BERT for question answering, examples with distributed training. |
<ide> | [Multiple Choice](#multiple choice) | Examples running BERT/XLNet/RoBERTa on the SWAG/RACE/ARC tasks.
<add>| [Seq2seq Model fine-tuning](#seq2seq-model-fine-tuning) | Fine-tuning the library models for seq2seq tasks on the CNN/Daily Mail dataset. |
<ide>
<ide> ## Language model fine-tuning
<ide>
<ide> f1 = 93.15
<ide> exact_match = 86.91
<ide> ```
<ide>
<del>This fine-tuneds model is available as a checkpoint under the reference
<add>This fine-tuned model is available as a checkpoint under the reference
<ide> `bert-large-uncased-whole-word-masking-finetuned-squad`.
<ide>
<add>## Seq2seq model fine-tuning
<add>
<add>Based on the script [`run_seq2seq_finetuning.py`](https://github.com/huggingface/transformers/blob/master/examples/run_seq2seq_finetuning.py).
<add>
<add>Before running this script you should download **both** CNN and Daily Mail datasets (the links next to "Stories") from [Kyunghyun Cho's website](https://cs.nyu.edu/~kcho/DMQA/) in the same folder. Then uncompress the archives by running:
<add>
<add>```bash
<add>tar -xvf cnn_stories.tgz && tar -xvf dailymail_stories.tgz
<add>```
<add>
<add>We will refer as `$DATA_PATH` the path to where you uncompressed both archive.
<add>
<add>## Bert2Bert and abstractive summarization
<add>
<add>```bash
<add>export DATA_PATH=/path/to/dataset/
<add>
<add>python run_seq2seq_finetuning.py \
<add> --output_dir=output \
<add> --model_type=bert2bert \
<add> --model_name_or_path=bert2bert \
<add> --do_train \
<add> --data_path=$DATA_PATH \
<add>```
<ide>\ No newline at end of file | 1 |
Text | Text | fix broken links in arabic challenges | fce8e8efee916c8b5fdfbc3ba954d4ba98b8f076 | <ide><path>curriculum/challenges/arabic/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.arabic.md
<ide> localeTitle: التنازل مع القيمة المرتجعة
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> إذا كنت ستتذكر من مناقشتنا لـ <a href="javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Storing Values مع Assignment Operator</a> ، يتم حل كل شيء على يمين علامة المساواة قبل تعيين القيمة. هذا يعني أنه يمكننا أخذ قيمة الإرجاع للدالة وتعيينها لمتغير. افترض أننا حددنا مسبقا <code>sum</code> وظيفة يضيف رقمين معا ، ثم: <code>ourSum = sum(5, 12);</code> سوف تستدعي دالة <code>sum</code> ، والتي تُرجع قيمة <code>17</code> <code>ourSum</code> المتغير. </section>
<add><section id="description"> إذا كنت ستتذكر من مناقشتنا لـ <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Storing Values مع Assignment Operator</a> ، يتم حل كل شيء على يمين علامة المساواة قبل تعيين القيمة. هذا يعني أنه يمكننا أخذ قيمة الإرجاع للدالة وتعيينها لمتغير. افترض أننا حددنا مسبقا <code>sum</code> وظيفة يضيف رقمين معا ، ثم: <code>ourSum = sum(5, 12);</code> سوف تستدعي دالة <code>sum</code> ، والتي تُرجع قيمة <code>17</code> <code>ourSum</code> المتغير. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> استدعاء الدالة <code>processArg</code> مع وسيطة من <code>7</code> وتعيين قيمته الإرجاع إلى المتغير <code>processed</code> . </section>
<ide><path>curriculum/challenges/arabic/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.arabic.md
<ide> localeTitle: توليد الكسور العشوائية مع جافا سكريب
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> الأرقام العشوائية مفيدة لإنشاء سلوك عشوائي. يحتوي JavaScript على دالة <code>Math.random()</code> التي تنشئ رقمًا عشريًا عشوائيًا بين <code>0</code> (شامل) وليس تمامًا <code>1</code> (خاص). وبالتالي ، يمكن أن يقوم <code>Math.random()</code> بإرجاع <code>0</code> ولكن لا يُرجع أبدًا <strong>ملاحظة</strong> <code>1</code> <br> مثل <a href="storing-values-with-the-assignment-operator" target="_blank">تخزين القيم مع عامل التشغيل المتساوي</a> ، سيتم حل جميع استدعاءات الدوال قبل تنفيذ عملية <code>return</code> ، حتى نتمكن من <code>return</code> قيمة الدالة <code>Math.random()</code> . </section>
<add><section id="description"> الأرقام العشوائية مفيدة لإنشاء سلوك عشوائي. يحتوي JavaScript على دالة <code>Math.random()</code> التي تنشئ رقمًا عشريًا عشوائيًا بين <code>0</code> (شامل) وليس تمامًا <code>1</code> (خاص). وبالتالي ، يمكن أن يقوم <code>Math.random()</code> بإرجاع <code>0</code> ولكن لا يُرجع أبدًا <strong>ملاحظة</strong> <code>1</code> <br> مثل <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">تخزين القيم مع عامل التشغيل المتساوي</a> ، سيتم حل جميع استدعاءات الدوال قبل تنفيذ عملية <code>return</code> ، حتى نتمكن من <code>return</code> قيمة الدالة <code>Math.random()</code> . </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> قم بتغيير <code>randomFraction</code> لإرجاع رقم عشوائي بدلاً من إرجاع <code>0</code> . </section>
<ide><path>curriculum/challenges/arabic/03-front-end-libraries/react/introducing-inline-styles.arabic.md
<ide> localeTitle: ''
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> هناك مفاهيم معقدة أخرى تضيف إمكانات قوية لرمز React الخاص بك. ولكن قد تتساءل عن المشكلة الأكثر بساطة حول كيفية تصميم عناصر JSX التي تقوم بإنشائها في React. من المحتمل أنك تعلم أنه لن يكون بالضبط نفس العمل مع HTML بسبب <a target="_blank" href="front-end-libraries/react/define-an-html-class-in-jsx">طريقة تطبيق الطبقات على عناصر JSX</a> . إذا قمت باستيراد أنماط من ورقة أنماط ، فإنها لا تختلف كثيرًا على الإطلاق. يمكنك تطبيق فئة على عنصر JSX باستخدام السمة <code>className</code> ، وتطبيق الأنماط على الفصل الدراسي في ورقة الأنماط. خيار آخر هو تطبيق الأنماط <strong><em>المضمنة</em></strong> ، والتي تكون شائعة جدًا في تطوير ReactJS. يمكنك تطبيق أنماط مضمنة على عناصر JSX مشابهة لطريقة عمل ذلك في HTML ، ولكن مع بعض الاختلافات في JSX. في ما يلي مثال لنمط مضمَّن في HTML: <code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code> تستخدم عناصر JSX سمة <code>style</code> ، ولكن نظرًا لطريقة تشفير JSX ، يمكنك قم بتعيين القيمة إلى <code>string</code> . بدلاً من ذلك ، يمكنك تعيينه يساوي <code>object</code> JavaScript. إليك مثال على ذلك: <code><div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div></code> لاحظ كيف نحصل على خاصية "fontSize"؟ وذلك لأن React لن يقبل مفاتيح حالة الكباب في كائن النمط. سيطبق React اسم الخاصية الصحيح لنا في HTML. </section>
<add><section id="description"> هناك مفاهيم معقدة أخرى تضيف إمكانات قوية لرمز React الخاص بك. ولكن قد تتساءل عن المشكلة الأكثر بساطة حول كيفية تصميم عناصر JSX التي تقوم بإنشائها في React. من المحتمل أنك تعلم أنه لن يكون بالضبط نفس العمل مع HTML بسبب <a target="_blank" href="learn/front-end-libraries/react/define-an-html-class-in-jsx">طريقة تطبيق الطبقات على عناصر JSX</a> . إذا قمت باستيراد أنماط من ورقة أنماط ، فإنها لا تختلف كثيرًا على الإطلاق. يمكنك تطبيق فئة على عنصر JSX باستخدام السمة <code>className</code> ، وتطبيق الأنماط على الفصل الدراسي في ورقة الأنماط. خيار آخر هو تطبيق الأنماط <strong><em>المضمنة</em></strong> ، والتي تكون شائعة جدًا في تطوير ReactJS. يمكنك تطبيق أنماط مضمنة على عناصر JSX مشابهة لطريقة عمل ذلك في HTML ، ولكن مع بعض الاختلافات في JSX. في ما يلي مثال لنمط مضمَّن في HTML: <code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code> تستخدم عناصر JSX سمة <code>style</code> ، ولكن نظرًا لطريقة تشفير JSX ، يمكنك قم بتعيين القيمة إلى <code>string</code> . بدلاً من ذلك ، يمكنك تعيينه يساوي <code>object</code> JavaScript. إليك مثال على ذلك: <code><div style={{color: "yellow", fontSize: 16}}>Mellow Yellow</div></code> لاحظ كيف نحصل على خاصية "fontSize"؟ وذلك لأن React لن يقبل مفاتيح حالة الكباب في كائن النمط. سيطبق React اسم الخاصية الصحيح لنا في HTML. </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> أضف سمة <code>style</code> إلى <code>div</code> في محرر الشفرة لإعطاء النص لونًا أحمر وحجم خط يبلغ 72 بكسل. لاحظ أنه يمكنك تعيين حجم الخط بشكل اختياري ليكون رقمًا ، أو حذف الوحدات "px" ، أو كتابتها كـ "72px". </section> | 3 |
Javascript | Javascript | add some documentation to ember.view helpers | b0d48458e28d484ac58b8ea85698aaa589e578a5 | <ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View.reopen({
<ide> });
<ide>
<ide> Ember.View.reopenClass({
<add>
<add> /**
<add> @private
<add>
<add> Parse a path and return an object which holds the parsed properties.
<add>
<add> For example a path like "content.isEnabled:enabled:disabled" wil return the
<add> following object:
<add>
<add> {
<add> path: "content.isEnabled",
<add> className: "enabled",
<add> falsyClassName: "disabled",
<add> classNames: ":enabled:disabled"
<add> }
<add>
<add> */
<ide> _parsePropertyPath: function(path) {
<ide> var split = path.split(/:/),
<ide> propertyPath = split[0],
<ide> Ember.View.reopenClass({
<ide> };
<ide> },
<ide>
<add> /**
<add> @private
<add>
<add> Get the class name for a given value, based on the path, optional className
<add> and optional falsyClassName.
<add>
<add> - if the value is truthy and a className is defined, the className is returned
<add> - if the value is true, the dasherized last part of the supplied path is returned
<add> - if the value is false and a falsyClassName is supplied, the falsyClassName is returned
<add> - if the value is truthy, the value is returned
<add> - if none of the above rules apply, null is returned
<add>
<add> */
<ide> _classStringForValue: function(path, val, className, falsyClassName) {
<ide> // If the value is truthy and we're using the colon syntax,
<ide> // we should return the className directly | 1 |
Text | Text | add images of deprecations | d523f9e1ecc1163fd2ba90e73a29769d0a51db5e | <ide><path>docs/upgrading/upgrading-your-package.md
<ide> All of the methods in Atom core that have changes will emit deprecation messages
<ide>
<ide> Just run your specs, and all the deprecations will be displayed in yellow.
<ide>
<del>TODO: image of deprecations in specs
<add>
<add>
<ide>
<del>TODO: Comand line spec deprecation image?
<ide>
<ide> ### Deprecation Cop
<ide>
<ide> Run an atom window in dev mode (`atom -d`) with your package loaded, and open Deprecation Cop (search for `deprecation` in the command palette).
<ide>
<del>TODO: image of deprecations in DepCop
<add>
<ide>
<ide> ## Upgrading your Views
<ide> | 1 |
PHP | PHP | fix inconsistency in php7.1 | 5ac906226510176d45ed5095f040bcca28b78846 | <ide><path>src/Cache/CacheRegistry.php
<ide> protected function _create($class, $alias, $config)
<ide> * @param string $name The adapter name.
<ide> * @return void
<ide> */
<del> public function unload($name)
<add> public function unload(string $name)
<ide> {
<ide> unset($this->_loaded[$name]);
<ide> } | 1 |
Python | Python | apply itertools fixer | 5de56efaad908f2b731a7eda2b9ca2a9196f820a | <ide><path>numpy/lib/npyio.py
<ide>
<ide> if sys.version_info[0] >= 3:
<ide> import pickle
<add> imap = map
<ide> else:
<ide> import cPickle as pickle
<add> imap = itertools.imap
<ide>
<ide> loads = pickle.loads
<ide>
<ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> converter.iterupgrade(current_column)
<ide> except ConverterLockError:
<ide> errmsg = "Converter #%i is locked and cannot be upgraded: " % i
<del> current_column = itertools.imap(itemgetter(i), rows)
<add> current_column = imap(itemgetter(i), rows)
<ide> for (j, value) in enumerate(current_column):
<ide> try:
<ide> converter.upgrade(value)
<ide><path>numpy/lib/recfunctions.py
<ide> from numpy.ma.mrecords import MaskedRecords
<ide> from numpy.lib._iotools import _is_string_like
<ide>
<add>if sys.version_info[0] >= 3:
<add> izip = zip
<add>else:
<add> izip = itertools.izip
<add>
<ide> _check_fill_value = np.ma.core._check_fill_value
<ide>
<ide> __all__ = ['append_fields',
<ide> def sentinel(counter=([fill_value] * (len(seqarrays) - 1)).pop):
<ide> zipfunc = _izip_fields
<ide> #
<ide> try:
<del> for tup in itertools.izip(*iters):
<add> for tup in izip(*iters):
<ide> yield tuple(zipfunc(tup))
<ide> except IndexError:
<ide> pass
<ide> def merge_arrays(seqarrays,
<ide> seqmask = []
<ide> # If we expect some kind of MaskedArray, make a special loop.
<ide> if usemask:
<del> for (a, n) in itertools.izip(seqarrays, sizes):
<add> for (a, n) in izip(seqarrays, sizes):
<ide> nbmissing = (maxlength - n)
<ide> # Get the data and mask
<ide> data = a.ravel().__array__()
<ide> def merge_arrays(seqarrays,
<ide> output = output.view(MaskedRecords)
<ide> else:
<ide> # Same as before, without the mask we don't need...
<del> for (a, n) in itertools.izip(seqarrays, sizes):
<add> for (a, n) in izip(seqarrays, sizes):
<ide> nbmissing = (maxlength - n)
<ide> data = a.ravel().__array__()
<ide> if nbmissing:
<ide><path>tools/py3tool.py
<ide> 'input',
<ide> 'intern',
<ide> # 'isinstance',
<del># 'itertools',
<ide> 'itertools_imports',
<add> 'itertools',
<ide> # 'long',
<ide> 'map',
<ide> 'metaclass', | 3 |
PHP | PHP | update factorylocator tests | 955914ccda06972170fb9f28639370a316064e4a | <ide><path>tests/TestCase/Datasource/FactoryLocatorTest.php
<ide>
<ide> use Cake\Datasource\FactoryLocator;
<ide> use Cake\Datasource\LocatorInterface;
<del>use Cake\Datasource\RepositoryInterface;
<ide> use Cake\TestSuite\TestCase;
<del>use TestApp\Stub\Stub;
<ide>
<ide> /**
<ide> * FactoryLocatorTest test case
<ide> public function testAdd()
<ide>
<ide> return $mock;
<ide> });
<del>
<ide> $this->assertIsCallable(FactoryLocator::get('Test'));
<add>
<add> $locator = $this->getMockBuilder(LocatorInterface::class)->getMock();
<add> FactoryLocator::add('MyType', $locator);
<add> $this->assertInstanceOf(LocatorInterface::class, FactoryLocator::get('MyType'));
<ide> }
<ide>
<ide> /**
<ide> public function testDrop()
<ide> FactoryLocator::get('Test');
<ide> }
<ide>
<del> /**
<del> * test loadModel() with plugin prefixed models
<del> *
<del> * Load model should not be called with Foo.Model Bar.Model Model
<del> * But if it is, the first call wins.
<del> *
<del> * @return void
<del> */
<del> public function testLoadModelPlugin()
<del> {
<del> $stub = new Stub();
<del> $stub->setProps('Articles');
<del> $stub->setModelType('Table');
<del>
<del> $result = $stub->loadModel('TestPlugin.Comments');
<del> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $result);
<del> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $stub->Comments);
<del>
<del> $result = $stub->loadModel('Comments');
<del> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $result);
<del> $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $stub->Comments);
<del> }
<del>
<del> /**
<del> * test alternate model factories.
<del> *
<del> * @return void
<del> */
<del> public function testModelFactory()
<del> {
<del> $stub = new Stub();
<del> $stub->setProps('Articles');
<del>
<del> $stub->modelFactory('Table', function ($name) {
<del> $mock = $this->getMockBuilder(RepositoryInterface::class)->getMock();
<del> $mock->name = $name;
<del>
<del> return $mock;
<del> });
<del>
<del> $result = $stub->loadModel('Magic', 'Table');
<del> $this->assertInstanceOf(RepositoryInterface::class, $result);
<del> $this->assertInstanceOf(RepositoryInterface::class, $stub->Magic);
<del> $this->assertSame('Magic', $stub->Magic->name);
<del> }
<del>
<del> /**
<del> * test alternate default model type.
<del> *
<del> * @return void
<del> */
<del> public function testModelType()
<del> {
<del> $stub = new Stub();
<del> $stub->setProps('Articles');
<del>
<del> FactoryLocator::add('Test', function ($name) {
<del> $mock = $this->getMockBuilder(RepositoryInterface::class)->getMock();
<del> $mock->name = $name;
<del>
<del> return $mock;
<del> });
<del> $stub->setModelType('Test');
<del>
<del> $result = $stub->loadModel('Magic');
<del> $this->assertInstanceOf(RepositoryInterface::class, $result);
<del> $this->assertInstanceOf(RepositoryInterface::class, $stub->Magic);
<del> $this->assertSame('Magic', $stub->Magic->name);
<del> }
<del>
<del> /**
<del> * test MissingModelException being thrown
<del> *
<del> * @return void
<del> */
<del> public function testMissingModelException()
<del> {
<del> $this->expectException(\Cake\Datasource\Exception\MissingModelException::class);
<del> $this->expectExceptionMessage('Model class "Magic" of type "Test" could not be found.');
<del> $stub = new Stub();
<del>
<del> FactoryLocator::add('Test', function ($name) {
<del> return false;
<del> });
<del>
<del> $stub->loadModel('Magic', 'Test');
<del> }
<del>
<ide> public function tearDown(): void
<ide> {
<ide> FactoryLocator::drop('Test');
<add> FactoryLocator::drop('MyType');
<ide>
<ide> parent::tearDown();
<ide> } | 1 |
PHP | PHP | interface the queue factory | d08dc59aa0eb1d19ce9cd936a58da32d609dbfbe | <ide><path>src/Illuminate/Contracts/Queue/Factory.php
<add><?php namespace Illuminate\Contracts\Queue;
<add>
<add>interface Factory {
<add>
<add> /**
<add> * Resolve a queue connection instance.
<add> *
<add> * @param string $name
<add> * @return \Illuminate\Contracts\Queue\Queue
<add> */
<add> public function connection($name = null);
<add>
<add>}
<ide><path>src/Illuminate/Foundation/Application.php
<ide> public function registerCoreContainerAliases()
<ide> 'mailer' => ['Illuminate\Mail\Mailer', 'Illuminate\Contracts\Mail\Mailer', 'Illuminate\Contracts\Mail\MailQueue'],
<ide> 'paginator' => 'Illuminate\Pagination\Factory',
<ide> 'auth.reminder' => ['Illuminate\Auth\Reminders\PasswordBroker', 'Illuminate\Contracts\Auth\PasswordBroker'],
<del> 'queue' => 'Illuminate\Queue\QueueManager',
<add> 'queue' => ['Illuminate\Queue\QueueManager', 'Illuminate\Contracts\Queue\Factory'],
<ide> 'queue.connection' => 'Illuminate\Contracts\Queue\Queue',
<ide> 'redirect' => 'Illuminate\Routing\Redirector',
<ide> 'redis' => ['Illuminate\Redis\Database', 'Illuminate\Contracts\Redis\Database'],
<ide><path>src/Illuminate/Queue/QueueManager.php
<ide> <?php namespace Illuminate\Queue;
<ide>
<ide> use Closure;
<add>use Illuminate\Contracts\Queue\Factory as FactoryContract;
<ide>
<del>class QueueManager {
<add>class QueueManager implements FactoryContract {
<ide>
<ide> /**
<ide> * The application instance. | 3 |
PHP | PHP | ignore static properties in serializes model | 8fad785de66ffaa18e7d8b9e9cd7c4465e60daac | <ide><path>src/Illuminate/Queue/SerializesModels.php
<ide> public function __sleep()
<ide> ));
<ide> }
<ide>
<del> return array_map(function ($p) {
<del> return $p->getName();
<del> }, $properties);
<add> return array_filter(array_map(function ($p) {
<add> return $p->isStatic() ? null : $p->getName();
<add> }, $properties));
<ide> }
<ide>
<ide> /**
<ide> public function __sleep()
<ide> public function __wakeup()
<ide> {
<ide> foreach ((new ReflectionClass($this))->getProperties() as $property) {
<add> if ($property->isStatic()) {
<add> continue;
<add> }
<add>
<ide> $property->setValue($this, $this->getRestoredPropertyValue(
<ide> $this->getPropertyValue($property)
<ide> )); | 1 |
Ruby | Ruby | remove private attribute? warning | 16bd04f6bbb4bf461ca375e077e84e224552bc79 | <ide><path>actionpack/lib/action_view/dependency_tracker.rb
<ide> def dependencies
<ide> render_dependencies + explicit_dependencies
<ide> end
<ide>
<add> attr_reader :name, :template
<add> private :name, :template
<add>
<ide> private
<del> attr_reader :name, :template
<ide>
<ide> def source
<ide> template.source | 1 |
Javascript | Javascript | fix a bunch of warnings from firebug strict mode | 26389c083ab26499ac3f9836ff4dcee82ebaaf7d | <ide><path>fonts.js
<ide> var Font = (function () {
<ide> return font.getBytes();
<ide> },
<ide>
<del> convert: function font_convert(name, font, properties) {
<add> convert: function font_convert(fontName, font, properties) {
<ide> var otf = new Uint8Array(kMaxFontFileSize);
<ide>
<ide> function createNameTable(name) {
<ide> var names = [
<ide> "See original licence", // Copyright
<del> name, // Font family
<add> fontName, // Font family
<ide> "undefined", // Font subfamily (font weight)
<ide> "uniqueID", // Unique ID
<del> name, // Full font name
<add> fontName, // Full font name
<ide> "0.1", // Version
<ide> "undefined", // Postscript name
<ide> "undefined", // Trademark
<ide> "undefined", // Manufacturer
<ide> "undefined" // Designer
<ide> ];
<ide>
<del> var name =
<add> var nameTable =
<ide> "\x00\x00" + // format
<ide> "\x00\x0A" + // Number of names Record
<ide> "\x00\x7E"; // Storage
<ide> var Font = (function () {
<ide> "\x00\x00" + // name ID
<ide> string16(str.length) +
<ide> string16(strOffset);
<del> name += nameRecord;
<add> nameTable += nameRecord;
<ide>
<ide> strOffset += str.length;
<ide> }
<ide>
<del> name += names.join("");
<del> return name;
<add> nameTable += names.join("");
<add> return nameTable;
<ide> }
<ide>
<ide> // Required Tables
<ide> var FontsUtils = {
<ide> bytes.set([value >> 24, value >> 16, value >> 8, value]);
<ide> return [bytes[0], bytes[1], bytes[2], bytes[3]];
<ide> }
<add>
<add> error("This number of bytes " + bytesCount + " is not supported");
<add> return null;
<ide> },
<ide>
<ide> bytesToInteger: function fu_bytesToInteger(bytesArray) {
<ide> var CFF = function(name, file, properties) {
<ide> };
<ide>
<ide> CFF.prototype = {
<del> createCFFIndexHeader: function(objects, isByte) {
<add> createCFFIndexHeader: function cff_createCFFIndexHeader(objects, isByte) {
<ide> // First 2 bytes contains the number of objects contained into this index
<ide> var count = objects.length;
<ide>
<ide> CFF.prototype = {
<ide> return data;
<ide> },
<ide>
<del> encodeNumber: function(value) {
<add> encodeNumber: function cff_encodeNumber(value) {
<ide> var x = 0;
<ide> if (value >= -32768 && value <= 32767) {
<ide> return [ 28, value >> 8, value & 0xFF ];
<ide> } else if (value >= (-2147483647-1) && value <= 2147483647) {
<ide> return [ 0xFF, value >> 24, Value >> 16, value >> 8, value & 0xFF ];
<del> } else {
<del> error("Value: " + value + " is not allowed");
<ide> }
<add> error("Value: " + value + " is not allowed");
<add> return null;
<ide> },
<ide>
<del> getOrderedCharStrings: function(glyphs) {
<add> getOrderedCharStrings: function cff_getOrderedCharStrings(glyphs) {
<ide> var charstrings = [];
<ide>
<ide> for (var i = 0; i < glyphs.length; i++) {
<ide><path>pdf.js
<ide> var Stream = (function() {
<ide> get length() {
<ide> return this.end - this.start;
<ide> },
<del> getByte: function() {
<add> getByte: function stream_getByte() {
<ide> if (this.pos >= this.end)
<del> return;
<add> return null;
<ide> return this.bytes[this.pos++];
<ide> },
<ide> // returns subarray of original buffer
<ide> // should only be read
<del> getBytes: function(length) {
<add> getBytes: function stream_getBytes(length) {
<ide> var bytes = this.bytes;
<ide> var pos = this.pos;
<ide> var strEnd = this.end;
<ide> var Stream = (function() {
<ide> this.pos = end;
<ide> return bytes.subarray(pos, end);
<ide> },
<del> lookChar: function() {
<add> lookChar: function stream_lookChar() {
<ide> if (this.pos >= this.end)
<del> return;
<add> return null;
<ide> return String.fromCharCode(this.bytes[this.pos]);
<ide> },
<del> getChar: function() {
<add> getChar: function stream_getChar() {
<ide> if (this.pos >= this.end)
<del> return;
<add> return null;
<ide> return String.fromCharCode(this.bytes[this.pos++]);
<ide> },
<del> skip: function(n) {
<add> skip: function stream_skip(n) {
<ide> if (!n)
<ide> n = 1;
<ide> this.pos += n;
<ide> },
<del> reset: function() {
<add> reset: function stream_reset() {
<ide> this.pos = this.start;
<ide> },
<del> moveStart: function() {
<add> moveStart: function stream_moveStart() {
<ide> this.start = this.pos;
<ide> },
<del> makeSubStream: function(start, length, dict) {
<add> makeSubStream: function stream_makeSubstream(start, length, dict) {
<ide> return new Stream(this.bytes.buffer, start, length, dict);
<ide> }
<ide> };
<ide> var DecodeStream = (function() {
<ide> }
<ide>
<ide> constructor.prototype = {
<del> ensureBuffer: function(requested) {
<add> ensureBuffer: function decodestream_ensureBuffer(requested) {
<ide> var buffer = this.buffer;
<ide> var current = buffer ? buffer.byteLength : 0;
<ide> if (requested < current)
<ide> var DecodeStream = (function() {
<ide> buffer2[i] = buffer[i];
<ide> return this.buffer = buffer2;
<ide> },
<del> getByte: function() {
<add> getByte: function decodestream_getByte() {
<ide> var pos = this.pos;
<ide> while (this.bufferLength <= pos) {
<ide> if (this.eof)
<del> return;
<add> return null;
<ide> this.readBlock();
<ide> }
<ide> return this.buffer[this.pos++];
<ide> },
<del> getBytes: function(length) {
<add> getBytes: function decodestream_getBytes(length) {
<ide> var pos = this.pos;
<ide>
<ide> if (length) {
<ide> var DecodeStream = (function() {
<ide> this.pos = end;
<ide> return this.buffer.subarray(pos, end)
<ide> },
<del> lookChar: function() {
<add> lookChar: function decodestream_lookChar() {
<ide> var pos = this.pos;
<ide> while (this.bufferLength <= pos) {
<ide> if (this.eof)
<del> return;
<add> return null;
<ide> this.readBlock();
<ide> }
<ide> return String.fromCharCode(this.buffer[this.pos]);
<ide> },
<del> getChar: function() {
<add> getChar: function decodestream_getChar() {
<ide> var pos = this.pos;
<ide> while (this.bufferLength <= pos) {
<ide> if (this.eof)
<del> return;
<add> return null;
<ide> this.readBlock();
<ide> }
<ide> return String.fromCharCode(this.buffer[this.pos++]);
<ide> },
<del> skip: function(n) {
<add> skip: function decodestream_skip(n) {
<ide> if (!n)
<ide> n = 1;
<ide> this.pos += n;
<ide> var PredictorStream = (function() {
<ide> var rowBytes = this.rowBytes = (columns * colors * bits + 7) >> 3;
<ide>
<ide> DecodeStream.call(this);
<add> return this;
<ide> }
<ide>
<ide> constructor.prototype = Object.create(DecodeStream.prototype);
<ide> var Dict = (function() {
<ide>
<ide> constructor.prototype = {
<ide> get: function(key) {
<del> return this.map[key];
<add> if (key in this.map)
<add> return this.map[key];
<add> return null;
<ide> },
<ide> get2: function(key1, key2) {
<ide> return this.get(key1) || this.get(key2);
<ide> var XRef = (function() {
<ide> }
<ide>
<ide> constructor.prototype = {
<del> readXRefTable: function(parser) {
<add> readXRefTable: function readXRefTable(parser) {
<ide> var obj;
<ide> while (true) {
<ide> if (IsCmd(obj = parser.getObj(), "trailer"))
<ide> var XRef = (function() {
<ide>
<ide> return dict;
<ide> },
<del> readXRefStream: function(stream) {
<add> readXRefStream: function readXRefStream(stream) {
<ide> var streamParameters = stream.parameters;
<ide> var length = streamParameters.get("Length");
<ide> var byteWidths = streamParameters.get("W");
<ide> var XRef = (function() {
<ide> this.readXRef(prev);
<ide> return streamParameters;
<ide> },
<del> readXRef: function(startXRef) {
<add> readXRef: function readXref(startXRef) {
<ide> var stream = this.stream;
<ide> stream.pos = startXRef;
<ide> var parser = new Parser(new Lexer(stream), true);
<ide> var XRef = (function() {
<ide> return this.readXRefStream(obj);
<ide> }
<ide> error("Invalid XRef");
<add> return null;
<ide> },
<ide> getEntry: function(i) {
<ide> var e = this.entries[i];
<ide> var CanvasGraphics = (function() {
<ide> if (!fd)
<ide> // XXX deprecated "special treatment" for standard
<ide> // fonts? What do we need to do here?
<del> return;
<add> return null;
<ide> var descriptor = xref.fetch(fd);
<ide>
<ide> var fontName = descriptor.get("FontName");
<ide> var CanvasGraphics = (function() {
<ide> this.restore();
<ide>
<ide> TODO("Inverse pattern is painted");
<del> var pattern = this.ctx.createPattern(tmpCanvas, "repeat");
<add> pattern = this.ctx.createPattern(tmpCanvas, "repeat");
<ide> this.ctx.fillStyle = pattern;
<ide> },
<ide> setStrokeGray: function(gray) { | 2 |
PHP | PHP | use implicit mixed | 648e2dd12b7acdae55a8129c4a90c3c44c3e8acf | <ide><path>src/Http/Uri.php
<ide> public function __construct(UriInterface $uri, string $base, string $webroot)
<ide> * @param string $name The attribute to read.
<ide> * @return mixed
<ide> */
<del> public function __get(string $name): mixed
<add> public function __get(string $name)
<ide> {
<ide> if ($name === 'base' || $name === 'webroot') {
<ide> return $this->{$name}; | 1 |
Python | Python | remove use of compiler module | 9917a12d397e6e1188823752aa21996dbb1444d5 | <ide><path>numpy/lib/utils.py
<ide> class SafeEval(object):
<ide>
<ide> """
<ide>
<del> if sys.version_info[0] < 3:
<del> def visit(self, node, **kw):
<del> cls = node.__class__
<del> meth = getattr(self, 'visit'+cls.__name__, self.default)
<del> return meth(node, **kw)
<del>
<del> def default(self, node, **kw):
<del> raise SyntaxError("Unsupported source construct: %s"
<del> % node.__class__)
<del>
<del> def visitExpression(self, node, **kw):
<del> for child in node.getChildNodes():
<del> return self.visit(child, **kw)
<del>
<del> def visitConst(self, node, **kw):
<del> return node.value
<del>
<del> def visitDict(self, node,**kw):
<del> return dict(
<del> [(self.visit(k), self.visit(v)) for k, v in node.items]
<del> )
<del>
<del> def visitTuple(self, node, **kw):
<del> return tuple([self.visit(i) for i in node.nodes])
<del>
<del> def visitList(self, node, **kw):
<del> return [self.visit(i) for i in node.nodes]
<del>
<del> def visitUnaryAdd(self, node, **kw):
<del> return +self.visit(node.getChildNodes()[0])
<del>
<del> def visitUnarySub(self, node, **kw):
<del> return -self.visit(node.getChildNodes()[0])
<del>
<del> def visitName(self, node, **kw):
<del> if node.name == 'False':
<del> return False
<del> elif node.name == 'True':
<del> return True
<del> elif node.name == 'None':
<del> return None
<del> else:
<del> raise SyntaxError("Unknown name: %s" % node.name)
<del> else:
<add> def visit(self, node):
<add> cls = node.__class__
<add> meth = getattr(self, 'visit' + cls.__name__, self.default)
<add> return meth(node)
<ide>
<del> def visit(self, node):
<del> cls = node.__class__
<del> meth = getattr(self, 'visit' + cls.__name__, self.default)
<del> return meth(node)
<add> def default(self, node):
<add> raise SyntaxError("Unsupported source construct: %s"
<add> % node.__class__)
<ide>
<del> def default(self, node):
<del> raise SyntaxError("Unsupported source construct: %s"
<del> % node.__class__)
<add> def visitExpression(self, node):
<add> return self.visit(node.body)
<ide>
<del> def visitExpression(self, node):
<del> return self.visit(node.body)
<add> def visitNum(self, node):
<add> return node.n
<ide>
<del> def visitNum(self, node):
<del> return node.n
<add> def visitStr(self, node):
<add> return node.s
<ide>
<del> def visitStr(self, node):
<del> return node.s
<add> def visitBytes(self, node):
<add> return node.s
<ide>
<del> def visitBytes(self, node):
<del> return node.s
<add> def visitDict(self, node,**kw):
<add> return dict([(self.visit(k), self.visit(v))
<add> for k, v in zip(node.keys, node.values)])
<ide>
<del> def visitDict(self, node,**kw):
<del> return dict([(self.visit(k), self.visit(v))
<del> for k, v in zip(node.keys, node.values)])
<add> def visitTuple(self, node):
<add> return tuple([self.visit(i) for i in node.elts])
<ide>
<del> def visitTuple(self, node):
<del> return tuple([self.visit(i) for i in node.elts])
<add> def visitList(self, node):
<add> return [self.visit(i) for i in node.elts]
<ide>
<del> def visitList(self, node):
<del> return [self.visit(i) for i in node.elts]
<add> def visitUnaryOp(self, node):
<add> import ast
<add> if isinstance(node.op, ast.UAdd):
<add> return +self.visit(node.operand)
<add> elif isinstance(node.op, ast.USub):
<add> return -self.visit(node.operand)
<add> else:
<add> raise SyntaxError("Unknown unary op: %r" % node.op)
<add>
<add> def visitName(self, node):
<add> if node.id == 'False':
<add> return False
<add> elif node.id == 'True':
<add> return True
<add> elif node.id == 'None':
<add> return None
<add> else:
<add> raise SyntaxError("Unknown name: %s" % node.id)
<ide>
<del> def visitUnaryOp(self, node):
<del> import ast
<del> if isinstance(node.op, ast.UAdd):
<del> return +self.visit(node.operand)
<del> elif isinstance(node.op, ast.USub):
<del> return -self.visit(node.operand)
<del> else:
<del> raise SyntaxError("Unknown unary op: %r" % node.op)
<del>
<del> def visitName(self, node):
<del> if node.id == 'False':
<del> return False
<del> elif node.id == 'True':
<del> return True
<del> elif node.id == 'None':
<del> return None
<del> else:
<del> raise SyntaxError("Unknown name: %s" % node.id)
<add> def visitNameConstant(self, node):
<add> return node.value
<ide>
<del> def visitNameConstant(self, node):
<del> return node.value
<ide>
<ide> def safe_eval(source):
<ide> """
<ide> def safe_eval(source):
<ide> >>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
<ide> Traceback (most recent call last):
<ide> ...
<del> SyntaxError: Unsupported source construct: compiler.ast.CallFunc
<add> SyntaxError: Unsupported source construct: <class '_ast.Call'>
<ide>
<ide> """
<ide> # Local imports to speed up numpy's import time.
<ide> import warnings
<del>
<del> with warnings.catch_warnings():
<del> # compiler package is deprecated for 3.x, which is already solved
<del> # here
<del> warnings.simplefilter('ignore', DeprecationWarning)
<del> try:
<del> import compiler
<del> except ImportError:
<del> import ast as compiler
<add> import ast
<ide>
<ide> walker = SafeEval()
<ide> try:
<del> ast = compiler.parse(source, mode="eval")
<add> res = ast.parse(source, mode="eval")
<ide> except SyntaxError:
<ide> raise
<ide> try:
<del> return walker.visit(ast)
<add> return walker.visit(res)
<ide> except SyntaxError:
<ide> raise
<ide> | 1 |
Text | Text | update model documentation with recent changes | 12318cf4ff0368fe4a296b2076950fd029928ad6 | <ide><path>docs/sources/models.md
<ide> model = keras.models.Sequential()
<ide> - __optimizer__: str (name of optimizer) or optimizer object. See [optimizers](optimizers.md).
<ide> - __loss__: str (name of objective function) or objective function. See [objectives](objectives.md).
<ide> - __class_mode__: one of "categorical", "binary". This is only used for computing classification accuracy or using the predict_classes method.
<del> - __theano_mode__: A `theano.compile.mode.Mode` instance controlling specifying compilation options.
<add> - __theano_mode__: A `theano.compile.mode.Mode` ([reference](http://deeplearning.net/software/theano/library/compile/mode.html)) instance controlling specifying compilation options.
<ide> - __fit__(X, y, batch_size=128, nb_epoch=100, verbose=1, validation_split=0., validation_data=None, shuffle=True, show_accuracy=False): Train a model for a fixed number of epochs.
<add> - __Return__: a history dictionary with a record of training loss values at successive epochs, as well as validation loss values (if applicable), accuracy (if applicable), etc.
<ide> - __Arguments__:
<ide> - __X__: data.
<ide> - __y__: labels.
<ide> model = keras.models.Sequential()
<ide> - __shuffle__: boolean. Whether to shuffle the samples at each epoch.
<ide> - __show_accuracy__: boolean. Whether to display class accuracy in the logs to stdout at each epoch.
<ide> - __evaluate__(X, y, batch_size=128, show_accuracy=False, verbose=1): Show performance of the model over some validation data.
<add> - __Return__: The loss score over the data.
<ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing).
<del> - __predict_proba__(X, batch_size=128, verbose=1): Return an array of predictions for some test data.
<add> - __predict__(X, batch_size=128, verbose=1):
<add> - __Return__: An array of predictions for some test data.
<ide> - __Arguments__: Same meaning as fit method above.
<ide> - __predict_classes__(X, batch_size=128, verbose=1): Return an array of class predictions for some test data.
<add> - __Return__: An array of labels for some test data.
<ide> - __Arguments__: Same meaning as fit method above. verbose is used as a binary flag (progress bar or nothing).
<ide> - __train__(X, y, accuracy=False): Single gradient update on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch.
<add> - __Return__: loss over the data, or tuple `(loss, accuracy)` if `accuracy=True`.
<ide> - __test__(X, y, accuracy=False): Single performance evaluation on one batch. if accuracy==False, return tuple (loss_on_batch, accuracy_on_batch). Else, return loss_on_batch.
<add> - __Return__: loss over the data, or tuple `(loss, accuracy)` if `accuracy=True`.
<ide> - __save_weights__(fname): Store the weights of all layers to a HDF5 file.
<ide> - __load_weights__(fname): Sets the weights of a model, based to weights stored by __save__weights__. You can only __load__weights__ on a savefile from a model with an identical architecture. __load_weights__ can be called either before or after the __compile__ step.
<ide> | 1 |
PHP | PHP | add opera mobi to mobile detectors | 621cb43e93eeb2ee64667ba21d5a3a8e114cc832 | <ide><path>lib/Cake/Network/CakeRequest.php
<ide> class CakeRequest implements ArrayAccess {
<ide> 'flash' => array('env' => 'HTTP_USER_AGENT', 'pattern' => '/^(Shockwave|Adobe) Flash/'),
<ide> 'mobile' => array('env' => 'HTTP_USER_AGENT', 'options' => array(
<ide> 'Android', 'AvantGo', 'BlackBerry', 'DoCoMo', 'Fennec', 'iPod', 'iPhone',
<del> 'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'PalmOS', 'PalmSource',
<add> 'J2ME', 'MIDP', 'NetFront', 'Nokia', 'Opera Mini', 'Opera Mobi', 'PalmOS', 'PalmSource',
<ide> 'portalmmm', 'Plucker', 'ReqwirelessWeb', 'SonyEricsson', 'Symbian', 'UP\\.Browser',
<ide> 'webOS', 'Windows CE', 'Xiino'
<ide> )) | 1 |
Text | Text | fix an awkward expression in the readme | ee227dda766d769b7499a5549e8ed77b5e88105b | <ide><path>README.md
<ide> to free you to focus on the parts of the problem that really matter.
<ide> simple workflows should be quick and easy, while arbitrarily advanced workflows
<ide> should be *possible* via a clear path that builds upon what you've already learned.
<ide> - **Powerful** -- Keras provides industry-strength performance and scalability:
<del>it is used by organizations and companies including NASA, YouTube, or Waymo.
<add>it is used by organizations and companies including NASA, YouTube, and Waymo.
<ide>
<ide> ---
<ide> | 1 |
Python | Python | fix python 2.5 test failure | 4cdf4474856082ce7fbdc9366361c3b33ce031a9 | <ide><path>libcloud/compute/drivers/ec2.py
<ide> def create_node(self, **kwargs):
<ide> if not isinstance(kwargs['ex_blockdevicemappings'], (list, tuple)):
<ide> raise AttributeError('ex_blockdevicemappings not list or tuple')
<ide>
<del> for idx, mapping in enumerate(kwargs['ex_blockdevicemappings'],
<del> start=1):
<add> for idx, mapping in enumerate(kwargs['ex_blockdevicemappings']):
<add> idx += 1 # we want 1-based indexes
<ide> if not isinstance(mapping, dict):
<ide> raise AttributeError('mapping %s in ex_blockdevicemappings '
<ide> 'not a dict' % mapping) | 1 |
Ruby | Ruby | add some basic render_test to abstractcontroller | 03960048616593c249745d1e321dbcc7f0483c76 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> def formats
<ide> [:"*/*"]
<ide> end
<ide>
<del> # Refactor out all mailer_name
<del> def _prefix
<del> mailer_name
<del> end
<del>
<ide> class << self
<ide> attr_writer :mailer_name
<ide>
<ide><path>actionpack/lib/abstract_controller/layouts.rb
<ide> def _layout_for_option(name, details)
<ide> def _determine_template(options)
<ide> super
<ide>
<del> return if (options.key?(:text) || options.key?(:inline) || options.key?(:partial)) && !options.key?(:layout)
<add> return unless (options.keys & [:text, :inline, :partial]).empty? || options.key?(:layout)
<ide> layout = options.key?(:layout) ? options[:layout] : :default
<ide> options[:_layout] = _layout_for_option(layout, options[:_template].details)
<ide> end
<ide><path>actionpack/lib/abstract_controller/rendering_controller.rb
<ide> def _determine_template(options)
<ide> options[:_template_name] = options[:template]
<ide> elsif options.key?(:file)
<ide> options[:_template_name] = options[:file]
<del> elsif !options.key?(:partial)
<del> options[:_template_name] ||= options[:action]
<del> options[:_prefix] = _prefix
<ide> end
<ide>
<ide> name = (options[:_template_name] || action_name).to_s
<ide> def template_exists?(name, details, options)
<ide> view_paths.exists?(name, details, options[:_prefix], options[:_partial])
<ide> end
<ide>
<del> def _prefix
<del> self.class.name.underscore
<del> end
<del>
<ide> def with_template_cache(name)
<ide> yield
<ide> end
<ide><path>actionpack/lib/action_controller/metal/rendering_controller.rb
<ide> def _prefix
<ide> controller_path
<ide> end
<ide>
<add> def _determine_template(options)
<add> if (options.keys & [:partial, :file, :template, :text, :inline]).empty?
<add> options[:_template_name] ||= options[:action]
<add> options[:_prefix] = _prefix
<add> end
<add>
<add> super
<add> end
<add>
<ide> def format_for_text
<ide> formats.first
<ide> end
<ide><path>actionpack/test/abstract/render_test.rb
<add>require 'abstract_unit'
<add>
<add>module AbstractController
<add> module Testing
<add>
<add> class ControllerRenderer < AbstractController::Base
<add> include AbstractController::RenderingController
<add>
<add> self.view_paths = [ActionView::FixtureResolver.new(
<add> "default.erb" => "With Default",
<add> "template.erb" => "With Template",
<add> "some/file.erb" => "With File",
<add> "template_name.erb" => "With Template Name"
<add> )]
<add>
<add> def template
<add> render :template => "template"
<add> end
<add>
<add> def file
<add> render :file => "some/file"
<add> end
<add>
<add> def inline
<add> render :inline => "With <%= :Inline %>"
<add> end
<add>
<add> def text
<add> render :text => "With Text"
<add> end
<add>
<add> def default
<add> render
<add> end
<add>
<add> def template_name
<add> render :_template_name => :template_name
<add> end
<add>
<add> def object
<add> render :_template => ActionView::TextTemplate.new("With Object")
<add> end
<add> end
<add>
<add> class TestRenderer < ActiveSupport::TestCase
<add>
<add> def setup
<add> @controller = ControllerRenderer.new
<add> end
<add>
<add> def test_render_template
<add> @controller.process(:template)
<add> assert_equal "With Template", @controller.response_body
<add> end
<add>
<add> def test_render_file
<add> @controller.process(:file)
<add> assert_equal "With File", @controller.response_body
<add> end
<add>
<add> def test_render_inline
<add> @controller.process(:inline)
<add> assert_equal "With Inline", @controller.response_body
<add> end
<add>
<add> def test_render_text
<add> @controller.process(:text)
<add> assert_equal "With Text", @controller.response_body
<add> end
<add>
<add> def test_render_default
<add> @controller.process(:default)
<add> assert_equal "With Default", @controller.response_body
<add> end
<add>
<add> def test_render_template_name
<add> @controller.process(:template_name)
<add> assert_equal "With Template Name", @controller.response_body
<add> end
<add>
<add> def test_render_object
<add> @controller.process(:object)
<add> assert_equal "With Object", @controller.response_body
<add> end
<add>
<add> end
<add> end
<add>end | 5 |
Javascript | Javascript | fix missing name copy in bufferattribute.copy | 03f74c4dca672a6d413138f70b4a971997379edf | <ide><path>src/core/BufferAttribute.js
<ide> Object.assign( BufferAttribute.prototype, {
<ide>
<ide> copy: function ( source ) {
<ide>
<add> this.name = source.name;
<ide> this.array = new source.array.constructor( source.array );
<ide> this.itemSize = source.itemSize;
<ide> this.count = source.count; | 1 |
Java | Java | use collection factory methods when applicable | 941b6af9acada0c85522a1aeb91178f71c2c641a | <ide><path>spring-beans/src/main/java/org/springframework/beans/BeanUtils.java
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.Date;
<del>import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide> import java.util.Map;
<ide> public abstract class BeanUtils {
<ide> private static final Set<Class<?>> unknownEditorTypes =
<ide> Collections.newSetFromMap(new ConcurrentReferenceHashMap<>(64));
<ide>
<del> private static final Map<Class<?>, Object> DEFAULT_TYPE_VALUES;
<del>
<del> static {
<del> Map<Class<?>, Object> values = new HashMap<>();
<del> values.put(boolean.class, false);
<del> values.put(byte.class, (byte) 0);
<del> values.put(short.class, (short) 0);
<del> values.put(int.class, 0);
<del> values.put(long.class, 0L);
<del> values.put(float.class, 0F);
<del> values.put(double.class, 0D);
<del> values.put(char.class, '\0');
<del> DEFAULT_TYPE_VALUES = Collections.unmodifiableMap(values);
<del> }
<add> private static final Map<Class<?>, Object> DEFAULT_TYPE_VALUES = Map.of(
<add> boolean.class, false,
<add> byte.class, (byte) 0,
<add> short.class, (short) 0,
<add> int.class, 0,
<add> long.class, 0L,
<add> float.class, 0F,
<add> double.class, 0D,
<add> char.class, '\0');
<ide>
<ide>
<ide> /**
<ide><path>spring-context/src/main/java/org/springframework/format/datetime/DateTimeFormatAnnotationFormatterFactory.java
<ide>
<ide> import java.util.ArrayList;
<ide> import java.util.Calendar;
<del>import java.util.Collections;
<ide> import java.util.Date;
<del>import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide>
<ide> public class DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
<ide> implements AnnotationFormatterFactory<DateTimeFormat> {
<ide>
<del> private static final Set<Class<?>> FIELD_TYPES;
<del>
<del> static {
<del> Set<Class<?>> fieldTypes = new HashSet<>(4);
<del> fieldTypes.add(Date.class);
<del> fieldTypes.add(Calendar.class);
<del> fieldTypes.add(Long.class);
<del> FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
<del> }
<del>
<add> private static final Set<Class<?>> FIELD_TYPES = Set.of(Date.class, Calendar.class, Long.class);
<ide>
<ide> @Override
<ide> public Set<Class<?>> getFieldTypes() {
<ide><path>spring-context/src/main/java/org/springframework/format/datetime/standard/Jsr310DateTimeFormatAnnotationFormatterFactory.java
<ide> import java.time.format.DateTimeFormatter;
<ide> import java.time.temporal.TemporalAccessor;
<ide> import java.util.ArrayList;
<del>import java.util.Collections;
<del>import java.util.HashSet;
<ide> import java.util.List;
<ide> import java.util.Set;
<ide>
<ide> public class Jsr310DateTimeFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
<ide> implements AnnotationFormatterFactory<DateTimeFormat> {
<ide>
<del> private static final Set<Class<?>> FIELD_TYPES;
<del>
<del> static {
<del> // Create the set of field types that may be annotated with @DateTimeFormat.
<del> Set<Class<?>> fieldTypes = new HashSet<>(8);
<del> fieldTypes.add(Instant.class);
<del> fieldTypes.add(LocalDate.class);
<del> fieldTypes.add(LocalTime.class);
<del> fieldTypes.add(LocalDateTime.class);
<del> fieldTypes.add(ZonedDateTime.class);
<del> fieldTypes.add(OffsetDateTime.class);
<del> fieldTypes.add(OffsetTime.class);
<del> fieldTypes.add(YearMonth.class);
<del> fieldTypes.add(MonthDay.class);
<del> FIELD_TYPES = Collections.unmodifiableSet(fieldTypes);
<del> }
<add> // Create the set of field types that may be annotated with @DateTimeFormat.
<add> private static final Set<Class<?>> FIELD_TYPES = Set.of(
<add> Instant.class,
<add> LocalDate.class,
<add> LocalTime.class,
<add> LocalDateTime.class,
<add> ZonedDateTime.class,
<add> OffsetDateTime.class,
<add> OffsetTime.class,
<add> YearMonth.class,
<add> MonthDay.class);
<ide>
<ide> @Override
<ide> public final Set<Class<?>> getFieldTypes() {
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/TypeMappedAnnotation.java
<ide> import java.lang.reflect.Member;
<ide> import java.lang.reflect.Method;
<ide> import java.util.Collections;
<del>import java.util.HashMap;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> */
<ide> final class TypeMappedAnnotation<A extends Annotation> extends AbstractMergedAnnotation<A> {
<ide>
<del> private static final Map<Class<?>, Object> EMPTY_ARRAYS;
<del> static {
<del> Map<Class<?>, Object> emptyArrays = new HashMap<>();
<del> emptyArrays.put(boolean.class, new boolean[0]);
<del> emptyArrays.put(byte.class, new byte[0]);
<del> emptyArrays.put(char.class, new char[0]);
<del> emptyArrays.put(double.class, new double[0]);
<del> emptyArrays.put(float.class, new float[0]);
<del> emptyArrays.put(int.class, new int[0]);
<del> emptyArrays.put(long.class, new long[0]);
<del> emptyArrays.put(short.class, new short[0]);
<del> emptyArrays.put(String.class, new String[0]);
<del> EMPTY_ARRAYS = Collections.unmodifiableMap(emptyArrays);
<del> }
<add> private static final Map<Class<?>, Object> EMPTY_ARRAYS = Map.of(
<add> boolean.class, new boolean[0],
<add> byte.class, new byte[0],
<add> char.class, new char[0],
<add> double.class, new double[0],
<add> float.class, new float[0],
<add> int.class, new int[0],
<add> long.class, new long[0],
<add> short.class, new short[0],
<add> String.class, new String[0]);
<ide>
<ide>
<ide> private final AnnotationTypeMapping mapping;
<ide><path>spring-core/src/main/java/org/springframework/core/convert/support/ByteBufferConverter.java
<ide> package org.springframework.core.convert.support;
<ide>
<ide> import java.nio.ByteBuffer;
<del>import java.util.Collections;
<del>import java.util.HashSet;
<ide> import java.util.Set;
<ide>
<ide> import org.springframework.core.convert.ConversionService;
<ide> final class ByteBufferConverter implements ConditionalGenericConverter {
<ide>
<ide> private static final TypeDescriptor BYTE_ARRAY_TYPE = TypeDescriptor.valueOf(byte[].class);
<ide>
<del> private static final Set<ConvertiblePair> CONVERTIBLE_PAIRS;
<del>
<del> static {
<del> Set<ConvertiblePair> convertiblePairs = new HashSet<>(4);
<del> convertiblePairs.add(new ConvertiblePair(ByteBuffer.class, byte[].class));
<del> convertiblePairs.add(new ConvertiblePair(byte[].class, ByteBuffer.class));
<del> convertiblePairs.add(new ConvertiblePair(ByteBuffer.class, Object.class));
<del> convertiblePairs.add(new ConvertiblePair(Object.class, ByteBuffer.class));
<del> CONVERTIBLE_PAIRS = Collections.unmodifiableSet(convertiblePairs);
<del> }
<del>
<add> private static final Set<ConvertiblePair> CONVERTIBLE_PAIRS = Set.of(
<add> new ConvertiblePair(ByteBuffer.class, byte[].class),
<add> new ConvertiblePair(byte[].class, ByteBuffer.class),
<add> new ConvertiblePair(ByteBuffer.class, Object.class),
<add> new ConvertiblePair(Object.class, ByteBuffer.class));
<ide>
<ide> private final ConversionService conversionService;
<ide>
<ide><path>spring-core/src/main/java/org/springframework/util/NumberUtils.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.text.DecimalFormat;
<ide> import java.text.NumberFormat;
<ide> import java.text.ParseException;
<del>import java.util.Collections;
<del>import java.util.HashSet;
<ide> import java.util.Set;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> public abstract class NumberUtils {
<ide> * Standard number types (all immutable):
<ide> * Byte, Short, Integer, Long, BigInteger, Float, Double, BigDecimal.
<ide> */
<del> public static final Set<Class<?>> STANDARD_NUMBER_TYPES;
<del>
<del> static {
<del> Set<Class<?>> numberTypes = new HashSet<>(8);
<del> numberTypes.add(Byte.class);
<del> numberTypes.add(Short.class);
<del> numberTypes.add(Integer.class);
<del> numberTypes.add(Long.class);
<del> numberTypes.add(BigInteger.class);
<del> numberTypes.add(Float.class);
<del> numberTypes.add(Double.class);
<del> numberTypes.add(BigDecimal.class);
<del> STANDARD_NUMBER_TYPES = Collections.unmodifiableSet(numberTypes);
<del> }
<del>
<add> public static final Set<Class<?>> STANDARD_NUMBER_TYPES = Set.of(
<add> Byte.class,
<add> Short.class,
<add> Integer.class,
<add> Long.class,
<add> BigInteger.class,
<add> Float.class,
<add> Double.class,
<add> BigDecimal.class);
<ide>
<ide> /**
<ide> * Convert the given number into an instance of the given target class.
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java
<ide> import java.lang.reflect.Modifier;
<ide> import java.util.Arrays;
<ide> import java.util.Collections;
<del>import java.util.HashSet;
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide> public class ReflectivePropertyAccessor implements PropertyAccessor {
<ide>
<ide> private static final Set<Class<?>> ANY_TYPES = Collections.emptySet();
<ide>
<del> private static final Set<Class<?>> BOOLEAN_TYPES;
<del>
<del> static {
<del> Set<Class<?>> booleanTypes = new HashSet<>(4);
<del> booleanTypes.add(Boolean.class);
<del> booleanTypes.add(Boolean.TYPE);
<del> BOOLEAN_TYPES = Collections.unmodifiableSet(booleanTypes);
<del> }
<del>
<add> private static final Set<Class<?>> BOOLEAN_TYPES = Set.of(Boolean.class, Boolean.TYPE);
<ide>
<ide> private final boolean allowWrite;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/json/Jackson2CodecSupport.java
<ide> import java.lang.annotation.Annotation;
<ide> import java.lang.reflect.Type;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.HashMap;
<ide> import java.util.LinkedHashMap;
<ide> public abstract class Jackson2CodecSupport {
<ide> private static final String JSON_VIEW_HINT_ERROR =
<ide> "@JsonView only supported for write hints with exactly 1 class argument: ";
<ide>
<del> private static final List<MimeType> DEFAULT_MIME_TYPES = Collections.unmodifiableList(
<del> Arrays.asList(
<del> MediaType.APPLICATION_JSON,
<del> new MediaType("application", "*+json"),
<del> MediaType.APPLICATION_NDJSON));
<add> private static final List<MimeType> DEFAULT_MIME_TYPES = List.of(
<add> MediaType.APPLICATION_JSON,
<add> new MediaType("application", "*+json"),
<add> MediaType.APPLICATION_NDJSON);
<ide>
<ide>
<ide> protected final Log logger = HttpLogging.forLogName(getClass());
<ide> protected Jackson2CodecSupport(ObjectMapper objectMapper, MimeType... mimeTypes)
<ide> Assert.notNull(objectMapper, "ObjectMapper must not be null");
<ide> this.defaultObjectMapper = objectMapper;
<ide> this.mimeTypes = !ObjectUtils.isEmpty(mimeTypes) ?
<del> Collections.unmodifiableList(Arrays.asList(mimeTypes)) : DEFAULT_MIME_TYPES;
<add> List.of(mimeTypes) : DEFAULT_MIME_TYPES;
<ide> }
<ide>
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/multipart/MultipartHttpMessageReader.java
<ide> /*
<del> * Copyright 2002-2020 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.http.codec.multipart;
<ide>
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.Collection;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Map;
<ide> import java.util.stream.Collectors;
<ide> public class MultipartHttpMessageReader extends LoggingCodecSupport
<ide> private static final ResolvableType MULTIPART_VALUE_TYPE = ResolvableType.forClassWithGenerics(
<ide> MultiValueMap.class, String.class, Part.class);
<ide>
<del> static final List<MediaType> MIME_TYPES = Collections.unmodifiableList(Arrays.asList(
<del> MediaType.MULTIPART_FORM_DATA, MediaType.MULTIPART_MIXED, MediaType.MULTIPART_RELATED));
<del>
<add> static final List<MediaType> MIME_TYPES = List.of(
<add> MediaType.MULTIPART_FORM_DATA,
<add> MediaType.MULTIPART_MIXED,
<add> MediaType.MULTIPART_RELATED);
<ide>
<ide> private final HttpMessageReader<Part> partReader;
<ide>
<ide><path>spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufCodecSupport.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.http.codec.protobuf;
<ide>
<del>import java.util.Arrays;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide>
<ide> import org.springframework.lang.Nullable;
<ide> */
<ide> public abstract class ProtobufCodecSupport {
<ide>
<del> static final List<MimeType> MIME_TYPES = Collections.unmodifiableList(
<del> Arrays.asList(
<add> static final List<MimeType> MIME_TYPES = List.of(
<ide> new MimeType("application", "x-protobuf"),
<ide> new MimeType("application", "octet-stream"),
<del> new MimeType("application", "vnd.google.protobuf")));
<add> new MimeType("application", "vnd.google.protobuf"));
<ide>
<ide> static final String DELIMITED_KEY = "delimited";
<ide>
<ide><path>spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java
<ide>
<ide> import java.time.Duration;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.LinkedHashSet;
<ide> import java.util.List;
<ide> public class CorsConfiguration {
<ide>
<ide> private static final List<String> DEFAULT_PERMIT_ALL = Collections.singletonList(ALL);
<ide>
<del> private static final List<HttpMethod> DEFAULT_METHODS = Collections.unmodifiableList(
<del> Arrays.asList(HttpMethod.GET, HttpMethod.HEAD));
<add> private static final List<HttpMethod> DEFAULT_METHODS = List.of(HttpMethod.GET, HttpMethod.HEAD);
<ide>
<del> private static final List<String> DEFAULT_PERMIT_METHODS = Collections.unmodifiableList(
<del> Arrays.asList(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name()));
<add> private static final List<String> DEFAULT_PERMIT_METHODS = List.of(HttpMethod.GET.name(),
<add> HttpMethod.HEAD.name(), HttpMethod.POST.name());
<ide>
<ide>
<ide> @Nullable
<ide><path>spring-web/src/main/java/org/springframework/web/filter/HiddenHttpMethodFilter.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.web.filter;
<ide>
<ide> import java.io.IOException;
<del>import java.util.Arrays;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide>
<ide> public class HiddenHttpMethodFilter extends OncePerRequestFilter {
<ide>
<ide> private static final List<String> ALLOWED_METHODS =
<del> Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(),
<del> HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
<add> List.of(HttpMethod.PUT.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name());
<ide>
<ide> /** Default method parameter: {@code _method}. */
<ide> public static final String DEFAULT_METHOD_PARAM = "_method";
<ide><path>spring-web/src/main/java/org/springframework/web/filter/reactive/HiddenHttpMethodFilter.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2021 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.web.filter.reactive;
<ide>
<del>import java.util.Arrays;
<del>import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Locale;
<ide>
<ide> public class HiddenHttpMethodFilter implements WebFilter {
<ide>
<ide> private static final List<HttpMethod> ALLOWED_METHODS =
<del> Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT,
<del> HttpMethod.DELETE, HttpMethod.PATCH));
<add> List.of(HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.PATCH);
<ide>
<ide> /** Default name of the form parameter with the HTTP method to use. */
<ide> public static final String DEFAULT_METHOD_PARAMETER_NAME = "_method";
<ide><path>spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java
<ide> import java.net.URISyntaxException;
<ide> import java.nio.charset.Charset;
<ide> import java.util.ArrayList;
<del>import java.util.Arrays;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.StringJoiner;
<ide> public String getPath() {
<ide> @Override
<ide> public List<String> getPathSegments() {
<ide> String[] segments = StringUtils.tokenizeToStringArray(getPath(), PATH_DELIMITER_STRING);
<del> return Collections.unmodifiableList(Arrays.asList(segments));
<add> return List.of(segments);
<ide> }
<ide>
<ide> @Override | 14 |
Text | Text | add debugging native code | 2fe55734921d07952e4c5cbf78af5f2a8b3ea31c | <ide><path>docs/Debugging.md
<ide> The debugger will receive a list of all project roots, separated by a space. For
<ide>
<ide> 5. In a new chrome tab, open : ```chrome://inspect```, click on 'Inspect device' (the one followed by "Powered by Stetho")
<ide>
<add>## Debugging native code
<add>
<add>When working with native code (e.g. when writing native modules) you can launch the app from Android Studio or Xcode and take advantage of the debugging features (setup breakpoints, etc.) as you would in case of building a standard native app.
<add>
<ide> ## Performance Monitor
<ide>
<ide> You can enable a performance overlay to help you debug performance problems by selecting "Perf Monitor" in the Developer Menu. | 1 |
Text | Text | fix module name in section 3 | 71129dc747fd59bfcd3b3c1ffd250988a979d30a | <ide><path>docs/tutorial/3-class-based-views.md
<ide> We can also write our API views using class based views, rather than function ba
<ide>
<ide> We'll start by rewriting the root view as a class based view. All this involves is a little bit of refactoring.
<ide>
<del> from snippet.models import Snippet
<del> from snippet.serializers import SnippetSerializer
<add> from snippets.models import Snippet
<add> from snippets.serializers import SnippetSerializer
<ide> from django.http import Http404
<ide> from rest_framework.views import APIView
<ide> from rest_framework.response import Response
<ide> We'll also need to refactor our URLconf slightly now we're using class based vie
<ide>
<ide> from django.conf.urls import patterns, url
<ide> from rest_framework.urlpatterns import format_suffix_patterns
<del> from snippetpost import views
<add> from snippets import views
<ide>
<ide> urlpatterns = patterns('',
<ide> url(r'^snippets/$', views.SnippetList.as_view()),
<ide> The create/retrieve/update/delete operations that we've been using so far are go
<ide>
<ide> Let's take a look at how we can compose our views by using the mixin classes.
<ide>
<del> from snippet.models import Snippet
<del> from snippet.serializers import SnippetSerializer
<add> from snippets.models import Snippet
<add> from snippets.serializers import SnippetSerializer
<ide> from rest_framework import mixins
<ide> from rest_framework import generics
<ide>
<ide> Pretty similar. This time we're using the `SingleObjectBaseView` class to provi
<ide>
<ide> Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use.
<ide>
<del> from snippet.models import Snippet
<del> from snippet.serializers import SnippetSerializer
<add> from snippets.models import Snippet
<add> from snippets.serializers import SnippetSerializer
<ide> from rest_framework import generics
<ide>
<ide> | 1 |
Python | Python | remove some unnecesary uses of bool | 98788d3c3af9f6cce2b94c276d17726f46608b08 | <ide><path>django/contrib/gis/gdal/datasource.py
<ide> def __init__(self, ds_input, ds_driver=False, write=False, encoding='utf-8'):
<ide> else:
<ide> raise OGRException('Invalid data source input type: %s' % type(ds_input))
<ide>
<del> if bool(ds):
<add> if ds:
<ide> self.ptr = ds
<ide> self.driver = Driver(ds_driver)
<ide> else:
<ide><path>django/contrib/gis/gdal/geometries.py
<ide> def __init__(self, geom_input, srs=None):
<ide> self.ptr = g
<ide>
<ide> # Assigning the SpatialReference object to the geometry, if valid.
<del> if bool(srs):
<add> if srs:
<ide> self.srs = srs
<ide>
<ide> # Setting the class depending upon the OGR Geometry Type
<ide><path>django/contrib/gis/gdal/prototypes/errcheck.py
<ide> def check_pointer(result, func, cargs):
<ide> "Makes sure the result pointer is valid."
<ide> if isinstance(result, six.integer_types):
<ide> result = c_void_p(result)
<del> if bool(result):
<add> if result:
<ide> return result
<ide> else:
<ide> raise OGRException('Invalid pointer returned from "%s"' % func.__name__)
<ide><path>django/contrib/gis/geoip/prototypes.py
<ide> class GeoIPTag(Structure):
<ide>
<ide> # For retrieving records by name or address.
<ide> def check_record(result, func, cargs):
<del> if bool(result):
<add> if result:
<ide> # Checking the pointer to the C structure, if valid pull out elements
<ide> # into a dicionary.
<ide> rec = result.contents
<ide><path>django/contrib/gis/geos/geometry.py
<ide> def __init__(self, geo_input, srid=None):
<ide> # Invalid geometry type.
<ide> raise TypeError('Improper geometry input type: %s' % str(type(geo_input)))
<ide>
<del> if bool(g):
<add> if g:
<ide> # Setting the pointer object with a valid pointer.
<ide> self.ptr = g
<ide> else:
<ide><path>django/contrib/gis/geos/prototypes/io.py
<ide> def _get_include_srid(self):
<ide> return bool(ord(wkb_writer_get_include_srid(self.ptr)))
<ide>
<ide> def _set_include_srid(self, include):
<del> if bool(include):
<add> if include:
<ide> flag = b'\x01'
<ide> else:
<ide> flag = b'\x00'
<ide><path>django/db/backends/mysql/introspection.py
<ide> def get_indexes(self, cursor, table_name):
<ide> # It's possible to have the unique and PK constraints in separate indexes.
<ide> if row[2] == 'PRIMARY':
<ide> indexes[row[4]]['primary_key'] = True
<del> if not bool(row[1]):
<add> if not row[1]:
<ide> indexes[row[4]]['unique'] = True
<ide> return indexes
<ide> | 7 |
PHP | PHP | remove bonus intval() | 5270721adee6aa4b2d07a61f589f729092ab9632 | <ide><path>lib/Cake/Test/Case/Utility/SetTest.php
<ide> public function testClassicExtract() {
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide>
<add>/**
<add> * test classicExtract with keys that exceed 32bit max int.
<add> *
<add> * @return void
<add> */
<add> public function testClassicExtractMaxInt() {
<add> $data = array(
<add> 'Data' => array(
<add> '13376924712' => 'abc'
<add> )
<add> );
<add> $this->assertEquals('abc', Set::classicExtract($data, 'Data.13376924712'));
<add> }
<add>
<ide> /**
<ide> * testInsert method
<ide> *
<ide><path>lib/Cake/Utility/Set.php
<ide> public static function classicExtract($data, $path = null) {
<ide>
<ide> foreach ($path as $i => $key) {
<ide> if (is_numeric($key) && intval($key) > 0 || $key === '0') {
<del> if (isset($data[intval($key)])) {
<del> $data = $data[intval($key)];
<add> if (isset($data[$key])) {
<add> $data = $data[$key];
<ide> } else {
<ide> return null;
<ide> } | 2 |
Ruby | Ruby | fix variable name | 2b1d7ea335afa46fa167a680492cdf5461c46064 | <ide><path>activesupport/lib/active_support/callbacks.rb
<ide> def recompile!(_options)
<ide> end
<ide>
<ide> # Wraps code with filter
<del> def apply(code)
<add> def apply(next_callback)
<ide> conditions = conditions_lambdas
<ide> source = make_lambda @raw_filter
<ide>
<ide> def apply(code)
<ide> target.send :halted_callback_hook, @raw_filter.inspect
<ide> end
<ide> end
<del> code.call target, halted, value, &block
<add> next_callback.call target, halted, value, &block
<ide> }
<ide> when :after
<ide> if chain.config[:skip_after_callbacks_if_terminated]
<ide> lambda { |target, halted, value, &block|
<del> target, halted, value = code.call target, halted, value, &block
<add> target, halted, value = next_callback.call target, halted, value, &block
<ide> if !halted && conditions.all? { |c| c.call(target, value) }
<ide> source.call target, value
<ide> end
<ide> [target, halted, value]
<ide> }
<ide> else
<ide> lambda { |target, halted, value, &block|
<del> target, halted, value = code.call target, halted, value, &block
<add> target, halted, value = next_callback.call target, halted, value, &block
<ide> if conditions.all? { |c| c.call(target, value) }
<ide> source.call target, value
<ide> end
<ide> def apply(code)
<ide> if !halted && conditions.all? { |c| c.call(target, value) }
<ide> retval = nil
<ide> source.call(target, value) {
<del> retval = code.call(target, halted, value, &block)
<add> retval = next_callback.call(target, halted, value, &block)
<ide> retval.last
<ide> }
<ide> retval
<ide> else
<del> code.call target, halted, value, &block
<add> next_callback.call target, halted, value, &block
<ide> end
<ide> }
<ide> end | 1 |
Python | Python | use new huggingface_hub tools for download models | 5cd40323684c183c30b34758aea1e877996a7ac9 | <ide><path>src/transformers/configuration_utils.py
<ide>
<ide> from packaging import version
<ide>
<del>from requests import HTTPError
<del>
<ide> from . import __version__
<ide> from .dynamic_module_utils import custom_object_save
<del>from .utils import (
<del> CONFIG_NAME,
<del> HUGGINGFACE_CO_RESOLVE_ENDPOINT,
<del> EntryNotFoundError,
<del> PushToHubMixin,
<del> RepositoryNotFoundError,
<del> RevisionNotFoundError,
<del> cached_path,
<del> copy_func,
<del> hf_bucket_url,
<del> is_offline_mode,
<del> is_remote_url,
<del> is_torch_available,
<del> logging,
<del>)
<add>from .utils import CONFIG_NAME, PushToHubMixin, cached_file, copy_func, is_torch_available, logging
<ide>
<ide>
<ide> logger = logging.get_logger(__name__)
<ide> def _get_config_dict(
<ide> if from_pipeline is not None:
<ide> user_agent["using_pipeline"] = from_pipeline
<ide>
<del> if is_offline_mode() and not local_files_only:
<del> logger.info("Offline mode: forcing local_files_only=True")
<del> local_files_only = True
<del>
<ide> pretrained_model_name_or_path = str(pretrained_model_name_or_path)
<del> if os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)) or is_remote_url(
<del> pretrained_model_name_or_path
<del> ):
<del> config_file = pretrained_model_name_or_path
<add>
<add> is_local = os.path.isdir(pretrained_model_name_or_path)
<add> if os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
<add> # Soecial case when pretrained_model_name_or_path is a local file
<add> resolved_config_file = pretrained_model_name_or_path
<add> is_local = True
<ide> else:
<ide> configuration_file = kwargs.pop("_configuration_file", CONFIG_NAME)
<ide>
<del> if os.path.isdir(os.path.join(pretrained_model_name_or_path, subfolder)):
<del> config_file = os.path.join(pretrained_model_name_or_path, subfolder, configuration_file)
<del> else:
<del> config_file = hf_bucket_url(
<add> try:
<add> # Load from local folder or from cache or download from model Hub and cache
<add> resolved_config_file = cached_file(
<ide> pretrained_model_name_or_path,
<del> filename=configuration_file,
<add> configuration_file,
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> local_files_only=local_files_only,
<add> use_auth_token=use_auth_token,
<add> user_agent=user_agent,
<ide> revision=revision,
<del> subfolder=subfolder if len(subfolder) > 0 else None,
<del> mirror=None,
<add> subfolder=subfolder,
<add> )
<add> except EnvironmentError:
<add> # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
<add> # the original exception.
<add> raise
<add> except Exception:
<add> # For any other exception, we throw a generic error.
<add> raise EnvironmentError(
<add> f"Can't load the configuration of '{pretrained_model_name_or_path}'. If you were trying to load it"
<add> " from 'https://huggingface.co/models', make sure you don't have a local directory with the same"
<add> f" name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory"
<add> f" containing a {configuration_file} file"
<ide> )
<del>
<del> try:
<del> # Load from URL or cache if already cached
<del> resolved_config_file = cached_path(
<del> config_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<del> )
<del>
<del> except RepositoryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier listed on "
<del> "'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a token having "
<del> "permission to this repo with `use_auth_token` or log in with `huggingface-cli login` and pass "
<del> "`use_auth_token=True`."
<del> )
<del> except RevisionNotFoundError:
<del> raise EnvironmentError(
<del> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this "
<del> f"model name. Check the model page at 'https://huggingface.co/{pretrained_model_name_or_path}' for "
<del> "available revisions."
<del> )
<del> except EntryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} does not appear to have a file named {configuration_file}."
<del> )
<del> except HTTPError as err:
<del> raise EnvironmentError(
<del> f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}"
<del> )
<del> except ValueError:
<del> raise EnvironmentError(
<del> f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it in"
<del> f" the cached files and it looks like {pretrained_model_name_or_path} is not the path to a directory"
<del> f" containing a {configuration_file} file.\nCheckout your internet connection or see how to run the"
<del> " library in offline mode at 'https://huggingface.co/docs/transformers/installation#offline-mode'."
<del> )
<del> except EnvironmentError:
<del> raise EnvironmentError(
<del> f"Can't load config for '{pretrained_model_name_or_path}'. If you were trying to load it from "
<del> "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
<del> f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
<del> f"containing a {configuration_file} file"
<del> )
<ide>
<ide> try:
<ide> # Load config dict
<ide> def _get_config_dict(
<ide> f"It looks like the config file at '{resolved_config_file}' is not a valid JSON file."
<ide> )
<ide>
<del> if resolved_config_file == config_file:
<del> logger.info(f"loading configuration file {config_file}")
<add> if is_local:
<add> logger.info(f"loading configuration file {resolved_config_file}")
<ide> else:
<del> logger.info(f"loading configuration file {config_file} from cache at {resolved_config_file}")
<add> logger.info(f"loading configuration file {configuration_file} from cache at {resolved_config_file}")
<ide>
<ide> return config_dict, kwargs
<ide>
<ide><path>src/transformers/feature_extraction_utils.py
<ide>
<ide> import numpy as np
<ide>
<del>from requests import HTTPError
<del>
<ide> from .dynamic_module_utils import custom_object_save
<ide> from .utils import (
<ide> FEATURE_EXTRACTOR_NAME,
<del> HUGGINGFACE_CO_RESOLVE_ENDPOINT,
<del> EntryNotFoundError,
<ide> PushToHubMixin,
<del> RepositoryNotFoundError,
<del> RevisionNotFoundError,
<ide> TensorType,
<del> cached_path,
<add> cached_file,
<ide> copy_func,
<del> hf_bucket_url,
<ide> is_flax_available,
<ide> is_offline_mode,
<del> is_remote_url,
<ide> is_tf_available,
<ide> is_torch_available,
<ide> logging,
<ide> def get_feature_extractor_dict(
<ide> local_files_only = True
<ide>
<ide> pretrained_model_name_or_path = str(pretrained_model_name_or_path)
<add> is_local = os.path.isdir(pretrained_model_name_or_path)
<ide> if os.path.isdir(pretrained_model_name_or_path):
<ide> feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME)
<del> elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
<del> feature_extractor_file = pretrained_model_name_or_path
<add> if os.path.isfile(pretrained_model_name_or_path):
<add> resolved_feature_extractor_file = pretrained_model_name_or_path
<add> is_local = True
<ide> else:
<del> feature_extractor_file = hf_bucket_url(
<del> pretrained_model_name_or_path, filename=FEATURE_EXTRACTOR_NAME, revision=revision, mirror=None
<del> )
<del>
<del> try:
<del> # Load from URL or cache if already cached
<del> resolved_feature_extractor_file = cached_path(
<del> feature_extractor_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<del> )
<del>
<del> except RepositoryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier listed on "
<del> "'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a token having "
<del> "permission to this repo with `use_auth_token` or log in with `huggingface-cli login` and pass "
<del> "`use_auth_token=True`."
<del> )
<del> except RevisionNotFoundError:
<del> raise EnvironmentError(
<del> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this "
<del> f"model name. Check the model page at 'https://huggingface.co/{pretrained_model_name_or_path}' for "
<del> "available revisions."
<del> )
<del> except EntryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} does not appear to have a file named {FEATURE_EXTRACTOR_NAME}."
<del> )
<del> except HTTPError as err:
<del> raise EnvironmentError(
<del> f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}"
<del> )
<del> except ValueError:
<del> raise EnvironmentError(
<del> f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it in"
<del> f" the cached files and it looks like {pretrained_model_name_or_path} is not the path to a directory"
<del> f" containing a {FEATURE_EXTRACTOR_NAME} file.\nCheckout your internet connection or see how to run"
<del> " the library in offline mode at"
<del> " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
<del> )
<del> except EnvironmentError:
<del> raise EnvironmentError(
<del> f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load it "
<del> "from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
<del> f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
<del> f"containing a {FEATURE_EXTRACTOR_NAME} file"
<del> )
<add> feature_extractor_file = FEATURE_EXTRACTOR_NAME
<add> try:
<add> # Load from local folder or from cache or download from model Hub and cache
<add> resolved_feature_extractor_file = cached_file(
<add> pretrained_model_name_or_path,
<add> feature_extractor_file,
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> local_files_only=local_files_only,
<add> use_auth_token=use_auth_token,
<add> user_agent=user_agent,
<add> revision=revision,
<add> )
<add> except EnvironmentError:
<add> # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
<add> # the original exception.
<add> raise
<add> except Exception:
<add> # For any other exception, we throw a generic error.
<add> raise EnvironmentError(
<add> f"Can't load feature extractor for '{pretrained_model_name_or_path}'. If you were trying to load"
<add> " it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
<add> f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
<add> f" directory containing a {FEATURE_EXTRACTOR_NAME} file"
<add> )
<ide>
<ide> try:
<ide> # Load feature_extractor dict
<ide> def get_feature_extractor_dict(
<ide> f"It looks like the config file at '{resolved_feature_extractor_file}' is not a valid JSON file."
<ide> )
<ide>
<del> if resolved_feature_extractor_file == feature_extractor_file:
<del> logger.info(f"loading feature extractor configuration file {feature_extractor_file}")
<add> if is_local:
<add> logger.info(f"loading configuration file {resolved_feature_extractor_file}")
<ide> else:
<ide> logger.info(
<del> f"loading feature extractor configuration file {feature_extractor_file} from cache at"
<del> f" {resolved_feature_extractor_file}"
<add> f"loading configuration file {feature_extractor_file} from cache at {resolved_feature_extractor_file}"
<ide> )
<ide>
<ide> return feature_extractor_dict, kwargs
<ide><path>src/transformers/modeling_flax_utils.py
<ide> from flax.serialization import from_bytes, to_bytes
<ide> from flax.traverse_util import flatten_dict, unflatten_dict
<ide> from jax.random import PRNGKey
<del>from requests import HTTPError
<ide>
<ide> from .configuration_utils import PretrainedConfig
<ide> from .dynamic_module_utils import custom_object_save
<ide> from .utils import (
<ide> FLAX_WEIGHTS_INDEX_NAME,
<ide> FLAX_WEIGHTS_NAME,
<del> HUGGINGFACE_CO_RESOLVE_ENDPOINT,
<ide> WEIGHTS_NAME,
<del> EntryNotFoundError,
<ide> PushToHubMixin,
<del> RepositoryNotFoundError,
<del> RevisionNotFoundError,
<ide> add_code_sample_docstrings,
<ide> add_start_docstrings_to_model_forward,
<del> cached_path,
<add> cached_file,
<ide> copy_func,
<ide> has_file,
<del> hf_bucket_url,
<ide> is_offline_mode,
<del> is_remote_url,
<ide> logging,
<ide> replace_return_docstrings,
<ide> )
<ide> def from_pretrained(
<ide> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
<ide> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
<ide> identifier allowed by git.
<add> subfolder (`str`, *optional*, defaults to `""`):
<add> In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
<add> specify the folder name here.
<ide> kwargs (remaining dictionary of keyword arguments, *optional*):
<ide> Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
<ide> `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
<ide> def from_pretrained(
<ide> from_pipeline = kwargs.pop("_from_pipeline", None)
<ide> from_auto_class = kwargs.pop("_from_auto", False)
<ide> _do_init = kwargs.pop("_do_init", True)
<add> subfolder = kwargs.pop("subfolder", "")
<ide>
<ide> if trust_remote_code is True:
<ide> logger.warning(
<ide> def from_pretrained(
<ide>
<ide> # Load model
<ide> if pretrained_model_name_or_path is not None:
<add> pretrained_model_name_or_path = str(pretrained_model_name_or_path)
<add> is_local = os.path.isdir(pretrained_model_name_or_path)
<ide> if os.path.isdir(pretrained_model_name_or_path):
<ide> if from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)):
<ide> # Load from a PyTorch checkpoint
<ide> def from_pretrained(
<ide> f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
<ide> f"{pretrained_model_name_or_path}."
<ide> )
<del> elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
<add> elif os.path.isfile(pretrained_model_name_or_path):
<ide> archive_file = pretrained_model_name_or_path
<add> is_local = True
<ide> else:
<ide> filename = WEIGHTS_NAME if from_pt else FLAX_WEIGHTS_NAME
<del> archive_file = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=filename,
<del> revision=revision,
<del> )
<del>
<del> # redirect to the cache, if necessary
<add> try:
<add> # Load from URL or cache if already cached
<add> cached_file_kwargs = dict(
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> local_files_only=local_files_only,
<add> use_auth_token=use_auth_token,
<add> user_agent=user_agent,
<add> revision=revision,
<add> subfolder=subfolder,
<add> _raise_exceptions_for_missing_entries=False,
<add> )
<add> resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)
<ide>
<del> try:
<del> resolved_archive_file = cached_path(
<del> archive_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<del> )
<del>
<del> except RepositoryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
<del> "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
<del> "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli "
<del> "login` and pass `use_auth_token=True`."
<del> )
<del> except RevisionNotFoundError:
<del> raise EnvironmentError(
<del> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
<del> "this model name. Check the model page at "
<del> f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
<del> )
<del> except EntryNotFoundError:
<del> if filename == FLAX_WEIGHTS_NAME:
<del> try:
<add> # Since we set _raise_exceptions_for_missing_entries=False, we don't get an expection but a None
<add> # result when internet is up, the repo and revision exist, but the file does not.
<add> if resolved_archive_file is None and filename == FLAX_WEIGHTS_NAME:
<ide> # Maybe the checkpoint is sharded, we try to grab the index name in this case.
<del> archive_file = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=FLAX_WEIGHTS_INDEX_NAME,
<del> revision=revision,
<del> )
<del> resolved_archive_file = cached_path(
<del> archive_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<add> resolved_archive_file = cached_file(
<add> pretrained_model_name_or_path, FLAX_WEIGHTS_INDEX_NAME, **cached_file_kwargs
<ide> )
<del> is_sharded = True
<del> except EntryNotFoundError:
<del> has_file_kwargs = {"revision": revision, "proxies": proxies, "use_auth_token": use_auth_token}
<add> if resolved_archive_file is not None:
<add> is_sharded = True
<add> if resolved_archive_file is None:
<add> # Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error
<add> # message.
<add> has_file_kwargs = {
<add> "revision": revision,
<add> "proxies": proxies,
<add> "use_auth_token": use_auth_token,
<add> }
<ide> if has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs):
<ide> raise EnvironmentError(
<ide> f"{pretrained_model_name_or_path} does not appear to have a file named"
<ide> def from_pretrained(
<ide> f"{pretrained_model_name_or_path} does not appear to have a file named"
<ide> f" {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
<ide> )
<del> else:
<add> except EnvironmentError:
<add> # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
<add> # to the original exception.
<add> raise
<add> except Exception:
<add> # For any other exception, we throw a generic error.
<ide> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} does not appear to have a file named {filename}."
<add> f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it"
<add> " from 'https://huggingface.co/models', make sure you don't have a local directory with the"
<add> f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
<add> f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
<ide> )
<del> except HTTPError as err:
<del> raise EnvironmentError(
<del> f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
<del> f"{err}"
<del> )
<del> except ValueError:
<del> raise EnvironmentError(
<del> f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
<del> f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
<del> f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\nCheckout your"
<del> " internet connection or see how to run the library in offline mode at"
<del> " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
<del> )
<del> except EnvironmentError:
<del> raise EnvironmentError(
<del> f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
<del> "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
<del> f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
<del> f"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
<del> )
<del>
<del> if resolved_archive_file == archive_file:
<add>
<add> if is_local:
<ide> logger.info(f"loading weights file {archive_file}")
<add> resolved_archive_file = archive_file
<ide> else:
<del> logger.info(f"loading weights file {archive_file} from cache at {resolved_archive_file}")
<add> logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}")
<ide> else:
<ide> resolved_archive_file = None
<ide>
<ide><path>src/transformers/modeling_tf_utils.py
<ide>
<ide> from huggingface_hub import Repository, list_repo_files
<ide> from keras.saving.hdf5_format import save_attributes_to_hdf5_group
<del>from requests import HTTPError
<ide> from transformers.utils.hub import convert_file_size_to_int, get_checkpoint_shard_files
<ide>
<ide> from . import DataCollatorWithPadding, DefaultDataCollator
<ide> from .tf_utils import shape_list
<ide> from .utils import (
<ide> DUMMY_INPUTS,
<del> HUGGINGFACE_CO_RESOLVE_ENDPOINT,
<ide> TF2_WEIGHTS_INDEX_NAME,
<ide> TF2_WEIGHTS_NAME,
<ide> WEIGHTS_INDEX_NAME,
<ide> WEIGHTS_NAME,
<del> EntryNotFoundError,
<ide> ModelOutput,
<ide> PushToHubMixin,
<del> RepositoryNotFoundError,
<del> RevisionNotFoundError,
<del> cached_path,
<add> cached_file,
<ide> find_labels,
<ide> has_file,
<del> hf_bucket_url,
<ide> is_offline_mode,
<del> is_remote_url,
<ide> logging,
<ide> requires_backends,
<ide> working_or_temp_dir,
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> Mirror source to accelerate downloads in China. If you are from China and have an accessibility
<ide> problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
<ide> Please refer to the mirror site for more information.
<add> subfolder (`str`, *optional*, defaults to `""`):
<add> In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
<add> specify the folder name here.
<ide> kwargs (remaining dictionary of keyword arguments, *optional*):
<ide> Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
<ide> `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> load_weight_prefix = kwargs.pop("load_weight_prefix", None)
<ide> from_pipeline = kwargs.pop("_from_pipeline", None)
<ide> from_auto_class = kwargs.pop("_from_auto", False)
<add> subfolder = kwargs.pop("subfolder", "")
<ide>
<ide> if trust_remote_code is True:
<ide> logger.warning(
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> # This variable will flag if we're loading a sharded checkpoint. In this case the archive file is just the
<ide> # index of the files.
<ide> is_sharded = False
<del> sharded_metadata = None
<ide> # Load model
<ide> if pretrained_model_name_or_path is not None:
<add> pretrained_model_name_or_path = str(pretrained_model_name_or_path)
<add> is_local = os.path.isdir(pretrained_model_name_or_path)
<ide> if os.path.isdir(pretrained_model_name_or_path):
<ide> if from_pt and os.path.isfile(os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME)):
<ide> # Load from a PyTorch checkpoint in priority if from_pt
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> f"Error no file named {TF2_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
<ide> f"{pretrained_model_name_or_path}."
<ide> )
<del> elif os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
<add> elif os.path.isfile(pretrained_model_name_or_path):
<ide> archive_file = pretrained_model_name_or_path
<add> is_local = True
<ide> elif os.path.isfile(pretrained_model_name_or_path + ".index"):
<ide> archive_file = pretrained_model_name_or_path + ".index"
<add> is_local = True
<ide> else:
<add> # set correct filename
<ide> filename = WEIGHTS_NAME if from_pt else TF2_WEIGHTS_NAME
<del> archive_file = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=filename,
<del> revision=revision,
<del> mirror=mirror,
<del> )
<ide>
<del> try:
<del> # Load from URL or cache if already cached
<del> resolved_archive_file = cached_path(
<del> archive_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<del> )
<add> try:
<add> # Load from URL or cache if already cached
<add> cached_file_kwargs = dict(
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> local_files_only=local_files_only,
<add> use_auth_token=use_auth_token,
<add> user_agent=user_agent,
<add> revision=revision,
<add> subfolder=subfolder,
<add> _raise_exceptions_for_missing_entries=False,
<add> )
<add> resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)
<ide>
<del> except RepositoryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
<del> "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
<del> "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli "
<del> "login` and pass `use_auth_token=True`."
<del> )
<del> except RevisionNotFoundError:
<del> raise EnvironmentError(
<del> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
<del> "this model name. Check the model page at "
<del> f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
<del> )
<del> except EntryNotFoundError:
<del> if filename == TF2_WEIGHTS_NAME:
<del> try:
<add> # Since we set _raise_exceptions_for_missing_entries=False, we don't get an expection but a None
<add> # result when internet is up, the repo and revision exist, but the file does not.
<add> if resolved_archive_file is None and filename == TF2_WEIGHTS_NAME:
<ide> # Maybe the checkpoint is sharded, we try to grab the index name in this case.
<del> archive_file = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=TF2_WEIGHTS_INDEX_NAME,
<del> revision=revision,
<del> mirror=mirror,
<del> )
<del> resolved_archive_file = cached_path(
<del> archive_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<add> resolved_archive_file = cached_file(
<add> pretrained_model_name_or_path, TF2_WEIGHTS_INDEX_NAME, **cached_file_kwargs
<ide> )
<del> is_sharded = True
<del> except EntryNotFoundError:
<del> # Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error
<add> if resolved_archive_file is not None:
<add> is_sharded = True
<add> if resolved_archive_file is None:
<add> # Otherwise, maybe there is a PyTorch or Flax model file. We try those to give a helpful error
<ide> # message.
<ide> has_file_kwargs = {
<ide> "revision": revision,
<ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
<ide> f"{pretrained_model_name_or_path} does not appear to have a file named"
<ide> f" {TF2_WEIGHTS_NAME} or {WEIGHTS_NAME}."
<ide> )
<del> else:
<add>
<add> except EnvironmentError:
<add> # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
<add> # to the original exception.
<add> raise
<add> except Exception:
<add> # For any other exception, we throw a generic error.
<add>
<ide> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} does not appear to have a file named {filename}."
<add> f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it"
<add> " from 'https://huggingface.co/models', make sure you don't have a local directory with the"
<add> f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
<add> f" directory containing a file named {TF2_WEIGHTS_NAME} or {WEIGHTS_NAME}."
<ide> )
<del> except HTTPError as err:
<del> raise EnvironmentError(
<del> f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
<del> f"{err}"
<del> )
<del> except ValueError:
<del> raise EnvironmentError(
<del> f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
<del> f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
<del> f" directory containing a file named {TF2_WEIGHTS_NAME} or {WEIGHTS_NAME}.\nCheckout your internet"
<del> " connection or see how to run the library in offline mode at"
<del> " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
<del> )
<del> except EnvironmentError:
<del> raise EnvironmentError(
<del> f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
<del> "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
<del> f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
<del> f"containing a file named {TF2_WEIGHTS_NAME} or {WEIGHTS_NAME}."
<del> )
<del>
<del> if resolved_archive_file == archive_file:
<add> if is_local:
<ide> logger.info(f"loading weights file {archive_file}")
<add> resolved_archive_file = archive_file
<ide> else:
<del> logger.info(f"loading weights file {archive_file} from cache at {resolved_archive_file}")
<add> logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}")
<ide> else:
<ide> resolved_archive_file = None
<ide>
<ide> # We'll need to download and cache each checkpoint shard if the checkpoint is sharded.
<ide> if is_sharded:
<ide> # resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
<del> resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(
<add> resolved_archive_file, _ = get_checkpoint_shard_files(
<ide> pretrained_model_name_or_path,
<ide> resolved_archive_file,
<ide> cache_dir=cache_dir,
<ide><path>src/transformers/modeling_utils.py
<ide> from torch import Tensor, device, nn
<ide> from torch.nn import CrossEntropyLoss
<ide>
<del>from requests import HTTPError
<ide> from transformers.utils.hub import convert_file_size_to_int, get_checkpoint_shard_files
<ide> from transformers.utils.import_utils import is_sagemaker_mp_enabled
<ide>
<ide> from .utils import (
<ide> DUMMY_INPUTS,
<ide> FLAX_WEIGHTS_NAME,
<del> HUGGINGFACE_CO_RESOLVE_ENDPOINT,
<ide> TF2_WEIGHTS_NAME,
<ide> TF_WEIGHTS_NAME,
<ide> WEIGHTS_INDEX_NAME,
<ide> WEIGHTS_NAME,
<ide> ContextManagers,
<del> EntryNotFoundError,
<ide> ModelOutput,
<ide> PushToHubMixin,
<del> RepositoryNotFoundError,
<del> RevisionNotFoundError,
<del> cached_path,
<add> cached_file,
<ide> copy_func,
<ide> has_file,
<del> hf_bucket_url,
<ide> is_accelerate_available,
<ide> is_offline_mode,
<del> is_remote_url,
<ide> logging,
<ide> replace_return_docstrings,
<ide> )
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide>
<ide> if pretrained_model_name_or_path is not None:
<ide> pretrained_model_name_or_path = str(pretrained_model_name_or_path)
<del> if os.path.isdir(pretrained_model_name_or_path):
<add> is_local = os.path.isdir(pretrained_model_name_or_path)
<add> if is_local:
<ide> if from_tf and os.path.isfile(
<ide> os.path.join(pretrained_model_name_or_path, subfolder, TF_WEIGHTS_NAME + ".index")
<ide> ):
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> f"Error no file named {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME + '.index'} or "
<ide> f"{FLAX_WEIGHTS_NAME} found in directory {pretrained_model_name_or_path}."
<ide> )
<del> elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)) or is_remote_url(
<del> pretrained_model_name_or_path
<del> ):
<add> elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
<ide> archive_file = pretrained_model_name_or_path
<add> is_local = True
<ide> elif os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path + ".index")):
<ide> if not from_tf:
<ide> raise ValueError(
<ide> f"We found a TensorFlow checkpoint at {pretrained_model_name_or_path + '.index'}, please set "
<ide> "from_tf to True to load from this checkpoint."
<ide> )
<ide> archive_file = os.path.join(subfolder, pretrained_model_name_or_path + ".index")
<add> is_local = True
<ide> else:
<ide> # set correct filename
<ide> if from_tf:
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> else:
<ide> filename = WEIGHTS_NAME
<ide>
<del> archive_file = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=filename,
<del> revision=revision,
<del> mirror=mirror,
<del> subfolder=subfolder if len(subfolder) > 0 else None,
<del> )
<del>
<del> try:
<del> # Load from URL or cache if already cached
<del> resolved_archive_file = cached_path(
<del> archive_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<del> )
<add> try:
<add> # Load from URL or cache if already cached
<add> cached_file_kwargs = dict(
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> local_files_only=local_files_only,
<add> use_auth_token=use_auth_token,
<add> user_agent=user_agent,
<add> revision=revision,
<add> subfolder=subfolder,
<add> _raise_exceptions_for_missing_entries=False,
<add> )
<add> resolved_archive_file = cached_file(pretrained_model_name_or_path, filename, **cached_file_kwargs)
<ide>
<del> except RepositoryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
<del> "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
<del> "token having permission to this repo with `use_auth_token` or log in with `huggingface-cli "
<del> "login` and pass `use_auth_token=True`."
<del> )
<del> except RevisionNotFoundError:
<del> raise EnvironmentError(
<del> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
<del> "this model name. Check the model page at "
<del> f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
<del> )
<del> except EntryNotFoundError:
<del> if filename == WEIGHTS_NAME:
<del> try:
<add> # Since we set _raise_exceptions_for_missing_entries=False, we don't get an expection but a None
<add> # result when internet is up, the repo and revision exist, but the file does not.
<add> if resolved_archive_file is None and filename == WEIGHTS_NAME:
<ide> # Maybe the checkpoint is sharded, we try to grab the index name in this case.
<del> archive_file = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=WEIGHTS_INDEX_NAME,
<del> revision=revision,
<del> mirror=mirror,
<del> subfolder=subfolder if len(subfolder) > 0 else None,
<del> )
<del> resolved_archive_file = cached_path(
<del> archive_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<add> resolved_archive_file = cached_file(
<add> pretrained_model_name_or_path, WEIGHTS_INDEX_NAME, **cached_file_kwargs
<ide> )
<del> is_sharded = True
<del> except EntryNotFoundError:
<add> if resolved_archive_file is not None:
<add> is_sharded = True
<add> if resolved_archive_file is None:
<ide> # Otherwise, maybe there is a TF or Flax model file. We try those to give a helpful error
<ide> # message.
<ide> has_file_kwargs = {
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
<ide> f"{pretrained_model_name_or_path} does not appear to have a file named {WEIGHTS_NAME},"
<ide> f" {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or {FLAX_WEIGHTS_NAME}."
<ide> )
<del> else:
<add> except EnvironmentError:
<add> # Raise any environment error raise by `cached_file`. It will have a helpful error message adapted
<add> # to the original exception.
<add> raise
<add> except Exception:
<add> # For any other exception, we throw a generic error.
<ide> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} does not appear to have a file named {filename}."
<add> f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it"
<add> " from 'https://huggingface.co/models', make sure you don't have a local directory with the"
<add> f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
<add> f" directory containing a file named {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or"
<add> f" {FLAX_WEIGHTS_NAME}."
<ide> )
<del> except HTTPError as err:
<del> raise EnvironmentError(
<del> f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
<del> f"{err}"
<del> )
<del> except ValueError:
<del> raise EnvironmentError(
<del> f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
<del> f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
<del> f" directory containing a file named {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or"
<del> f" {FLAX_WEIGHTS_NAME}.\nCheckout your internet connection or see how to run the library in"
<del> " offline mode at 'https://huggingface.co/docs/transformers/installation#offline-mode'."
<del> )
<del> except EnvironmentError:
<del> raise EnvironmentError(
<del> f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
<del> "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
<del> f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
<del> f"containing a file named {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME} or "
<del> f"{FLAX_WEIGHTS_NAME}."
<del> )
<ide>
<del> if resolved_archive_file == archive_file:
<add> if is_local:
<ide> logger.info(f"loading weights file {archive_file}")
<add> resolved_archive_file = archive_file
<ide> else:
<del> logger.info(f"loading weights file {archive_file} from cache at {resolved_archive_file}")
<add> logger.info(f"loading weights file {filename} from cache at {resolved_archive_file}")
<ide> else:
<ide> resolved_archive_file = None
<ide>
<ide> # We'll need to download and cache each checkpoint shard if the checkpoint is sharded.
<ide> if is_sharded:
<del> # resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
<add> # rsolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
<ide> resolved_archive_file, sharded_metadata = get_checkpoint_shard_files(
<ide> pretrained_model_name_or_path,
<ide> resolved_archive_file,
<ide><path>src/transformers/tokenization_utils_base.py
<ide> from . import __version__
<ide> from .dynamic_module_utils import custom_object_save
<ide> from .utils import (
<del> EntryNotFoundError,
<ide> ExplicitEnum,
<ide> PaddingStrategy,
<ide> PushToHubMixin,
<del> RepositoryNotFoundError,
<del> RevisionNotFoundError,
<ide> TensorType,
<ide> add_end_docstrings,
<del> cached_path,
<add> cached_file,
<ide> copy_func,
<ide> get_file_from_repo,
<del> hf_bucket_url,
<ide> is_flax_available,
<ide> is_offline_mode,
<del> is_remote_url,
<ide> is_tf_available,
<ide> is_tokenizers_available,
<ide> is_torch_available,
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
<ide> vocab_files = {}
<ide> init_configuration = {}
<ide>
<del> if os.path.isfile(pretrained_model_name_or_path) or is_remote_url(pretrained_model_name_or_path):
<add> is_local = os.path.isdir(pretrained_model_name_or_path)
<add> if os.path.isfile(pretrained_model_name_or_path):
<ide> if len(cls.vocab_files_names) > 1:
<ide> raise ValueError(
<ide> f"Calling {cls.__name__}.from_pretrained() with the path to a single file or url is not "
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
<ide> "special_tokens_map_file": SPECIAL_TOKENS_MAP_FILE,
<ide> "tokenizer_config_file": TOKENIZER_CONFIG_FILE,
<ide> }
<del> vocab_files_target = {**cls.vocab_files_names, **additional_files_names}
<add> vocab_files = {**cls.vocab_files_names, **additional_files_names}
<ide>
<del> if "tokenizer_file" in vocab_files_target:
<add> if "tokenizer_file" in vocab_files:
<ide> # Try to get the tokenizer config to see if there are versioned tokenizer files.
<ide> fast_tokenizer_file = FULL_TOKENIZER_FILE
<ide> resolved_config_file = get_file_from_repo(
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
<ide> use_auth_token=use_auth_token,
<ide> revision=revision,
<ide> local_files_only=local_files_only,
<add> subfolder=subfolder,
<ide> )
<ide> if resolved_config_file is not None:
<ide> with open(resolved_config_file, encoding="utf-8") as reader:
<ide> tokenizer_config = json.load(reader)
<ide> if "fast_tokenizer_files" in tokenizer_config:
<ide> fast_tokenizer_file = get_fast_tokenizer_file(tokenizer_config["fast_tokenizer_files"])
<del> vocab_files_target["tokenizer_file"] = fast_tokenizer_file
<del>
<del> # Look for the tokenizer files
<del> for file_id, file_name in vocab_files_target.items():
<del> if os.path.isdir(pretrained_model_name_or_path):
<del> if subfolder is not None:
<del> full_file_name = os.path.join(pretrained_model_name_or_path, subfolder, file_name)
<del> else:
<del> full_file_name = os.path.join(pretrained_model_name_or_path, file_name)
<del> if not os.path.exists(full_file_name):
<del> logger.info(f"Didn't find file {full_file_name}. We won't load it.")
<del> full_file_name = None
<del> else:
<del> full_file_name = hf_bucket_url(
<del> pretrained_model_name_or_path,
<del> filename=file_name,
<del> subfolder=subfolder,
<del> revision=revision,
<del> mirror=None,
<del> )
<del>
<del> vocab_files[file_id] = full_file_name
<add> vocab_files["tokenizer_file"] = fast_tokenizer_file
<ide>
<ide> # Get files from url, cache, or disk depending on the case
<ide> resolved_vocab_files = {}
<ide> unresolved_files = []
<ide> for file_id, file_path in vocab_files.items():
<add> print(file_id, file_path)
<ide> if file_path is None:
<ide> resolved_vocab_files[file_id] = None
<ide> else:
<del> try:
<del> resolved_vocab_files[file_id] = cached_path(
<del> file_path,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> user_agent=user_agent,
<del> )
<del>
<del> except FileNotFoundError as error:
<del> if local_files_only:
<del> unresolved_files.append(file_id)
<del> else:
<del> raise error
<del>
<del> except RepositoryNotFoundError:
<del> raise EnvironmentError(
<del> f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
<del> "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to "
<del> "pass a token having permission to this repo with `use_auth_token` or log in with "
<del> "`huggingface-cli login` and pass `use_auth_token=True`."
<del> )
<del> except RevisionNotFoundError:
<del> raise EnvironmentError(
<del> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists "
<del> "for this model name. Check the model page at "
<del> f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
<del> )
<del> except EntryNotFoundError:
<del> logger.debug(f"{pretrained_model_name_or_path} does not contain a file named {file_path}.")
<del> resolved_vocab_files[file_id] = None
<del>
<del> except ValueError:
<del> logger.debug(f"Connection problem to access {file_path} and it wasn't found in the cache.")
<del> resolved_vocab_files[file_id] = None
<add> resolved_vocab_files[file_id] = cached_file(
<add> pretrained_model_name_or_path,
<add> file_path,
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> local_files_only=local_files_only,
<add> use_auth_token=use_auth_token,
<add> user_agent=user_agent,
<add> revision=revision,
<add> subfolder=subfolder,
<add> _raise_exceptions_for_missing_entries=False,
<add> _raise_exceptions_for_connection_errors=False,
<add> )
<ide>
<ide> if len(unresolved_files) > 0:
<ide> logger.info(
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
<ide> if file_id not in resolved_vocab_files:
<ide> continue
<ide>
<del> if file_path == resolved_vocab_files[file_id]:
<add> if is_local:
<ide> logger.info(f"loading file {file_path}")
<ide> else:
<ide> logger.info(f"loading file {file_path} from cache at {resolved_vocab_files[file_id]}")
<ide><path>src/transformers/utils/__init__.py
<ide> PushToHubMixin,
<ide> RepositoryNotFoundError,
<ide> RevisionNotFoundError,
<add> cached_file,
<ide> cached_path,
<ide> default_cache_path,
<ide> define_sagemaker_information,
<ide> is_local_clone,
<ide> is_offline_mode,
<ide> is_remote_url,
<add> move_cache,
<ide> send_example_telemetry,
<ide> url_to_filename,
<ide> )
<ide><path>src/transformers/utils/hub.py
<ide> import io
<ide> import json
<ide> import os
<add>import re
<ide> import shutil
<ide> import subprocess
<ide> import sys
<ide> import tarfile
<ide> import tempfile
<add>import traceback
<ide> import warnings
<ide> from contextlib import contextmanager
<ide> from functools import partial
<ide> from uuid import uuid4
<ide> from zipfile import ZipFile, is_zipfile
<ide>
<add>import huggingface_hub
<ide> import requests
<ide> from filelock import FileLock
<del>from huggingface_hub import CommitOperationAdd, HfFolder, create_commit, create_repo, list_repo_files, whoami
<add>from huggingface_hub import (
<add> CommitOperationAdd,
<add> HfFolder,
<add> create_commit,
<add> create_repo,
<add> hf_hub_download,
<add> list_repo_files,
<add> whoami,
<add>)
<add>from huggingface_hub.constants import HUGGINGFACE_HEADER_X_LINKED_ETAG, HUGGINGFACE_HEADER_X_REPO_COMMIT
<add>from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError, RevisionNotFoundError
<ide> from requests.exceptions import HTTPError
<ide> from requests.models import Response
<ide> from transformers.utils.logging import tqdm
<ide> def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
<ide> return ua
<ide>
<ide>
<del>class RepositoryNotFoundError(HTTPError):
<del> """
<del> Raised when trying to access a hf.co URL with an invalid repository name, or with a private repo name the user does
<del> not have access to.
<del> """
<del>
<del>
<del>class EntryNotFoundError(HTTPError):
<del> """Raised when trying to access a hf.co URL with a valid repository and revision but an invalid filename."""
<del>
<del>
<del>class RevisionNotFoundError(HTTPError):
<del> """Raised when trying to access a hf.co URL with a valid repository but an invalid revision."""
<del>
<del>
<ide> def _raise_for_status(response: Response):
<ide> """
<ide> Internal version of `request.raise_for_status()` that will refine a potential HTTPError.
<ide> def _resumable_file_manager() -> "io.BufferedWriter":
<ide> return cache_path
<ide>
<ide>
<del>def get_file_from_repo(
<del> path_or_repo: Union[str, os.PathLike],
<add>def try_to_load_from_cache(cache_dir, repo_id, filename, revision=None):
<add> """
<add> Explores the cache to return the latest cached file for a given revision.
<add> """
<add> if revision is None:
<add> revision = "main"
<add>
<add> model_id = repo_id.replace("/", "--")
<add> model_cache = os.path.join(cache_dir, f"models--{model_id}")
<add> if not os.path.isdir(model_cache):
<add> # No cache for this model
<add> return None
<add>
<add> # Resolve refs (for instance to convert main to the associated commit sha)
<add> cached_refs = os.listdir(os.path.join(model_cache, "refs"))
<add> if revision in cached_refs:
<add> with open(os.path.join(model_cache, "refs", revision)) as f:
<add> revision = f.read()
<add>
<add> cached_shas = os.listdir(os.path.join(model_cache, "snapshots"))
<add> if revision not in cached_shas:
<add> # No cache for this revision and we won't try to return a random revision
<add> return None
<add>
<add> cached_file = os.path.join(model_cache, "snapshots", revision, filename)
<add> return cached_file if os.path.isfile(cached_file) else None
<add>
<add>
<add># If huggingface_hub changes the class of error for this to FileNotFoundError, we will be able to avoid that in the
<add># future.
<add>LOCAL_FILES_ONLY_HF_ERROR = (
<add> "Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co "
<add> "look-ups and downloads online, set 'local_files_only' to False."
<add>)
<add>
<add>
<add># In the future, this ugly contextmanager can be removed when huggingface_hub as a released version where we can
<add># activate/deactivate progress bars.
<add>@contextmanager
<add>def _patch_hf_hub_tqdm():
<add> """
<add> A context manager to make huggingface hub use the tqdm version of Transformers (which is controlled by some utils)
<add> in logging.
<add> """
<add> old_tqdm = huggingface_hub.file_download.tqdm
<add> huggingface_hub.file_download.tqdm = tqdm
<add> yield
<add> huggingface_hub.file_download.tqdm = old_tqdm
<add>
<add>
<add>def cached_file(
<add> path_or_repo_id: Union[str, os.PathLike],
<ide> filename: str,
<ide> cache_dir: Optional[Union[str, os.PathLike]] = None,
<ide> force_download: bool = False,
<ide> def get_file_from_repo(
<ide> use_auth_token: Optional[Union[bool, str]] = None,
<ide> revision: Optional[str] = None,
<ide> local_files_only: bool = False,
<add> subfolder: str = "",
<add> user_agent: Optional[Union[str, Dict[str, str]]] = None,
<add> _raise_exceptions_for_missing_entries=True,
<add> _raise_exceptions_for_connection_errors=True,
<ide> ):
<ide> """
<ide> Tries to locate a file in a local folder and repo, downloads and cache it if necessary.
<ide>
<ide> Args:
<del> path_or_repo (`str` or `os.PathLike`):
<add> path_or_repo_id (`str` or `os.PathLike`):
<ide> This can be either:
<ide>
<ide> - a string, the *model id* of a model repo on huggingface.co.
<ide> def get_file_from_repo(
<ide> identifier allowed by git.
<ide> local_files_only (`bool`, *optional*, defaults to `False`):
<ide> If `True`, will only try to load the tokenizer configuration from local files.
<add> subfolder (`str`, *optional*, defaults to `""`):
<add> In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
<add> specify the folder name here.
<ide>
<ide> <Tip>
<ide>
<ide> def get_file_from_repo(
<ide> </Tip>
<ide>
<ide> Returns:
<del> `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo) or `None` if the
<del> file does not exist.
<add> `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo).
<ide>
<ide> Examples:
<ide>
<ide> ```python
<del> # Download a tokenizer configuration from huggingface.co and cache.
<del> tokenizer_config = get_file_from_repo("bert-base-uncased", "tokenizer_config.json")
<del> # This model does not have a tokenizer config so the result will be None.
<del> tokenizer_config = get_file_from_repo("xlm-roberta-base", "tokenizer_config.json")
<add> # Download a model weight from the Hub and cache it.
<add> model_weights_file = cached_file("bert-base-uncased", "pytorch_model.bin")
<ide> ```"""
<ide> if is_offline_mode() and not local_files_only:
<ide> logger.info("Offline mode: forcing local_files_only=True")
<ide> local_files_only = True
<add> if subfolder is None:
<add> subfolder = ""
<add>
<add> path_or_repo_id = str(path_or_repo_id)
<add> full_filename = os.path.join(subfolder, filename)
<add> if os.path.isdir(path_or_repo_id):
<add> resolved_file = os.path.join(os.path.join(path_or_repo_id, subfolder), filename)
<add> if not os.path.isfile(resolved_file):
<add> if _raise_exceptions_for_missing_entries:
<add> raise EnvironmentError(f"Could not locate {full_filename} inside {path_or_repo_id}.")
<add> else:
<add> return None
<add> return resolved_file
<ide>
<del> path_or_repo = str(path_or_repo)
<del> if os.path.isdir(path_or_repo):
<del> resolved_file = os.path.join(path_or_repo, filename)
<del> return resolved_file if os.path.isfile(resolved_file) else None
<del> else:
<del> resolved_file = hf_bucket_url(path_or_repo, filename=filename, revision=revision, mirror=None)
<del>
<add> if cache_dir is None:
<add> cache_dir = TRANSFORMERS_CACHE
<add> if isinstance(cache_dir, Path):
<add> cache_dir = str(cache_dir)
<add> user_agent = http_user_agent(user_agent)
<ide> try:
<ide> # Load from URL or cache if already cached
<del> resolved_file = cached_path(
<del> resolved_file,
<del> cache_dir=cache_dir,
<del> force_download=force_download,
<del> proxies=proxies,
<del> resume_download=resume_download,
<del> local_files_only=local_files_only,
<del> use_auth_token=use_auth_token,
<del> )
<add> with _patch_hf_hub_tqdm():
<add> resolved_file = hf_hub_download(
<add> path_or_repo_id,
<add> filename,
<add> subfolder=None if len(subfolder) == 0 else subfolder,
<add> revision=revision,
<add> cache_dir=cache_dir,
<add> user_agent=user_agent,
<add> force_download=force_download,
<add> proxies=proxies,
<add> resume_download=resume_download,
<add> use_auth_token=use_auth_token,
<add> local_files_only=local_files_only,
<add> )
<ide>
<ide> except RepositoryNotFoundError:
<ide> raise EnvironmentError(
<del> f"{path_or_repo} is not a local folder and is not a valid model identifier "
<add> f"{path_or_repo_id} is not a local folder and is not a valid model identifier "
<ide> "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to "
<ide> "pass a token having permission to this repo with `use_auth_token` or log in with "
<ide> "`huggingface-cli login` and pass `use_auth_token=True`."
<ide> def get_file_from_repo(
<ide> raise EnvironmentError(
<ide> f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists "
<ide> "for this model name. Check the model page at "
<del> f"'https://huggingface.co/{path_or_repo}' for available revisions."
<add> f"'https://huggingface.co/{path_or_repo_id}' for available revisions."
<add> )
<add> except EntryNotFoundError:
<add> if not _raise_exceptions_for_missing_entries:
<add> return None
<add> if revision is None:
<add> revision = "main"
<add> raise EnvironmentError(
<add> f"{path_or_repo_id} does not appear to have a file named {full_filename}. Checkout "
<add> f"'https://huggingface.co/{path_or_repo_id}/{revision}' for available files."
<add> )
<add> except HTTPError as err:
<add> # First we try to see if we have a cached version (not up to date):
<add> resolved_file = try_to_load_from_cache(cache_dir, path_or_repo_id, full_filename, revision=revision)
<add> if resolved_file is not None:
<add> return resolved_file
<add> if not _raise_exceptions_for_connection_errors:
<add> return None
<add>
<add> raise EnvironmentError(f"There was a specific connection error when trying to load {path_or_repo_id}:\n{err}")
<add> except ValueError as err:
<add> # HuggingFace Hub returns a ValueError for a missing file when local_files_only=True we need to catch it here
<add> # This could be caught above along in `EntryNotFoundError` if hf_hub sent a different error message here
<add> if LOCAL_FILES_ONLY_HF_ERROR in err.args[0] and local_files_only and not _raise_exceptions_for_missing_entries:
<add> return None
<add>
<add> # Otherwise we try to see if we have a cached version (not up to date):
<add> resolved_file = try_to_load_from_cache(cache_dir, path_or_repo_id, full_filename, revision=revision)
<add> if resolved_file is not None:
<add> return resolved_file
<add> if not _raise_exceptions_for_connection_errors:
<add> return None
<add> raise EnvironmentError(
<add> f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this file, couldn't find it in the"
<add> f" cached files and it looks like {path_or_repo_id} is not the path to a directory containing a file named"
<add> f" {full_filename}.\nCheckout your internet connection or see how to run the library in offline mode at"
<add> " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
<ide> )
<del> except EnvironmentError:
<del> # The repo and revision exist, but the file does not or there was a connection error fetching it.
<del> return None
<ide>
<ide> return resolved_file
<ide>
<ide>
<add>def get_file_from_repo(
<add> path_or_repo: Union[str, os.PathLike],
<add> filename: str,
<add> cache_dir: Optional[Union[str, os.PathLike]] = None,
<add> force_download: bool = False,
<add> resume_download: bool = False,
<add> proxies: Optional[Dict[str, str]] = None,
<add> use_auth_token: Optional[Union[bool, str]] = None,
<add> revision: Optional[str] = None,
<add> local_files_only: bool = False,
<add> subfolder: str = "",
<add>):
<add> """
<add> Tries to locate a file in a local folder and repo, downloads and cache it if necessary.
<add>
<add> Args:
<add> path_or_repo (`str` or `os.PathLike`):
<add> This can be either:
<add>
<add> - a string, the *model id* of a model repo on huggingface.co.
<add> - a path to a *directory* potentially containing the file.
<add> filename (`str`):
<add> The name of the file to locate in `path_or_repo`.
<add> cache_dir (`str` or `os.PathLike`, *optional*):
<add> Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
<add> cache should not be used.
<add> force_download (`bool`, *optional*, defaults to `False`):
<add> Whether or not to force to (re-)download the configuration files and override the cached versions if they
<add> exist.
<add> resume_download (`bool`, *optional*, defaults to `False`):
<add> Whether or not to delete incompletely received file. Attempts to resume the download if such a file exists.
<add> proxies (`Dict[str, str]`, *optional*):
<add> A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
<add> 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
<add> use_auth_token (`str` or *bool*, *optional*):
<add> The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
<add> when running `transformers-cli login` (stored in `~/.huggingface`).
<add> revision (`str`, *optional*, defaults to `"main"`):
<add> The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
<add> git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
<add> identifier allowed by git.
<add> local_files_only (`bool`, *optional*, defaults to `False`):
<add> If `True`, will only try to load the tokenizer configuration from local files.
<add> subfolder (`str`, *optional*, defaults to `""`):
<add> In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
<add> specify the folder name here.
<add>
<add> <Tip>
<add>
<add> Passing `use_auth_token=True` is required when you want to use a private model.
<add>
<add> </Tip>
<add>
<add> Returns:
<add> `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo) or `None` if the
<add> file does not exist.
<add>
<add> Examples:
<add>
<add> ```python
<add> # Download a tokenizer configuration from huggingface.co and cache.
<add> tokenizer_config = get_file_from_repo("bert-base-uncased", "tokenizer_config.json")
<add> # This model does not have a tokenizer config so the result will be None.
<add> tokenizer_config = get_file_from_repo("xlm-roberta-base", "tokenizer_config.json")
<add> ```"""
<add> return cached_file(
<add> path_or_repo_id=path_or_repo,
<add> filename=filename,
<add> cache_dir=cache_dir,
<add> force_download=force_download,
<add> resume_download=resume_download,
<add> proxies=proxies,
<add> use_auth_token=use_auth_token,
<add> revision=revision,
<add> local_files_only=local_files_only,
<add> subfolder=subfolder,
<add> _raise_exceptions_for_missing_entries=False,
<add> _raise_exceptions_for_connection_errors=False,
<add> )
<add>
<add>
<ide> def has_file(
<ide> path_or_repo: Union[str, os.PathLike],
<ide> filename: str,
<ide> def has_file(
<ide>
<ide> r = requests.head(url, headers=headers, allow_redirects=False, proxies=proxies, timeout=10)
<ide> try:
<del> _raise_for_status(r)
<add> huggingface_hub.utils._errors._raise_for_status(r)
<ide> return True
<ide> except RepositoryNotFoundError as e:
<ide> logger.error(e)
<ide> def get_checkpoint_shard_files(
<ide> cached_filenames.append(cached_filename)
<ide>
<ide> return cached_filenames, sharded_metadata
<add>
<add>
<add># All what is below is for conversion between old cache format and new cache format.
<add>
<add>
<add>def get_all_cached_files(cache_dir=None):
<add> """
<add> Returns a list for all files cached with appropriate metadata.
<add> """
<add> if cache_dir is None:
<add> cache_dir = TRANSFORMERS_CACHE
<add> else:
<add> cache_dir = str(cache_dir)
<add>
<add> cached_files = []
<add> for file in os.listdir(cache_dir):
<add> meta_path = os.path.join(cache_dir, f"{file}.json")
<add> if not os.path.isfile(meta_path):
<add> continue
<add>
<add> with open(meta_path, encoding="utf-8") as meta_file:
<add> metadata = json.load(meta_file)
<add> url = metadata["url"]
<add> etag = metadata["etag"].replace('"', "")
<add> cached_files.append({"file": file, "url": url, "etag": etag})
<add>
<add> return cached_files
<add>
<add>
<add>def get_hub_metadata(url, token=None):
<add> """
<add> Returns the commit hash and associated etag for a given url.
<add> """
<add> if token is None:
<add> token = HfFolder.get_token()
<add> headers = {"user-agent": http_user_agent()}
<add> headers["authorization"] = f"Bearer {token}"
<add>
<add> r = huggingface_hub.file_download._request_with_retry(
<add> method="HEAD", url=url, headers=headers, allow_redirects=False
<add> )
<add> huggingface_hub.file_download._raise_for_status(r)
<add> commit_hash = r.headers.get(HUGGINGFACE_HEADER_X_REPO_COMMIT)
<add> etag = r.headers.get(HUGGINGFACE_HEADER_X_LINKED_ETAG) or r.headers.get("ETag")
<add> if etag is not None:
<add> etag = huggingface_hub.file_download._normalize_etag(etag)
<add> return etag, commit_hash
<add>
<add>
<add>def extract_info_from_url(url):
<add> """
<add> Extract repo_name, revision and filename from an url.
<add> """
<add> search = re.search(r"^https://huggingface\.co/(.*)/resolve/([^/]*)/(.*)$", url)
<add> if search is None:
<add> return None
<add> repo, revision, filename = search.groups()
<add> cache_repo = "--".join(["models"] + repo.split("/"))
<add> return {"repo": cache_repo, "revision": revision, "filename": filename}
<add>
<add>
<add>def clean_files_for(file):
<add> """
<add> Remove, if they exist, file, file.json and file.lock
<add> """
<add> for f in [file, f"{file}.json", f"{file}.lock"]:
<add> if os.path.isfile(f):
<add> os.remove(f)
<add>
<add>
<add>def move_to_new_cache(file, repo, filename, revision, etag, commit_hash):
<add> """
<add> Move file to repo following the new huggingface hub cache organization.
<add> """
<add> os.makedirs(repo, exist_ok=True)
<add>
<add> # refs
<add> os.makedirs(os.path.join(repo, "refs"), exist_ok=True)
<add> if revision != commit_hash:
<add> ref_path = os.path.join(repo, "refs", revision)
<add> with open(ref_path, "w") as f:
<add> f.write(commit_hash)
<add>
<add> # blobs
<add> os.makedirs(os.path.join(repo, "blobs"), exist_ok=True)
<add> # TODO: replace copy by move when all works well.
<add> blob_path = os.path.join(repo, "blobs", etag)
<add> shutil.move(file, blob_path)
<add>
<add> # snapshots
<add> os.makedirs(os.path.join(repo, "snapshots"), exist_ok=True)
<add> os.makedirs(os.path.join(repo, "snapshots", commit_hash), exist_ok=True)
<add> pointer_path = os.path.join(repo, "snapshots", commit_hash, filename)
<add> huggingface_hub.file_download._create_relative_symlink(blob_path, pointer_path)
<add> clean_files_for(file)
<add>
<add>
<add>def move_cache(cache_dir=None, token=None):
<add> if cache_dir is None:
<add> cache_dir = TRANSFORMERS_CACHE
<add> if token is None:
<add> token = HfFolder.get_token()
<add> cached_files = get_all_cached_files(cache_dir=cache_dir)
<add> print(f"Moving {len(cached_files)} files to the new cache system")
<add>
<add> hub_metadata = {}
<add> for file_info in tqdm(cached_files):
<add> url = file_info.pop("url")
<add> if url not in hub_metadata:
<add> try:
<add> hub_metadata[url] = get_hub_metadata(url, token=token)
<add> except requests.HTTPError:
<add> continue
<add>
<add> etag, commit_hash = hub_metadata[url]
<add> if etag is None or commit_hash is None:
<add> continue
<add>
<add> if file_info["etag"] != etag:
<add> # Cached file is not up to date, we just throw it as a new version will be downloaded anyway.
<add> clean_files_for(os.path.join(cache_dir, file_info["file"]))
<add> continue
<add>
<add> url_info = extract_info_from_url(url)
<add> if url_info is None:
<add> # Not a file from huggingface.co
<add> continue
<add>
<add> repo = os.path.join(cache_dir, url_info["repo"])
<add> move_to_new_cache(
<add> file=os.path.join(cache_dir, file_info["file"]),
<add> repo=repo,
<add> filename=url_info["filename"],
<add> revision=url_info["revision"],
<add> etag=etag,
<add> commit_hash=commit_hash,
<add> )
<add>
<add>
<add>cache_version_file = os.path.join(TRANSFORMERS_CACHE, "version.txt")
<add>if not os.path.isfile(cache_version_file):
<add> cache_version = 0
<add>else:
<add> with open(cache_version_file) as f:
<add> cache_version = int(f.read())
<add>
<add>
<add>if cache_version < 1:
<add> if is_offline_mode():
<add> logger.warn(
<add> "You are offline and the cache for model files in Transformers v4.22.0 has been updated while your local "
<add> "cache seems to be the one of a previous version. It is very likely that all your calls to any "
<add> "`from_pretrained()` method will fail. Remove the offline mode and enable internet connection to have "
<add> "your cache be updated automatically, then you can go back to offline mode."
<add> )
<add> else:
<add> logger.warn(
<add> "The cache for model files in Transformers v4.22.0 has been udpated. Migrating your old cache. This is a "
<add> "one-time only operation. You can interrupt this and resume the migration later on by calling "
<add> "`transformers.utils.move_cache()`."
<add> )
<add> try:
<add> move_cache()
<add> except Exception as e:
<add> trace = "\n".join(traceback.format_tb(e.__traceback__))
<add> logger.error(
<add> f"There was a problem when trying to move your cache:\n\n{trace}\n\nPlease file an issue at "
<add> "https://github.com/huggingface/transformers/issues/new/choose and copy paste this whole message and we "
<add> "will do our best to help."
<add> )
<add>
<add> try:
<add> os.makedirs(TRANSFORMERS_CACHE, exist_ok=True)
<add> with open(cache_version_file, "w") as f:
<add> f.write("1")
<add> except Exception:
<add> logger.warn(
<add> f"There was a problem when trying to write in your cache folder ({TRANSFORMERS_CACHE}). You should set "
<add> "the environment variable TRANSFORMERS_CACHE to a writable directory."
<add> )
<ide><path>tests/test_configuration_common.py
<ide> def test_cached_files_are_used_when_internet_is_down(self):
<ide> # A mock response for an HTTP head request to emulate server down
<ide> response_mock = mock.Mock()
<ide> response_mock.status_code = 500
<del> response_mock.headers = []
<add> response_mock.headers = {}
<ide> response_mock.raise_for_status.side_effect = HTTPError
<ide>
<ide> # Download this model to make sure it's in the cache.
<ide> _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide>
<ide> # Under the mock environment we get a 500 error when trying to reach the model.
<del> with mock.patch("transformers.utils.hub.requests.head", return_value=response_mock) as mock_head:
<add> with mock.patch("requests.request", return_value=response_mock) as mock_head:
<ide> _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide> # This check we did call the fake head request
<ide> mock_head.assert_called()
<ide><path>tests/test_feature_extraction_common.py
<ide> def test_cached_files_are_used_when_internet_is_down(self):
<ide> # A mock response for an HTTP head request to emulate server down
<ide> response_mock = mock.Mock()
<ide> response_mock.status_code = 500
<del> response_mock.headers = []
<add> response_mock.headers = {}
<ide> response_mock.raise_for_status.side_effect = HTTPError
<ide>
<ide> # Download this model to make sure it's in the cache.
<ide> _ = Wav2Vec2FeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2")
<ide> # Under the mock environment we get a 500 error when trying to reach the model.
<del> with mock.patch("transformers.utils.hub.requests.head", return_value=response_mock) as mock_head:
<add> with mock.patch("requests.request", return_value=response_mock) as mock_head:
<ide> _ = Wav2Vec2FeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2")
<ide> # This check we did call the fake head request
<ide> mock_head.assert_called()
<ide><path>tests/test_modeling_common.py
<ide> def test_cached_files_are_used_when_internet_is_down(self):
<ide> # A mock response for an HTTP head request to emulate server down
<ide> response_mock = mock.Mock()
<ide> response_mock.status_code = 500
<del> response_mock.headers = []
<add> response_mock.headers = {}
<ide> response_mock.raise_for_status.side_effect = HTTPError
<ide>
<ide> # Download this model to make sure it's in the cache.
<ide> _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide>
<ide> # Under the mock environment we get a 500 error when trying to reach the model.
<del> with mock.patch("transformers.utils.hub.requests.head", return_value=response_mock) as mock_head:
<add> with mock.patch("requests.request", return_value=response_mock) as mock_head:
<ide> _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide> # This check we did call the fake head request
<ide> mock_head.assert_called()
<ide><path>tests/test_modeling_tf_common.py
<ide> def test_cached_files_are_used_when_internet_is_down(self):
<ide> # A mock response for an HTTP head request to emulate server down
<ide> response_mock = mock.Mock()
<ide> response_mock.status_code = 500
<del> response_mock.headers = []
<add> response_mock.headers = {}
<ide> response_mock.raise_for_status.side_effect = HTTPError
<ide>
<ide> # Download this model to make sure it's in the cache.
<ide> _ = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide>
<ide> # Under the mock environment we get a 500 error when trying to reach the model.
<del> with mock.patch("transformers.utils.hub.requests.head", return_value=response_mock) as mock_head:
<add> with mock.patch("requests.request", return_value=response_mock) as mock_head:
<ide> _ = TFBertModel.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide> # This check we did call the fake head request
<ide> mock_head.assert_called()
<ide><path>tests/test_tokenization_common.py
<ide> def test_cached_files_are_used_when_internet_is_down(self):
<ide> # A mock response for an HTTP head request to emulate server down
<ide> response_mock = mock.Mock()
<ide> response_mock.status_code = 500
<del> response_mock.headers = []
<add> response_mock.headers = {}
<ide> response_mock.raise_for_status.side_effect = HTTPError
<ide>
<ide> # Download this model to make sure it's in the cache.
<ide> _ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide>
<ide> # Under the mock environment we get a 500 error when trying to reach the model.
<del> with mock.patch("transformers.utils.hub.requests.head", return_value=response_mock) as mock_head:
<add> with mock.patch("requests.request", return_value=response_mock) as mock_head:
<ide> _ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert")
<ide> # This check we did call the fake head request
<ide> mock_head.assert_called() | 13 |
Javascript | Javascript | add ember.handlebars.get in ember-htmlbars/compat | 2ac6f1219e664a95d656f4656b63ac51aca65c97 | <ide><path>packages/ember-handlebars/lib/ext.js
<ide> import {
<ide> readArray,
<ide> readHash
<ide> } from "ember-metal/streams/read";
<add>import handlebarsGet from "ember-htmlbars/compat/handlebars-get";
<ide>
<ide> var slice = [].slice;
<ide>
<del>/**
<del> Lookup both on root and on window. If the path starts with
<del> a keyword, the corresponding object will be looked up in the
<del> template's data hash and used to resolve the path.
<del>
<del> @method get
<del> @for Ember.Handlebars
<del> @param {Object} root The object to look up the property on
<del> @param {String} path The path to be lookedup
<del> @param {Object} options The template's option hash
<del> @deprecated
<del>*/
<del>function handlebarsGet(root, path, options) {
<del> Ember.deprecate('Usage of Ember.Handlebars.get is deprecated, use a Component or Ember.Handlebars.makeBoundHelper instead.');
<del>
<del> return options.data.view.getStream(path).value();
<del>}
<del>
<ide> /**
<ide> handlebarsGetView resolves a view based on strings passed into a template.
<ide> For example:
<ide><path>packages/ember-htmlbars/lib/compat/handlebars-get.js
<add>/**
<add> Lookup both on root and on window. If the path starts with
<add> a keyword, the corresponding object will be looked up in the
<add> template's data hash and used to resolve the path.
<add>
<add> @method get
<add> @for Ember.Handlebars
<add> @param {Object} root The object to look up the property on
<add> @param {String} path The path to be lookedup
<add> @param {Object} options The template's option hash
<add> @deprecated
<add>*/
<add>export default function handlebarsGet(root, path, options) {
<add> Ember.deprecate('Usage of Ember.Handlebars.get is deprecated, use a Component or Ember.Handlebars.makeBoundHelper instead.');
<add>
<add> return options.data.view.getStream(path).value();
<add>}
<add><path>packages/ember-htmlbars/tests/compat/handlebars_get_test.js
<del><path>packages/ember-handlebars/tests/handlebars_get_test.js
<ide> import _MetamorphView from "ember-views/views/metamorph_view";
<ide> import EmberView from "ember-views/views/view";
<ide> import run from "ember-metal/run_loop";
<ide> import EmberHandlebars from "ember-handlebars";
<del>import { handlebarsGet } from "ember-handlebars/ext";
<add>import handlebarsGet from "ember-htmlbars/compat/handlebars-get";
<ide> import Container from "ember-runtime/system/container";
<ide>
<del>var compile = EmberHandlebars.compile;
<add>import EmberHandlebars from "ember-handlebars";
<add>import htmlbarsCompile from "ember-htmlbars/system/compile";
<add>
<add>var compile;
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add> compile = htmlbarsCompile;
<add>} else {
<add> compile = EmberHandlebars.compile;
<add>}
<add>
<ide> var originalLookup = Ember.lookup;
<ide> var TemplateTests, container, lookup, view;
<ide>
<ide> function appendView() {
<ide> run(view, 'appendTo', '#qunit-fixture');
<ide> }
<ide>
<del>QUnit.module("Ember.Handlebars.get", {
<add>QUnit.module("ember-htmlbars: Ember.Handlebars.get", {
<ide> setup: function() {
<ide> Ember.lookup = lookup = {};
<ide> container = new Container(); | 3 |
Text | Text | clarify fs.access works on directories too | d976d66cfc3159e0405ab66dcac3cb14fba2c5da | <ide><path>doc/api/fs.md
<ide> added: v1.0.0
<ide> * `mode` {Integer}
<ide> * `callback` {Function}
<ide>
<del>Tests a user's permissions for the file specified by `path`. `mode` is an
<del>optional integer that specifies the accessibility checks to be performed. The
<del>following constants define the possible values of `mode`. It is possible to
<del>create a mask consisting of the bitwise OR of two or more values.
<add>Tests a user's permissions for the file or directory specified by `path`.
<add>The `mode` argument is an optional integer that specifies the accessibility
<add>checks to be performed. The following constants define the possible values of
<add>`mode`. It is possible to create a mask consisting of the bitwise OR of two or
<add>more values.
<ide>
<del>- `fs.constants.F_OK` - File is visible to the calling process. This is useful
<add>- `fs.constants.F_OK` - `path` is visible to the calling process. This is useful
<ide> for determining if a file exists, but says nothing about `rwx` permissions.
<ide> Default if no `mode` is specified.
<del>- `fs.constants.R_OK` - File can be read by the calling process.
<del>- `fs.constants.W_OK` - File can be written by the calling process.
<del>- `fs.constants.X_OK` - File can be executed by the calling process. This has no
<del>effect on Windows (will behave like `fs.constants.F_OK`).
<add>- `fs.constants.R_OK` - `path` can be read by the calling process.
<add>- `fs.constants.W_OK` - `path` can be written by the calling process.
<add>- `fs.constants.X_OK` - `path` can be executed by the calling process. This has
<add>no effect on Windows (will behave like `fs.constants.F_OK`).
<ide>
<ide> The final argument, `callback`, is a callback function that is invoked with
<ide> a possible error argument. If any of the accessibility checks fail, the error
<ide> added: v0.1.93
<ide> * `path` {String | Buffer}
<ide> * `mode` {Integer}
<ide>
<del>Synchronous version of [`fs.access()`][]. This throws if any accessibility
<add>Synchronous version of [`fs.access()`][]. This throws if any accessibility
<ide> checks fail, and does nothing otherwise.
<ide>
<ide> ## fs.appendFile(file, data[, options], callback)
<ide> the file instead of the entire file. Both `start` and `end` are inclusive and
<ide> start at 0. The `encoding` can be any one of those accepted by [`Buffer`][].
<ide>
<ide> If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
<del>the specified file descriptor. This means that no `'open'` event will be
<del>emitted. Note that `fd` should be blocking; non-blocking `fd`s should be passed
<add>the specified file descriptor. This means that no `'open'` event will be
<add>emitted. Note that `fd` should be blocking; non-blocking `fd`s should be passed
<ide> to [`net.Socket`][].
<ide>
<ide> If `autoClose` is false, then the file descriptor won't be closed, even if
<ide> The following constants are meant for use with `fs.open()`.
<ide> </tr>
<ide> <tr>
<ide> <td><code>O_SYMLINK</code></td>
<del> <td>Flag indicating to open the symbolic link itself rather than the
<add> <td>Flag indicating to open the symbolic link itself rather than the
<ide> resource it is pointing to.</td>
<ide> </tr>
<ide> <tr> | 1 |
Text | Text | add contribution and license in readme | 40093e13dc89c2e424d5c66320ded2fa399ecb1d | <ide><path>README.md
<ide> The [research models](https://github.com/tensorflow/models/tree/master/research)
<ide> The [samples folder](samples) contains code snippets and smaller models that demonstrate features of TensorFlow, including code presented in various blog posts.
<ide>
<ide> The [tutorials folder](tutorials) is a collection of models described in the [TensorFlow tutorials](https://www.tensorflow.org/tutorials/).
<add>
<add>## Contribution guidelines
<add>
<add>If you want to contribute to models, be sure to review the [contribution guidelines](CONTRIBUTING.md).
<add>
<add>## License
<add>
<add>[Apache License 2.0](LICENSE) | 1 |
PHP | PHP | remove duplicated attribute handling code | 6279a0d8ae6b35aa2a725ee7c061dd7cf36cfe9a | <ide><path>Cake/View/Input/SelectBox.php
<ide> */
<ide> class SelectBox {
<ide>
<del>/**
<del> * Minimized attributes
<del> *
<del> * @var array
<del> */
<del> protected $_minimizedAttributes = array(
<del> 'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
<del> 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
<del> 'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
<del> );
<del>
<del>/**
<del> * Format to attribute
<del> *
<del> * @var string
<del> */
<del> protected $_attributeFormat = '%s="%s"';
<del>
<del>/**
<del> * Format to attribute
<del> *
<del> * @var string
<del> */
<del> protected $_minimizedAttributeFormat = '%s="%s"';
<del>
<ide> protected $_templates;
<ide>
<ide> public function __construct($templates) {
<ide> public function render($data) {
<ide> unset($data['disabled']);
<ide> }
<ide>
<del> $attrs = $this->_parseAttributes($data);
<add> $attrs = $this->_templates->formatAttributes($data);
<ide> return $this->_templates->format('select', [
<ide> 'name' => $name,
<ide> 'attrs' => $attrs,
<ide> protected function _isDisabled($key, $disabled) {
<ide> return in_array((string)$key, $disabled, $strict);
<ide> }
<ide>
<del> protected function _parseAttributes($options, $exclude = null) {
<del> $insertBefore = ' ';
<del> $options = (array)$options + array('escape' => true);
<del>
<del> if (!is_array($exclude)) {
<del> $exclude = array();
<del> }
<del>
<del> $exclude = array('escape' => true) + array_flip($exclude);
<del> $escape = $options['escape'];
<del> $attributes = array();
<del>
<del> foreach ($options as $key => $value) {
<del> if (!isset($exclude[$key]) && $value !== false && $value !== null) {
<del> $attributes[] = $this->_formatAttribute($key, $value, $escape);
<del> }
<del> }
<del> $out = implode(' ', $attributes);
<del> return $out ? $insertBefore . $out : '';
<del> }
<del>
<del>/**
<del> * Formats an individual attribute, and returns the string value of the composed attribute.
<del> * Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
<del> *
<del> * TODO MOVE TO StringTemplate class?
<del> *
<del> * @param string $key The name of the attribute to create
<del> * @param string $value The value of the attribute to create.
<del> * @param boolean $escape Define if the value must be escaped
<del> * @return string The composed attribute.
<del> * @deprecated This method will be moved to HtmlHelper in 3.0
<del> */
<del> protected function _formatAttribute($key, $value, $escape = true) {
<del> if (is_array($value)) {
<del> $value = implode(' ', $value);
<del> }
<del> if (is_numeric($key)) {
<del> return sprintf($this->_minimizedAttributeFormat, $value, $value);
<del> }
<del> $truthy = array(1, '1', true, 'true', $key);
<del> $isMinimized = in_array($key, $this->_minimizedAttributes);
<del> if ($isMinimized && in_array($value, $truthy, true)) {
<del> return sprintf($this->_minimizedAttributeFormat, $key, $key);
<del> }
<del> if ($isMinimized) {
<del> return '';
<del> }
<del> return sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value));
<del> }
<del>
<ide> } | 1 |
PHP | PHP | add proper method to cut the string | f405fdfade475709b0f99ca0a89ddd7c76bbc65b | <ide><path>src/Filesystem/File.php
<ide> public function name()
<ide> }
<ide>
<ide> /**
<del> * Returns the file basename. simulate the php basename().
<add> * Returns the file basename. simulate the php basename() for multibyte (mb_basename).
<ide> *
<ide> * @param string $path Path to file
<ide> * @param string|null $ext The name of the extension
<ide> * @return string the file basename.
<ide> */
<ide> protected static function _basename($path, $ext = null)
<ide> {
<add> //check for multibyte string and use basename() if not found
<add> if (mb_strlen($path) === strlen($path)) {
<add> return ($ext===null)? basename($path) : basename($path, $ext);
<add> }
<add>
<ide> $splInfo = new SplFileInfo($path);
<ide> $name = ltrim($splInfo->getFilename(), DS);
<del> if ($ext === null || rtrim($name, $ext) === '') {
<add>
<add> if ($ext === null || $ext === '') {
<ide> return $name;
<ide> }
<add> $ext = preg_quote($ext);
<add> $new = preg_replace("/({$ext})$/u", "", $name);
<add>
<add> // basename of '/etc/.d' is '.d' not ''
<add> return ($new === '')? $name : $new;
<ide>
<del> return rtrim($name, $ext);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Filesystem/FileTest.php
<ide> public function baseNameValueProvider()
<ide> ['/نام.txt', '.txt'],
<ide> ['/نام فارسی.txt', '.txt'],
<ide> //
<add> ['abcde.ab', '.abe'],
<ide> ['/etc/sudoers.d', null],
<ide> ['/etc/.d', '.d'],
<ide> ['/etc/sudoers.d', '.d'], | 2 |
Ruby | Ruby | fix bug in levenshtein distance calculation | 6f0a69c5899ebdc892e2aa23e68e2604fa70fb73 | <ide><path>guides/rails_guides/levenshtein.rb
<ide> def self.distance str1, str2
<ide> t = str2
<ide> n = s.length
<ide> m = t.length
<del> max = n/2
<ide>
<ide> return m if (0 == n)
<ide> return n if (0 == m)
<del> return n if (n - m).abs > max
<ide>
<ide> d = (0..m).to_a
<ide> x = nil | 1 |
Javascript | Javascript | remove event listener on dispose | c70c29885a96c3b2b77fe9bd28bb30db763f0d7e | <ide><path>src/js/control-bar/progress-control/seek-bar.js
<ide> class SeekBar extends Slider {
<ide>
<ide> this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
<ide> if (this.player_.liveTracker) {
<del> this.on(this.player_.liveTracker, 'liveedgechange', this.update);
<add> this.off(this.player_.liveTracker, 'liveedgechange', this.update);
<ide> }
<ide>
<ide> this.off(this.player_, ['playing'], this.enableIntervalHandler_); | 1 |
Java | Java | register annotated handlers in rsocketrequester | dd15ff79d7223bb33c8e69558d69deb546aadfe1 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/DefaultRSocketRequesterBuilder.java
<ide>
<ide> import java.net.URI;
<ide> import java.util.ArrayList;
<add>import java.util.Arrays;
<ide> import java.util.List;
<ide> import java.util.function.Consumer;
<ide> import java.util.stream.Stream;
<ide>
<ide> import io.rsocket.RSocketFactory;
<add>import io.rsocket.frame.decoder.PayloadDecoder;
<ide> import io.rsocket.transport.ClientTransport;
<ide> import io.rsocket.transport.netty.client.TcpClientTransport;
<ide> import io.rsocket.transport.netty.client.WebsocketClientTransport;
<ide> import reactor.core.publisher.Mono;
<ide>
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.MimeType;
<ide>
<ide> final class DefaultRSocketRequesterBuilder implements RSocketRequester.Builder {
<ide>
<ide> private List<Consumer<RSocketStrategies.Builder>> strategiesConfigurers = new ArrayList<>();
<ide>
<add> private List<Object> handlers = new ArrayList<>();
<ide>
<ide> @Override
<ide> public RSocketRequester.Builder dataMimeType(@Nullable MimeType mimeType) {
<ide> public RSocketRequester.Builder rsocketStrategies(@Nullable RSocketStrategies st
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public RSocketRequester.Builder annotatedHandlers(Object... handlers) {
<add> this.handlers.addAll(Arrays.asList(handlers));
<add> return this;
<add> }
<add>
<ide> @Override
<ide> public RSocketRequester.Builder rsocketStrategies(Consumer<RSocketStrategies.Builder> configurer) {
<ide> this.strategiesConfigurers.add(configurer);
<ide> public Mono<RSocketRequester> connect(ClientTransport transport) {
<ide> }
<ide>
<ide> private Mono<RSocketRequester> doConnect(ClientTransport transport) {
<del>
<ide> RSocketStrategies rsocketStrategies = getRSocketStrategies();
<ide> Assert.isTrue(!rsocketStrategies.encoders().isEmpty(), "No encoders");
<ide> Assert.isTrue(!rsocketStrategies.decoders().isEmpty(), "No decoders");
<ide> private Mono<RSocketRequester> doConnect(ClientTransport transport) {
<ide> MimeType dataMimeType = getDataMimeType(rsocketStrategies);
<ide> rsocketFactory.dataMimeType(dataMimeType.toString());
<ide> rsocketFactory.metadataMimeType(this.metadataMimeType.toString());
<add>
<add> if (!this.handlers.isEmpty()) {
<add> RSocketMessageHandler messageHandler = new RSocketMessageHandler();
<add> messageHandler.setHandlers(this.handlers);
<add> messageHandler.setRSocketStrategies(rsocketStrategies);
<add> messageHandler.afterPropertiesSet();
<add> rsocketFactory.acceptor(messageHandler.clientAcceptor());
<add> }
<add> rsocketFactory.frameDecoder(PayloadDecoder.ZERO_COPY);
<ide> this.factoryConfigurers.forEach(consumer -> consumer.accept(rsocketFactory));
<ide>
<ide> return rsocketFactory.transport(transport)
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/rsocket/RSocketRequester.java
<ide> import org.springframework.core.ParameterizedTypeReference;
<ide> import org.springframework.core.ReactiveAdapterRegistry;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler;
<ide> import org.springframework.util.MimeType;
<ide>
<ide> /**
<ide> interface Builder {
<ide> */
<ide> RSocketRequester.Builder rsocketStrategies(Consumer<RSocketStrategies.Builder> configurer);
<ide>
<add> /**
<add> * Add handlers for processing requests sent by the server.
<add> * <p>This is a shortcut for registering client handlers (i.e. annotated controllers)
<add> * to a {@link RSocketMessageHandler} and configuring it as an acceptor.
<add> * You can take full control by manually registering an acceptor on the
<add> * {@link RSocketFactory.ClientRSocketFactory} using {@link #rsocketFactory(Consumer)}
<add> * instead.
<add> * @param handlers the client handlers to configure on the requester
<add> */
<add> RSocketRequester.Builder annotatedHandlers(Object... handlers);
<add>
<ide> /**
<ide> * Connect to the RSocket server over TCP.
<ide> * @param host the server host
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/rsocket/RSocketServerToClientIntegrationTests.java
<ide> package org.springframework.messaging.rsocket;
<ide>
<ide> import java.time.Duration;
<del>import java.util.Collections;
<ide>
<ide> import io.netty.buffer.PooledByteBufAllocator;
<del>import io.rsocket.Closeable;
<del>import io.rsocket.RSocket;
<ide> import io.rsocket.RSocketFactory;
<ide> import io.rsocket.frame.decoder.PayloadDecoder;
<del>import io.rsocket.transport.netty.client.TcpClientTransport;
<add>import io.rsocket.transport.netty.server.CloseableChannel;
<ide> import io.rsocket.transport.netty.server.TcpServerTransport;
<del>import io.rsocket.util.DefaultPayload;
<ide> import org.junit.AfterClass;
<ide> import org.junit.BeforeClass;
<ide> import org.junit.Test;
<ide> * Client-side handling of requests initiated from the server side.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Brian Clozel
<ide> */
<ide> public class RSocketServerToClientIntegrationTests {
<ide>
<ide> private static AnnotationConfigApplicationContext context;
<ide>
<del> private static Closeable server;
<add> private static CloseableChannel server;
<ide>
<ide>
<ide> @BeforeClass
<ide> public static void setupOnce() {
<ide>
<ide> server = RSocketFactory.receive()
<ide> .frameDecoder(PayloadDecoder.ZERO_COPY)
<del> .acceptor(context.getBean("serverMessageHandler", RSocketMessageHandler.class).serverAcceptor())
<del> .transport(TcpServerTransport.create("localhost", 7000))
<add> .acceptor(context.getBean(RSocketMessageHandler.class).serverAcceptor())
<add> .transport(TcpServerTransport.create("localhost", 0))
<ide> .start()
<ide> .block();
<ide> }
<ide> private static void connectAndVerify(String destination) {
<ide> ServerController serverController = context.getBean(ServerController.class);
<ide> serverController.reset();
<ide>
<del> RSocket rsocket = null;
<add> RSocketRequester requester = null;
<ide> try {
<del> rsocket = RSocketFactory.connect()
<del> .metadataMimeType("message/x.rsocket.routing.v0")
<del> .dataMimeType("text/plain")
<del> .setupPayload(DefaultPayload.create("", destination))
<del> .frameDecoder(PayloadDecoder.ZERO_COPY)
<del> .acceptor(context.getBean("clientMessageHandler", RSocketMessageHandler.class).clientAcceptor())
<del> .transport(TcpClientTransport.create("localhost", 7000))
<del> .start()
<add> requester = RSocketRequester.builder()
<add> .annotatedHandlers(new ClientHandler())
<add> .rsocketStrategies(context.getBean(RSocketStrategies.class))
<add> .connectTcp("localhost", server.address().getPort())
<ide> .block();
<ide>
<add> requester.route(destination).data("").send().block();
<add>
<ide> serverController.await(Duration.ofSeconds(5));
<ide> }
<ide> finally {
<del> if (rsocket != null) {
<del> rsocket.dispose();
<add> if (requester != null) {
<add> requester.rsocket().dispose();
<ide> }
<ide> }
<ide> }
<ide> Flux<String> echoChannel(Flux<String> payloads) {
<ide> @Configuration
<ide> static class RSocketConfig {
<ide>
<del> @Bean
<del> public ClientHandler clientHandler() {
<del> return new ClientHandler();
<del> }
<del>
<ide> @Bean
<ide> public ServerController serverController() {
<ide> return new ServerController();
<ide> }
<ide>
<del> @Bean
<del> public RSocketMessageHandler clientMessageHandler() {
<del> RSocketMessageHandler handler = new RSocketMessageHandler();
<del> handler.setHandlers(Collections.singletonList(clientHandler()));
<del> handler.setRSocketStrategies(rsocketStrategies());
<del> return handler;
<del> }
<del>
<ide> @Bean
<ide> public RSocketMessageHandler serverMessageHandler() {
<ide> RSocketMessageHandler handler = new RSocketMessageHandler(); | 3 |
Go | Go | add unit test to ensure log line order | 5ba6cab0a9b9e51029fd48858ba6722103356b1a | <ide><path>daemon/logger/awslogs/cloudwatchlogs_test.go
<ide> import (
<ide> "errors"
<ide> "fmt"
<ide> "net/http"
<add> "reflect"
<ide> "runtime"
<ide> "strings"
<ide> "testing"
<ide> func TestCollectBatchMaxTotalBytes(t *testing.T) {
<ide> t.Errorf("Expected message to be %s but was %s", "B", message[len(message)-1:])
<ide> }
<ide> }
<add>
<add>func TestCollectBatchWithDuplicateTimestamps(t *testing.T) {
<add> mockClient := newMockClient()
<add> stream := &logStream{
<add> client: mockClient,
<add> logGroupName: groupName,
<add> logStreamName: streamName,
<add> sequenceToken: aws.String(sequenceToken),
<add> messages: make(chan *logger.Message),
<add> }
<add> mockClient.putLogEventsResult <- &putLogEventsResult{
<add> successResult: &cloudwatchlogs.PutLogEventsOutput{
<add> NextSequenceToken: aws.String(nextSequenceToken),
<add> },
<add> }
<add> ticks := make(chan time.Time)
<add> newTicker = func(_ time.Duration) *time.Ticker {
<add> return &time.Ticker{
<add> C: ticks,
<add> }
<add> }
<add>
<add> go stream.collectBatch()
<add>
<add> times := maximumLogEventsPerPut
<add> expectedEvents := []*cloudwatchlogs.InputLogEvent{}
<add> timestamp := time.Now()
<add> for i := 0; i < times; i++ {
<add> line := fmt.Sprintf("%d", i)
<add> if i%2 == 0 {
<add> timestamp.Add(1 * time.Nanosecond)
<add> }
<add> stream.Log(&logger.Message{
<add> Line: []byte(line),
<add> Timestamp: timestamp,
<add> })
<add> expectedEvents = append(expectedEvents, &cloudwatchlogs.InputLogEvent{
<add> Message: aws.String(line),
<add> Timestamp: aws.Int64(timestamp.UnixNano() / int64(time.Millisecond)),
<add> })
<add> }
<add>
<add> ticks <- time.Time{}
<add> stream.Close()
<add>
<add> argument := <-mockClient.putLogEventsArgument
<add> if argument == nil {
<add> t.Fatal("Expected non-nil PutLogEventsInput")
<add> }
<add> if len(argument.LogEvents) != times {
<add> t.Errorf("Expected LogEvents to contain %d elements, but contains %d", times, len(argument.LogEvents))
<add> }
<add> for i := 0; i < times; i++ {
<add> if !reflect.DeepEqual(*argument.LogEvents[i], *expectedEvents[i]) {
<add> t.Errorf("Expected event to be %v but was %v", *expectedEvents[i], *argument.LogEvents[i])
<add> }
<add> }
<add>} | 1 |
PHP | PHP | add missing tests for mysql | 7bc185df5b990ecfae7e4faafd575dab6e05d7b8 | <ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/Driver/MysqlTest.php
<ide> public function setUp() {
<ide> $config = Configure::read('Datasource.test');
<ide> $this->skipIf(strpos($config['datasource'], 'Mysql') === false, 'Not using Mysql for test config');
<ide> }
<add>
<ide> /**
<ide> * Test connecting to Mysql with default configuration
<ide> *
<ide> public static function columnProvider() {
<ide> 'TINYINT(2)',
<ide> ['integer', 2]
<ide> ],
<add> [
<add> 'INTEGER(11)',
<add> ['integer', 11]
<add> ],
<ide> [
<ide> 'BIGINT',
<ide> ['biginteger', null] | 1 |
Javascript | Javascript | add day marker character for japanese | 6dd81c9f993de7352fce5ad303d441aff2f422cb | <ide><path>locale/ja.js
<ide> lastWeek : '[前週]dddd LT',
<ide> sameElse : 'L'
<ide> },
<add> ordinalParse : /\d{1,2}日/,
<add> ordinal : function (number, period) {
<add> switch (period) {
<add> case 'd':
<add> case 'D':
<add> case 'DDD':
<add> return number + '日';
<add> default:
<add> return number;
<add> }
<add> },
<ide> relativeTime : {
<ide> future : '%s後',
<ide> past : '%s前', | 1 |
Python | Python | add groups in ci output for parallell tasks | 62bf0f8a611688d551413476d14b649d095b35de | <ide><path>dev/breeze/src/airflow_breeze/commands/ci_commands.py
<ide> def fix_ownership(github_repository: str, use_sudo: bool, verbose: bool, dry_run
<ide> shell_params.airflow_image_name_with_tag,
<ide> "/opt/airflow/scripts/in_container/run_fix_ownership.sh",
<ide> ]
<del> run_command(
<del> cmd, verbose=verbose, dry_run=dry_run, text=True, env=env, check=False, enabled_output_group=True
<del> )
<add> run_command(cmd, verbose=verbose, dry_run=dry_run, text=True, env=env, check=False)
<ide> # Always succeed
<ide> sys.exit(0)
<ide>
<ide><path>dev/breeze/src/airflow_breeze/commands/ci_image_commands.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>import multiprocessing as mp
<ide> import os
<add>import subprocess
<ide> import sys
<ide> from pathlib import Path
<ide> from typing import List, Optional, Tuple, Union
<ide>
<ide> from airflow_breeze.params.build_ci_params import BuildCiParams
<ide> from airflow_breeze.params.shell_params import ShellParams
<add>from airflow_breeze.utils.ci_group import ci_group
<ide> from airflow_breeze.utils.click_utils import BreezeGroup
<ide> from airflow_breeze.utils.common_options import (
<ide> option_additional_dev_apt_command,
<ide> option_wait_for_image,
<ide> )
<ide> from airflow_breeze.utils.confirm import STANDARD_TIMEOUT, Answer, user_confirm
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.docker_command_utils import (
<ide> build_cache,
<ide> make_sure_builder_configured,
<ide> from airflow_breeze.utils.image import run_pull_image, run_pull_in_parallel, tag_image_as_latest
<ide> from airflow_breeze.utils.mark_image_as_refreshed import mark_image_as_refreshed
<ide> from airflow_breeze.utils.md5_build_check import md5sum_check_if_build_is_needed
<del>from airflow_breeze.utils.parallel import check_async_run_results
<add>from airflow_breeze.utils.parallel import (
<add> check_async_run_results,
<add> progress_method_docker_buildx,
<add> run_with_pool,
<add>)
<ide> from airflow_breeze.utils.path_utils import AIRFLOW_SOURCES_ROOT, BUILD_CACHE_DIR
<ide> from airflow_breeze.utils.python_versions import get_python_version_list
<ide> from airflow_breeze.utils.registry import login_to_github_docker_registry
<ide> def ci_image():
<ide> pass
<ide>
<ide>
<del>def check_if_image_building_is_needed(ci_image_params: BuildCiParams, dry_run: bool, verbose: bool) -> bool:
<add>def check_if_image_building_is_needed(
<add> ci_image_params: BuildCiParams, output: Optional[Output], dry_run: bool, verbose: bool
<add>) -> bool:
<ide> """Starts building attempt. Returns false if we should not continue"""
<ide> if not ci_image_params.force_build and not ci_image_params.upgrade_to_newer_dependencies:
<ide> if not should_we_run_the_build(build_ci_params=ci_image_params):
<ide> return False
<ide> if ci_image_params.prepare_buildx_cache or ci_image_params.push:
<del> login_to_github_docker_registry(image_params=ci_image_params, dry_run=dry_run, verbose=verbose)
<add> login_to_github_docker_registry(
<add> image_params=ci_image_params, dry_run=dry_run, output=output, verbose=verbose
<add> )
<ide> return True
<ide>
<ide>
<ide> def run_build_in_parallel(
<ide> verbose: bool,
<ide> ) -> None:
<ide> warm_up_docker_builder(image_params_list[0], verbose=verbose, dry_run=dry_run)
<del> get_console().print(
<del> f"\n[info]Building with parallelism = {parallelism} for the images: {python_version_list}:"
<del> )
<del> pool = mp.Pool(parallelism)
<del> results = [
<del> pool.apply_async(
<del> run_build_ci_image,
<del> args=(verbose, dry_run, image_param, True),
<del> )
<del> for image_param in image_params_list
<del> ]
<del> check_async_run_results(results)
<del> pool.close()
<add> with ci_group(f"Building for {python_version_list}"):
<add> all_params = [f"CI {image_params.python}" for image_params in image_params_list]
<add> with run_with_pool(
<add> parallelism=parallelism, all_params=all_params, progress_method=progress_method_docker_buildx
<add> ) as (pool, outputs):
<add> results = [
<add> pool.apply_async(
<add> run_build_ci_image,
<add> kwds={
<add> "ci_image_params": image_params,
<add> "verbose": verbose,
<add> "dry_run": dry_run,
<add> "output": outputs[index],
<add> },
<add> )
<add> for index, image_params in enumerate(image_params_list)
<add> ]
<add> check_async_run_results(results, outputs)
<ide>
<ide>
<ide> def start_building(params: BuildCiParams, dry_run: bool, verbose: bool):
<del> check_if_image_building_is_needed(params, dry_run=dry_run, verbose=verbose)
<del> make_sure_builder_configured(parallel=True, params=params, dry_run=dry_run, verbose=verbose)
<add> check_if_image_building_is_needed(params, output=None, dry_run=dry_run, verbose=verbose)
<add> make_sure_builder_configured(params=params, dry_run=dry_run, verbose=verbose)
<ide>
<ide>
<ide> @ci_image.command(name='build')
<ide> def build(
<ide>
<ide> def run_build(ci_image_params: BuildCiParams) -> None:
<ide> return_code, info = run_build_ci_image(
<del> verbose=verbose, dry_run=dry_run, ci_image_params=ci_image_params, parallel=False
<add> ci_image_params=ci_image_params,
<add> output=None,
<add> verbose=verbose,
<add> dry_run=dry_run,
<ide> )
<ide> if return_code != 0:
<ide> get_console().print(f"[error]Error when building image! {info}")
<ide> def run_build(ci_image_params: BuildCiParams) -> None:
<ide> params.python = python
<ide> params.answer = answer
<ide> params_list.append(params)
<del> start_building(params_list[0], dry_run, verbose)
<add> start_building(params=params_list[0], dry_run=dry_run, verbose=verbose)
<ide> run_build_in_parallel(
<ide> image_params_list=params_list,
<ide> python_version_list=python_version_list,
<ide> def run_build(ci_image_params: BuildCiParams) -> None:
<ide> )
<ide> else:
<ide> params = BuildCiParams(**parameters_passed)
<del> start_building(params, dry_run, verbose)
<add> start_building(params=params, dry_run=dry_run, verbose=verbose)
<ide> run_build(ci_image_params=params)
<ide>
<ide>
<ide> def pull(
<ide> )
<ide> return_code, info = run_pull_image(
<ide> image_params=image_params,
<add> output=None,
<ide> dry_run=dry_run,
<ide> verbose=verbose,
<ide> wait_for_image=wait_for_image,
<ide> def verify(
<ide> get_console().print(f"[info]Verifying CI image: {image_name}[/]")
<ide> return_code, info = verify_an_image(
<ide> image_name=image_name,
<add> output=None,
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> image_type='CI',
<ide> def should_we_run_the_build(build_ci_params: BuildCiParams) -> bool:
<ide> * Builds Image/Skips/Quits depending on the answer
<ide>
<ide> :param build_ci_params: parameters for the build
<del> :param verbose: should we get verbose information
<ide> """
<ide> # We import those locally so that click autocomplete works
<ide> from inputimeout import TimeoutOccurred
<ide> def should_we_run_the_build(build_ci_params: BuildCiParams) -> bool:
<ide>
<ide>
<ide> def run_build_ci_image(
<del> verbose: bool, dry_run: bool, ci_image_params: BuildCiParams, parallel: bool
<add> ci_image_params: BuildCiParams,
<add> verbose: bool,
<add> dry_run: bool,
<add> output: Optional[Output],
<ide> ) -> Tuple[int, str]:
<ide> """
<ide> Builds CI image:
<ide> def run_build_ci_image(
<ide> :param verbose: print commands when running
<ide> :param dry_run: do not execute "write" commands - just print what would happen
<ide> :param ci_image_params: CI image parameters
<del> :param parallel: whether the pull is run as part of parallel execution
<add> :param output: output redirection
<ide> """
<ide> if (
<ide> ci_image_params.is_multi_platform()
<ide> and not ci_image_params.push
<ide> and not ci_image_params.prepare_buildx_cache
<ide> ):
<del> get_console().print(
<add> get_console(output=output).print(
<ide> "\n[red]You cannot use multi-platform build without using --push flag or "
<ide> "preparing buildx cache![/]\n"
<ide> )
<ide> return 1, "Error: building multi-platform image without --push."
<ide> if verbose or dry_run:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"\n[info]Building CI image of airflow from {AIRFLOW_SOURCES_ROOT} "
<ide> f"python version: {ci_image_params.python}[/]\n"
<ide> )
<ide> if ci_image_params.prepare_buildx_cache:
<ide> build_command_result = build_cache(
<del> image_params=ci_image_params, dry_run=dry_run, verbose=verbose, parallel=parallel
<add> image_params=ci_image_params, output=output, dry_run=dry_run, verbose=verbose
<ide> )
<ide> else:
<ide> if ci_image_params.empty_image:
<ide> env = os.environ.copy()
<ide> env['DOCKER_BUILDKIT'] = "1"
<del> get_console().print(f"\n[info]Building empty CI Image for Python {ci_image_params.python}\n")
<add> get_console(output=output).print(
<add> f"\n[info]Building empty CI Image for Python {ci_image_params.python}\n"
<add> )
<ide> build_command_result = run_command(
<ide> prepare_docker_build_from_input(image_params=ci_image_params),
<ide> input="FROM scratch\n",
<ide> def run_build_ci_image(
<ide> cwd=AIRFLOW_SOURCES_ROOT,
<ide> text=True,
<ide> env=env,
<del> enabled_output_group=not parallel,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> )
<ide> else:
<del> get_console().print(f"\n[info]Building CI Image for Python {ci_image_params.python}\n")
<add> get_console(output=output).print(
<add> f"\n[info]Building CI Image for Python {ci_image_params.python}\n"
<add> )
<ide> build_command_result = run_command(
<ide> prepare_docker_build_command(
<ide> image_params=ci_image_params,
<ide> def run_build_ci_image(
<ide> cwd=AIRFLOW_SOURCES_ROOT,
<ide> text=True,
<ide> check=False,
<del> enabled_output_group=not parallel,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> )
<ide> if build_command_result.returncode == 0:
<ide> if ci_image_params.tag_as_latest:
<del> build_command_result = tag_image_as_latest(ci_image_params, dry_run, verbose)
<add> build_command_result = tag_image_as_latest(
<add> image_params=ci_image_params,
<add> output=output,
<add> dry_run=dry_run,
<add> verbose=verbose,
<add> )
<ide> if ci_image_params.preparing_latest_image():
<ide> if dry_run:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> "[info]Not updating build hash because we are in `dry_run` mode.[/]"
<ide> )
<ide> else:
<ide> def rebuild_or_pull_ci_image_if_needed(
<ide> if command_params.image_tag is not None and command_params.image_tag != "latest":
<ide> return_code, message = run_pull_image(
<ide> image_params=ci_image_params,
<add> output=None,
<ide> dry_run=dry_run,
<ide> verbose=verbose,
<del> parallel=False,
<ide> wait_for_image=True,
<ide> tag_as_latest=False,
<ide> )
<ide> def rebuild_or_pull_ci_image_if_needed(
<ide> 'Forcing build.[/]'
<ide> )
<ide> ci_image_params.force_build = True
<del> if check_if_image_building_is_needed(ci_image_params=ci_image_params, dry_run=dry_run, verbose=verbose):
<del> run_build_ci_image(verbose, dry_run=dry_run, ci_image_params=ci_image_params, parallel=False)
<add> if check_if_image_building_is_needed(
<add> ci_image_params=ci_image_params, output=None, dry_run=dry_run, verbose=verbose
<add> ):
<add> run_build_ci_image(ci_image_params=ci_image_params, output=None, verbose=verbose, dry_run=dry_run)
<ide><path>dev/breeze/src/airflow_breeze/commands/main_command.py
<ide> def cleanup(verbose: bool, dry_run: bool, github_repository: str, all: bool, ans
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> check=False,
<del> enabled_output_group=True,
<ide> )
<ide> elif given_answer == Answer.QUIT:
<ide> sys.exit(0)
<ide><path>dev/breeze/src/airflow_breeze/commands/production_image_commands.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide> import contextlib
<del>import multiprocessing as mp
<ide> import os
<add>import subprocess
<ide> import sys
<ide> from typing import List, Optional, Tuple
<ide>
<ide> import click
<ide>
<ide> from airflow_breeze.global_constants import ALLOWED_INSTALLATION_METHODS, DEFAULT_EXTRAS
<ide> from airflow_breeze.params.build_prod_params import BuildProdParams
<add>from airflow_breeze.utils.ci_group import ci_group
<ide> from airflow_breeze.utils.click_utils import BreezeGroup
<ide> from airflow_breeze.utils.common_options import (
<ide> option_additional_dev_apt_command,
<ide> option_verify,
<ide> option_wait_for_image,
<ide> )
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.custom_param_types import BetterChoice
<ide> from airflow_breeze.utils.docker_command_utils import (
<ide> build_cache,
<ide> warm_up_docker_builder,
<ide> )
<ide> from airflow_breeze.utils.image import run_pull_image, run_pull_in_parallel, tag_image_as_latest
<del>from airflow_breeze.utils.parallel import check_async_run_results
<add>from airflow_breeze.utils.parallel import (
<add> check_async_run_results,
<add> progress_method_docker_buildx,
<add> run_with_pool,
<add>)
<ide> from airflow_breeze.utils.path_utils import AIRFLOW_SOURCES_ROOT, DOCKER_CONTEXT_DIR
<ide> from airflow_breeze.utils.python_versions import get_python_version_list
<ide> from airflow_breeze.utils.registry import login_to_github_docker_registry
<ide> from airflow_breeze.utils.run_tests import verify_an_image
<ide> from airflow_breeze.utils.run_utils import filter_out_none, fix_group_permissions, run_command
<ide>
<ide>
<del>def start_building(parallel: bool, prod_image_params: BuildProdParams, dry_run: bool, verbose: bool):
<del> make_sure_builder_configured(
<del> parallel=parallel, params=prod_image_params, dry_run=dry_run, verbose=verbose
<del> )
<add>def start_building(prod_image_params: BuildProdParams, dry_run: bool, verbose: bool):
<add> make_sure_builder_configured(params=prod_image_params, dry_run=dry_run, verbose=verbose)
<ide> if prod_image_params.cleanup_context:
<ide> clean_docker_context_files(verbose=verbose, dry_run=dry_run)
<ide> check_docker_context_files(prod_image_params.install_packages_from_context)
<ide> if prod_image_params.prepare_buildx_cache or prod_image_params.push:
<del> login_to_github_docker_registry(image_params=prod_image_params, dry_run=dry_run, verbose=verbose)
<add> login_to_github_docker_registry(
<add> image_params=prod_image_params, output=None, dry_run=dry_run, verbose=verbose
<add> )
<ide>
<ide>
<ide> def run_build_in_parallel(
<ide> def run_build_in_parallel(
<ide> verbose: bool,
<ide> ) -> None:
<ide> warm_up_docker_builder(image_params_list[0], verbose=verbose, dry_run=dry_run)
<del> get_console().print(
<del> f"\n[info]Building with parallelism = {parallelism} for the images: {python_version_list}:"
<del> )
<del> pool = mp.Pool(parallelism)
<del> results = [
<del> pool.apply_async(
<del> run_build_production_image,
<del> args=(
<del> verbose,
<del> dry_run,
<del> image_param,
<del> True,
<del> ),
<del> )
<del> for image_param in image_params_list
<del> ]
<del> check_async_run_results(results)
<del> pool.close()
<add> with ci_group(f"Building for {python_version_list}"):
<add> all_params = [f"PROD {image_params.python}" for image_params in image_params_list]
<add> with run_with_pool(
<add> parallelism=parallelism, all_params=all_params, progress_method=progress_method_docker_buildx
<add> ) as (pool, outputs):
<add> results = [
<add> pool.apply_async(
<add> run_build_production_image,
<add> kwds={
<add> "prod_image_params": image_params,
<add> "dry_run": dry_run,
<add> "verbose": verbose,
<add> "output": outputs[index],
<add> },
<add> )
<add> for index, image_params in enumerate(image_params_list)
<add> ]
<add> check_async_run_results(results, outputs)
<ide>
<ide>
<ide> @click.group(
<ide> def build(
<ide>
<ide> def run_build(prod_image_params: BuildProdParams) -> None:
<ide> return_code, info = run_build_production_image(
<del> verbose=verbose, dry_run=dry_run, prod_image_params=prod_image_params, parallel=False
<add> verbose=verbose, dry_run=dry_run, output=None, prod_image_params=prod_image_params
<ide> )
<ide> if return_code != 0:
<ide> get_console().print(f"[error]Error when building image! {info}")
<ide> def run_build(prod_image_params: BuildProdParams) -> None:
<ide> params.python = python
<ide> params.answer = answer
<ide> params_list.append(params)
<del> start_building(parallel=True, prod_image_params=params_list[0], dry_run=dry_run, verbose=verbose)
<add> start_building(prod_image_params=params_list[0], dry_run=dry_run, verbose=verbose)
<ide> run_build_in_parallel(
<ide> image_params_list=params_list,
<ide> python_version_list=python_version_list,
<ide> def run_build(prod_image_params: BuildProdParams) -> None:
<ide> )
<ide> else:
<ide> params = BuildProdParams(**parameters_passed)
<del> start_building(parallel=False, prod_image_params=params, dry_run=dry_run, verbose=verbose)
<add> start_building(prod_image_params=params, dry_run=dry_run, verbose=verbose)
<ide> run_build(prod_image_params=params)
<ide>
<ide>
<ide> def pull_prod_image(
<ide> )
<ide> return_code, info = run_pull_image(
<ide> image_params=image_params,
<add> output=None,
<ide> dry_run=dry_run,
<ide> verbose=verbose,
<ide> wait_for_image=wait_for_image,
<ide> tag_as_latest=tag_as_latest,
<ide> poll_time=10.0,
<del> parallel=False,
<ide> )
<ide> if return_code != 0:
<ide> get_console().print(f"[error]There was an error when pulling PROD image: {info}[/]")
<ide> def verify(
<ide> get_console().print(f"[info]Verifying PROD image: {image_name}[/]")
<ide> return_code, info = verify_an_image(
<ide> image_name=image_name,
<add> output=None,
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> image_type='PROD',
<ide> def check_docker_context_files(install_packages_from_context: bool):
<ide>
<ide>
<ide> def run_build_production_image(
<del> verbose: bool, dry_run: bool, prod_image_params: BuildProdParams, parallel: bool
<add> verbose: bool,
<add> dry_run: bool,
<add> prod_image_params: BuildProdParams,
<add> output: Optional[Output],
<ide> ) -> Tuple[int, str]:
<ide> """
<ide> Builds PROD image:
<ide> def run_build_production_image(
<ide> :param verbose: print commands when running
<ide> :param dry_run: do not execute "write" commands - just print what would happen
<ide> :param prod_image_params: PROD image parameters
<del> :param parallel: run build in parallel
<add> :param output: output redirection
<ide> """
<ide> if (
<ide> prod_image_params.is_multi_platform()
<ide> and not prod_image_params.push
<ide> and not prod_image_params.prepare_buildx_cache
<ide> ):
<del> get_console().print(
<add> get_console(output=output).print(
<ide> "\n[red]You cannot use multi-platform build without using --push flag"
<ide> " or preparing buildx cache![/]\n"
<ide> )
<ide> return 1, "Error: building multi-platform image without --push."
<del> get_console().print(f"\n[info]Building PROD Image for Python {prod_image_params.python}\n")
<add> get_console(output=output).print(f"\n[info]Building PROD Image for Python {prod_image_params.python}\n")
<ide> if prod_image_params.prepare_buildx_cache:
<ide> build_command_result = build_cache(
<del> image_params=prod_image_params, dry_run=dry_run, verbose=verbose, parallel=parallel
<add> image_params=prod_image_params, output=output, dry_run=dry_run, verbose=verbose
<ide> )
<ide> else:
<ide> if prod_image_params.empty_image:
<ide> env = os.environ.copy()
<ide> env['DOCKER_BUILDKIT'] = "1"
<del> get_console().print(f"\n[info]Building empty PROD Image for Python {prod_image_params.python}\n")
<add> get_console(output=output).print(
<add> f"\n[info]Building empty PROD Image for Python {prod_image_params.python}\n"
<add> )
<ide> build_command_result = run_command(
<ide> prepare_docker_build_from_input(image_params=prod_image_params),
<ide> input="FROM scratch\n",
<ide> def run_build_production_image(
<ide> check=False,
<ide> text=True,
<ide> env=env,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> )
<ide> else:
<ide> build_command_result = run_command(
<ide> def run_build_production_image(
<ide> cwd=AIRFLOW_SOURCES_ROOT,
<ide> check=False,
<ide> text=True,
<del> enabled_output_group=not parallel,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> )
<ide> if build_command_result.returncode == 0:
<ide> if prod_image_params.tag_as_latest:
<del> build_command_result = tag_image_as_latest(prod_image_params, dry_run, verbose)
<add> build_command_result = tag_image_as_latest(
<add> image_params=prod_image_params,
<add> output=output,
<add> dry_run=dry_run,
<add> verbose=verbose,
<add> )
<ide> return build_command_result.returncode, f"Image build: {prod_image_params.python}"
<ide><path>dev/breeze/src/airflow_breeze/commands/release_management_commands.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>import multiprocessing as mp
<ide> import shlex
<add>import subprocess
<ide> import sys
<ide> import time
<ide> from copy import deepcopy
<ide> MULTI_PLATFORM,
<ide> )
<ide> from airflow_breeze.params.shell_params import ShellParams
<add>from airflow_breeze.utils.ci_group import ci_group
<ide> from airflow_breeze.utils.click_utils import BreezeGroup
<ide> from airflow_breeze.utils.common_options import (
<ide> argument_packages,
<ide> option_version_suffix_for_pypi,
<ide> )
<ide> from airflow_breeze.utils.confirm import Answer, user_confirm
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.custom_param_types import BetterChoice
<ide> from airflow_breeze.utils.docker_command_utils import (
<ide> get_env_variables_for_docker_commands,
<ide> get_extra_docker_flags,
<ide> perform_environment_checks,
<ide> )
<del>from airflow_breeze.utils.parallel import check_async_run_results
<add>from airflow_breeze.utils.parallel import check_async_run_results, run_with_pool
<ide> from airflow_breeze.utils.python_versions import get_python_version_list
<ide> from airflow_breeze.utils.run_utils import RunCommandResult, run_command, run_compile_www_assets
<ide>
<ide> def run_with_debug(
<ide> dry_run: bool,
<ide> debug: bool,
<ide> enable_input: bool = False,
<del> enabled_output_group: bool = False,
<add> **kwargs,
<ide> ) -> RunCommandResult:
<ide> env_variables = get_env_variables_for_docker_commands(params)
<ide> extra_docker_flags = get_extra_docker_flags(mount_sources=params.mount_sources)
<ide> def run_with_debug(
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> env=env_variables,
<del> enabled_output_group=enabled_output_group,
<add> **kwargs,
<ide> )
<ide> else:
<ide> base_command.extend(command)
<ide> return run_command(
<ide> base_command,
<del> enabled_output_group=enabled_output_group,
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> env=env_variables,
<ide> check=False,
<add> **kwargs,
<ide> )
<ide>
<ide>
<ide> def prepare_airflow_packages(
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> debug=debug,
<del> enabled_output_group=True,
<ide> )
<ide> sys.exit(result_command.returncode)
<ide>
<ide> def prepare_provider_packages(
<ide>
<ide>
<ide> def run_generate_constraints(
<del> shell_params: ShellParams, dry_run: bool, verbose: bool, debug: bool, parallel: bool = False
<add> shell_params: ShellParams,
<add> dry_run: bool,
<add> verbose: bool,
<add> debug: bool,
<add> output: Optional[Output],
<ide> ) -> Tuple[int, str]:
<ide> cmd_to_run = [
<ide> "/opt/airflow/scripts/in_container/run_generate_constraints.sh",
<ide> def run_generate_constraints(
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> debug=debug,
<del> enabled_output_group=not parallel,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> )
<ide> return (
<ide> generate_constraints_result.returncode,
<del> f"Generate constraints Python {shell_params.python}:{shell_params.airflow_constraints_mode}",
<add> f"Constraints {shell_params.airflow_constraints_mode}:{shell_params.python}",
<ide> )
<ide>
<ide>
<ide> def run_generate_constraints_in_parallel(
<ide> verbose: bool,
<ide> ):
<ide> """Run generate constraints in parallel"""
<del> get_console().print(
<del> f"\n[info]Generating constraints with parallelism = {parallelism} "
<del> f"for the constraints: {python_version_list}[/]"
<del> )
<del> pool = mp.Pool(parallelism)
<del> results = [
<del> pool.apply_async(
<del> run_generate_constraints,
<del> args=(shell_param, dry_run, verbose, False, True),
<del> )
<del> for shell_param in shell_params_list
<del> ]
<del> check_async_run_results(results)
<del> pool.close()
<add> with ci_group(f"Constraints for {python_version_list}"):
<add> all_params = [
<add> f"Constraints {shell_params.airflow_constraints_mode}:{shell_params.python}"
<add> for shell_params in shell_params_list
<add> ]
<add> with run_with_pool(parallelism=parallelism, all_params=all_params) as (pool, outputs):
<add> results = [
<add> pool.apply_async(
<add> run_generate_constraints,
<add> kwds={
<add> "shell_params": shell_params,
<add> "dry_run": dry_run,
<add> "verbose": verbose,
<add> "debug": False,
<add> "output": outputs[index],
<add> },
<add> )
<add> for index, shell_params in enumerate(shell_params_list)
<add> ]
<add> check_async_run_results(results, outputs)
<ide>
<ide>
<ide> @release_management.command(
<ide> def generate_constraints(
<ide> )
<ide> return_code, info = run_generate_constraints(
<ide> shell_params=shell_params,
<add> output=None,
<ide> dry_run=dry_run,
<ide> verbose=verbose,
<ide> debug=debug,
<del> parallel=False,
<ide> )
<ide> if return_code != 0:
<ide> get_console().print(f"[error]There was an error when generating constraints: {info}[/]")
<ide> def verify_provider_packages(
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> debug=debug,
<del> enabled_output_group=True,
<ide> )
<ide> sys.exit(result_command.returncode)
<ide>
<ide><path>dev/breeze/src/airflow_breeze/utils/ci_group.py
<ide> from contextlib import contextmanager
<ide>
<ide> from airflow_breeze.utils.console import MessageType, get_console
<add>from airflow_breeze.utils.path_utils import skip_group_putput
<add>
<add># only allow top-level group
<add>_in_ci_group = False
<ide>
<ide>
<ide> @contextmanager
<del>def ci_group(title: str, enabled: bool = True, message_type: MessageType = MessageType.INFO):
<add>def ci_group(title: str, message_type: MessageType = MessageType.INFO):
<ide> """
<ide> If used in GitHub Action, creates an expandable group in the GitHub Action log.
<ide> Otherwise, display simple text groups.
<ide>
<ide> For more information, see:
<ide> https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#grouping-log-lines
<ide> """
<del> if not enabled:
<del> yield
<del> return
<del> if os.environ.get('GITHUB_ACTIONS', 'false') != "true":
<del> get_console().print(f"[{message_type.value}]{title}[/]")
<add> global _in_ci_group
<add> if _in_ci_group or skip_group_putput() or os.environ.get('GITHUB_ACTIONS', 'false') != "true":
<ide> yield
<ide> return
<del> get_console().print(f"::group::<CLICK_TO_EXPAND>: [{message_type.value}]{title}[/]")
<add> _in_ci_group = True
<add> get_console().print(f"::group::[{message_type.value}]{title}[/]")
<ide> yield
<ide> get_console().print("::endgroup::")
<add> _in_ci_group = False
<ide><path>dev/breeze/src/airflow_breeze/utils/console.py
<ide> import os
<ide> from enum import Enum
<ide> from functools import lru_cache
<add>from typing import NamedTuple, Optional, TextIO
<ide>
<ide> from rich.console import Console
<ide> from rich.theme import Theme
<ide> def message_type_from_return_code(return_code: int) -> MessageType:
<ide> return MessageType.ERROR
<ide>
<ide>
<add>class Output(NamedTuple):
<add> title: str
<add> file_name: str
<add>
<add> @property
<add> def file(self) -> TextIO:
<add> return open(self.file_name, "a+t")
<add>
<add>
<ide> @lru_cache(maxsize=None)
<del>def get_console() -> Console:
<add>def get_console(output: Optional[Output] = None) -> Console:
<ide> return Console(
<ide> force_terminal=True,
<ide> color_system="standard",
<ide> width=180 if not recording_width else int(recording_width),
<add> file=output.file if output else None,
<ide> theme=get_theme(),
<ide> record=True if recording_file else False,
<ide> )
<ide>
<ide>
<ide> @lru_cache(maxsize=None)
<del>def get_stderr_console() -> Console:
<add>def get_stderr_console(output: Optional[Output] = None) -> Console:
<ide> return Console(
<ide> force_terminal=True,
<ide> color_system="standard",
<ide> stderr=True,
<add> file=output.file if output else None,
<ide> width=180 if not recording_width else int(recording_width),
<ide> theme=get_theme(),
<ide> record=True if recording_file else False,
<ide><path>dev/breeze/src/airflow_breeze/utils/docker_command_utils.py
<ide> """Various utils to prepare docker and docker compose commands."""
<ide> import os
<ide> import re
<add>import subprocess
<ide> import sys
<ide> from copy import deepcopy
<ide> from random import randint
<ide> from subprocess import DEVNULL, STDOUT, CalledProcessError, CompletedProcess
<del>from typing import Dict, List, Union
<add>from typing import Dict, List, Optional, Union
<ide>
<ide> from airflow_breeze.params.build_ci_params import BuildCiParams
<ide> from airflow_breeze.params.build_prod_params import BuildProdParams
<ide> SSH_PORT,
<ide> WEBSERVER_HOST_PORT,
<ide> )
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.run_utils import (
<ide> RunCommandResult,
<ide> check_if_buildx_plugin_installed,
<ide> def prepare_docker_build_from_input(
<ide>
<ide>
<ide> def build_cache(
<del> image_params: CommonBuildParams, dry_run: bool, verbose: bool, parallel: bool
<add> image_params: CommonBuildParams, output: Optional[Output], dry_run: bool, verbose: bool
<ide> ) -> RunCommandResult:
<ide> build_command_result: Union[CompletedProcess, CalledProcessError] = CompletedProcess(
<ide> args=[], returncode=0
<ide> def build_cache(
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> cwd=AIRFLOW_SOURCES_ROOT,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> check=False,
<ide> text=True,
<del> enabled_output_group=not parallel,
<ide> )
<ide> if build_command_result.returncode != 0:
<ide> break
<ide> return build_command_result
<ide>
<ide>
<del>def make_sure_builder_configured(parallel: bool, params: CommonBuildParams, dry_run: bool, verbose: bool):
<add>def make_sure_builder_configured(params: CommonBuildParams, dry_run: bool, verbose: bool):
<ide> if params.builder != 'default':
<ide> cmd = ['docker', 'buildx', 'inspect', params.builder]
<del> buildx_command_result = run_command(
<del> cmd, verbose=verbose, dry_run=dry_run, text=True, check=False, enabled_output_group=not parallel
<del> )
<add> buildx_command_result = run_command(cmd, verbose=verbose, dry_run=dry_run, text=True, check=False)
<ide> if buildx_command_result and buildx_command_result.returncode != 0:
<ide> next_cmd = ['docker', 'buildx', 'create', '--name', params.builder]
<del> run_command(next_cmd, verbose=verbose, text=True, check=False, enabled_output_group=not parallel)
<add> run_command(next_cmd, verbose=verbose, text=True, check=False)
<ide>
<ide>
<ide> def set_value_to_default_if_not_set(env: Dict[str, str], name: str, default: str):
<ide> def warm_up_docker_builder(image_params: CommonBuildParams, verbose: bool, dry_r
<ide> cwd=AIRFLOW_SOURCES_ROOT,
<ide> text=True,
<ide> check=False,
<del> enabled_output_group=True,
<ide> )
<ide> if warm_up_command_result.returncode != 0:
<ide> get_console().print(
<ide><path>dev/breeze/src/airflow_breeze/utils/image.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>import multiprocessing as mp
<ide> import subprocess
<ide> import time
<del>from typing import List, Tuple, Union
<add>from typing import Callable, List, Optional, Tuple, Union
<ide>
<ide> from airflow_breeze.global_constants import (
<ide> ALLOWED_PYTHON_MAJOR_MINOR_VERSIONS,
<ide> from airflow_breeze.params.build_prod_params import BuildProdParams
<ide> from airflow_breeze.params.common_build_params import CommonBuildParams
<ide> from airflow_breeze.params.shell_params import ShellParams
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.ci_group import ci_group
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.mark_image_as_refreshed import mark_image_as_refreshed
<del>from airflow_breeze.utils.parallel import check_async_run_results
<add>from airflow_breeze.utils.parallel import check_async_run_results, progress_method_docker_pull, run_with_pool
<ide> from airflow_breeze.utils.registry import login_to_github_docker_registry
<ide> from airflow_breeze.utils.run_tests import verify_an_image
<ide> from airflow_breeze.utils.run_utils import RunCommandResult, run_command
<ide> def run_pull_in_parallel(
<ide> extra_pytest_args: Tuple,
<ide> ):
<ide> """Run image pull in parallel"""
<del> get_console().print(
<del> f"\n[info]Pulling with parallelism = {parallelism} for the images: {python_version_list}:"
<del> )
<del> pool = mp.Pool(parallelism)
<del> poll_time = 10.0
<del> if not verify:
<del> results = [
<del> pool.apply_async(
<del> run_pull_image,
<del> args=(image_param, dry_run, verbose, wait_for_image, tag_as_latest, poll_time, True),
<del> )
<del> for image_param in image_params_list
<del> ]
<del> else:
<del> results = [
<del> pool.apply_async(
<del> run_pull_and_verify_image,
<del> args=(
<del> image_param,
<del> dry_run,
<del> verbose,
<del> wait_for_image,
<del> tag_as_latest,
<del> poll_time,
<del> extra_pytest_args,
<del> ),
<del> )
<del> for image_param in image_params_list
<del> ]
<del> check_async_run_results(results)
<del> pool.close()
<add> all_params = [f"Image {image_params.python}" for image_params in image_params_list]
<add> with ci_group(f"Pull{'/verify' if verify else ''} for {python_version_list}"):
<add> with run_with_pool(
<add> parallelism=parallelism, all_params=all_params, progress_method=progress_method_docker_pull
<add> ) as (pool, outputs):
<add>
<add> def get_right_method() -> Callable[..., Tuple[int, str]]:
<add> if verify:
<add> return run_pull_and_verify_image
<add> else:
<add> return run_pull_image
<add>
<add> def get_kwds(index: int, image_param: Union[BuildCiParams, BuildProdParams]):
<add> d = {
<add> "image_params": image_param,
<add> "wait_for_image": wait_for_image,
<add> "tag_as_latest": tag_as_latest,
<add> "poll_time": 10.0,
<add> "output": outputs[index],
<add> "dry_run": dry_run,
<add> "verbose": verbose,
<add> }
<add> if verify:
<add> d['extra_pytest_args'] = extra_pytest_args
<add> return d
<add>
<add> results = [
<add> pool.apply_async(get_right_method(), kwds=get_kwds(index, image_param))
<add> for index, image_param in enumerate(image_params_list)
<add> ]
<add> check_async_run_results(results, outputs)
<ide>
<ide>
<ide> def run_pull_image(
<ide> image_params: CommonBuildParams,
<del> dry_run: bool,
<del> verbose: bool,
<ide> wait_for_image: bool,
<ide> tag_as_latest: bool,
<add> dry_run: bool,
<add> verbose: bool,
<add> output: Optional[Output],
<ide> poll_time: float = 10.0,
<del> parallel: bool = False,
<ide> ) -> Tuple[int, str]:
<ide> """
<ide> Pull image specified.
<ide> :param image_params: Image parameters.
<ide> :param dry_run: whether it's dry run
<ide> :param verbose: whether it's verbose
<add> :param output: output to write to
<ide> :param wait_for_image: whether we should wait for the image to be available
<ide> :param tag_as_latest: tag the image as latest
<ide> :param poll_time: what's the polling time between checks if images are there (default 10 s)
<del> :param parallel: whether the pull is run as part of parallel execution
<ide> :return: Tuple of return code and description of the image pulled
<ide> """
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"\n[info]Pulling {image_params.image_type} image of airflow python version: "
<ide> f"{image_params.python} image: {image_params.airflow_image_name_with_tag} "
<ide> f"with wait for image: {wait_for_image}[/]\n"
<ide> )
<ide> while True:
<del> login_to_github_docker_registry(image_params=image_params, dry_run=dry_run, verbose=verbose)
<add> login_to_github_docker_registry(
<add> image_params=image_params, output=output, dry_run=dry_run, verbose=verbose
<add> )
<ide> command_to_run = ["docker", "pull", image_params.airflow_image_name_with_tag]
<ide> command_result = run_command(
<ide> command_to_run,
<ide> verbose=verbose,
<ide> dry_run=dry_run,
<ide> check=False,
<del> enabled_output_group=not parallel,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> )
<ide> if command_result.returncode == 0:
<ide> command_result = run_command(
<ide> def run_pull_image(
<ide> if command_result.returncode == 0:
<ide> image_size = int(command_result.stdout.strip())
<ide> if image_size == 0:
<del> get_console().print("\n[error]The image size was 0 - image creation failed.[/]\n")
<add> get_console(output=output).print(
<add> "\n[error]The image size was 0 - image creation failed.[/]\n"
<add> )
<ide> return 1, f"Image Python {image_params.python}"
<ide> else:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> "\n[error]There was an error pulling the size of the image. Failing.[/]\n"
<ide> )
<ide> return (
<ide> command_result.returncode,
<ide> f"Image Python {image_params.python}",
<ide> )
<ide> if tag_as_latest:
<del> command_result = tag_image_as_latest(image_params, dry_run, verbose)
<add> command_result = tag_image_as_latest(
<add> image_params=image_params,
<add> output=output,
<add> dry_run=dry_run,
<add> verbose=verbose,
<add> )
<ide> if command_result.returncode == 0 and isinstance(image_params, BuildCiParams):
<ide> mark_image_as_refreshed(image_params)
<ide> return command_result.returncode, f"Image Python {image_params.python}"
<ide> if wait_for_image:
<ide> if verbose or dry_run:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"\n[info]Waiting for {poll_time} seconds for "
<ide> f"{image_params.airflow_image_name_with_tag}.[/]\n"
<ide> )
<ide> time.sleep(poll_time)
<ide> continue
<ide> else:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"\n[error]There was an error pulling the image {image_params.python}. Failing.[/]\n"
<ide> )
<ide> return command_result.returncode, f"Image Python {image_params.python}"
<ide>
<ide>
<del>def tag_image_as_latest(image_params: CommonBuildParams, dry_run: bool, verbose: bool) -> RunCommandResult:
<add>def tag_image_as_latest(
<add> image_params: CommonBuildParams, output: Optional[Output], dry_run: bool, verbose: bool
<add>) -> RunCommandResult:
<ide> if image_params.airflow_image_name_with_tag == image_params.airflow_image_name:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"[info]Skip tagging {image_params.airflow_image_name} as latest as it is already 'latest'[/]"
<ide> )
<ide> return subprocess.CompletedProcess(returncode=0, args=[])
<ide> def tag_image_as_latest(image_params: CommonBuildParams, dry_run: bool, verbose:
<ide>
<ide> def run_pull_and_verify_image(
<ide> image_params: CommonBuildParams,
<del> dry_run: bool,
<del> verbose: bool,
<ide> wait_for_image: bool,
<ide> tag_as_latest: bool,
<add> dry_run: bool,
<add> verbose: bool,
<ide> poll_time: float,
<ide> extra_pytest_args: Tuple,
<add> output: Optional[Output],
<ide> ) -> Tuple[int, str]:
<ide> return_code, info = run_pull_image(
<del> image_params, dry_run, verbose, wait_for_image, tag_as_latest, poll_time
<add> image_params=image_params,
<add> wait_for_image=wait_for_image,
<add> tag_as_latest=tag_as_latest,
<add> output=output,
<add> dry_run=dry_run,
<add> verbose=verbose,
<add> poll_time=poll_time,
<ide> )
<ide> if return_code != 0:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"\n[error]Not running verification for {image_params.python} as pulling failed.[/]\n"
<ide> )
<ide> return verify_an_image(
<ide> image_name=image_params.airflow_image_name_with_tag,
<ide> image_type=image_params.image_type,
<add> output=output,
<ide> dry_run=dry_run,
<ide> verbose=verbose,
<ide> slim_image=False,
<ide><path>dev/breeze/src/airflow_breeze/utils/parallel.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>
<add>import datetime
<add>import os
<add>import re
<add>import signal
<ide> import sys
<ide> import time
<del>from multiprocessing.pool import ApplyResult
<del>from typing import List
<add>from contextlib import contextmanager
<add>from multiprocessing.pool import ApplyResult, Pool
<add>from pathlib import Path
<add>from tempfile import NamedTemporaryFile
<add>from threading import Event, Thread
<add>from typing import Callable, Dict, Generator, List, Optional, Tuple
<add>
<add>from airflow_breeze.utils.ci_group import ci_group
<add>from airflow_breeze.utils.console import MessageType, Output, get_console
<add>
<add>
<add>def init_worker():
<add> signal.signal(signal.SIGINT, signal.SIG_IGN)
<add>
<add>
<add>def create_pool(parallelism: int) -> Pool:
<add> # we need to ignore SIGINT handling in workers in order to handle Ctrl-C nicely (with Pool's terminate)
<add> return Pool(parallelism, initializer=init_worker())
<add>
<add>
<add>def get_temp_file_name() -> str:
<add> file = NamedTemporaryFile(mode="w+t", delete=False)
<add> name = file.name
<add> file.close()
<add> return name
<add>
<add>
<add>def get_output_files(titles: List[str]) -> List[Output]:
<add> outputs = [Output(title=titles[i], file_name=get_temp_file_name()) for i in range(len(titles))]
<add> for out in outputs:
<add> get_console().print(f"[info]Capturing output of {out.title}:[/] {out.file_name}")
<add> return outputs
<add>
<add>
<add>def nice_timedelta(delta: datetime.timedelta):
<add> d = {'d': delta.days}
<add> d['h'], rem = divmod(delta.seconds, 3600)
<add> d['m'], d['s'] = divmod(rem, 60)
<add> return "{d} days {h:02}:{m:02}:{s:02}".format(**d) if d['d'] else "{h:02}:{m:02}:{s:02}".format(**d)
<add>
<add>
<add>ANSI_COLOUR_MATCHER = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
<add>
<add>
<add>def remove_ansi_colours(line):
<add> return ANSI_COLOUR_MATCHER.sub('', line)
<add>
<add>
<add>def get_last_lines_of_file(file_name: str, num_lines: int = 2) -> Tuple[List[str], List[str]]:
<add> """
<add> Get last lines of a file efficiently, without reading the whole file (with some limitations).
<add> Assumptions ara that line length not bigger than ~180 chars.
<add>
<add> :param file_name: name of the file
<add> :param num_lines: number of lines to return (max)
<add> :return: Tuple - last lines of the file in two variants: original and with removed ansi colours
<add> """
<add> # account for EOL
<add> max_read = (180 + 2) * num_lines
<add> seek_size = min(os.stat(file_name).st_size, max_read)
<add> with open(file_name, 'rb') as temp_f:
<add> temp_f.seek(-seek_size, os.SEEK_END)
<add> tail = temp_f.read().decode(errors="ignore")
<add> last_lines = tail.splitlines()[-num_lines:]
<add> last_lines_no_colors = [remove_ansi_colours(line) for line in last_lines]
<add> return last_lines, last_lines_no_colors
<add>
<add>
<add>DOCKER_BUILDX_PROGRESS_MATCHER = re.compile(r'\s*#(\d*) ')
<add>last_docker_build_lines: Dict[Output, str] = {}
<add>
<add>
<add>def progress_method_docker_buildx(output: Output) -> Optional[str]:
<add> last_lines, last_lines_no_colors = get_last_lines_of_file(output.file_name, num_lines=5)
<add> best_progress: int = 0
<add> best_line: Optional[str] = None
<add> for index, line in enumerate(last_lines_no_colors):
<add> match = DOCKER_BUILDX_PROGRESS_MATCHER.match(line)
<add> if match:
<add> docker_progress = int(match.group(1))
<add> if docker_progress > best_progress:
<add> best_progress = docker_progress
<add> best_line = last_lines[index]
<add> if best_line is None:
<add> best_line = last_docker_build_lines.get(output)
<add> else:
<add> last_docker_build_lines[output] = best_line
<add> return f"Progress: {output.title:<20} {best_line}"
<add>
<add>
<add>DOCKER_PULL_PROGRESS_MATCHER = re.compile(r'^[0-9a-f]+: .*|.*\[[ 0-9]+%].*')
<add>last_docker_pull_lines: Dict[Output, str] = {}
<add>
<add>
<add>def progress_method_docker_pull(output: Output) -> Optional[str]:
<add> last_lines, last_lines_no_colors = get_last_lines_of_file(output.file_name, num_lines=15)
<add> best_line: Optional[str] = None
<add> for index, line in enumerate(last_lines_no_colors):
<add> match = DOCKER_PULL_PROGRESS_MATCHER.match(line)
<add> if match:
<add> best_line = last_lines[index]
<add> if best_line is None:
<add> best_line = last_docker_pull_lines.get(output)
<add> else:
<add> last_docker_pull_lines[output] = best_line
<add> return f"Progress: {output.title:<20} {best_line}"
<add>
<add>
<add>class ParallelMonitor(Thread):
<add> def __init__(
<add> self,
<add> outputs: List[Output],
<add> time_in_seconds: int = 10,
<add> progress_method: Optional[Callable[[Output], Optional[str]]] = None,
<add> ):
<add> super().__init__()
<add> self.outputs = outputs
<add> self.time_in_seconds = time_in_seconds
<add> self.exit_event = Event()
<add> self.progress_method = progress_method
<add> self.start_time = datetime.datetime.utcnow()
<add> self.last_custom_progress: Optional[str] = None
<add>
<add> def print_single_progress(self, output: Output):
<add> if self.progress_method:
<add> progress = self.progress_method(output)
<add> if not progress and self.last_custom_progress:
<add> progress = self.last_custom_progress
<add> if progress:
<add> print(self.progress_method(output))
<add> return
<add> size = os.path.getsize(output.file_name) if Path(output.file_name).exists() else 0
<add> print(f"Progress: {output.title:<70} {size:>93} bytes")
<add>
<add> def print_summary(self):
<add> time_passed = datetime.datetime.utcnow() - self.start_time
<add> get_console().rule()
<add> for output in self.outputs:
<add> self.print_single_progress(output)
<add> get_console().rule(title=f"Time passed: {nice_timedelta(time_passed)}")
<ide>
<del>from airflow_breeze.utils.console import get_console
<add> def cancel(self):
<add> get_console().print("[info]Finishing progress monitoring.")
<add> self.exit_event.set()
<add>
<add> def run(self):
<add> try:
<add> while not self.exit_event.is_set():
<add> self.print_summary()
<add> self.exit_event.wait(self.time_in_seconds)
<add> except Exception:
<add> get_console().print_exception(show_locals=True)
<ide>
<ide>
<ide> def print_async_summary(completed_list: List[ApplyResult]) -> None:
<ide> def get_completed_result_list(results: List[ApplyResult]) -> List[ApplyResult]:
<ide> return list(filter(lambda result: result.ready(), results))
<ide>
<ide>
<del>def check_async_run_results(results: List[ApplyResult], poll_time: float = 0.2):
<add>def check_async_run_results(results: List[ApplyResult], outputs: List[Output], poll_time: float = 0.2):
<ide> """
<ide> Check if all async results were success. Exits with error if not.
<ide> :param results: results of parallel runs (expected in the form of Tuple: (return_code, info)
<add> :param outputs: outputs where results are written to
<ide> :param poll_time: what's the poll time between checks
<ide> """
<ide> completed_number = 0
<ide> def check_async_run_results(results: List[ApplyResult], poll_time: float = 0.2):
<ide> )
<ide> print_async_summary(completed_list)
<ide> errors = False
<del> for result in results:
<add> for i, result in enumerate(results):
<ide> if result.get()[0] != 0:
<ide> errors = True
<add> message_type = MessageType.ERROR
<add> else:
<add> message_type = MessageType.SUCCESS
<add> with ci_group(title=f"{outputs[i].title}", message_type=message_type):
<add> os.write(1, Path(outputs[i].file_name).read_bytes())
<add>
<ide> if errors:
<ide> get_console().print("\n[error]There were errors when running some tasks. Quitting.[/]\n")
<ide> sys.exit(1)
<ide> else:
<ide> get_console().print("\n[success]All images are OK.[/]\n")
<add>
<add>
<add>@contextmanager
<add>def run_with_pool(
<add> parallelism: int,
<add> all_params: List[str],
<add> time_in_seconds: int = 10,
<add> progress_method: Optional[Callable[[Output], Optional[str]]] = None,
<add>) -> Generator[Tuple[Pool, List[Output]], None, None]:
<add> get_console().print(f"Parallelism: {parallelism}")
<add> pool = create_pool(parallelism)
<add> outputs = get_output_files(all_params)
<add> m = ParallelMonitor(outputs=outputs, time_in_seconds=time_in_seconds, progress_method=progress_method)
<add> m.start()
<add> yield pool, outputs
<add> pool.close()
<add> pool.join()
<add> m.cancel()
<ide><path>dev/breeze/src/airflow_breeze/utils/path_utils.py
<ide> def skip_upgrade_check():
<ide> return in_self_upgrade() or in_autocomplete() or in_help() or hasattr(sys, '_called_from_test')
<ide>
<ide>
<add>def skip_group_putput():
<add> return in_autocomplete() or in_help()
<add>
<add>
<ide> def get_package_setup_metadata_hash() -> str:
<ide> """
<ide> Retrieves hash of setup files from the source of installation of Breeze.
<ide> def create_directories_and_files() -> None:
<ide> (AIRFLOW_SOURCES_ROOT / ".bash_aliases").touch()
<ide> (AIRFLOW_SOURCES_ROOT / ".bash_history").touch()
<ide> (AIRFLOW_SOURCES_ROOT / ".inputrc").touch()
<del> create_static_check_volumes()
<ide><path>dev/breeze/src/airflow_breeze/utils/registry.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>
<ide> import os
<del>from typing import Tuple
<add>import subprocess
<add>from typing import Optional, Tuple
<ide>
<ide> from airflow_breeze.params.common_build_params import CommonBuildParams
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.run_utils import run_command
<ide>
<ide>
<ide> def login_to_github_docker_registry(
<del> image_params: CommonBuildParams, dry_run: bool, verbose: bool
<add> image_params: CommonBuildParams, output: Optional[Output], dry_run: bool, verbose: bool
<ide> ) -> Tuple[int, str]:
<ide> """
<ide> In case of CI environment, we need to login to GitHub Registry.
<ide>
<ide> :param image_params: parameters to use for Building prod image
<add> :param output: Output to redirect to
<ide> :param dry_run: whether we are in dry_run mode
<ide> :param verbose: whether to show commands.
<ide> """
<ide> if os.environ.get("CI"):
<ide> if len(image_params.github_token) == 0:
<del> get_console().print("\n[info]Skip logging in to GitHub Registry. No Token available!")
<add> get_console(output=output).print(
<add> "\n[info]Skip logging in to GitHub Registry. No Token available!"
<add> )
<ide> elif len(image_params.github_token) > 0:
<ide> run_command(
<del> ['docker', 'logout', 'ghcr.io'], dry_run=dry_run, verbose=verbose, text=False, check=False
<add> ['docker', 'logout', 'ghcr.io'],
<add> dry_run=dry_run,
<add> verbose=verbose,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<add> text=False,
<add> check=False,
<ide> )
<ide> command_result = run_command(
<ide> [
<ide> def login_to_github_docker_registry(
<ide> 'ghcr.io',
<ide> ],
<ide> verbose=verbose,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> text=True,
<ide> input=image_params.github_token,
<ide> check=False,
<ide><path>dev/breeze/src/airflow_breeze/utils/run_tests.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<del>
<ide> import os
<add>import subprocess
<ide> import sys
<ide> from subprocess import DEVNULL
<del>from typing import Tuple
<add>from typing import Optional, Tuple
<ide>
<del>from airflow_breeze.utils.console import get_console
<add>from airflow_breeze.utils.console import Output, get_console
<ide> from airflow_breeze.utils.path_utils import AIRFLOW_SOURCES_ROOT
<ide> from airflow_breeze.utils.run_utils import run_command
<ide>
<ide>
<ide> def verify_an_image(
<del> image_name: str, image_type: str, dry_run: bool, verbose: bool, slim_image: bool, extra_pytest_args: Tuple
<add> image_name: str,
<add> image_type: str,
<add> output: Optional[Output],
<add> dry_run: bool,
<add> verbose: bool,
<add> slim_image: bool,
<add> extra_pytest_args: Tuple,
<ide> ) -> Tuple[int, str]:
<ide> command_result = run_command(
<del> ["docker", "inspect", image_name], dry_run=dry_run, verbose=verbose, check=False, stdout=DEVNULL
<add> ["docker", "inspect", image_name],
<add> dry_run=dry_run,
<add> verbose=verbose,
<add> check=False,
<add> stdout=DEVNULL,
<add> stderr=output.file if output else None,
<ide> )
<ide> if command_result.returncode != 0:
<del> get_console().print(
<add> get_console(output=output).print(
<ide> f"[error]Error when inspecting {image_type} image: {command_result.returncode}[/]"
<ide> )
<ide> return command_result.returncode, f"Testing {image_type} python {image_name}"
<ide> def verify_an_image(
<ide> dry_run=dry_run,
<ide> verbose=verbose,
<ide> env=env,
<add> stdout=output.file if output else None,
<add> stderr=subprocess.STDOUT,
<ide> check=False,
<ide> )
<ide> return command_result.returncode, f"Testing {image_type} python {image_name}"
<ide><path>dev/breeze/src/airflow_breeze/utils/run_utils.py
<ide> def run_command(
<ide> env: Optional[Mapping[str, str]] = None,
<ide> cwd: Optional[Path] = None,
<ide> input: Optional[str] = None,
<del> enabled_output_group: bool = False,
<ide> **kwargs,
<ide> ) -> RunCommandResult:
<ide> """
<ide> def run_command(
<ide> :param env: mapping of environment variables to set for the run command
<ide> :param cwd: working directory to set for the command
<ide> :param input: input string to pass to stdin of the process
<del> :param enabled_output_group: if set to true, in CI the logs will be placed in separate, foldable group.
<ide> :param kwargs: kwargs passed to POpen
<ide> """
<ide> if not title:
<ide> def run_command(
<ide> if verbose or dry_run:
<ide> command_to_print = ' '.join(shlex.quote(c) for c in cmd)
<ide> env_to_print = get_environments_to_print(env)
<del> with ci_group(title=f"Running {title}"):
<add> with ci_group(title=f"Click to expand command run: {title}"):
<ide> get_console().print(f"\n[info]Working directory {workdir}\n")
<ide> if input:
<ide> get_console().print("[info]Input:")
<ide> def run_command(
<ide> cmd_env.setdefault("HOME", str(Path.home()))
<ide> if env:
<ide> cmd_env.update(env)
<del> with ci_group(title=f"Output of {title}", enabled=enabled_output_group):
<add> if 'capture_output' in kwargs and kwargs['capture_output']:
<add> return subprocess.run(cmd, input=input, check=check, env=cmd_env, cwd=workdir, **kwargs)
<add> with ci_group(f"Click to expand the output of {title}"):
<ide> return subprocess.run(cmd, input=input, check=check, env=cmd_env, cwd=workdir, **kwargs)
<ide> except subprocess.CalledProcessError as ex:
<ide> if not no_output_dump_on_exception: | 14 |
Javascript | Javascript | correct the spec name | cb44450e923ec6040c4b7151d0106fd2dbd52f41 | <ide><path>spec/git-repository-async-spec.js
<ide> describe('GitRepositoryAsync', () => {
<ide> repo = GitRepositoryAsync.open(workingDirectory)
<ide> })
<ide>
<del> it('returns 0, 0 for a branch with no upstream', async () => {
<add> it('returns 1, 0 for a branch which is ahead by 1', async () => {
<ide> await repo.refreshStatus()
<ide>
<ide> const {ahead, behind} = await repo.getCachedUpstreamAheadBehindCount('You-Dont-Need-jQuery') | 1 |
Text | Text | update props description | f965e6072d5346dbe8092df56de29df1e68b08b2 | <ide><path>guide/portuguese/react/props/index.md
<ide> localeTitle: Adereços
<ide> ---
<ide> ### Quais são os adereços?
<ide>
<del>Adereços (abreviação de propriedades) são a data passada no componente. Eles são imutáveis (somente leitura).
<ide>\ No newline at end of file
<add>Adereços (abreviação de propriedades) são os dados passados para o componente. Eles são imutáveis (somente leitura). | 1 |
Javascript | Javascript | add a currentview property to statemanager | 7429f461cb8b5ee82b12efefe5e15f936b25ff97 | <ide><path>packages/ember-states/lib/state_manager.js
<ide> Ember.StateManager = Ember.State.extend({
<ide>
<ide> currentState: null,
<ide>
<add> /**
<add> If the current state is a view state or the descendent of a view state,
<add> this property will be the view associated with it. If there is no
<add> view state active in this state manager, this value will be null.
<add> */
<add> currentView: SC.computed(function() {
<add> var currentState = get(this, 'currentState'),
<add> view;
<add>
<add> while (currentState) {
<add> if (get(currentState, 'isViewState')) {
<add> view = get(currentState, 'view');
<add> if (view) { return view; }
<add> }
<add>
<add> currentState = get(currentState, 'parentState')
<add> }
<add>
<add> return null;
<add> }).property('currentState').cacheable(),
<add>
<ide> send: function(event, context) {
<ide> this.sendRecursively(event, get(this, 'currentState'), context);
<ide> },
<ide><path>packages/ember-states/tests/state_manager_test.js
<ide> test("it automatically transitions to a default state specified using the initia
<ide> ok(get(stateManager, 'currentState').isStart, "automatically transitions to beginning state");
<ide> });
<ide>
<add>test("it reports the view associated with the current view state, if any", function() {
<add> var view = SC.View.create();
<add>
<add> stateManager = SC.StateManager.create({
<add> foo: SC.ViewState.create({
<add> view: view,
<add> bar: SC.State.create()
<add> })
<add> });
<add>
<add> stateManager.goToState('foo.bar');
<add>
<add> equal(get(stateManager, 'currentView'), view, "returns nearest parent view state's view");
<add>});
<add>
<ide> module("Ember.StateManager - Transitions on Complex State Managers");
<ide>
<ide> /** | 2 |
PHP | PHP | fix failing test case for `validate` option | 6337937a62670838af94852f44c8867e3630243a | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testSaveDeepAssociationOptions() {
<ide> ->with($entity->author->supervisor, ['name' => 'Marc'])
<ide> ->will($this->returnValue($entity->author->supervisor));
<ide>
<del> $options = new \ArrayObject([
<del> 'validate' => false,
<del> 'atomic' => false,
<del> 'associated' => []
<del> ]);
<del> $supervisors->expects($this->once())
<del> ->method('validate')
<del> ->with($entity->author->supervisor, $options)
<del> ->will($this->returnValue(true));
<add> $supervisors->expects($this->never())->method('validate');
<ide>
<ide> $tags->expects($this->never())->method('_insert');
<ide> | 1 |
PHP | PHP | fix unrelated test | 3db385623bf1bc56ca49b8a3bf01aff5c44c5abb | <ide><path>tests/Integration/View/templates/components/hello-span.blade.php
<ide> @props([
<ide> 'name',
<ide> ])
<del>
<ide> <span {{ $attributes }}>
<ide> Hello {{ $name }}
<ide> </span> | 1 |
Text | Text | add micnic as collaborator | 00f822f276c08465db3f6c70f154e9f28cc372d6 | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Brendan Ashworth** ([@brendanashworth](https://github.com/brendanashworth)) <brendan.ashworth@me.com>
<ide> * **Vladimir Kurchatkin** ([@vkurchatkin](https://github.com/vkurchatkin)) <vladimir.kurchatkin@gmail.com>
<ide> * **Nikolai Vavilov** ([@seishun](https://github.com/seishun)) <vvnicholas@gmail.com>
<add>* **Nicu Micleușanu** ([@micnic](https://github.com/micnic)) <micnic90@gmail.com>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Python | Python | fix sign order for clipvalue | 46a2fb6fd8e52b02df78f1416cc9fbd4b3156604 | <ide><path>keras/optimizers.py
<ide> def get_gradients(self, loss, params):
<ide> grads = [clip_norm(g, self.clipnorm, norm) for g in grads]
<ide>
<ide> if hasattr(self, 'clipvalue') and self.clipvalue > 0:
<del> grads = [T.clip(g, self.clipvalue, -self.clipvalue) for g in grads]
<add> grads = [T.clip(g, -self.clipvalue, self.clipvalue) for g in grads]
<ide>
<ide> return grads
<ide> | 1 |
Python | Python | fix typo in warning messages | 74944fabc1dcaf0a42418029366eae8af23316bc | <ide><path>weave/build_tools.py
<ide> def configure_temp_dir(temp_dir=None):
<ide> if temp_dir is None:
<ide> temp_dir = tempfile.gettempdir()
<ide> elif not os.path.exists(temp_dir) or not os.access(temp_dir,os.W_OK):
<del> print "warning: specified temp_dir '%s' does not exist or is " \
<add> print "warning: specified temp_dir '%s' does not exist " \
<ide> "or is not writable. Using the default temp directory" % \
<ide> temp_dir
<ide> temp_dir = tempfile.gettempdir()
<ide> def configure_build_dir(build_dir=None):
<ide> # make sure build_dir exists and is writable
<ide> if build_dir and (not os.path.exists(build_dir) or
<ide> not os.access(build_dir,os.W_OK)):
<del> print "warning: specified build_dir '%s' does not exist or is " \
<add> print "warning: specified build_dir '%s' does not exist " \
<ide> "or is not writable. Trying default locations" % build_dir
<ide> build_dir = None
<ide> | 1 |
Python | Python | fix local starage driver, add tests for it | ed1d64c02589e904ef2a034569751881c39c4248 | <ide><path>libcloud/storage/drivers/local.py
<ide> def download_object_range_as_stream(self, obj, start_bytes, end_bytes=None,
<ide> file_size = len(obj_file.read())
<ide>
<ide> if not end_bytes:
<del> read_bytes = file_size
<add> read_bytes = (file_size - start_bytes) + 1
<ide> else:
<del> read_bytes = (file_size - end_bytes - start_bytes) - 1
<add> read_bytes = (end_bytes - start_bytes) + 1
<ide>
<del> obj_file.seek(start_bytes)
<add> obj_file.seek(start_bytes - 1)
<ide> data = obj_file.read(read_bytes)
<ide> yield data
<ide>
<ide><path>libcloud/test/storage/test_local.py
<ide> def tearDown(self):
<ide> shutil.rmtree(self.key)
<ide> self.key = None
<ide>
<del> def make_tmp_file(self):
<add> def make_tmp_file(self, content=None):
<add> if not content:
<add> content = b'blah' * 1024
<ide> _, tmppath = tempfile.mkstemp()
<ide> with open(tmppath, 'wb') as fp:
<del> fp.write(b'blah' * 1024)
<add> fp.write(content)
<ide> return tmppath
<ide>
<ide> def remove_tmp_file(self, tmppath):
<ide> def test_download_object_as_stream_success(self):
<ide> container.delete()
<ide> self.remove_tmp_file(tmppath)
<ide>
<add> def test_download_object_range_success(self):
<add> content = b'foo bar baz'
<add> tmppath = self.make_tmp_file(content=content)
<add> container = self.driver.create_container('test6')
<add> obj = container.upload_object(tmppath, 'test')
<add>
<add> destination_path = tmppath + '.temp'
<add>
<add> # 1. Only start_bytes provided
<add> result = self.driver.download_object_range(obj=obj,
<add> destination_path=destination_path,
<add> start_bytes=5,
<add> overwrite_existing=True,
<add> delete_on_failure=True)
<add> self.assertTrue(result)
<add>
<add> with open(destination_path, 'rb') as fp:
<add> written_content = fp.read()
<add>
<add> self.assertEqual(written_content, b'bar baz')
<add> self.assertEqual(written_content, content[5 - 1:])
<add>
<add> # 2. start_bytes and end_bytes is provided
<add> result = self.driver.download_object_range(obj=obj,
<add> destination_path=destination_path,
<add> start_bytes=5,
<add> end_bytes=7,
<add> overwrite_existing=True,
<add> delete_on_failure=True)
<add> self.assertTrue(result)
<add>
<add> with open(destination_path, 'rb') as fp:
<add> written_content = fp.read()
<add>
<add> self.assertEqual(written_content, b'bar')
<add> self.assertEqual(written_content, content[5 - 1:7])
<add>
<add> result = self.driver.download_object_range(obj=obj,
<add> destination_path=destination_path,
<add> start_bytes=1,
<add> end_bytes=1,
<add> overwrite_existing=True,
<add> delete_on_failure=True)
<add> self.assertTrue(result)
<add>
<add> with open(destination_path, 'rb') as fp:
<add> written_content = fp.read()
<add>
<add> self.assertEqual(written_content, b'f')
<add> self.assertEqual(written_content, content[1 - 1:1])
<add>
<add> result = self.driver.download_object_range(obj=obj,
<add> destination_path=destination_path,
<add> start_bytes=1,
<add> end_bytes=3,
<add> overwrite_existing=True,
<add> delete_on_failure=True)
<add> self.assertTrue(result)
<add>
<add> with open(destination_path, 'rb') as fp:
<add> written_content = fp.read()
<add>
<add> self.assertEqual(written_content, b'foo')
<add> self.assertEqual(written_content, content[1 - 1:3])
<add>
<add> obj.delete()
<add> container.delete()
<add> self.remove_tmp_file(tmppath)
<add> os.unlink(destination_path)
<add>
<add> def test_download_object_range_as_stream_success(self):
<add> content = b'foo bar baz'
<add> tmppath = self.make_tmp_file(content=content)
<add> container = self.driver.create_container('test6')
<add> obj = container.upload_object(tmppath, 'test')
<add>
<add> # 1. Only start_bytes provided
<add> stream = self.driver.download_object_range_as_stream(obj=obj,
<add> start_bytes=5,
<add> chunk_size=1024)
<add> written_content = b''.join(stream)
<add>
<add> self.assertEqual(written_content, b'bar baz')
<add> self.assertEqual(written_content, content[5 - 1:])
<add>
<add> # 2. start_bytes and end_bytes is provided
<add> stream = self.driver.download_object_range_as_stream(obj=obj,
<add> start_bytes=5,
<add> end_bytes=7,
<add> chunk_size=1024)
<add> written_content = b''.join(stream)
<add>
<add> self.assertEqual(written_content, b'bar')
<add> self.assertEqual(written_content, content[5 - 1:7])
<add>
<add> stream = self.driver.download_object_range_as_stream(obj=obj,
<add> start_bytes=1,
<add> end_bytes=1,
<add> chunk_size=1024)
<add> written_content = b''.join(stream)
<add>
<add> self.assertEqual(written_content, b'f')
<add> self.assertEqual(written_content, content[1 - 1:1])
<add>
<add> stream = self.driver.download_object_range_as_stream(obj=obj,
<add> start_bytes=1,
<add> end_bytes=3,
<add> chunk_size=1024)
<add> written_content = b''.join(stream)
<add>
<add> self.assertEqual(written_content, b'foo')
<add> self.assertEqual(written_content, content[1 - 1:3])
<add>
<add> obj.delete()
<add> container.delete()
<add> self.remove_tmp_file(tmppath)
<add>
<ide> @mock.patch("lockfile.mkdirlockfile.MkdirLockFile.acquire",
<ide> mock.MagicMock(side_effect=LockTimeout))
<ide> def test_proper_lockfile_imports(self): | 2 |
PHP | PHP | remove unused variable | 437e1f0668f94000f2c7ce0abcf774f00c30ce9d | <ide><path>src/Illuminate/Console/Scheduling/ScheduleWorkCommand.php
<ide> public function handle()
<ide> {
<ide> $this->components->info('Running schedule tasks every minute.');
<ide>
<del> [$lastExecutionStartedAt, $keyOfLastExecutionWithOutput, $executions] = [null, null, []];
<add> [$lastExecutionStartedAt, $executions] = [null, []];
<ide>
<ide> while (true) {
<ide> usleep(100 * 1000); | 1 |
Ruby | Ruby | use public api when adding legacy options | 045a02aa74bf4924ae7d2d2108a2cb89d75a6897 | <ide><path>Library/Homebrew/formula.rb
<ide> def self.method_added method
<ide>
<ide> specs.each do |spec|
<ide> instance.options.each do |opt, desc|
<del> spec.options << Option.new(opt[/^--(.+)$/, 1], desc)
<add> spec.option(opt[/^--(.+)$/, 1], desc)
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | use map rather than array concatenation | c6b4ef082f80255c1e3ec6e4feb1d199ed1e7efa | <ide><path>activemodel/lib/active_model/errors.rb
<ide> def add_on_blank(attributes, options = {})
<ide> # company.errors.full_messages # =>
<ide> # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"]
<ide> def full_messages
<del> full_messages = []
<del>
<del> each do |attribute, messages|
<add> map { |attribute, messages|
<ide> messages = Array.wrap(messages)
<del> next if messages.empty?
<ide>
<ide> if attribute == :base
<del> full_messages.concat messages
<add> messages
<ide> else
<ide> attr_name = attribute.to_s.gsub('.', '_').humanize
<ide> attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
<ide> options = { :default => "%{attribute} %{message}", :attribute => attr_name }
<ide>
<del> full_messages.concat messages.map { |m|
<add> messages.map { |m|
<ide> I18n.t(:"errors.format", options.merge(:message => m))
<ide> }
<ide> end
<del> end
<del>
<del> full_messages
<add> }.flatten
<ide> end
<ide>
<ide> # Translates an error message in its default scope | 1 |
Javascript | Javascript | remove duplicate class members | c0e489b7293f15858cb706f1b8587600e429af28 | <ide><path>Libraries/Animated/AnimatedEvent.js
<ide> function validateMapping(argMapping, args) {
<ide> class AnimatedEvent {
<ide> _argMapping: $ReadOnlyArray<?Mapping>;
<ide> _listeners: Array<Function> = [];
<del> _callListeners: Function;
<ide> _attachedEvent: ?{detach: () => void, ...};
<ide> __isNative: boolean;
<ide>
<ide> class AnimatedEvent {
<ide> if (config.listener) {
<ide> this.__addListener(config.listener);
<ide> }
<del> this._callListeners = this._callListeners.bind(this);
<ide> this._attachedEvent = null;
<ide> this.__isNative = shouldUseNativeDriver(config);
<ide> }
<ide> class AnimatedEvent {
<ide> };
<ide> }
<ide>
<del> _callListeners(...args: any) {
<add> _callListeners = (...args: any) => {
<ide> this._listeners.forEach(listener => listener(...args));
<del> }
<add> };
<ide> }
<ide>
<ide> module.exports = {AnimatedEvent, attachNativeEvent};
<ide><path>Libraries/Network/XMLHttpRequest.js
<ide> class XMLHttpRequest extends (EventTarget(...XHR_EVENTS): any) {
<ide> _lowerCaseResponseHeaders: Object;
<ide> _method: ?string = null;
<ide> _perfKey: ?string = null;
<del> _response: string | ?Object;
<ide> _responseType: ResponseType;
<ide> _response: string = '';
<ide> _sent: boolean;
<ide><path>packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExApp.js
<ide> const NUM_CIRCLES = 30;
<ide> class Circle extends React.Component<any, any> {
<ide> longTimer: number;
<ide>
<del> _onLongPress: () => void;
<del> _toggleIsActive: () => void;
<ide> constructor(props: Object): void {
<ide> super();
<del> this._onLongPress = this._onLongPress.bind(this);
<del> this._toggleIsActive = this._toggleIsActive.bind(this);
<ide> this.state = {
<ide> isActive: false,
<ide> pan: new Animated.ValueXY(), // Vectors reduce boilerplate. (step1: uncomment)
<ide> pop: new Animated.Value(0), // Initial value. (step2a: uncomment)
<ide> };
<ide> }
<ide>
<del> _onLongPress(): void {
<add> _onLongPress = (): void => {
<ide> const config = {tension: 40, friction: 3};
<ide> this.state.pan.addListener(value => {
<ide> // Async listener for state changes (step1: uncomment)
<ide> class Circle extends React.Component<any, any> {
<ide> this.props.onActivate();
<ide> },
<ide> );
<del> }
<add> };
<ide>
<ide> render(): React.Node {
<ide> let handlers;
<ide> class Circle extends React.Component<any, any> {
<ide> </Animated.View>
<ide> );
<ide> }
<del> _toggleIsActive(velocity) {
<add> _toggleIsActive = velocity => {
<ide> const config = {tension: 30, friction: 7};
<ide> if (this.state.isActive) {
<ide> Animated.spring(this.props.openVal, {
<ide> class Circle extends React.Component<any, any> {
<ide> }).start(); // (step4: uncomment)
<ide> });
<ide> }
<del> }
<add> };
<ide> }
<ide>
<ide> class AnExApp extends React.Component<any, any> {
<del> _onMove: (position: Point) => void;
<ide> constructor(props: any): void {
<ide> super(props);
<ide> const keys = [];
<ide> class AnExApp extends React.Component<any, any> {
<ide> restLayouts: [],
<ide> openVal: new Animated.Value(0),
<ide> };
<del> this._onMove = this._onMove.bind(this);
<ide> }
<ide>
<ide> render(): React.Node {
<ide> class AnExApp extends React.Component<any, any> {
<ide> );
<ide> }
<ide>
<del> _onMove(position: Point): void {
<add> _onMove = (position: Point): void => {
<ide> const newKeys = moveToClosest(this.state, position);
<ide> if (newKeys !== this.state.keys) {
<ide> LayoutAnimation.easeInEaseOut(); // animates layout update as one batch (step3: uncomment)
<ide> this.setState({keys: newKeys});
<ide> }
<del> }
<add> };
<ide> }
<ide>
<ide> type Point = {
<ide><path>packages/rn-tester/js/examples/Image/ImageExample.js
<ide> class MultipleSourcesExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> increaseImageSize = () => {
<del> if (this.state.width >= 100) {
<del> return;
<del> }
<del> this.setState({
<del> width: this.state.width + 10,
<del> height: this.state.height + 10,
<del> });
<del> };
<del>
<ide> decreaseImageSize = () => {
<ide> if (this.state.width <= 10) {
<ide> return;
<ide> class OnLayoutExample extends React.Component<
<ide> });
<ide> };
<ide>
<del> increaseImageSize = () => {
<del> if (this.state.width >= 100) {
<del> return;
<del> }
<del> this.setState({
<del> width: this.state.width + 10,
<del> height: this.state.height + 10,
<del> });
<del> };
<del>
<ide> decreaseImageSize = () => {
<ide> if (this.state.width <= 10) {
<ide> return; | 4 |
Javascript | Javascript | handle multi-file solutions | 301212e194250051413ff846e3c0ea8cc9f37138 | <ide><path>curriculum/getChallenges.js
<ide> Trying to parse ${fullPath}`);
<ide> return prepareChallenge(challenge);
<ide> }
<ide>
<add>// TODO: tests and more descriptive name.
<add>function filesToObject(files) {
<add> return reduce(
<add> files,
<add> (map, file) => {
<add> map[file.key] = {
<add> ...file,
<add> head: arrToString(file.head),
<add> contents: arrToString(file.contents),
<add> tail: arrToString(file.tail)
<add> };
<add> return map;
<add> },
<add> {}
<add> );
<add>}
<add>
<ide> // gets the challenge ready for sourcing into Gatsby
<ide> function prepareChallenge(challenge) {
<ide> challenge.name = nameify(challenge.title);
<ide> if (challenge.files) {
<del> challenge.files = reduce(
<del> challenge.files,
<del> (map, file) => {
<del> map[file.key] = {
<del> ...file,
<del> head: arrToString(file.head),
<del> contents: arrToString(file.contents),
<del> tail: arrToString(file.tail)
<del> };
<del> return map;
<del> },
<del> {}
<del> );
<add> challenge.files = filesToObject(challenge.files);
<ide> // TODO: This should be something that can be folded into the above reduce
<add> // EDIT: maybe not, now that we're doing the same for solutionFiles.
<ide> challenge.files = Object.keys(challenge.files)
<ide> .filter(key => challenge.files[key])
<ide> .map(key => challenge.files[key])
<ide> function prepareChallenge(challenge) {
<ide> {}
<ide> );
<ide> }
<add>
<add> if (challenge.solutionFiles) {
<add> challenge.solutionFiles = filesToObject(challenge.solutionFiles);
<add> }
<ide> challenge.block = dasherize(challenge.block);
<ide> challenge.superBlock = blockNameify(challenge.superBlock);
<ide> return challenge;
<ide><path>curriculum/schema/challengeSchema.js
<ide> function getSchemaForLang(lang) {
<ide> })
<ide> ),
<ide> solutions: Joi.array().items(Joi.string().optional()),
<del> solutionFiles: Joi.array().items(fileJoi),
<add> solutionFiles: Joi.object().keys({
<add> indexcss: fileJoi,
<add> indexhtml: fileJoi,
<add> indexjs: fileJoi,
<add> indexjsx: fileJoi
<add> }),
<ide> superBlock: Joi.string(),
<ide> superOrder: Joi.number(),
<ide> suborder: Joi.number(),
<ide><path>curriculum/test/test-challenges.js
<ide> const {
<ide>
<ide> const { assert, AssertionError } = require('chai');
<ide> const Mocha = require('mocha');
<del>const { flatten, isEmpty } = require('lodash');
<add>const { flatten, isEmpty, cloneDeep } = require('lodash');
<ide>
<ide> const jsdom = require('jsdom');
<ide>
<ide> function populateTestsForLang({ lang, challenges, meta }) {
<ide> ? buildJSChallenge
<ide> : buildDOMChallenge;
<ide>
<del> // TODO: create more sophisticated validation now we allow for more
<del> // than one seed/solution file.
<del>
<ide> it('Test suite must fail on the initial contents', async function() {
<ide> this.timeout(5000 * tests.length + 1000);
<ide> // suppress errors in the console.
<ide> function populateTestsForLang({ lang, challenges, meta }) {
<ide> assert(fails, 'Test suit does not fail on the initial contents');
<ide> });
<ide>
<del> let { solutions = [] } = challenge;
<add> let { solutions = [], solutionFiles = {} } = challenge;
<add>
<add> const noSolution = new RegExp('// solution required');
<add> solutions = solutions.filter(
<add> solution => !!solution && !noSolution.test(solution)
<add> );
<add>
<ide> // if there are no solutions in the challenge, it's assumed the next
<ide> // challenge's seed will be a solution to the current challenge.
<ide> // This is expected to happen in the project based curriculum.
<add>
<ide> if (isEmpty(solutions)) {
<del> const nextChallenge = challenges[id + 1];
<del> if (nextChallenge) {
<del> solutions = [nextChallenge.files[0].contents];
<add> if (!isEmpty(solutionFiles)) {
<add> solutions = [solutionFiles];
<add> // TODO: there needs to be a way of telling that a challenge uses
<add> // multiple files when it doesn't have anything in solutionFiles!
<add> } else {
<add> const nextChallenge = challenges[id + 1];
<add> if (nextChallenge) {
<add> solutions = [nextChallenge.files[0].contents];
<add> }
<ide> }
<ide> }
<del> const noSolution = new RegExp('// solution required');
<del> solutions = solutions.filter(
<del> solution => !!solution && !noSolution.test(solution)
<del> );
<ide>
<del> if (solutions.length === 0) {
<add> if (solutions.length === 0 && isEmpty(solutionFiles)) {
<ide> it('Check tests. No solutions');
<ide> return;
<ide> }
<ide> function populateTestsForLang({ lang, challenges, meta }) {
<ide> });
<ide> }
<ide>
<del>// TODO: solutions will need to be multi-file, too, with a fallback when there
<del>// is only one file.
<del>// we cannot simply use the solution instead of files, because the are not
<del>// just the seed(s), they contain the head and tail code. The best approach
<del>// is probably to separate out the head and tail from the files. Then the
<del>// files can be entirely replaced by the solution.
<del>
<del>async function createTestRunner(
<del> { required = [], template, files },
<del> solution,
<del> buildChallenge
<del>) {
<del> // fallback for single solution
<del> const sortedFiles = sortFiles(files);
<del> if (solution) {
<add>async function createTestRunner(challenge, solution, buildChallenge) {
<add> const { required = [], template } = challenge;
<add> // we should avoid modifying challenge, as it gets reused:
<add> const files = cloneDeep(challenge.files);
<add>
<add> // TODO: there must be a better way of handling both single and multi-file
<add> // solutions
<add> if (typeof solution === 'object' && !isEmpty(solution)) {
<add> Object.keys(solution).forEach(key => {
<add> files[key].contents = solution[key].contents;
<add> });
<add> } else if (solution) {
<add> // fallback for single solution
<add> const sortedFiles = sortFiles(files);
<add>
<ide> files[sortedFiles[0].key].contents = solution;
<add> } else {
<add> throw Error('Tried to create test runner without a solution.');
<ide> }
<ide>
<ide> const { build, sources, loadEnzyme } = await buildChallenge({ | 3 |
PHP | PHP | review feedback on docs and class refs | ec4c3647b3284537078ecfebf3175a69b4b50223 | <ide><path>src/Error/Middleware/ErrorHandlerMiddleware.php
<ide> protected function getRenderer($exception)
<ide> *
<ide> * @param \Psr\Http\Message\ServerRequestInterface $request The current request.
<ide> * @param \Exception $exception The exception to log a message for.
<del> * @return void|null
<add> * @return void
<ide> */
<ide> protected function logException($request, $exception)
<ide> {
<ide><path>tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php
<ide> use Cake\Network\Response as CakeResponse;
<ide> use Cake\TestSuite\TestCase;
<ide> use LogicException;
<add>use Psr\Log\LoggerInterface;
<ide> use Zend\Diactoros\Request;
<ide> use Zend\Diactoros\Response;
<ide>
<ide> public function setUp()
<ide> parent::setUp();
<ide>
<ide> Configure::write('App.namespace', 'TestApp');
<del> $this->logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
<add> $this->logger = $this->getMockBuilder(LoggerInterface::class)->getMock();
<ide>
<ide> Log::reset();
<ide> Log::config('error_test', [ | 2 |
Mixed | Ruby | fix relation merging with skip_query_cache! | 28ef2de2292695815eace5f2645fe4e305768403 | <ide><path>activerecord/CHANGELOG.md
<del>* Add `ActiveRecord::Base.base_class?` predicate.
<add>* Fix relation merging with skip_query_cache!
<add>
<add> *James Williams*
<add>
<add>* Add `ActiveRecord::Base.base_class?` predicate.
<ide>
<ide> *Bogdan Gusiev*
<ide>
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def reverse_order! # :nodoc:
<ide> self
<ide> end
<ide>
<del> def skip_query_cache! # :nodoc:
<del> self.skip_query_cache_value = true
<add> def skip_query_cache!(value = true) # :nodoc:
<add> self.skip_query_cache_value = value
<ide> self
<ide> end
<ide>
<ide><path>activerecord/test/cases/relation/merging_test.rb
<ide> def test_relation_merging_with_left_outer_joins
<ide> assert_equal 1, comments.count
<ide> end
<ide>
<add> def test_relation_merging_with_skip_query_cache
<add> assert_equal Post.all.merge(Post.all.skip_query_cache!).skip_query_cache_value, true
<add> end
<add>
<ide> def test_relation_merging_with_association
<ide> assert_queries(2) do # one for loading post, and another one merged query
<ide> post = Post.where(body: "Such a lovely day").first | 3 |
PHP | PHP | remove unused element | 248896c9a045534b4dc599dec935c74b40f4636e | <ide><path>src/View/XmlView.php
<ide> class XmlView extends SerializedView
<ide> */
<ide> protected $_responseType = 'xml';
<ide>
<del> /**
<del> * Option to allow setting an array of custom options for Xml::fromArray()
<del> *
<del> * For e.g. 'format' as 'attributes' instead of 'tags'.
<del> *
<del> * @var array|null
<del> */
<del> protected $xmlOptions;
<del>
<ide> /**
<ide> * Default config options.
<ide> * | 1 |
Mixed | Ruby | add option to stop swallowing errors on callbacks | b11b1e868a89319b8523c5f7b0da4c130ee42992 | <ide><path>activerecord/CHANGELOG.md
<add>* Currently, Active Record will rescue any errors raised within
<add> after_rollback/after_create callbacks and print them to the logs. Next versions of rails
<add> will not rescue those errors anymore, and just bubble them up, as the other callbacks.
<add>
<add> This adds a opt-in flag to enable that behaviour, of not rescuing the errors.
<add> Example:
<add>
<add> # For not swallow errors in after_commit/after_rollback callbacks.
<add> config.active_record.errors_in_transactional_callbacks = true
<add>
<add> Fixes #13460.
<add>
<add> *arthurnn*
<add>
<ide> * Fixed an issue where custom accessor methods (such as those generated by
<ide> `enum`) with the same name as a global method are incorrectly overridden
<ide> when subclassing.
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/transaction.rb
<ide> def rolledback?
<ide> @state == :rolledback
<ide> end
<ide>
<add> def completed?
<add> committed? || rolledback?
<add> end
<add>
<ide> def set_state(state)
<ide> if !VALID_STATES.include?(state)
<ide> raise ArgumentError, "Invalid transaction state: #{state}"
<ide> def rollback
<ide> end
<ide>
<ide> def rollback_records
<del> records.uniq.each do |record|
<add> ite = records.uniq
<add> while record = ite.shift
<ide> begin
<ide> record.rolledback! full_rollback?
<ide> rescue => e
<add> raise if ActiveRecord::Base.raise_in_transactional_callbacks
<ide> record.logger.error(e) if record.respond_to?(:logger) && record.logger
<ide> end
<ide> end
<add> ensure
<add> ite.each do |i|
<add> i.rolledback!(full_rollback?, false)
<add> end
<ide> end
<ide>
<ide> def commit
<ide> @state.set_state(:committed)
<ide> end
<ide>
<ide> def commit_records
<del> records.uniq.each do |record|
<add> ite = records.uniq
<add> while record = ite.shift
<ide> begin
<ide> record.committed!
<ide> rescue => e
<add> raise if ActiveRecord::Base.raise_in_transactional_callbacks
<ide> record.logger.error(e) if record.respond_to?(:logger) && record.logger
<ide> end
<ide> end
<add> ensure
<add> ite.each do |i|
<add> i.committed!(false)
<add> end
<ide> end
<ide>
<ide> def full_rollback?; true; end
<ide> def initialize(connection, savepoint_name, options)
<ide> end
<ide>
<ide> def rollback
<del> super
<ide> connection.rollback_to_savepoint(savepoint_name)
<add> super
<ide> rollback_records
<ide> end
<ide>
<ide> def commit
<del> super
<ide> connection.release_savepoint(savepoint_name)
<add> super
<ide> parent = connection.transaction_manager.current_transaction
<ide> records.each { |r| parent.add_record(r) }
<ide> end
<ide> def initialize(connection, options)
<ide> end
<ide>
<ide> def rollback
<del> super
<ide> connection.rollback_db_transaction
<add> super
<ide> rollback_records
<ide> end
<ide>
<ide> def commit
<del> super
<ide> connection.commit_db_transaction
<add> super
<ide> commit_records
<ide> end
<ide> end
<ide> def within_new_transaction(options = {})
<ide> begin
<ide> commit_transaction unless error
<ide> rescue Exception
<del> transaction.rollback
<add> transaction.rollback unless transaction.state.completed?
<ide> raise
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> module ActiveRecord
<ide> module Transactions
<ide> extend ActiveSupport::Concern
<ide> ACTIONS = [:create, :destroy, :update]
<add> CALLBACK_WARN_MESSAGE = <<-EOF
<add>Currently, Active Record will rescue any errors raised within
<add>after_rollback/after_create callbacks and print them to the logs. In the next
<add>version, these errors will no longer be rescued. Instead, they will simply
<add>bubble just like other Active Record callbacks.
<add>
<add>You can opt into the new behavior and remove this warning by setting
<add>config.active_record.raise_in_transactional_callbacks to true.
<add>EOF
<ide>
<ide> included do
<ide> define_callbacks :commit, :rollback,
<ide> terminator: ->(_, result) { result == false },
<ide> scope: [:kind, :name]
<add>
<add> mattr_accessor :raise_in_transactional_callbacks, instance_writer: false
<add> self.raise_in_transactional_callbacks = false
<ide> end
<ide>
<ide> # = Active Record Transactions
<ide> def transaction(options = {}, &block)
<ide> def after_commit(*args, &block)
<ide> set_options_for_callbacks!(args)
<ide> set_callback(:commit, :after, *args, &block)
<add> unless ActiveRecord::Base.raise_in_transactional_callbacks
<add> ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE)
<add> end
<ide> end
<ide>
<ide> # This callback is called after a create, update, or destroy are rolled back.
<ide> def after_commit(*args, &block)
<ide> def after_rollback(*args, &block)
<ide> set_options_for_callbacks!(args)
<ide> set_callback(:rollback, :after, *args, &block)
<add> unless ActiveRecord::Base.raise_in_transactional_callbacks
<add> ActiveSupport::Deprecation.warn(CALLBACK_WARN_MESSAGE)
<add> end
<ide> end
<ide>
<ide> private
<ide> def rollback_active_record_state!
<ide> #
<ide> # Ensure that it is not called if the object was never persisted (failed create),
<ide> # but call it after the commit of a destroyed object.
<del> def committed! #:nodoc:
<del> run_callbacks :commit if destroyed? || persisted?
<add> def committed!(should_run_callbacks = true) #:nodoc:
<add> run_callbacks :commit if should_run_callbacks && destroyed? || persisted?
<ide> ensure
<ide> force_clear_transaction_record_state
<ide> end
<ide>
<ide> # Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
<ide> # state should be rolled back to the beginning or just to the last savepoint.
<del> def rolledback!(force_restore_state = false) #:nodoc:
<del> run_callbacks :rollback
<add> def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc:
<add> run_callbacks :rollback if should_run_callbacks
<ide> ensure
<ide> restore_transaction_record_state(force_restore_state)
<ide> clear_transaction_record_state
<ide><path>activerecord/test/cases/helper.rb
<ide> # Disable available locale checks to avoid warnings running the test suite.
<ide> I18n.enforce_available_locales = false
<ide>
<add># Enable raise errors in after_commit and after_rollback.
<add>ActiveRecord::Base.raise_in_transactional_callbacks = true
<add>
<ide> # Connect to the database
<ide> ARTest.connect
<ide>
<ide><path>activerecord/test/cases/transaction_callbacks_test.rb
<ide> def @first.commits(i=0); @commits ||= 0; @commits += i if i; end
<ide> end
<ide>
<ide> def test_after_transaction_callbacks_should_prevent_callbacks_from_being_called
<add> old_transaction_config = ActiveRecord::Base.raise_in_transactional_callbacks
<add> ActiveRecord::Base.raise_in_transactional_callbacks = false
<add>
<ide> def @first.last_after_transaction_error=(e); @last_transaction_error = e; end
<ide> def @first.last_after_transaction_error; @last_transaction_error; end
<ide> @first.after_commit_block{|r| r.last_after_transaction_error = :commit; raise "fail!";}
<ide> def @first.last_after_transaction_error; @last_transaction_error; end
<ide> end
<ide> assert_equal :rollback, @first.last_after_transaction_error
<ide> assert_equal [:after_rollback], second.history
<add> ensure
<add> ActiveRecord::Base.raise_in_transactional_callbacks = old_transaction_config
<add> end
<add>
<add> def test_after_commit_should_not_raise_when_raise_in_transactional_callbacks_false
<add> old_transaction_config = ActiveRecord::Base.raise_in_transactional_callbacks
<add> ActiveRecord::Base.raise_in_transactional_callbacks = false
<add> @first.after_commit_block{ fail "boom" }
<add> Topic.transaction { @first.save! }
<add> ensure
<add> ActiveRecord::Base.raise_in_transactional_callbacks = old_transaction_config
<add> end
<add>
<add> def test_after_commit_callback_should_not_swallow_errors
<add> @first.after_commit_block{ fail "boom" }
<add> assert_raises(RuntimeError) do
<add> Topic.transaction do
<add> @first.save!
<add> end
<add> end
<add> end
<add>
<add> def test_after_commit_callback_when_raise_should_not_restore_state
<add> first = TopicWithCallbacks.new
<add> second = TopicWithCallbacks.new
<add> first.after_commit_block{ fail "boom" }
<add> second.after_commit_block{ fail "boom" }
<add>
<add> begin
<add> Topic.transaction do
<add> first.save!
<add> assert_not_nil first.id
<add> second.save!
<add> assert_not_nil second.id
<add> end
<add> rescue
<add> end
<add> assert_not_nil first.id
<add> assert_not_nil second.id
<add> assert first.reload
<add> end
<add>
<add> def test_after_rollback_callback_should_not_swallow_errors_when_set_to_raise
<add> error_class = Class.new(StandardError)
<add> @first.after_rollback_block{ raise error_class }
<add> assert_raises(error_class) do
<add> Topic.transaction do
<add> @first.save!
<add> raise ActiveRecord::Rollback
<add> end
<add> end
<add> end
<add>
<add> def test_after_rollback_callback_when_raise_should_restore_state
<add> error_class = Class.new(StandardError)
<add>
<add> first = TopicWithCallbacks.new
<add> second = TopicWithCallbacks.new
<add> first.after_rollback_block{ raise error_class }
<add> second.after_rollback_block{ raise error_class }
<add>
<add> begin
<add> Topic.transaction do
<add> first.save!
<add> assert_not_nil first.id
<add> second.save!
<add> assert_not_nil second.id
<add> raise ActiveRecord::Rollback
<add> end
<add> rescue error_class
<add> end
<add> assert_nil first.id
<add> assert_nil second.id
<ide> end
<ide>
<ide> def test_after_rollback_callbacks_should_validate_on_condition | 5 |
Ruby | Ruby | handle legacy bottle os tags | 42c9ecd6654e65ed39f1cf20ccc8e24007254c3a | <ide><path>Library/Homebrew/software_spec.rb
<ide> def checksums
<ide> checksum_os_versions = send checksum_type
<ide> next unless checksum_os_versions
<ide> os_versions = checksum_os_versions.keys
<del> os_versions.map! {|osx| MacOS::Version.from_symbol osx }
<add> os_versions.map! {|osx| MacOS::Version.from_symbol osx rescue nil }
<ide> os_versions.sort.reverse.each do |os_version|
<ide> osx = os_version.to_sym
<ide> checksum = checksum_os_versions[osx] | 1 |
Python | Python | fix regexes with escape sequence | 4c722e9e227bb5850172100ea51d8d498adf1aa7 | <ide><path>src/transformers/dynamic_module_utils.py
<ide> def get_relative_imports(module_file):
<ide> content = f.read()
<ide>
<ide> # Imports of the form `import .xxx`
<del> relative_imports = re.findall("^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
<add> relative_imports = re.findall(r"^\s*import\s+\.(\S+)\s*$", content, flags=re.MULTILINE)
<ide> # Imports of the form `from .xxx import yyy`
<del> relative_imports += re.findall("^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
<add> relative_imports += re.findall(r"^\s*from\s+\.(\S+)\s+import", content, flags=re.MULTILINE)
<ide> # Unique-ify
<ide> return list(set(relative_imports))
<ide>
<ide> def check_imports(filename):
<ide> content = f.read()
<ide>
<ide> # Imports of the form `import xxx`
<del> imports = re.findall("^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
<add> imports = re.findall(r"^\s*import\s+(\S+)\s*$", content, flags=re.MULTILINE)
<ide> # Imports of the form `from xxx import yyy`
<del> imports += re.findall("^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
<add> imports += re.findall(r"^\s*from\s+(\S+)\s+import", content, flags=re.MULTILINE)
<ide> # Only keep the top-level module
<ide> imports = [imp.split(".")[0] for imp in imports if not imp.startswith(".")]
<ide>
<ide><path>src/transformers/modeling_utils.py
<ide> def dtype_byte_size(dtype):
<ide> """
<ide> if dtype == torch.bool:
<ide> return 1 / 8
<del> bit_search = re.search("[^\d](\d+)$", str(dtype))
<add> bit_search = re.search(r"[^\d](\d+)$", str(dtype))
<ide> if bit_search is None:
<ide> raise ValueError(f"`dtype` is not a valid dtype: {dtype}.")
<ide> bit_size = int(bit_search.groups()[0]) | 2 |
Java | Java | fix subtle bugs in cloning and fabricuimanager | ac929ef4f6069dfbf4a9be93a33dd938b3801e6c | <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java
<ide> public ReactShadowNode createNode(int reactTag,
<ide> ReactShadowNode node = viewManager.createShadowNodeInstance(mReactApplicationContext);
<ide> ReactShadowNode rootNode = getRootNode(rootTag);
<ide> node.setRootNode(rootNode);
<add> node.setViewClassName(viewName);
<ide> node.setReactTag(reactTag);
<ide> node.setThemedContext(rootNode.getThemedContext());
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ReactShadowNodeImpl.java
<ide> public ReactShadowNodeImpl(ReactShadowNodeImpl original) {
<ide> mShouldNotifyOnLayout = original.mShouldNotifyOnLayout;
<ide> mNodeUpdated = original.mNodeUpdated;
<ide> mChildren = original.mChildren == null ? null : new ArrayList<>(original.mChildren);
<del> mParent = original.mParent;
<add> mParent = null;
<ide> mIsLayoutOnly = original.mIsLayoutOnly;
<ide> mTotalNativeChildren = original.mTotalNativeChildren;
<ide> mNativeParent = original.mNativeParent; | 2 |
Mixed | Ruby | fix logic on disabling commit callbacks | a779b1a08bb73be2b50d42ae69b3946de98e5af4 | <ide><path>activerecord/CHANGELOG.md
<add>* Fix logic on disabling commit callbacks so they are not called unexpectedly when errors occur.
<add>
<add> *Brian Durand*
<add>
<ide> * Ensure `Associations::CollectionAssociation#size` and `Associations::CollectionAssociation#empty?`
<ide> use loaded association ids if present.
<ide>
<ide><path>activerecord/lib/active_record/transactions.rb
<ide> def before_committed! # :nodoc:
<ide> # Ensure that it is not called if the object was never persisted (failed create),
<ide> # but call it after the commit of a destroyed object.
<ide> def committed!(should_run_callbacks: true) #:nodoc:
<del> if should_run_callbacks && destroyed? || persisted?
<add> if should_run_callbacks && (destroyed? || persisted?)
<ide> _run_commit_without_transaction_enrollment_callbacks
<ide> _run_commit_callbacks
<ide> end
<ide><path>activerecord/test/cases/transaction_callbacks_test.rb
<ide> def test_after_commit_callbacks_should_validate_on_condition
<ide> assert_match(/:on conditions for after_commit and after_rollback callbacks have to be one of \[:create, :destroy, :update\]/, e.message)
<ide> end
<ide>
<add> def test_after_commit_chain_not_called_on_errors
<add> record_1 = TopicWithCallbacks.create!
<add> record_2 = TopicWithCallbacks.create!
<add> record_3 = TopicWithCallbacks.create!
<add> callbacks = []
<add> record_1.after_commit_block { raise }
<add> record_2.after_commit_block { callbacks << record_2.id }
<add> record_3.after_commit_block { callbacks << record_3.id }
<add> begin
<add> TopicWithCallbacks.transaction do
<add> record_1.save!
<add> record_2.save!
<add> record_3.save!
<add> end
<add> rescue
<add> # From record_1.after_commit
<add> end
<add> assert_equal [], callbacks
<add> end
<add>
<ide> def test_saving_a_record_with_a_belongs_to_that_specifies_touching_the_parent_should_call_callbacks_on_the_parent_object
<ide> pet = Pet.first
<ide> owner = pet.owner | 3 |
PHP | PHP | apply fixes from styleci | 3d8ae049e84f5ed06107bd0bbf9a68538576f5d2 | <ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testPartition()
<ide>
<ide> public function testPartitionCallbackWithKey()
<ide> {
<del> $collection = new Collection(['zero', 'one','two', 'three']);
<add> $collection = new Collection(['zero', 'one', 'two', 'three']);
<ide>
<ide> list($even, $odd) = $collection->partition(function ($item, $index) {
<ide> return $index % 2 === 0; | 1 |
Python | Python | expose config through the cli arguments | 7711403bbdefad62e7ee88a88e04ec08b53412bc | <ide><path>transformers/commands/run.py
<ide> def try_infer_format_from_ext(path: str):
<ide>
<ide>
<ide> def run_command_factory(args):
<del> nlp = pipeline(task=args.task, model=args.model, tokenizer=args.tokenizer, device=args.device)
<add> nlp = pipeline(task=args.task, model=args.model, config=args.config, tokenizer=args.tokenizer, device=args.device)
<ide> format = try_infer_format_from_ext(args.input) if args.format == 'infer' else args.format
<ide> reader = PipelineDataFormat.from_str(format, args.output, args.input, args.column)
<ide> return RunCommand(nlp, reader)
<ide> def register_subcommand(parser: ArgumentParser):
<ide> run_parser.add_argument('--device', type=int, default=-1, help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)')
<ide> run_parser.add_argument('--task', choices=SUPPORTED_TASKS.keys(), help='Task to run')
<ide> run_parser.add_argument('--model', type=str, required=True, help='Name or path to the model to instantiate.')
<add> run_parser.add_argument('--config', type=str, help='Name or path to the model\'s config to instantiate.')
<ide> run_parser.add_argument('--tokenizer', type=str, help='Name of the tokenizer to use. (default: same as the model name)')
<ide> run_parser.add_argument('--column', type=str, required=True, help='Name of the column to use as input. (For multi columns input as QA use column1,columns2)')
<ide> run_parser.add_argument('--format', type=str, default='infer', choices=PipelineDataFormat.SUPPORTED_FORMATS, help='Input format to read from') | 1 |
Python | Python | fix some style issues (mainly long lines) | 7a4251853534001e4c9ff7b942ff15f42f86ca4f | <ide><path>numpy/lib/npyio.py
<ide> def _ensure_ndmin_ndarray(a, *, ndmin: int):
<ide> _loadtxt_chunksize = 50000
<ide>
<ide>
<del>def _loadtxt_dispatcher(fname, dtype=None, comments=None, delimiter=None,
<del> converters=None, skiprows=None, usecols=None, unpack=None,
<del> ndmin=None, encoding=None, max_rows=None, *, like=None):
<add>def _loadtxt_dispatcher(
<add> fname, dtype=None, comments=None, delimiter=None,
<add> converters=None, skiprows=None, usecols=None, unpack=None,
<add> ndmin=None, encoding=None, max_rows=None, *, like=None):
<ide> return (like,)
<ide>
<ide>
<ide> def _preprocess_comments(iterable, comments, encoding):
<ide>
<ide>
<ide> def _read(fname, *, delimiter=',', comment='#', quote='"',
<del> imaginary_unit='j', usecols=None, skiprows=0,
<del> max_rows=None, converters=None, ndmin=None, unpack=False,
<del> dtype=np.float64, encoding="bytes"):
<add> imaginary_unit='j', usecols=None, skiprows=0,
<add> max_rows=None, converters=None, ndmin=None, unpack=False,
<add> dtype=np.float64, encoding="bytes"):
<ide> r"""
<ide> Read a NumPy array from a text file.
<ide>
<ide> def _read(fname, *, delimiter=',', comment='#', quote='"',
<ide>
<ide> read_dtype_via_object_chunks = None
<ide> if dtype.kind in 'SUM' and (
<del> dtype == "S0" or dtype == "U0" or dtype == "M8" or dtype == 'm8'):
<add> dtype == "S0" or dtype == "U0" or dtype == "M8" or dtype == 'm8'):
<ide> # This is a legacy "flexible" dtype. We do not truly support
<ide> # parametric dtypes currently (no dtype discovery step in the core),
<ide> # but have to support these for backward compatibility.
<ide> def _read(fname, *, delimiter=',', comment='#', quote='"',
<ide> # rare enough to not optimize for.
<ide> if quote != "":
<ide> raise ValueError(
<del> "when multiple comments or a multi-character comment is given, "
<del> "quotes are not supported. In this case the quote character "
<del> "must be set to the empty string: `quote=''`.")
<add> "when multiple comments or a multi-character comment is "
<add> "given, quotes are not supported. In this case the quote "
<add> "character must be set to the empty string: `quote=''`.")
<ide> else:
<ide> # No preprocessing necessary
<ide> assert comments is None
<ide> def _read(fname, *, delimiter=',', comment='#', quote='"',
<ide> else:
<ide> # This branch reads the file into chunks of object arrays and then
<ide> # casts them to the desired actual dtype. This ensures correct
<del> # string-length and datetime-unit discovery (as for `arr.astype()`).
<add> # string-length and datetime-unit discovery (like `arr.astype()`).
<ide> # Due to chunking, certain error reports are less clear, currently.
<ide> if filelike:
<ide> data = iter(data) # cannot chunk when reading from file
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> else:
<ide> if isinstance(comment, (str, bytes)):
<ide> comment = [comment]
<del> comment = [x.decode('latin1') if isinstance(x, bytes) else x for x in comment]
<add> comment = [
<add> x.decode('latin1') if isinstance(x, bytes) else x for x in comment]
<ide>
<ide> arr = _read(fname, dtype=dtype, comment=comment, delimiter=delimiter,
<ide> converters=converters, skiprows=skiprows, usecols=usecols, | 1 |
Text | Text | add descriptions to api ref pages | a76c9efe8453e69be3b98f864db951d9743f91f1 | <ide><path>docs/FAQ.md
<ide> id: faq
<ide> title: FAQ Index
<ide> hide_title: true
<add>description: 'FAQ Index: Frequently Asked Questions about Redux'
<ide> ---
<ide>
<ide>
<ide><path>docs/api/Store.md
<ide> id: store
<ide> title: Store
<ide> hide_title: true
<add>description: 'API > Store: the core Redux store methods'
<ide> ---
<ide>
<ide>
<ide><path>docs/api/applyMiddleware.md
<ide> id: applymiddleware
<ide> title: applyMiddleware
<ide> hide_title: true
<add>description: 'API > applyMiddleware: extending the Redux store'
<ide> ---
<ide>
<ide>
<ide><path>docs/api/bindActionCreators.md
<ide> id: bindactioncreators
<ide> title: bindActionCreators
<ide> hide_title: true
<add>description: 'API > bindActionCreators: wrapping action creators for dispatching'
<ide> ---
<ide>
<ide>
<ide><path>docs/api/combineReducers.md
<ide> id: combinereducers
<ide> title: combineReducers
<ide> hide_title: true
<add>description: 'API > combineReducers: merging slice reducers to create combined state'
<ide> ---
<ide>
<ide>
<ide><path>docs/api/compose.md
<ide> id: compose
<ide> title: compose
<ide> hide_title: true
<add>description: 'API > compose: composing multiple functions together'
<ide> ---
<ide>
<ide>
<ide><path>docs/api/createStore.md
<ide> id: createstore
<ide> title: createStore
<ide> hide_title: true
<add>description: 'API > createStore: creating a core Redux store'
<ide> ---
<ide>
<ide> | 7 |
Ruby | Ruby | pull `@template` in to a local variable | 5bb1ad59b1fea70c82d0a3b654ef81a0a31c715c | <ide><path>actionview/lib/action_view/renderer/abstract_renderer.rb
<ide> def extract_details(options) # :doc:
<ide> end
<ide>
<ide> def instrument(name, **options) # :doc:
<del> options[:identifier] ||= (@template && @template.identifier) || @path
<del>
<ide> ActiveSupport::Notifications.instrument("render_#{name}.action_view", options) do |payload|
<ide> yield payload
<ide> end
<ide><path>actionview/lib/action_view/renderer/partial_renderer.rb
<ide> def initialize(*)
<ide>
<ide> def render(context, options, block)
<ide> setup(context, options, block)
<del> @template = find_partial
<add> template = find_partial
<ide>
<ide> @lookup_context.rendered_format ||= begin
<del> if @template && @template.formats.present?
<del> @template.formats.first
<add> if template && template.formats.first
<add> template.formats.first
<ide> else
<ide> formats.first
<ide> end
<ide> end
<ide>
<ide> if @collection
<del> render_collection(context)
<add> render_collection(context, template)
<ide> else
<del> render_partial(context)
<add> render_partial(context, template)
<ide> end
<ide> end
<ide>
<ide> private
<ide>
<del> def render_collection(view)
<del> instrument(:collection, count: @collection.size) do |payload|
<add> def render_collection(view, template)
<add> identifier = (template && template.identifier) || @path
<add> instrument(:collection, identifier: identifier, count: @collection.size) do |payload|
<ide> return nil if @collection.blank?
<ide>
<ide> if @options.key?(:spacer_template)
<ide> spacer = find_template(@options[:spacer_template], @locals.keys).render(view, @locals)
<ide> end
<ide>
<del> cache_collection_render(payload, view) do
<del> @template ? collection_with_template(view) : collection_without_template(view)
<add> cache_collection_render(payload, view, template) do
<add> template ? collection_with_template(view, template) : collection_without_template(view)
<ide> end.join(spacer).html_safe
<ide> end
<ide> end
<ide>
<del> def render_partial(view)
<del> instrument(:partial) do |payload|
<add> def render_partial(view, template)
<add> instrument(:partial, identifier: template.identifier) do |payload|
<ide> locals, block = @locals, @block
<ide> object, as = @object, @variable
<ide>
<ide> def render_partial(view)
<ide> object = locals[as] if object.nil? # Respect object when object is false
<ide> locals[as] = object if @has_object
<ide>
<del> content = @template.render(view, locals) do |*name|
<add> content = template.render(view, locals) do |*name|
<ide> view._layout_for(*name, &block)
<ide> end
<ide>
<ide> content = layout.render(view, locals) { content } if layout
<del> payload[:cache_hit] = view.view_renderer.cache_hits[@template.virtual_path]
<add> payload[:cache_hit] = view.view_renderer.cache_hits[template.virtual_path]
<ide> content
<ide> end
<ide> end
<ide> def find_template(path, locals)
<ide> @lookup_context.find_template(path, prefixes, true, locals, @details)
<ide> end
<ide>
<del> def collection_with_template(view)
<del> locals, template = @locals, @template
<add> def collection_with_template(view, template)
<add> locals = @locals
<ide> as, counter, iteration = @variable, @variable_counter, @variable_iteration
<ide>
<ide> if layout = @options[:layout]
<ide><path>actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
<ide> module CollectionCaching # :nodoc:
<ide> end
<ide>
<ide> private
<del> def cache_collection_render(instrumentation_payload, view)
<add> def cache_collection_render(instrumentation_payload, view, template)
<ide> return yield unless @options[:cached]
<ide>
<ide> # Result is a hash with the key represents the
<ide> # key used for cache lookup and the value is the item
<ide> # on which the partial is being rendered
<del> keyed_collection = collection_by_cache_keys(view)
<add> keyed_collection = collection_by_cache_keys(view, template)
<ide>
<ide> # Pull all partials from cache
<ide> # Result is a hash, key matches the entry in
<ide> def callable_cache_key?
<ide> @options[:cached].respond_to?(:call)
<ide> end
<ide>
<del> def collection_by_cache_keys(view)
<add> def collection_by_cache_keys(view, template)
<ide> seed = callable_cache_key? ? @options[:cached] : ->(i) { i }
<ide>
<ide> @collection.each_with_object({}) do |item, hash|
<del> hash[expanded_cache_key(seed.call(item), view)] = item
<add> hash[expanded_cache_key(seed.call(item), view, template)] = item
<ide> end
<ide> end
<ide>
<del> def expanded_cache_key(key, view)
<del> key = view.combined_fragment_cache_key(view.cache_fragment_name(key, virtual_path: @template.virtual_path, digest_path: digest_path(view)))
<add> def expanded_cache_key(key, view, template)
<add> key = view.combined_fragment_cache_key(view.cache_fragment_name(key, virtual_path: template.virtual_path, digest_path: digest_path(view, template)))
<ide> key.frozen? ? key.dup : key # #read_multi & #write may require mutability, Dalli 2.6.0.
<ide> end
<ide>
<del> def digest_path(view)
<del> @digest_path ||= view.digest_path_from_virtual(@template.virtual_path)
<add> def digest_path(view, template)
<add> @digest_path ||= view.digest_path_from_virtual(template.virtual_path)
<ide> end
<ide>
<ide> # `order_by` is an enumerable object containing keys of the cache,
<ide><path>activerecord/lib/active_record/railties/collection_cache_association_loading.rb
<ide> def relation_from_options(cached: nil, partial: nil, collection: nil, **_)
<ide> end
<ide> end
<ide>
<del> def collection_without_template(_)
<add> def collection_without_template(*)
<ide> @relation.preload_associations(@collection) if @relation
<ide> super
<ide> end
<ide>
<del> def collection_with_template(_)
<add> def collection_with_template(*)
<ide> @relation.preload_associations(@collection) if @relation
<ide> super
<ide> end | 4 |
Javascript | Javascript | send progress events via multipart response | b8804fdbc30a3bfd161a9b55966e507040e6bf16 | <ide><path>packager/react-packager/src/Server/MultipartResponse.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const CRLF = '\r\n';
<add>const BOUNDARY = '3beqjf3apnqeu3h5jqorms4i';
<add>
<add>class MultipartResponse {
<add> static wrap(req, res) {
<add> if (acceptsMultipartResponse(req)) {
<add> return new MultipartResponse(res);
<add> }
<add> // Ugly hack, ideally wrap function should always return a proxy
<add> // object with the same interface
<add> res.writeChunk = () => {}; // noop
<add> return res;
<add> }
<add>
<add> constructor(res) {
<add> this.res = res;
<add> this.headers = {};
<add>
<add> res.writeHead(200, {
<add> 'Content-Type': `multipart/mixed; boundary="${BOUNDARY}"`,
<add> });
<add> res.write('If you are seeing this, your client does not support multipart response');
<add> }
<add>
<add> writeChunk(headers, data, isLast = false) {
<add> let chunk = `${CRLF}--${BOUNDARY}${CRLF}`;
<add> if (headers) {
<add> chunk += MultipartResponse.serializeHeaders(headers) + CRLF + CRLF;
<add> }
<add>
<add> if (data) {
<add> chunk += data;
<add> }
<add>
<add> if (isLast) {
<add> chunk += `${CRLF}--${BOUNDARY}--${CRLF}`;
<add> }
<add>
<add> this.res.write(chunk);
<add> }
<add>
<add> writeHead(status, headers) {
<add> // We can't actually change the response HTTP status code
<add> // because the headers have already been sent
<add> this.setHeader('X-Http-Status', status);
<add> if (!headers) {
<add> return;
<add> }
<add> for (let key in headers) {
<add> this.setHeader(key, headers[key]);
<add> }
<add> }
<add>
<add> setHeader(name, value) {
<add> this.headers[name] = value;
<add> }
<add>
<add> end(data) {
<add> this.writeChunk(this.headers, data, true);
<add> this.res.end();
<add> }
<add>
<add> static serializeHeaders(headers) {
<add> return Object.keys(headers)
<add> .map((key) => `${key}: ${headers[key]}`)
<add> .join(CRLF);
<add> }
<add>}
<add>
<add>function acceptsMultipartResponse(req) {
<add> return req.headers && req.headers['accept'] === 'multipart/mixed';
<add>}
<add>
<add>module.exports = MultipartResponse;
<ide><path>packager/react-packager/src/Server/__tests__/MultipartResponse-test.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>jest.dontMock('../MultipartResponse');
<add>
<add>const MultipartResponse = require('../MultipartResponse');
<add>
<add>describe('MultipartResponse', () => {
<add> it('forwards calls to response', () => {
<add> const nreq = mockNodeRequest({accept: 'text/html'});
<add> const nres = mockNodeResponse();
<add> const res = MultipartResponse.wrap(nreq, nres);
<add>
<add> expect(res).toBe(nres);
<add>
<add> res.writeChunk({}, 'foo');
<add> expect(nres.write).not.toBeCalled();
<add> });
<add>
<add> it('writes multipart response', () => {
<add> const nreq = mockNodeRequest({accept: 'multipart/mixed'});
<add> const nres = mockNodeResponse();
<add> const res = MultipartResponse.wrap(nreq, nres);
<add>
<add> expect(res).not.toBe(nres);
<add>
<add> res.setHeader('Result-Header-1', 1);
<add> res.writeChunk({foo: 'bar'}, 'first chunk');
<add> res.writeChunk({test: 2}, 'second chunk');
<add> res.writeChunk(null, 'empty headers third chunk');
<add> res.setHeader('Result-Header-2', 2);
<add> res.end('Hello, world!');
<add>
<add> expect(nres.toString()).toEqual([
<add> 'HTTP/1.1 200',
<add> 'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> '',
<add> 'If you are seeing this, your client does not support multipart response',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'foo: bar',
<add> '',
<add> 'first chunk',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'test: 2',
<add> '',
<add> 'second chunk',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'empty headers third chunk',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'Result-Header-1: 1',
<add> 'Result-Header-2: 2',
<add> '',
<add> 'Hello, world!',
<add> '--3beqjf3apnqeu3h5jqorms4i--',
<add> '',
<add> ].join('\r\n'));
<add> });
<add>
<add> it('sends status code as last chunk header', () => {
<add> const nreq = mockNodeRequest({accept: 'multipart/mixed'});
<add> const nres = mockNodeResponse();
<add> const res = MultipartResponse.wrap(nreq, nres);
<add>
<add> res.writeChunk({foo: 'bar'}, 'first chunk');
<add> res.writeHead(500, {
<add> 'Content-Type': 'application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> });
<add> res.end('{}');
<add>
<add> expect(nres.toString()).toEqual([
<add> 'HTTP/1.1 200',
<add> 'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> '',
<add> 'If you are seeing this, your client does not support multipart response',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'foo: bar',
<add> '',
<add> 'first chunk',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'X-Http-Status: 500',
<add> 'Content-Type: application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> '',
<add> '{}',
<add> '--3beqjf3apnqeu3h5jqorms4i--',
<add> '',
<add> ].join('\r\n'));
<add> });
<add>
<add> it('supports empty responses', () => {
<add> const nreq = mockNodeRequest({accept: 'multipart/mixed'});
<add> const nres = mockNodeResponse();
<add> const res = MultipartResponse.wrap(nreq, nres);
<add>
<add> res.writeHead(304, {
<add> 'Content-Type': 'application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> });
<add> res.end();
<add>
<add> expect(nres.toString()).toEqual([
<add> 'HTTP/1.1 200',
<add> 'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> '',
<add> 'If you are seeing this, your client does not support multipart response',
<add> '--3beqjf3apnqeu3h5jqorms4i',
<add> 'X-Http-Status: 304',
<add> 'Content-Type: application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
<add> '',
<add> '',
<add> '--3beqjf3apnqeu3h5jqorms4i--',
<add> '',
<add> ].join('\r\n'));
<add> });
<add>});
<add>
<add>function mockNodeRequest(headers = {}) {
<add> return {headers};
<add>}
<add>
<add>function mockNodeResponse() {
<add> let status = 200;
<add> let headers = {};
<add> let body = '';
<add> return {
<add> writeHead: jest.fn((st, hdrs) => {
<add> status = st;
<add> headers = {...headers, ...hdrs};
<add> }),
<add> setHeader: jest.fn((key, val) => { headers[key] = val; }),
<add> write: jest.fn((data) => { body += data; }),
<add> end: jest.fn((data) => { body += (data || ''); }),
<add>
<add> // For testing only
<add> toString() {
<add> return [
<add> `HTTP/1.1 ${status}`,
<add> MultipartResponse.serializeHeaders(headers),
<add> '',
<add> body,
<add> ].join('\r\n');
<add> }
<add> };
<add>}
<add>
<ide><path>packager/react-packager/src/Server/__tests__/Server-test.js
<ide> describe('processRequest', () => {
<ide> reqHandler(
<ide> { url: requrl, headers:{}, ...reqOptions },
<ide> {
<add> statusCode: 200,
<ide> headers: {},
<ide> getHeader(header) { return this.headers[header]; },
<ide> setHeader(header, value) { this.headers[header] = value; },
<add> writeHead(statusCode) { this.statusCode = statusCode; },
<ide> end(body) {
<ide> this.body = body;
<ide> resolve(this);
<ide> describe('processRequest', () => {
<ide> sourceMapUrl: 'index.ios.includeRequire.map',
<ide> dev: true,
<ide> platform: undefined,
<add> onProgress: jasmine.any(Function),
<ide> runBeforeMainModule: ['InitializeJavaScriptAppEngine'],
<ide> unbundle: false,
<ide> entryModuleOnly: false,
<ide> describe('processRequest', () => {
<ide> sourceMapUrl: 'index.map?platform=ios',
<ide> dev: true,
<ide> platform: 'ios',
<add> onProgress: jasmine.any(Function),
<ide> runBeforeMainModule: ['InitializeJavaScriptAppEngine'],
<ide> unbundle: false,
<ide> entryModuleOnly: false,
<ide> describe('processRequest', () => {
<ide> sourceMapUrl: 'index.map?assetPlugin=assetPlugin1&assetPlugin=assetPlugin2',
<ide> dev: true,
<ide> platform: undefined,
<add> onProgress: jasmine.any(Function),
<ide> runBeforeMainModule: ['InitializeJavaScriptAppEngine'],
<ide> unbundle: false,
<ide> entryModuleOnly: false,
<ide><path>packager/react-packager/src/Server/index.js
<ide> const AssetServer = require('../AssetServer');
<ide> const FileWatcher = require('../node-haste').FileWatcher;
<ide> const getPlatformExtension = require('../node-haste').getPlatformExtension;
<ide> const Bundler = require('../Bundler');
<add>const MultipartResponse = require('./MultipartResponse');
<ide> const ProgressBar = require('progress');
<ide> const Promise = require('promise');
<ide> const SourceMapConsumer = require('source-map').SourceMapConsumer;
<ide> class Server {
<ide> },
<ide> );
<ide>
<add> let consoleProgress = () => {};
<ide> if (process.stdout.isTTY && !this._opts.silent) {
<ide> const bar = new ProgressBar('transformed :current/:total (:percent)', {
<ide> complete: '=',
<ide> incomplete: ' ',
<ide> width: 40,
<ide> total: 1,
<ide> });
<del> options.onProgress = debouncedTick(bar);
<add> consoleProgress = debouncedTick(bar);
<ide> }
<add>
<add> const mres = MultipartResponse.wrap(req, res);
<add> options.onProgress = (done, total) => {
<add> consoleProgress(done, total);
<add> mres.writeChunk({'Content-Type': 'application/json'}, JSON.stringify({done, total}));
<add> };
<add>
<ide> debug('Getting bundle for request');
<ide> const building = this._useCachedOrUpdateOrCreateBundle(options);
<ide> building.then(
<ide> class Server {
<ide> dev: options.dev,
<ide> });
<ide> debug('Writing response headers');
<del> res.setHeader('Content-Type', 'application/javascript');
<del> res.setHeader('ETag', p.getEtag());
<del> if (req.headers['if-none-match'] === res.getHeader('ETag')){
<add> const etag = p.getEtag();
<add> mres.setHeader('Content-Type', 'application/javascript');
<add> mres.setHeader('ETag', etag);
<add>
<add> if (req.headers['if-none-match'] === etag) {
<ide> debug('Responding with 304');
<del> res.statusCode = 304;
<del> res.end();
<add> mres.writeHead(304);
<add> mres.end();
<ide> } else {
<del> debug('Writing request body');
<del> res.end(bundleSource);
<add> mres.end(bundleSource);
<ide> }
<ide> debug('Finished response');
<ide> Activity.endEvent(startReqEventId);
<ide> class Server {
<ide> sourceMap = JSON.stringify(sourceMap);
<ide> }
<ide>
<del> res.setHeader('Content-Type', 'application/json');
<del> res.end(sourceMap);
<add> mres.setHeader('Content-Type', 'application/json');
<add> mres.end(sourceMap);
<ide> Activity.endEvent(startReqEventId);
<ide> } else if (requestType === 'assets') {
<ide> const assetsList = JSON.stringify(p.getAssets());
<del> res.setHeader('Content-Type', 'application/json');
<del> res.end(assetsList);
<add> mres.setHeader('Content-Type', 'application/json');
<add> mres.end(assetsList);
<ide> Activity.endEvent(startReqEventId);
<ide> }
<ide> },
<del> error => this._handleError(res, this.optionsHash(options), error)
<add> error => this._handleError(mres, this.optionsHash(options), error)
<ide> ).catch(error => {
<ide> process.nextTick(() => {
<ide> throw error; | 4 |
Javascript | Javascript | fix the lint issue introduced in | 4c804361e089844c65dad251a0a1c7860771b563 | <ide><path>src/renderers/dom/client/ReactBrowserEventEmitter.js
<ide> var ReactBrowserEventEmitter = assign({}, ReactEventEmitterMixin, {
<ide> *
<ide> * @see http://www.quirksmode.org/dom/events/scroll.html
<ide> */
<del> ensureScrollValueMonitoring: function(){
<add> ensureScrollValueMonitoring: function() {
<ide> if (hasEventPageXY === undefined) {
<ide> hasEventPageXY =
<ide> document.createEvent && 'pageX' in document.createEvent('MouseEvent'); | 1 |
PHP | PHP | fix regex for sql execution duration | be7450801c4cd8d07fbab49a5a1d6f3c1dcc0e36 | <ide><path>tests/TestCase/Database/Log/LoggingStatementTest.php
<ide> public function testExecuteWithParams()
<ide>
<ide> $messages = Log::engine('queries')->read();
<ide> $this->assertCount(1, $messages);
<del> $this->assertRegExp('/^debug duration=\d rows=4 SELECT bar FROM foo WHERE x=1 AND y=2$/', $messages[0]);
<add> $this->assertRegExp('/^debug duration=\d+ rows=4 SELECT bar FROM foo WHERE x=1 AND y=2$/', $messages[0]);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | fix crash when maps are merged | 9a9d79f50931795014e0f631ea0ab1c774161eda | <ide><path>lib/FileSystemInfo.js
<ide> const applyMtime = mtime => {
<ide> };
<ide>
<ide> const mergeMaps = (a, b) => {
<del> if (b.size === 0) return a;
<add> if (!b || b.size === 0) return a;
<add> if (!a || a.size === 0) return b;
<ide> const map = new Map(a);
<ide> for (const [key, value] of b) {
<ide> map.set(key, value); | 1 |
Text | Text | fix broken table in "using an overload with ..." | 63572c792182f0c2446ceeb3262d843f28558459 | <ide><path>README.md
<ide> allow further customization of the backpressure behavior.
<ide> Many frequently used operator has overloads that can deal with the other types. These are usually named with the suffix of the target type:
<ide>
<ide> | Operator | Overloads |
<add>|----------|-----------|
<ide> | `flatMap` | `flatMapSingle`, `flatMapMaybe`, `flatMapCompletable`, `flatMapIterable` |
<ide> | `concatMap` | `concatMapSingle`, `concatMapMaybe`, `concatMapCompletable`, `concatMapIterable` |
<del>| `switchMap` | `switchMapSingle`, `switchMapMaybe`, `switchMapCompletable`, `switchMapIterable` |
<add>| `switchMap` | `switchMapSingle`, `switchMapMaybe`, `switchMapCompletable` |
<ide>
<ide> The reason these operators have a suffix instead of simply having the same name with different signature is type erasure. Java doesn't consider signatures such as `operator(Function<T, Single<R>>)` and `operator(Function<T, Maybe<R>>)` different (unlike C#) and due to erasure, the two `operator`s would end up as duplicate methods with the same signature.
<ide> | 1 |
Python | Python | add test for ssh command | 25c78501530e5f296d0a30534b4149772a43f6a6 | <ide><path>tests/core.py
<ide> def test_parse_s3_url(self):
<ide> "Incorrect parsing of the s3 url")
<ide>
<ide>
<add>class SSHHookTest(unittest.TestCase):
<add> def setUp(self):
<add> configuration.test_mode()
<add> from airflow.contrib.hooks.ssh_hook import SSHHook
<add> self.hook = SSHHook()
<add>
<add> def test_remote_cmd(self):
<add> output = self.hook.check_output(["echo", "-n", "airflow"])
<add> self.assertEqual(output, b"airflow")
<add>
<add>
<ide> if 'AIRFLOW_RUNALL_TESTS' in os.environ:
<ide>
<ide> | 1 |
Go | Go | add some adjectives to the namesgenerator | 169b4d92a15a08683e3f3afe7f278d9a0199153a | <ide><path>pkg/namesgenerator/names-generator.go
<ide> var (
<ide> "amazing",
<ide> "angry",
<ide> "awesome",
<del> "backstabbing",
<del> "berserk",
<del> "big",
<add> "blissful",
<ide> "boring",
<add> "brave",
<ide> "clever",
<ide> "cocky",
<ide> "compassionate",
<add> "competent",
<ide> "condescending",
<add> "confident",
<ide> "cranky",
<del> "desperate",
<add> "dazzling",
<ide> "determined",
<ide> "distracted",
<ide> "dreamy",
<del> "drunk",
<ide> "eager",
<ide> "ecstatic",
<ide> "elastic",
<ide> "elated",
<ide> "elegant",
<del> "evil",
<add> "eloquent",
<add> "epic",
<ide> "fervent",
<add> "festive",
<add> "flamboyant",
<ide> "focused",
<del> "furious",
<del> "gigantic",
<del> "gloomy",
<add> "friendly",
<add> "frosty",
<add> "gallant",
<add> "gifted",
<ide> "goofy",
<del> "grave",
<add> "gracious",
<ide> "happy",
<del> "high",
<add> "hardcore",
<add> "heuristic",
<ide> "hopeful",
<ide> "hungry",
<ide> "infallible",
<add> "inspiring",
<ide> "jolly",
<ide> "jovial",
<add> "keen",
<ide> "kickass",
<del> "lonely",
<add> "kind",
<add> "laughing",
<ide> "loving",
<del> "mad",
<add> "lucid",
<add> "mystifying",
<ide> "modest",
<add> "musing",
<ide> "naughty",
<del> "nauseous",
<add> "nervous",
<add> "nifty",
<ide> "nostalgic",
<add> "objective",
<add> "optimistic",
<ide> "peaceful",
<ide> "pedantic",
<ide> "pensive",
<del> "prickly",
<add> "practical",
<add> "priceless",
<add> "quirky",
<add> "quizzical",
<add> "relaxed",
<ide> "reverent",
<ide> "romantic",
<ide> "sad",
<ide> "serene",
<ide> "sharp",
<del> "sick",
<ide> "silly",
<ide> "sleepy",
<del> "small",
<ide> "stoic",
<ide> "stupefied",
<ide> "suspicious",
<ide> "tender",
<ide> "thirsty",
<del> "tiny",
<ide> "trusting",
<add> "unruffled",
<add> "upbeat",
<add> "vibrant",
<add> "vigilant",
<add> "wizardly",
<add> "wonderful",
<add> "xenodochial",
<add> "youthful",
<add> "zealous",
<ide> "zen",
<ide> }
<ide> | 1 |
Ruby | Ruby | add tests for cgirequest#content_type | 89eec91e670ae267cd88b2b3555bfefe527f0eaa | <ide><path>actionpack/test/controller/cgi_test.rb
<ide> def test_doesnt_interpret_request_uri_as_query_string_when_missing
<ide> end
<ide> end
<ide>
<add>class CgiRequestContentTypeTest < BaseCgiTest
<add> def test_html_content_type_verification
<add> @request.env['CONTENT_TYPE'] = Mime::HTML.to_s
<add> assert @request.content_type.verify_request?
<add> end
<add>
<add> def test_xml_content_type_verification
<add> @request.env['CONTENT_TYPE'] = Mime::XML.to_s
<add> assert !@request.content_type.verify_request?
<add> end
<add>end
<add>
<ide> class CgiRequestNeedsRewoundTest < BaseCgiTest
<ide> def test_body_should_be_rewound
<ide> data = 'foo' | 1 |
Ruby | Ruby | add a test case for | 58d52171bb8c7a5589bb13ce1bab81d635ae9cf0 | <ide><path>activerecord/test/cases/relation/where_test.rb
<ide> def test_where_on_association_with_custom_primary_key_with_array_of_ids
<ide> assert_equal essays(:david_modest_proposal), essay
<ide> end
<ide>
<add> def test_where_on_association_with_select_relation
<add> essay = Essay.where(author: Author.where(name: "David").select(:name)).take
<add> assert_equal essays(:david_modest_proposal), essay
<add> end
<add>
<ide> def test_where_with_strong_parameters
<ide> protected_params = Class.new do
<ide> attr_reader :permitted
<ide><path>activerecord/test/models/essay.rb
<ide> class Essay < ActiveRecord::Base
<add> belongs_to :author
<ide> belongs_to :writer, primary_key: :name, polymorphic: true
<ide> belongs_to :category, primary_key: :name
<ide> has_one :owner, primary_key: :name | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.