text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/filter/brotli_source_stream.h"

#include "base/bind.h"
#include "base/bit_cast.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/metrics/histogram_macros.h"
#include "net/base/io_buffer.h"
#include "starboard/memory.h"
#if defined(STARBOARD)
#include <brotli/decode.h>
#else
#include "starboard/types.h"
#include "third_party/brotli/include/brotli/decode.h"
#endif

namespace net {

namespace {

const char kBrotli[] = "BROTLI";
const uint8_t kGzipHeader[] = {0x1f, 0x8b, 0x08};

// BrotliSourceStream applies Brotli content decoding to a data stream.
// Brotli format specification: http://www.ietf.org/id/draft-alakuijala-brotli.
class BrotliSourceStream : public FilterSourceStream {
 public:
  explicit BrotliSourceStream(std::unique_ptr<SourceStream> upstream)
      : FilterSourceStream(SourceStream::TYPE_BROTLI, std::move(upstream)),
        decoding_status_(DecodingStatus::DECODING_IN_PROGRESS),
        used_memory_(0),
        used_memory_maximum_(0),
        consumed_bytes_(0),
        produced_bytes_(0),
        gzip_header_detected_(true) {
    brotli_state_ =
        BrotliDecoderCreateInstance(AllocateMemory, FreeMemory, this);
    CHECK(brotli_state_);
  }

  ~BrotliSourceStream() override {
    BrotliDecoderErrorCode error_code =
        BrotliDecoderGetErrorCode(brotli_state_);
    BrotliDecoderDestroyInstance(brotli_state_);
    brotli_state_ = nullptr;
    DCHECK_EQ(0u, used_memory_);

    // Don't report that gzip header was detected in case of lack of input.
    gzip_header_detected_ &= (consumed_bytes_ >= sizeof(kGzipHeader));

    UMA_HISTOGRAM_ENUMERATION(
        "BrotliFilter.Status", static_cast<int>(decoding_status_),
        static_cast<int>(DecodingStatus::DECODING_STATUS_COUNT));
    UMA_HISTOGRAM_BOOLEAN("BrotliFilter.GzipHeaderDetected",
                          gzip_header_detected_);
    if (decoding_status_ == DecodingStatus::DECODING_DONE) {
      // CompressionPercent is undefined when there is no output produced.
      if (produced_bytes_ != 0) {
        UMA_HISTOGRAM_PERCENTAGE(
            "BrotliFilter.CompressionPercent",
            static_cast<int>((consumed_bytes_ * 100) / produced_bytes_));
      }
    }
    if (error_code < 0) {
      UMA_HISTOGRAM_ENUMERATION("BrotliFilter.ErrorCode",
                                -static_cast<int>(error_code),
                                1 - BROTLI_LAST_ERROR_CODE);
    }

    // All code here is for gathering stats, and can be removed when
    // BrotliSourceStream is considered stable.
    const int kBuckets = 48;
    const int64_t kMaxKb = 1 << (kBuckets / 3);  // 64MiB in KiB
    UMA_HISTOGRAM_CUSTOM_COUNTS("BrotliFilter.UsedMemoryKB",
                                used_memory_maximum_ / 1024, 1, kMaxKb,
                                kBuckets);
  }

 private:
  // Reported in UMA and must be kept in sync with the histograms.xml file.
  enum class DecodingStatus : int {
    DECODING_IN_PROGRESS = 0,
    DECODING_DONE,
    DECODING_ERROR,

    DECODING_STATUS_COUNT
    // DECODING_STATUS_COUNT must always be the last element in this enum.
  };

  // SourceStream implementation
  std::string GetTypeAsString() const override { return kBrotli; }

  int FilterData(IOBuffer* output_buffer,
                 int output_buffer_size,
                 IOBuffer* input_buffer,
                 int input_buffer_size,
                 int* consumed_bytes,
                 bool /*upstream_eof_reached*/) override {
    if (decoding_status_ == DecodingStatus::DECODING_DONE) {
      *consumed_bytes = input_buffer_size;
      return OK;
    }

    if (decoding_status_ != DecodingStatus::DECODING_IN_PROGRESS)
      return ERR_CONTENT_DECODING_FAILED;

    const uint8_t* next_in = bit_cast<uint8_t*>(input_buffer->data());
    size_t available_in = input_buffer_size;
    uint8_t* next_out = bit_cast<uint8_t*>(output_buffer->data());
    size_t available_out = output_buffer_size;
    // Check if start of the input stream looks like gzip stream.
    for (size_t i = consumed_bytes_; i < sizeof(kGzipHeader); ++i) {
      if (!gzip_header_detected_)
        break;
      size_t j = i - consumed_bytes_;
      if (j < available_in && kGzipHeader[i] != next_in[j])
        gzip_header_detected_ = false;
    }

    BrotliDecoderResult result =
        BrotliDecoderDecompressStream(brotli_state_, &available_in, &next_in,
                                      &available_out, &next_out, nullptr);

    size_t bytes_used = input_buffer_size - available_in;
    size_t bytes_written = output_buffer_size - available_out;
    CHECK_GE(bytes_used, 0u);
    CHECK_GE(bytes_written, 0u);
    produced_bytes_ += bytes_written;
    consumed_bytes_ += bytes_used;

    *consumed_bytes = bytes_used;

    switch (result) {
      case BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:
        return bytes_written;
      case BROTLI_DECODER_RESULT_SUCCESS:
        decoding_status_ = DecodingStatus::DECODING_DONE;
        // Consume remaining bytes to avoid DCHECK in FilterSourceStream.
        // See crbug.com/659311.
        *consumed_bytes = input_buffer_size;
        return bytes_written;
      case BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:
        // Decompress needs more input has consumed all existing input.
        DCHECK_EQ(*consumed_bytes, input_buffer_size);
        decoding_status_ = DecodingStatus::DECODING_IN_PROGRESS;
        return bytes_written;
      // If the decompressor threw an error, fail synchronously.
      default:
        decoding_status_ = DecodingStatus::DECODING_ERROR;
        return ERR_CONTENT_DECODING_FAILED;
    }
  }

  static void* AllocateMemory(void* opaque, size_t size) {
    BrotliSourceStream* filter = reinterpret_cast<BrotliSourceStream*>(opaque);
    return filter->AllocateMemoryInternal(size);
  }

  static void FreeMemory(void* opaque, void* address) {
    BrotliSourceStream* filter = reinterpret_cast<BrotliSourceStream*>(opaque);
    filter->FreeMemoryInternal(address);
  }

  void* AllocateMemoryInternal(size_t size) {
    size_t* array =
        reinterpret_cast<size_t*>(SbMemoryAllocate(size + sizeof(size_t)));
    if (!array)
      return nullptr;
    used_memory_ += size;
    if (used_memory_maximum_ < used_memory_)
      used_memory_maximum_ = used_memory_;
    array[0] = size;
    return &array[1];
  }

  void FreeMemoryInternal(void* address) {
    if (!address)
      return;
    size_t* array = reinterpret_cast<size_t*>(address);
    used_memory_ -= array[-1];
    SbMemoryDeallocate(&array[-1]);
  }

  BrotliDecoderState* brotli_state_;

  DecodingStatus decoding_status_;

  size_t used_memory_;
  size_t used_memory_maximum_;
  size_t consumed_bytes_;
  size_t produced_bytes_;

  bool gzip_header_detected_;

  DISALLOW_COPY_AND_ASSIGN(BrotliSourceStream);
};

}  // namespace

std::unique_ptr<FilterSourceStream> CreateBrotliSourceStream(
    std::unique_ptr<SourceStream> previous) {
  return std::make_unique<BrotliSourceStream>(std::move(previous));
}

}  // namespace net


text:
"""
__M2ThenClausePart1IsolatedConnected_MDL.py_____________________________________________________

Automatically generated AToM3 Model File (Do not modify directly)
Author: gehan
Modified: Fri Oct 18 20:45:26 2013
________________________________________________________________________________________________
"""
from stickylink import *
from widthXfillXdecoration import *
from LHS import *
from graph_LHS import *
from ATOM3Enum import *
from ATOM3String import *
from ATOM3BottomType import *
from ATOM3Constraint import *
from ATOM3Attribute import *
from ATOM3Float import *
from ATOM3List import *
from ATOM3Link import *
from ATOM3Connection import *
from ATOM3Boolean import *
from ATOM3Appearance import *
from ATOM3Text import *
from ATOM3Action import *
from ATOM3Integer import *
from ATOM3Port import *
from ATOM3MSEnum import *

def M2ThenClausePart1IsolatedConnected_MDL(self, rootNode, MoTifRuleRootNode=None):

    # --- Generating attributes code for ASG MoTifRule ---
    if( MoTifRuleRootNode ):
        # author
        MoTifRuleRootNode.author.setValue('Annonymous')

        # description
        MoTifRuleRootNode.description.setValue('\n')
        MoTifRuleRootNode.description.setHeight(15)

        # name
        MoTifRuleRootNode.name.setValue('M2ThenClausePart1IsolatedConnected')
    # --- ASG attributes over ---

    self.obj17960=LHS(self)
    self.obj17960.isGraphObjectVisual = True

    if(hasattr(self.obj17960, '_setHierarchicalLink')):
      self.obj17960._setHierarchicalLink(False)

    # constraint
    self.obj17960.constraint.setValue('#===============================================================================\n# This code is executed after the nodes in the LHS have been matched.\n# You can access a matched node labelled n by: PreNode(\'n\').\n# To access attribute x of node n, use: PreNode(\'n\')[\'x\'].\n# The given constraint must evaluate to a boolean expression:\n#    returning True enables the rule to be applied,\n#    returning False forbids the rule from being applied.\n#===============================================================================\n\nreturn True\n')
    self.obj17960.constraint.setHeight(15)

    self.obj17960.graphClass_= graph_LHS
    if self.genGraphics:
       new_obj = graph_LHS(160.0,100.0,self.obj17960)
       new_obj.DrawObject(self.UMLmodel)
       self.UMLmodel.addtag_withtag("LHS", new_obj.tag)
       new_obj.layConstraints = dict() # Graphical Layout Constraints
       new_obj.layConstraints['scale'] = [1.0, 1.0]
    else: new_obj = None
    self.obj17960.graphObject_ = new_obj

    # Add node to the root: rootNode
    rootNode.addNode(self.obj17960)
    self.globalAndLocalPostcondition(self.obj17960, rootNode)
    self.obj17960.postAction( rootNode.CREATE )

    # Connections for obj17960 (graphObject_: Obj44) of type LHS
    self.drawConnections(
 )

newfunction = M2ThenClausePart1IsolatedConnected_MDL

loadedMMName = 'MoTifRule_META'

atom3version = '0.3'

redpajama_set_name: RedPajamaGithub


text:
#ifndef PARTBUNDLE_H
#define PARTBUNDLE_H

#include "pandabase.h"

#include "partGroup.h"
#include "animControl.h"
#include "partSubset.h"
#include "animPreloadTable.h"
#include "pointerTo.h"
#include "thread.h"
#include "cycleData.h"
#include "cycleDataLockedReader.h"
#include "cycleDataReader.h"
#include "cycleDataWriter.h"
#include "luse.h"
#include "pvector.h"
#include "transformState.h"
#include "weakPointerTo.h"
#include "copyOnWritePointer.h"

class Loader;
class AnimBundle;
class PartBundleNode;
class PartBundleNode;
class TransformState;
class AnimPreloadTable;

/**
 * This is the root of a MovingPart hierarchy.  It defines the hierarchy of
 * moving parts that make up an animatable object.
 */
class EXPCL_PANDA_CHAN PartBundle : public PartGroup {
public:

  // This is passed down through the MovingParts during the do_update() call
  // to specify the channels that are in effect.
  typedef pmap<AnimControl *, PN_stdfloat> ChannelBlend;

protected:
  // The copy constructor is protected; use make_copy() or copy_subgraph().
  PartBundle(const PartBundle &copy);

PUBLISHED:
  PartBundle(const string &name = "");
  virtual PartGroup *make_copy() const;

  INLINE CPT(AnimPreloadTable) get_anim_preload() const;
  INLINE PT(AnimPreloadTable) modify_anim_preload();
  INLINE void set_anim_preload(AnimPreloadTable *table);
  INLINE void clear_anim_preload();
  void merge_anim_preloads(const PartBundle *other);

  // This is the parameter to set_blend_type() and specifies the kind of
  // blending operation to be performed when multiple controls are in effect
  // simultaneously (see set_control_effect()) or between sequential frames of
  // the animation.
  enum BlendType {
    // BT_linear does a componentwise average of all blended matrices, which
    // is a linear blend.  The result of this is that if a particular vertex
    // would have been at point P in one animation and point Q in another one,
    // it will end up on the line in between them in the resulting blend
    // animation.  However, this tends to stretch and squash limbs in strange
    // and disturbing ways.
    BT_linear,

    // BT_normalized_linear is a compromise on BT_linear.  The matrix is
    // blended linearly without the scale and shear components, and the
    // blended scale and shear components are applied separately.  This keeps
    // all of the character's body parts in the correct size and shape.
    // However, if the hierarchy is disconnected, body parts can fly off.
    // It's essential the skeleton hierarchy be completely connected to use
    // this blend mode successully.
    BT_normalized_linear,

    // BT_componentwise linearly blends all components separately, including
    // H, P, and R, and recomposes the matrix.
    BT_componentwise,

    // BT_componentwise_quat linearly blends all components separately, except
    // for rotation which is blended as a quaternion.
    BT_componentwise_quat,
  };

  INLINE void set_blend_type(BlendType bt);
  INLINE BlendType get_blend_type() const;

  void set_anim_blend_flag(bool anim_blend_flag);
  INLINE bool get_anim_blend_flag() const;

  INLINE void set_frame_blend_flag(bool frame_blend_flag);
  INLINE bool get_frame_blend_flag() const;

  INLINE void set_root_xform(const LMatrix4 &root_xform);
  INLINE void xform(const LMatrix4 &mat);
  INLINE const LMatrix4 &get_root_xform() const;
  PT(PartBundle) apply_transform(const TransformState *transform);

  INLINE int get_num_nodes() const;
  INLINE PartBundleNode *get_node(int n) const;
  MAKE_SEQ(get_nodes, get_num_nodes, get_node);

  void clear_control_effects();
  INLINE void set_control_effect(AnimControl *control, PN_stdfloat effect);
  INLINE PN_stdfloat get_control_effect(AnimControl *control) const;

  virtual void output(ostream &out) const;
  virtual void write(ostream &out, int indent_level) const;

  PT(AnimControl) bind_anim(AnimBundle *anim,
                            int hierarchy_match_flags = 0,
                            const PartSubset &subset = PartSubset());
  PT(AnimControl) load_bind_anim(Loader *loader,
                                 const Filename &filename,
                                 int hierarchy_match_flags,
                                 const PartSubset &subset,
                                 bool allow_async);
  void wait_pending();

  bool freeze_joint(const string &joint_name, const TransformState *transform);
  bool freeze_joint(const string &joint_name, const LVecBase3 &pos, const LVecBase3 &hpr, const LVecBase3 &scale);
  bool freeze_joint(const string &joint_name, PN_stdfloat value);
  bool control_joint(const string &joint_name, PandaNode *node);
  bool release_joint(const string &joint_name);

  bool update();
  bool force_update();

public:
  // The following functions aren't really part of the public interface;
  // they're just public so we don't have to declare a bunch of friends.
  virtual void control_activated(AnimControl *control);
  INLINE void set_update_delay(double delay);

  bool do_bind_anim(AnimControl *control, AnimBundle *anim,
                    int hierarchy_match_flags, const PartSubset &subset);

protected:
  virtual void add_node(PartBundleNode *node);
  virtual void remove_node(PartBundleNode *node);

private:
  class CData;

  void do_set_control_effect(AnimControl *control, PN_stdfloat effect, CData *cdata);
  PN_stdfloat do_get_control_effect(AnimControl *control, const CData *cdata) const;
  void recompute_net_blend(CData *cdata);
  void clear_and_stop_intersecting(AnimControl *control, CData *cdata);

  COWPT(AnimPreloadTable) _anim_preload;

  typedef pvector<PartBundleNode *> Nodes;
  Nodes _nodes;

  typedef pmap<WCPT(TransformState), WPT(PartBundle) > AppliedTransforms;
  AppliedTransforms _applied_transforms;

  double _update_delay;

  // This is the data that must be cycled between pipeline stages.
  class CData : public CycleData {
  public:
    CData();
    CData(const CData &copy);

    virtual CycleData *make_copy() const;
    virtual void write_datagram(BamWriter *manager, Datagram &dg) const;
    virtual void fillin(DatagramIterator &scan, BamReader *manager);
    virtual TypeHandle get_parent_type() const {
      return PartBundle::get_class_type();
    }

    BlendType _blend_type;
    bool _anim_blend_flag;
    bool _frame_blend_flag;
    LMatrix4 _root_xform;
    AnimControl *_last_control_set;
    ChannelBlend _blend;
    PN_stdfloat _net_blend;
    bool _anim_changed;
    double _last_update;
  };

  PipelineCycler<CData> _cycler;
  typedef CycleDataLockedReader<CData> CDLockedReader;
  typedef CycleDataReader<CData> CDReader;
  typedef CycleDataWriter<CData> CDWriter;

public:
  static void register_with_read_factory();
  virtual void finalize(BamReader *manager);
  virtual void write_datagram(BamWriter *manager, Datagram &dg);
  virtual int complete_pointers(TypedWritable **p_list,
                                BamReader *manager);

protected:
  static TypedWritable *make_from_bam(const FactoryParams &params);
  void fillin(DatagramIterator &scan, BamReader *manager);

public:

  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    PartGroup::init_type();
    register_type(_type_handle, "PartBundle",
                  PartGroup::get_class_type());
  }

private:
  static TypeHandle _type_handle;

  friend class PartBundleNode;
  friend class Character;
  friend class MovingPartBase;
  friend class MovingPartMatrix;
  friend class MovingPartScalar;
};

inline ostream &operator <<(ostream &out, const PartBundle &bundle) {
  bundle.output(out);
  return out;
}

ostream &operator <<(ostream &out, PartBundle::BlendType blend_type);
istream &operator >>(istream &in, PartBundle::BlendType &blend_type);

#include "partBundle.I"

#endif


text:
package org.cloudfoundry.reactor.client.v2.serviceinstances;

import org.cloudfoundry.client.v2.serviceinstances.BindServiceInstanceToRouteRequest;
import org.cloudfoundry.client.v2.serviceinstances.BindServiceInstanceToRouteResponse;
import org.cloudfoundry.client.v2.serviceinstances.CreateServiceInstanceRequest;
import org.cloudfoundry.client.v2.serviceinstances.CreateServiceInstanceResponse;
import org.cloudfoundry.client.v2.serviceinstances.DeleteServiceInstanceRequest;
import org.cloudfoundry.client.v2.serviceinstances.DeleteServiceInstanceResponse;
import org.cloudfoundry.client.v2.serviceinstances.GetServiceInstancePermissionsRequest;
import org.cloudfoundry.client.v2.serviceinstances.GetServiceInstancePermissionsResponse;
import org.cloudfoundry.client.v2.serviceinstances.GetServiceInstanceRequest;
import org.cloudfoundry.client.v2.serviceinstances.GetServiceInstanceResponse;
import org.cloudfoundry.client.v2.serviceinstances.ListServiceInstanceServiceBindingsRequest;
import org.cloudfoundry.client.v2.serviceinstances.ListServiceInstanceServiceBindingsResponse;
import org.cloudfoundry.client.v2.serviceinstances.ListServiceInstanceServiceKeysRequest;
import org.cloudfoundry.client.v2.serviceinstances.ListServiceInstanceServiceKeysResponse;
import org.cloudfoundry.client.v2.serviceinstances.ListServiceInstancesRequest;
import org.cloudfoundry.client.v2.serviceinstances.ListServiceInstancesResponse;
import org.cloudfoundry.client.v2.serviceinstances.ServiceInstances;
import org.cloudfoundry.client.v2.serviceinstances.UpdateServiceInstanceRequest;
import org.cloudfoundry.client.v2.serviceinstances.UpdateServiceInstanceResponse;
import org.cloudfoundry.reactor.ConnectionContext;
import org.cloudfoundry.reactor.TokenProvider;
import org.cloudfoundry.reactor.client.v2.AbstractClientV2Operations;
import reactor.core.publisher.Mono;

/**
 * The Reactor-based implementation of {@link ServiceInstances}
 */
public final class ReactorServiceInstances extends AbstractClientV2Operations implements ServiceInstances {

    /**
     * Creates an instance
     *
     * @param connectionContext the {@link ConnectionContext} to use when communicating with the server
     * @param root              the root URI of the server.  Typically something like {@code https://api.run.pivotal.io}.
     * @param tokenProvider     the {@link TokenProvider} to use when communicating with the server
     */
    public ReactorServiceInstances(ConnectionContext connectionContext, Mono<String> root, TokenProvider tokenProvider) {
        super(connectionContext, root, tokenProvider);
    }

    @Override
    public Mono<BindServiceInstanceToRouteResponse> bindToRoute(BindServiceInstanceToRouteRequest request) {
        return put(request, BindServiceInstanceToRouteResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId(), "routes", request.getRouteId()));
    }

    @Override
    public Mono<CreateServiceInstanceResponse> create(CreateServiceInstanceRequest request) {
        return post(request, CreateServiceInstanceResponse.class, builder -> builder.pathSegment("v2", "service_instances"));
    }

    @Override
    public Mono<DeleteServiceInstanceResponse> delete(DeleteServiceInstanceRequest request) {
        return delete(request, DeleteServiceInstanceResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId()));
    }

    @Override
    public Mono<GetServiceInstanceResponse> get(GetServiceInstanceRequest request) {
        return get(request, GetServiceInstanceResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId()));
    }

    @Override
    public Mono<GetServiceInstancePermissionsResponse> getPermissions(GetServiceInstancePermissionsRequest request) {
        return get(request, GetServiceInstancePermissionsResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId(), "permissions"));
    }

    @Override
    public Mono<ListServiceInstancesResponse> list(ListServiceInstancesRequest request) {
        return get(request, ListServiceInstancesResponse.class, builder -> builder.pathSegment("v2", "service_instances"));
    }

    @Override
    public Mono<ListServiceInstanceServiceBindingsResponse> listServiceBindings(ListServiceInstanceServiceBindingsRequest request) {
        return get(request, ListServiceInstanceServiceBindingsResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId(), "service_bindings"));
    }

    @Override
    public Mono<ListServiceInstanceServiceKeysResponse> listServiceKeys(ListServiceInstanceServiceKeysRequest request) {
        return get(request, ListServiceInstanceServiceKeysResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId(), "service_keys"));
    }

    @Override
    public Mono<UpdateServiceInstanceResponse> update(UpdateServiceInstanceRequest request) {
        return put(request, UpdateServiceInstanceResponse.class, builder -> builder.pathSegment("v2", "service_instances", request.getServiceInstanceId()));
    }

}


text:
from random import random

def move_cars(car_positions):
    return map(lambda x: x + 1 if random() > 0.3 else x,
               car_positions)

def output_car(car_position):
    return '-' * car_position

def run_step_of_race(state):
    return {'time': state['time'] - 1,
            'car_positions': move_cars(state['car_positions'])}

def draw(state):
    print('')
    print('\n'.join(map(output_car, state['car_positions'])))

def race(state):
    draw(state)
    if state['time']:
        race(run_step_of_race(state))

race({'time': 5,
      'car_positions': [1, 1, 1]})


text:
import Vue from 'vue'
import toString from 'lodash-es/toString'
import config from 'config'
import i18n from '@vue-storefront/i18n'
import store from '@vue-storefront/core/store'
import EventBus from '@vue-storefront/core/compatibility/plugins/event-bus'
import { baseFilterProductsQuery, buildFilterProductsQuery, isServer } from '@vue-storefront/core/helpers'
import { htmlDecode } from '@vue-storefront/core/filters/html-decode'
import { currentStoreView, localizedRoute } from '@vue-storefront/core/lib/multistore'
import Composite from '@vue-storefront/core/mixins/composite'
import { Logger } from '@vue-storefront/core/lib/logger'
import { mapGetters, mapActions } from 'vuex'
import onBottomScroll from '@vue-storefront/core/mixins/onBottomScroll'

export default {
  name: 'Category',
  mixins: [Composite, onBottomScroll],
  data () {
    return {
      pagination: {
        perPage: 50,
        current: 0,
        enabled: false
      },
      lazyLoadProductsOnscroll: true
    }
  },
  computed: {
    ...mapGetters('category', ['getCurrentCategory', 'getCurrentCategoryProductQuery', 'getAllCategoryFilters', 'getCategoryBreadcrumbs', 'getCurrentCategoryPath']),
    ...mapGetters('tax', ['getIsUserGroupedTaxActive']),
    products () {
      return this.$store.getters['product/list']
    },
    productsCounter () {
      return this.products ? this.products.length : 0
    },
    productsTotal () {
      return this.$store.state.product.list.total
    },
    currentQuery () {
      return this.getCurrentCategoryProductQuery
    },
    isCategoryEmpty () {
      return (!(this.products) || this.products.length === 0)
    },
    category () {
      return this.getCurrentCategory
    },
    categoryName () {
      return this.getCurrentCategory ? this.getCurrentCategory.name : ''
    },
    categoryId () {
      return this.getCurrentCategory ? this.getCurrentCategory.id : ''
    },
    filters () {
      return this.getAllCategoryFilters
    },
    breadcrumbs () {
      return this.getCategoryBreadcrumbs
    }
  },
  preAsyncData ({ store, route }) {
    Logger.log('preAsyncData query setup')()
    const currentProductQuery = store.getters['category/getCurrentCategoryProductQuery']
    const sort = currentProductQuery && currentProductQuery.sort ? currentProductQuery.sort : config.entities.productList.sort
    store.dispatch('category/setSearchOptions', {
      populateAggregations: true,
      store: store,
      route: route,
      current: 0,
      perPage: 50,
      sort,
      filters: config.products.defaultFilters,
      includeFields: config.entities.optimize && isServer ? config.entities.productList.includeFields : null,
      excludeFields: config.entities.optimize && isServer ? config.entities.productList.excludeFields : null,
      append: false
    })
  },
  async asyncData ({ store, route, context }) { // this is for SSR purposes to prefetch data
    Logger.info('Entering asyncData in Category Page (core)')()
    try {
      if (context) context.output.cacheTags.add(`category`)
      const defaultFilters = config.products.defaultFilters
      store.dispatch('category/resetFilters')
      EventBus.$emit('filter-reset')
      const parentCategory = await store.dispatch('category/single', { key: config.products.useMagentoUrlKeys ? 'url_key' : 'slug', value: route.params.slug })
      let query = store.getters['category/getCurrentCategoryProductQuery']
      if (!query.searchProductQuery) {
        store.dispatch('category/mergeSearchOptions', {
          searchProductQuery: baseFilterProductsQuery(parentCategory, defaultFilters)
        })
      }
      const subloaders = await store.dispatch('category/products', query)
      if (subloaders) {
        await Promise.all(subloaders)
        await EventBus.$emitFilter('category-after-load', { store: store, route: route })
      } else {
        throw new Error('Category query returned empty result')
      }
    } catch (err) {
      Logger.error(err)()
      throw err
    }
  },
  async beforeRouteEnter (to, from, next) {
    if (!isServer && !from.name) { // Loading category products to cache on SSR render
      next(vm => {
        const defaultFilters = config.products.defaultFilters
        let parentCategory = store.getters['category/getCurrentCategory']
        let query = store.getters['category/getCurrentCategoryProductQuery']
        if (!query.searchProductQuery) {
          store.dispatch('category/mergeSearchOptions', {
            searchProductQuery: baseFilterProductsQuery(parentCategory, defaultFilters),
            cacheOnly: true// this is cache only request
          })
        }
        store.dispatch('category/products', query)
      })
    } else {
      next()
    }
  },
  beforeMount () {
    this.$bus.$on('filter-changed-category', this.onFilterChanged)
    this.$bus.$on('list-change-sort', this.onSortOrderChanged)
    if (config.usePriceTiers || this.getIsUserGroupedTaxActive) {
      this.$bus.$on('user-after-loggedin', this.onUserPricesRefreshed)
      this.$bus.$on('user-after-logout', this.onUserPricesRefreshed)
    }
  },
  beforeDestroy () {
    this.$bus.$off('list-change-sort', this.onSortOrderChanged)
    this.$bus.$off('filter-changed-category', this.onFilterChanged)
    if (config.usePriceTiers || this.getIsUserGroupedTaxActive) {
      this.$bus.$off('user-after-loggedin', this.onUserPricesRefreshed)
      this.$bus.$off('user-after-logout', this.onUserPricesRefreshed)
    }
  },
  beforeRouteUpdate (to, from, next) {
    this.validateRoute(to)
    next()
  },
  methods: {
    ...mapActions('category', ['mergeSearchOptions']),
    onBottomScroll () {
      this.pullMoreProducts()
    },
    bottomVisible () {
      const scrollY = Math.ceil(window.scrollY)
      const visible = window.innerHeight
      const pageHeight = document.documentElement.scrollHeight
      const bottomOfPage = visible + scrollY >= pageHeight
      return bottomOfPage || pageHeight < visible
    },
    pullMoreProducts () {
      if (typeof navigator !== 'undefined' && !navigator.onLine) return
      let current = this.getCurrentCategoryProductQuery.current + this.getCurrentCategoryProductQuery.perPage
      this.mergeSearchOptions({
        append: true,
        route: this.$route,
        store: this.$store,
        current
      })
      this.pagination.current = this.getCurrentCategoryProductQuery.current
      this.pagination.perPage = this.getCurrentCategoryProductQuery.perPage
      if (this.getCurrentCategoryProductQuery.current <= this.productsTotal) {
        this.mergeSearchOptions({
          searchProductQuery: buildFilterProductsQuery(this.category, this.filters.chosen)
        })
        return this.$store.dispatch('category/products', this.getCurrentCategoryProductQuery)
      }
    },
    onFilterChanged (filterOption) {
      this.pagination.current = 0
      if (this.filters.chosen[filterOption.attribute_code] && ((toString(filterOption.id) === toString(this.filters.chosen[filterOption.attribute_code].id)) || filterOption.id === this.filters.chosen[filterOption.attribute_code].id)) { // for price filter it's a string
        Vue.delete(this.filters.chosen, filterOption.attribute_code)
      } else {
        Vue.set(this.filters.chosen, filterOption.attribute_code, filterOption)
      }

      let filterQr = buildFilterProductsQuery(this.category, this.filters.chosen)

      const filtersConfig = Object.assign({}, this.filters.chosen) // create a copy because it will be used asynchronously (take a look below)
      this.mergeSearchOptions({
        populateAggregations: false,
        searchProductQuery: filterQr,
        current: this.pagination.current,
        perPage: this.pagination.perPage,
        configuration: filtersConfig,
        append: false,
        includeFields: null,
        excludeFields: null
      })
      this.$store.dispatch('category/products', this.getCurrentCategoryProductQuery).then((res) => {
      }) // because already aggregated
    },
    onSortOrderChanged (param) {
      this.pagination.current = 0
      if (param.attribute) {
        const filtersConfig = Object.assign({}, this.filters.chosen) // create a copy because it will be used asynchronously (take a look below)
        let filterQr = buildFilterProductsQuery(this.category, this.filters.chosen)
        this.mergeSearchOptions({
          sort: param.attribute,
          searchProductQuery: filterQr,
          current: this.pagination.current,
          perPage: this.pagination.perPage,
          configuration: filtersConfig,
          append: false,
          includeFields: null,
          excludeFields: null
        })
        this.$store.dispatch('category/products', this.getCurrentCategoryProductQuery).then((res) => {
        })
      } else {
        this.notify()
      }
    },
    validateRoute (route = this.$route) {
      this.$store.dispatch('category/resetFilters')
      this.$bus.$emit('filter-reset')

      this.$store.dispatch('category/single', { key: config.products.useMagentoUrlKeys ? 'url_key' : 'slug', value: route.params.slug }).then(category => {
        if (!category) {
          this.$router.push(this.localizedRoute('/'))
        } else {
          this.pagination.current = 0
          let searchProductQuery = baseFilterProductsQuery(this.getCurrentCategory, config.products.defaultFilters)
          this.$bus.$emit('current-category-changed', this.getCurrentCategoryPath)
          this.mergeSearchOptions({ // base prototype from the asyncData is being used here
            current: this.pagination.current,
            perPage: this.pagination.perPage,
            store: this.$store,
            route: this.$route,
            append: false,
            populateAggregations: true
          })
          if (!this.getCurrentCategoryProductQuery.searchProductQuery) {
            this.mergeSearchOptions({
              searchProductQuery
            })
          }
          this.$store.dispatch('category/products', this.getCurrentCategoryProductQuery)
          this.$bus.$emitFilter('category-after-load', { store: this.$store, route: route })
        }
      }).catch(err => {
        if (err.message.indexOf('query returned empty result') > 0) {
          this.$store.dispatch('notification/spawnNotification', {
            type: 'error',
            message: i18n.t('The product, category or CMS page is not available in Offline mode. Redirecting to Home.'),
            action1: { label: i18n.t('OK') }
          })
          this.$router.push(localizedRoute('/', currentStoreView().storeCode))
        }
      })
    },
    onUserPricesRefreshed () {
      const defaultFilters = config.products.defaultFilters
      this.$store.dispatch('category/single', {
        key: config.products.useMagentoUrlKeys ? 'url_key' : 'slug',
        value: this.$route.params.slug
      }).then((parentCategory) => {
        if (!this.getCurrentCategoryProductQuery.searchProductQuery) {
          this.mergeSearchOptions({
            searchProductQuery: baseFilterProductsQuery(parentCategory, defaultFilters),
            skipCache: true
          })
        }
        this.$store.dispatch('category/products', this.getCurrentCategoryProductQuery)
      })
    }
  },
  metaInfo () {
    const storeView = currentStoreView()
    return {
      /* link: [
        { rel: 'amphtml',
          href: this.$router.resolve(localizedRoute({
            name: 'category-amp',
            params: {
              slug: this.category.slug
            }
          }, storeView.storeCode)).href
        }
      ], */
      title: htmlDecode(this.category.meta_title || this.categoryName),
      meta: this.category.meta_description ? [{ vmid: 'description', name: 'description', content: htmlDecode(this.category.meta_description) }] : []
    }
  }
}


text:
<?php

namespace mdagostino\MultipleChoiceExams\Question;

use mdagostino\MultipleChoiceExams\Exception\InvalidAnswerException;

class Question implements QuestionInterface {

  // An object that will determinate if this question is or is not correct.
  protected $question_evaluator;

  // The information about this question, like title, explanation, etc.
  protected $info;

  // A keyed pair of key => text options where text is represent a possible
  // answer to this question.
  protected $choices = array();

  // An array of keys to identify the right answers of this question.
  protected $right_choices = array();

  // The selected options by the user to this question.
  protected $chossen_answers = array();

  public function __construct(QuestionEvaluatorInterface $question_evaluator, QuestionInfoInterface $info = NULL) {
    $this->question_evaluator = $question_evaluator;

    $this->info = $info;
  }

  /**
   * Return TRUE if the user already defined an answer for this question.
   *
   * @return boolean
   */
  public function wasAnswered() {
    return count($this->getAnswers()) > 0;
  }

  /**
   * Answer a this question using the answers defined by the user.
   *
   * @param  array $keys
   *   An array of ids that represent the options chossed by the user
   */
  public function answer(array $keys) {
    $invalid_keys = array_diff($keys, $this->getChoices());

    if (!empty($invalid_keys)) {
      $invalid = implode(', ', $invalid_keys);
      $valid = implode(', ', $this->getChoices());

      throw new InvalidAnswerException(
        "You cannot use the keys ($invalid) as a valid choices. Valid choices are: ($valid)"
      );
    }

    $this->chossen_answers = $keys;
    return $this;
  }

  /**
   * Reset the status of this question. This questions was never answered.
   */
  public function resetAnswer() {
    $this->chossen_answers = array();
  }

  public function isCorrect() {
    if (! $this->wasAnswered()) {
      return FALSE;
    }
    return $this->getQuestionEvaluator()->isCorrect($this);
  }

  public function setChoices(array $choices) {
    // Only save the keys on this object to reduce memory usage
    $this->choices = array_keys($choices);
    // Swapping the QuestionInfo interface could be used to retrive the info
    // from another source like a database.
    $this->getInfo()->setChoicesDescriptions($choices);

    if (isset($this->right_choices)) {
      $this->validateIntegrity();
    }
    return $this;
  }

  public function getChoices() {
    return $this->choices;
  }

  public function setRightChoices(array $right_choices) {
    $this->right_choices = $right_choices;

    if (isset($this->choices)) {
      $this->validateIntegrity();
    }
    return $this;
  }

  public function getRightChoices() {
    return $this->right_choices;
  }

  protected function validateIntegrity() {
    $invalid_keys = array_diff($this->right_choices, $this->choices);

    if (!empty($invalid_keys)) {
      $invalid = implode(', ', $invalid_keys);
      $valid = implode(', ', $this->choices);

      throw new InvalidAnswerException(
        "You cannot use the keys ($invalid) as a valid choices. Valid choices are: ($valid)"
      );
    }
  }

  public function getAnswers() {
    return $this->chossen_answers;
  }

  public function getInfo() {
    return $this->info;
  }

  public function getQuestionEvaluator() {
    return $this->question_evaluator;
  }

  public function __call($method, $arguments) {

    $method_to_call = array($this->info, $method);

    if (! is_callable($method_to_call, FALSE)) {
      throw new \Exception("There is no method called " . $method);
    }

    $return = call_user_func_array(array($this->info, $method), $arguments);

    if ($return === $this->info) {
      return $this;
    }
    return $return;
  }
}


text:
<?php

namespace AssetManagerTest\Service;

use AssetManager\Service\AssetCacheManager;
use AssetManager\Service\AssetFilterManager;
use PHPUnit_Framework_TestCase;
use AssetManager\Service\AssetManagerServiceFactory;
use Zend\ServiceManager\ServiceManager;

class AssetManagerServiceFactoryTest extends PHPUnit_Framework_TestCase
{
    public function testCreateService()
    {
        $assetFilterManager = new AssetFilterManager();
        $assetCacheManager = new AssetCacheManager();
        $serviceManager = new ServiceManager();
        $serviceManager->setService(
            'AssetManager\Service\AggregateResolver',
            $this->getMock('AssetManager\Resolver\ResolverInterface')
        );

        $serviceManager->setService(
            'AssetManager\Service\AssetFilterManager',
            $assetFilterManager
        );

        $serviceManager->setService(
            'AssetManager\Service\AssetCacheManager',
            $assetCacheManager
        );

        $serviceManager->setService('Config', array(
            'asset_manager' => array(
                'Dummy data',
                'Bacon',
            ),
        ));

        $factory = new AssetManagerServiceFactory();
        $this->assertInstanceOf('AssetManager\Service\AssetManager', $factory->createService($serviceManager));
    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-1105',
  templateUrl: './comp-1105.component.html',
  styleUrls: ['./comp-1105.component.css']
})
export class Comp1105Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
'use strict';

import * as React from 'react';
import {useCallback, useEffect, useReducer} from 'react';
import {FlatList, StyleSheet, Text, View} from 'react-native';

import RNTesterPage from '../../components/RNTesterPage';
import type {RNTesterModuleExample} from '../../types/RNTesterTypes';

type OuterItem = 'head' | 'vertical' | 'horizontal' | 'filler';

const outerItems: OuterItem[] = [
  'head',
  'vertical',
  'filler',
  'horizontal',
  'filler',
  'vertical',
];

const items = [1, 2, 3, 4, 5];

type ItemsState = {
  renderedItems: number[],
  viewableItems: number[],
};

const initialItemsState: ItemsState = {
  renderedItems: [],
  viewableItems: [],
};

type ItemsAction = {
  type: 'add-rendered' | 'add-viewable' | 'remove-rendered' | 'remove-viewable',
  item: number,
};

function reducer(state: ItemsState, action: ItemsAction): ItemsState {
  if (action.type === 'add-rendered') {
    if (state.renderedItems.includes(action.item)) {
      return state;
    } else {
      return {...state, renderedItems: [...state.renderedItems, action.item]};
    }
  } else if (action.type === 'add-viewable') {
    if (state.viewableItems.includes(action.item)) {
      return state;
    } else {
      return {...state, viewableItems: [...state.viewableItems, action.item]};
    }
  } else if (action.type === 'remove-rendered') {
    return {
      ...state,
      renderedItems: state.renderedItems.filter(i => i !== action.item),
    };
  } else if (action.type === 'remove-viewable') {
    return {
      ...state,
      viewableItems: state.viewableItems.filter(i => i !== action.item),
    };
  }

  return state;
}

function NestedListExample(): React.Node {
  const [outer, dispatchOuter] = useReducer(reducer, initialItemsState);
  const [inner, dispatchInner] = useReducer(reducer, initialItemsState);

  const onViewableItemsChanged = useCallback(
    ({changed}) => {
      for (const token of changed) {
        dispatchOuter({
          type: token.isViewable ? 'add-viewable' : 'remove-viewable',
          item: token.index ?? -1,
        });
      }
    },
    [dispatchOuter],
  );

  return (
    <RNTesterPage noSpacer={true} noScroll={true}>
      <Text style={styles.debugText}>
        <Text style={styles.debugTextHeader}>Outer Viewable:{'\n'}</Text>
        {outerItems
          .map((item, i) => ({item, i}))
          .filter(o => outer.viewableItems.includes(o.i))
          .map(({item, i}) => `${i} (${item})`)
          .join(', ')}
      </Text>
      <Text style={styles.debugText}>
        <Text style={styles.debugTextHeader}>Outer Rendered:{'\n'}</Text>
        {outerItems
          .map((item, i) => ({item, i}))
          .filter(o => outer.renderedItems.includes(o.i))
          .map(({item, i}) => `${i} (${item})`)
          .join(', ')}
      </Text>
      <Text style={styles.debugText}>
        <Text style={styles.debugTextHeader}>Inner Viewable:{'\n'}</Text>
        {inner.viewableItems.sort((a, b) => a - b).join(', ')}
      </Text>
      <Text style={styles.debugText}>
        <Text style={styles.debugTextHeader}>Inner Rendered:{'\n'}</Text>
        {inner.renderedItems.sort((a, b) => a - b).join(', ')}
      </Text>

      <FlatList
        data={outerItems}
        renderItem={({index, item}) => (
          <OuterItemRenderer
            index={index}
            item={item}
            dispatchOuter={dispatchOuter}
            dispatchInner={dispatchInner}
          />
        )}
        style={styles.list}
        windowSize={3}
        initialNumToRender={1}
        onViewableItemsChanged={onViewableItemsChanged}
      />
    </RNTesterPage>
  );
}

function OuterItemRenderer({
  index,
  item,
  dispatchOuter,
  dispatchInner,
}: {
  index: number,
  item: OuterItem,
  dispatchOuter: ItemsAction => void,
  dispatchInner: ItemsAction => void,
  ...
}) {
  useEffect(() => {
    dispatchOuter({
      type: 'add-rendered',
      item: index,
    });

    return () => {
      dispatchOuter({
        type: 'remove-rendered',
        item: index,
      });
    };
  }, [dispatchOuter, index]);

  const onViewableItemsChanged = useCallback(
    ({changed}) => {
      for (const token of changed) {
        dispatchInner({
          type: token.isViewable ? 'add-viewable' : 'remove-viewable',
          item: token.item,
        });
      }
    },
    [dispatchInner],
  );

  switch (item) {
    case 'head':
      return (
        <View style={styles.header}>
          <Text>Header</Text>
        </View>
      );

    case 'vertical':
      return (
        <View style={styles.body}>
          <View style={styles.col}>
            <FlatList
              data={items.map(i => index * items.length * 3 + i)}
              listKey={`${index}-col1`}
              renderItem={p => (
                <InnerItemRenderer
                  item={p.item}
                  dispatchInner={dispatchInner}
                />
              )}
              style={styles.childList}
              onViewableItemsChanged={onViewableItemsChanged}
              windowSize={1}
              initialNumToRender={1}
            />
          </View>
          <View style={styles.col}>
            <FlatList
              data={items.map(i => index * items.length * 3 + i + items.length)}
              listKey={`${index}-col2`}
              renderItem={p => (
                <InnerItemRenderer
                  item={p.item}
                  dispatchInner={dispatchInner}
                />
              )}
              style={styles.childList}
              onViewableItemsChanged={onViewableItemsChanged}
              windowSize={1}
              initialNumToRender={1}
            />
          </View>
        </View>
      );

    case 'horizontal':
      return (
        <View style={styles.row}>
          <FlatList
            horizontal={true}
            data={items.map(
              i => index * items.length * 3 + i + 2 * items.length,
            )}
            renderItem={p => (
              <InnerItemRenderer item={p.item} dispatchInner={dispatchInner} />
            )}
            style={styles.childList}
            onViewableItemsChanged={onViewableItemsChanged}
          />
        </View>
      );

    case 'filler':
      return <View style={styles.filler} />;
  }
}

function InnerItemRenderer({
  item,
  dispatchInner,
}: {
  item: number,
  dispatchInner: ItemsAction => void,
  ...
}) {
  useEffect(() => {
    dispatchInner({
      type: 'add-rendered',
      item: item,
    });

    return () => {
      dispatchInner({
        type: 'remove-rendered',
        item: item,
      });
    };
  }, [dispatchInner, item]);

  return (
    <View style={styles.cell}>
      <View style={styles.item}>
        <Text>{item}</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  debugText: {
    fontSize: 10,
  },
  debugTextHeader: {
    fontWeight: 'bold',
  },
  list: {
    borderWidth: 1,
    borderColor: 'black',
  },
  body: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  col: {
    flex: 1,
    padding: 10,
  },
  row: {
    flex: 1,
  },
  filler: {
    height: 72,
    backgroundColor: 'lightblue',
  },
  childList: {
    backgroundColor: 'lightgreen',
  },
  header: {
    height: 40,
    backgroundColor: 'lightcoral',
    alignItems: 'center',
    justifyContent: 'center',
  },
  cell: {
    padding: 10,
  },
  item: {
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'black',
    backgroundColor: 'oldlace',
    height: 72,
    minWidth: 144,
  },
});

export default ({
  title: 'Nested',
  description: 'Nested FlatLists of same and opposite orientation',
  name: 'nested',
  render: NestedListExample,
}: RNTesterModuleExample);


text:
package org.elasticsearch.indices.settings;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESIntegTestCase;

import java.io.IOException;

import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.equalTo;

@ESIntegTestCase.ClusterScope(minNumDataNodes = 2)
public class UpdateNumberOfReplicasIT extends ESIntegTestCase {
    @Override
    protected int maximumNumberOfReplicas() {
        return 1;
    }

    public void testSimpleUpdateNumberOfReplicas() throws Exception {
        logger.info("Creating index test");
        assertAcked(prepareCreate("test", 2));
        logger.info("Running Cluster Health");
        ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());

        NumShards numShards = getNumShards("test");

        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(numShards.numReplicas));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.totalNumShards));

        for (int i = 0; i < 10; i++) {
            client().prepareIndex("test", "type1", Integer.toString(i)).setSource(jsonBuilder().startObject()
                    .field("value", "test" + i)
                    .endObject()).get();
        }

        refresh();

        for (int i = 0; i < 10; i++) {
            SearchResponse countResponse = client().prepareSearch().setSize(0).setQuery(matchAllQuery()).get();
            assertHitCount(countResponse, 10l);
        }

        logger.info("Increasing the number of replicas from 1 to 2");
        assertAcked(client().admin().indices().prepareUpdateSettings("test").setSettings(settingsBuilder().put("index.number_of_replicas", 2)).execute().actionGet());
        logger.info("Running Cluster Health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().setWaitForActiveShards(numShards.numPrimaries * 2).execute().actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(2));
        //only 2 copies allocated (1 replica) across 2 nodes
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 2));

        logger.info("starting another node to new replicas will be allocated to it");
        allowNodes("test", 3);

        logger.info("Running Cluster Health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes(">=3").execute().actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(2));
        //all 3 copies allocated across 3 nodes
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 3));

        for (int i = 0; i < 10; i++) {
            SearchResponse countResponse = client().prepareSearch().setSize(0).setQuery(matchAllQuery()).get();
            assertHitCount(countResponse, 10l);
        }

        logger.info("Decreasing number of replicas from 2 to 0");
        assertAcked(client().admin().indices().prepareUpdateSettings("test").setSettings(settingsBuilder().put("index.number_of_replicas", 0)).get());

        logger.info("Running Cluster Health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForRelocatingShards(0).setWaitForNodes(">=3").execute().actionGet();
        logger.info("Done Cluster Health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(0));
        //a single copy is allocated (replica set to 0)
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries));

        for (int i = 0; i < 10; i++) {
            assertHitCount(client().prepareSearch().setQuery(matchAllQuery()).get(), 10);
        }
    }

    public void testAutoExpandNumberOfReplicas0ToData() throws IOException {
        internalCluster().ensureAtMostNumDataNodes(2);
        logger.info("--> creating index test with auto expand replicas");
        assertAcked(prepareCreate("test", 2, settingsBuilder().put("auto_expand_replicas", "0-all")));

        NumShards numShards = getNumShards("test");

        logger.info("--> running cluster health");
        ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 2).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(1));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 2));

        logger.info("--> add another node, should increase the number of replicas");
        allowNodes("test", 3);

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 3).setWaitForNodes(">=3").execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(2));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 3));

        logger.info("--> closing one node");
        internalCluster().ensureAtMostNumDataNodes(2);
        allowNodes("test", 2);

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 2).setWaitForNodes(">=2").execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(1));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 2));

        logger.info("--> closing another node");
        internalCluster().ensureAtMostNumDataNodes(1);
        allowNodes("test", 1);

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes(">=1").setWaitForActiveShards(numShards.numPrimaries).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(0));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries));
    }

    public void testAutoExpandNumberReplicas1ToData() throws IOException {
        logger.info("--> creating index test with auto expand replicas");
        internalCluster().ensureAtMostNumDataNodes(2);
        assertAcked(prepareCreate("test", 2, settingsBuilder().put("auto_expand_replicas", "1-all")));

        NumShards numShards = getNumShards("test");

        logger.info("--> running cluster health");
        ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 2).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(1));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 2));

        logger.info("--> add another node, should increase the number of replicas");
        allowNodes("test", 3);

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 3).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(2));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 3));

        logger.info("--> closing one node");
        internalCluster().ensureAtMostNumDataNodes(2);
        allowNodes("test", 2);

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForNodes(">=2").setWaitForActiveShards(numShards.numPrimaries * 2).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(1));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 2));

        logger.info("--> closing another node");
        internalCluster().ensureAtMostNumDataNodes(1);
        allowNodes("test", 1);

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().setWaitForNodes(">=1").setWaitForActiveShards(numShards.numPrimaries).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.YELLOW));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(1));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries));
    }

    public void testAutoExpandNumberReplicas2() {
        logger.info("--> creating index test with auto expand replicas set to 0-2");
        assertAcked(prepareCreate("test", 3, settingsBuilder().put("auto_expand_replicas", "0-2")));

        NumShards numShards = getNumShards("test");

        logger.info("--> running cluster health");
        ClusterHealthResponse clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 3).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(2));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 3));

        logger.info("--> add two more nodes");
        allowNodes("test", 4);
        allowNodes("test", 5);

        logger.info("--> update the auto expand replicas to 0-3");
        client().admin().indices().prepareUpdateSettings("test").setSettings(settingsBuilder().put("auto_expand_replicas", "0-3")).execute().actionGet();

        logger.info("--> running cluster health");
        clusterHealth = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().setWaitForActiveShards(numShards.numPrimaries * 4).execute().actionGet();
        logger.info("--> done cluster health, status " + clusterHealth.getStatus());
        assertThat(clusterHealth.isTimedOut(), equalTo(false));
        assertThat(clusterHealth.getStatus(), equalTo(ClusterHealthStatus.GREEN));
        assertThat(clusterHealth.getIndices().get("test").getActivePrimaryShards(), equalTo(numShards.numPrimaries));
        assertThat(clusterHealth.getIndices().get("test").getNumberOfReplicas(), equalTo(3));
        assertThat(clusterHealth.getIndices().get("test").getActiveShards(), equalTo(numShards.numPrimaries * 4));
    }

    public void testUpdateWithInvalidNumberOfReplicas() {
        createIndex("test");
        try {
            client().admin().indices().prepareUpdateSettings("test")
                .setSettings(Settings.settingsBuilder()
                        .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, randomIntBetween(-10, -1))
                )
                .execute().actionGet();
            fail("should have thrown an exception about the replica shard count");
        } catch (IllegalArgumentException e) {
            assertThat("message contains error about shard count: " + e.getMessage(),
                e.getMessage().contains("the value of the setting index.number_of_replicas must be a non negative integer"), equalTo(true));
        }
    }
}


text:
<?php

namespace power\genBundle\Controller;

/**
 * This code has been auto-generated by the JMSDiExtraBundle.
 *
 * Manual changes to it will be lost.
 */
class OwnertypeController__JMSInjector
{
    public static function inject($container) {
        $instance = new \power\genBundle\Controller\OwnertypeController();
        return $instance;
    }
}


text:
*Catalog prevents your download folder from being a mess on your Mac.*

## The problem

The *Downloads* folder on a Mac is the most cluttered folder there is. Even with the best intentions, we end up not cleaning it as often as we should.

*Catalog* allow us to create rules to automatically organize your downloads based on their origin (*i.e. http://someurl.com/path/to/file.pdf*).

## Installation

```bash
# Install `catalog` gem
$ gem install catalog

# Create the configuration file
$ touch ~/.catalog
```

## State of project

The current version **doesn't include a CLI**. You'll have to use it through IRB as you can see in the [How to use](#how-to-use) section. The next step will be to provide a CLI and a way to easily deamonize this.

## How to use

As mentionned above, *catalog* does not offer a CLI at the moment. You have to load it with IRB.

```ruby
> require 'catalog'
=> true

# Default location is ~/Downloads
> Catalog::Organizer.new.run!
=> true

# However, you can specify your own
> Catalog::Organizer.new(base_path: '/Volumes/Downloads/').run!
=> true
```

#### `~/.catalog` example

```yaml
drawers:
  # Basecamp related files
  - rule: basecamp.com\/39\/projects\/12837347\/
    path: /Users/garno/Downloads/Basecamp/ProjectName/
  - rule: basecamp.com
    path: /Users/garno/Downloads/Basecamp/

  # DMGs
  - rule: \.(?:dmg)$
    path: /Users/garno/Downloads/DMGs/

  # Alfred workflows
  - rule: \.(?:alfredworkflow)$
    path: /Users/garno/Downloads/Alfred workflows/
```

**Rules order is really important** since a file will be moved according to the first matched rule.

## License

Catalog is © 2014 Samuel Garneau and may be freely distributed under the MIT license. See the LICENSE.md file for more information.


text:
@interface Jastor : NSObject <NSCoding>

@property (nonatomic, copy) NSString *objectId;
+ (id)objectFromDictionary:(NSDictionary*)dictionary;

- (id)initWithDictionary:(NSDictionary *)dictionary;

- (NSMutableDictionary *)toDictionary;

- (NSDictionary *)map;

@end


text:
<meta charset="UTF-8">
<title>PendingTasks.tasksFactory - wendy</title>
<link rel="stylesheet" href="../../../style.css">

wendy / com.levibostian.wendy.service / PendingTasks / tasksFactory

tasksFactory

val tasksFactory: PendingTasksFactory


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Example of OneAPM SDK</title>

存储在 Cloud Insight 的列表


text:
package io.novaordis.gld.extensions.jboss.datagrid.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A generic implementation that mocks JBoss-specific aspects but allows testing the JBossDatagridServiceBase
 * functionality.
 *
 * @author Ovidiu Feodorov <ovidiu@novaordis.com>
 * @since 1/19/17
 */
public class GenericJBossDatagridService extends JBossDatagridServiceBase {

    // Constants -------------------------------------------------------------------------------------------------------

    private static final Logger log = LoggerFactory.getLogger(GenericJBossDatagridService.class);

    public static final String DEFAULT_CACHE_NAME = "N2ETG-4H34W-4534H";

    // Static ----------------------------------------------------------------------------------------------------------

    // Attributes ------------------------------------------------------------------------------------------------------

    private RuntimeException configureAndStartInfinispanCacheException;

    // Constructors ----------------------------------------------------------------------------------------------------

    // JBossDatagridServiceBase implementation -------------------------------------------------------------------------

    @Override
    protected InfinispanCache configureAndStartInfinispanCache() throws Exception {

        if (configureAndStartInfinispanCacheException != null) {

            throw configureAndStartInfinispanCacheException;
        }

        String cn = getCacheName();

        if (cn == null) {

            return new MockInfinispanCache(DEFAULT_CACHE_NAME);
        }
        else {

            return new MockInfinispanCache(cn);
        }
    }

    @Override
    protected void stopInfinispanCache(InfinispanCache cache) {

        //
        // noop
        //
        log.info("mock stop " + cache);
    }

    // Public ----------------------------------------------------------------------------------------------------------

    public void makeConfigureAndStartInfinispanCacheFail(RuntimeException e) {

        this.configureAndStartInfinispanCacheException = e;
    }

    // Package protected -----------------------------------------------------------------------------------------------

    // Protected -------------------------------------------------------------------------------------------------------

    // Private ---------------------------------------------------------------------------------------------------------

    // Inner classes ---------------------------------------------------------------------------------------------------

}


text:
import file_utility as utility

targets = ["../../Dooo-iOS/Challenger/common",
           "../../Dooo-iOS/Challenger/Network",
           "../../Dooo-iOS/Challenger/ViewControllers",
           "../../Dooo-iOS/Challenger/Plugin"]
# target = "../../Dooo-iOS/Challenger"
fout = open("output.txt", "w")
for t in targets:
    mfiles = utility.scan_m_files(t)
    for fp in mfiles:
        print("Scan " + fp[0])
        lines = utility.scan_lines(fp[0])
        if len(lines) > 0:
            fout.write("/* {0} */\n\n".format(fp[1]))
            fout.writelines(list(map(lambda x: x + "\n", lines)))
            fout.write("\n\n")

fout.close()


text:
"""tornado IOLoop API with zmq compatibility

If you have tornado ≥ 3.0, this is a subclass of tornado's IOLoop,
otherwise we ship a minimal subset of tornado in zmq.eventloop.minitornado.

The minimal shipped version of tornado's IOLoop does not include
support for concurrent futures - this will only be available if you
have tornado ≥ 3.0.
"""

# Copyright (C) PyZMQ Developers
# Distributed under the terms of the Modified BSD License.

from __future__ import absolute_import, division, with_statement

import os
import time
import warnings

from zmq import (
    Poller,
    POLLIN, POLLOUT, POLLERR,
    ZMQError, ETERM,
)

try:
    import tornado
    tornado_version = tornado.version_info
except (ImportError, AttributeError):
    tornado_version = ()

try:
    # tornado ≥ 3
    from tornado.ioloop import PollIOLoop, PeriodicCallback
    from tornado.log import gen_log
except ImportError:
    from .minitornado.ioloop import PollIOLoop, PeriodicCallback
    from .minitornado.log import gen_log

class DelayedCallback(PeriodicCallback):
    """Schedules the given callback to be called once.

    The callback is called once, after callback_time milliseconds.

    `start` must be called after the DelayedCallback is created.

    The timeout is calculated from when `start` is called.
    """
    def __init__(self, callback, callback_time, io_loop=None):
        # PeriodicCallback require callback_time to be positive
        warnings.warn("""DelayedCallback is deprecated.
        Use loop.add_timeout instead.""", DeprecationWarning)
        callback_time = max(callback_time, 1e-3)
        super(DelayedCallback, self).__init__(callback, callback_time, io_loop)

    def start(self):
        """Starts the timer."""
        self._running = True
        self._firstrun = True
        self._next_timeout = time.time() + self.callback_time / 1000.0
        self.io_loop.add_timeout(self._next_timeout, self._run)

    def _run(self):
        if not self._running: return
        self._running = False
        try:
            self.callback()
        except Exception:
            gen_log.error("Error in delayed callback", exc_info=True)

class ZMQPoller(object):
    """A poller that can be used in the tornado IOLoop.

    This simply wraps a regular zmq.Poller, scaling the timeout
    by 1000, so that it is in seconds rather than milliseconds.
    """

    def __init__(self):
        self._poller = Poller()

    @staticmethod
    def _map_events(events):
        """translate IOLoop.READ/WRITE/ERROR event masks into zmq.POLLIN/OUT/ERR"""
        z_events = 0
        if events & IOLoop.READ:
            z_events |= POLLIN
        if events & IOLoop.WRITE:
            z_events |= POLLOUT
        if events & IOLoop.ERROR:
            z_events |= POLLERR
        return z_events

    @staticmethod
    def _remap_events(z_events):
        """translate zmq.POLLIN/OUT/ERR event masks into IOLoop.READ/WRITE/ERROR"""
        events = 0
        if z_events & POLLIN:
            events |= IOLoop.READ
        if z_events & POLLOUT:
            events |= IOLoop.WRITE
        if z_events & POLLERR:
            events |= IOLoop.ERROR
        return events

    def register(self, fd, events):
        return self._poller.register(fd, self._map_events(events))

    def modify(self, fd, events):
        return self._poller.modify(fd, self._map_events(events))

    def unregister(self, fd):
        return self._poller.unregister(fd)

    def poll(self, timeout):
        """poll in seconds rather than milliseconds.

        Event masks will be IOLoop.READ/WRITE/ERROR
        """
        z_events = self._poller.poll(1000*timeout)
        return [ (fd,self._remap_events(evt)) for (fd,evt) in z_events ]

    def close(self):
        pass

class ZMQIOLoop(PollIOLoop):
    """ZMQ subclass of tornado's IOLoop"""
    def initialize(self, impl=None, **kwargs):
        impl = ZMQPoller() if impl is None else impl
        super(ZMQIOLoop, self).initialize(impl=impl, **kwargs)

    @staticmethod
    def instance(*args, **kwargs):
        """Returns a global `IOLoop` instance.

        Most applications have a single, global `IOLoop` running on the
        main thread.  Use this method to get this instance from
        another thread.  To get the current thread's `IOLoop`, use `current()`.
        """
        # install ZMQIOLoop as the active IOLoop implementation
        # when using tornado 3
        if tornado_version >= (3,):
            PollIOLoop.configure(ZMQIOLoop)
        return PollIOLoop.instance(*args, **kwargs)

    @staticmethod
    def current(*args, **kwargs):
        """Returns the current thread's IOLoop.
        """
        # install ZMQIOLoop as the active IOLoop implementation
        # when using tornado 3
        if tornado_version >= (3,):
            PollIOLoop.configure(ZMQIOLoop)
        return PollIOLoop.current(*args, **kwargs)

    def start(self):
        try:
            super(ZMQIOLoop, self).start()
        except ZMQError as e:
            if e.errno == ETERM:
                # quietly return on ETERM
                pass
            else:
                raise e

if (3, 0) <= tornado_version < (3, 1):
    def backport_close(self, all_fds=False):
        """backport IOLoop.close to 3.0 from 3.1 (supports fd.close() method)"""
        from zmq.eventloop.minitornado.ioloop import PollIOLoop as mini_loop
        return mini_loop.close.__get__(self)(all_fds)
    ZMQIOLoop.close = backport_close

# public API name
IOLoop = ZMQIOLoop

def install():
    """set the tornado IOLoop instance with the pyzmq IOLoop.

    After calling this function, tornado's IOLoop.instance() and pyzmq's
    IOLoop.instance() will return the same object.

    An assertion error will be raised if tornado's IOLoop has been initialized
    prior to calling this function.
    """
    from tornado import ioloop
    # check if tornado's IOLoop is already initialized to something other
    # than the pyzmq IOLoop instance:
    assert (not ioloop.IOLoop.initialized()) or \
        ioloop.IOLoop.instance() is IOLoop.instance(), "tornado IOLoop already initialized"

    if tornado_version >= (3,):
        # tornado 3 has an official API for registering new defaults, yay!
        ioloop.IOLoop.configure(ZMQIOLoop)
    else:
        # we have to set the global instance explicitly
        ioloop.IOLoop._instance = IOLoop.instance()


text:
<?php

namespace Predis\Command;

/**
 * @group commands
 * @group realm-pubsub
 */
class PubSubPubsubTest extends PredisCommandTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function getExpectedCommand()
    {
        return 'Predis\Command\PubSubPubsub';
    }

    /**
     * {@inheritdoc}
     */
    protected function getExpectedId()
    {
        return 'PUBSUB';
    }

    /**
     * @group disconnected
     */
    public function testFilterArguments()
    {
        $arguments = array('channels', 'predis:*');
        $expected = array('channels', 'predis:*');

        $command = $this->getCommand();
        $command->setArguments($arguments);

        $this->assertSame($expected, $command->getArguments());
    }

    /**
     * @group disconnected
     */
    public function testParseResponse()
    {
        $response = array('predis:incoming', 'predis:outgoing');
        $expected = array('predis:incoming', 'predis:outgoing');

        $command = $this->getCommandWithArguments('channels', 'predis:*');

        $this->assertSame($expected, $command->parseResponse($response));
    }

    /**
     * @group disconnected
     */
    public function testPubsubNumsub()
    {
        $response = array('predis:incoming', '10', 'predis:outgoing', '8');
        $expected = array('predis:incoming' => '10', 'predis:outgoing' => '8');

        $command = $this->getCommandWithArguments('numsub', 'predis:incoming', 'predis:outgoing');

        $this->assertSame($expected, $command->parseResponse($response));
    }

    /**
     * @group disconnected
     */
    public function testPubsubNumpat()
    {
        $response = 6;
        $expected = 6;

        $command = $this->getCommandWithArguments('numpat');

        $this->assertSame($expected, $command->parseResponse($response));
    }
}


text:
import pickle
import player_test

print('Welcome to the world of Pythonius!')

def save_game():
  with open('save.pickle', 'wb') as save_file:
    pickle.dump(player, save_file)

player = Player()

print('Welcome, oh great', player.name, 'the', player.profession)
save_game()


text:
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user
from django.contrib.auth.middleware import AuthenticationMiddleware
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import SimpleLazyObject

def get_anonymous_user_model():
    """
    Return the Anonymous User model that is active in this project.
    """
    try:
        app_name = settings.AUTH_ANONYMOUS_USER_MODEL.split(".")[0]
    except AttributeError:
        raise ImproperlyConfigured("AUTH_ANONYMOUS_USER_MODEL is not a string")
    try:
        model_name = settings.AUTH_ANONYMOUS_USER_MODEL.split(".")[1]
        app = apps.get_app_config(app_name)
        models_module = app.models_module
    except IndexError:
        raise ImproperlyConfigured(
            "AUTH_ANONYMOUS_USER_MODEL must be of the form 'app_label.model_name'"
        )
    except LookupError:
        raise ImproperlyConfigured(
            "AUTH_ANONYMOUS_USER_MODEL refers to an app '{}' that has not been installed".format(
                app_name
            )
        )
    try:
        return getattr(models_module, model_name)
    except AttributeError:
        raise ImproperlyConfigured(
            "AUTH_ANONYMOUS_USER_MODEL refers to a model '{}' that does not exist in the app '{}'".format(
                model_name, app_name
            )
        )

def _get_user(request):

    if not hasattr(request, "_cached_user"):
        user = get_user(request)
        if user.is_anonymous():
            AnonymousUser = get_anonymous_user_model()
            user = AnonymousUser()
        request._cached_user = user

    return request._cached_user

class CustomAuthenticationMiddleware(AuthenticationMiddleware):
    """
    Adaptation of Django's ``account.middleware.AuthenticationMiddleware``
    to replace the default AnonymousUser with a custom implementation.
    """

    def process_request(self, request):
        assert hasattr(request, "session"), (
            "The authentication middleware requires session middleware "
            "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert "
            "'django.contrib.sessions.middleware.SessionMiddleware' before "
            "'kolibri.core.auth.middleware.CustomAuthenticationMiddleware'."
        )
        request.user = SimpleLazyObject(lambda: _get_user(request))


text:
from copy import deepcopy
from dataclasses import dataclass
from http import HTTPStatus
from io import BytesIO
from journalpump.senders.base import LogSender
from journalpump.util import default_json_serialization, get_requests_session
from requests import Timeout as RequestsTimeout
from requests.exceptions import ConnectionError as RequestsConnectionError
from typing import Any, Dict, Set, Union

import enum
import json
import time

@enum.unique
class SenderType(enum.Enum):
    opensearch = "opensearch"
    elasticsearch = "elasticsearch"

@dataclass(frozen=True)
class Version:
    major: int
    minor: int
    patch: int

    def __str__(self) -> str:
        return f"version: {self.major}.{self.minor}.{self.patch}"

    @staticmethod
    def from_json(response_json: Dict[str, Any]) -> "Version":
        version_number = str(response_json["version"]["number"])  # help mypy here
        m, mi, p = tuple(map(int, version_number.split(".")))
        return Version(major=m, minor=mi, patch=p)

@dataclass(frozen=True)
class Config:
    _DEFAULT_REQUEST_TIMEOUT = 60.0

    _DEFAULT_INDEX_LIFETIME_IN_DAYS = 3

    _DEFAULT_INDEX_PREFIX = "journalpump"

    session_url: str
    request_timeout: int
    index_name: str
    index_lifetime_in_days: int
    sender_type: SenderType

    def request_url(self, path: str) -> str:
        return f"{self.session_url}/{path}"

    @staticmethod
    def create(*, sender_type: SenderType, config: Dict[str, Any]) -> "Config":
        if f"{sender_type.value}_url" not in config:
            raise ValueError(f"{sender_type.value}_url hasn't been defined")
        return Config(
            sender_type=sender_type,
            session_url=str(config[f"{sender_type.value}_url"]).rstrip("/"),
            request_timeout=config.get(f"{sender_type.value}_timeout", Config._DEFAULT_REQUEST_TIMEOUT),
            index_name=config.get(f"{sender_type.value}_index_prefix", Config._DEFAULT_INDEX_PREFIX),
            index_lifetime_in_days=config.get(f"{sender_type.value}_index_days_max", Config._DEFAULT_INDEX_LIFETIME_IN_DAYS),
        )

class _EsOsLogSenderBase(LogSender):

    _DEFAULT_MAX_SENDER_INTERVAL = 10.0

    _ONE_HOUR_LAST_INDEX_CHECK = 3600

    _SUCCESS_HTTP_STATUSES = {HTTPStatus.OK, HTTPStatus.CREATED}

    def __init__(self, *, sender_config: Config, config: Dict[str, Any], **kwargs) -> None:
        super().__init__(
            config=config,
            max_send_interval=config.get("max_send_interval", self._DEFAULT_MAX_SENDER_INTERVAL),
            **kwargs,
        )
        self._config = sender_config
        self._last_index_check_time = 0.0
        self._session = get_requests_session(timeout=self._config.request_timeout)
        # # If ca is set in config we use that, otherwise we verify using builtin CA cert list
        self._session.verify = self.config.get("ca", True)
        self._indices: Set[str] = set()
        self._last_es_error: Union[RequestsConnectionError, RequestsTimeout, None] = None
        self._version: Union[Version, None] = None

    @property
    def _indices_url(self) -> str:
        return self._config.request_url("_aliases")

    def _load_indices(self) -> bool:
        if self._indices:
            return True
        self.mark_disconnected()
        try:
            if not self._version:
                version_response = self._session.get(self._config.request_url(""))
                self._version = Version.from_json(version_response.json())
            self._indices = set(self._session.get(self._indices_url).json().keys())
            self._last_es_error = None
        except (RequestsConnectionError, RequestsTimeout) as ex:
            self.mark_disconnected(ex)
            if ex.__class__ != self._last_es_error.__class__:
                # only log these errors once, not every 10 seconds
                self.log.warning("Connection error to %s: %s: %s", self._config.sender_type, ex.__class__.__name__, ex)

            self._last_es_error = ex
            return False
        except Exception as ex:  # pylint: disable=broad-except
            self.mark_disconnected(ex)
            self.log.exception("Unexpected exception connecting to %s", self._config.sender_type)
            self.stats.unexpected_exception(ex, where="es_pump_init_es_client")
            return False

        self.log.info("Initialized %s HTTP connection", self._config.sender_type.value)
        self.mark_connected()
        return True

    @staticmethod
    def format_message_for_es(*, buf: BytesIO, header, message) -> None:
        buf.write(json.dumps(header, default=default_json_serialization).encode("utf8") + b"\n")
        # Message already in utf8 encoded bytestring form
        buf.write(message + b"\n")

    def _check_indices(self) -> None:
        aliases = self._session.get(self._indices_url).json()
        index_full_prefix = f"{self._config.index_name}-"
        indices = sorted(key for key in aliases.keys() if key.startswith(index_full_prefix))
        self.log.info(
            "Checking indices, currently: %r are available, max_indices: %r",
            indices,
            self._config.index_lifetime_in_days,
        )
        while len(indices) > self._config.index_lifetime_in_days:
            index_to_delete = indices.pop(0)
            self.log.info(
                "Deleting index: %r since we only keep %d days worth of indices",
                index_to_delete,
                self._config.index_lifetime_in_days,
            )
            try:
                self._session.delete(self._config.request_url(index_to_delete))
                self._indices.discard(index_to_delete)
            except Exception as ex:  # pylint: disable=broad-except
                self.log.exception("Unexpected exception deleting index %r", index_to_delete)
                self.stats.unexpected_exception(ex, where="es_pump_check_indices")

    def maintenance_operations(self) -> None:
        if time.monotonic() - self._last_index_check_time > self._ONE_HOUR_LAST_INDEX_CHECK:
            self._last_index_check_time = time.monotonic()
            self._check_indices()

    def send_messages(self, *, messages, cursor) -> bool:
        buf = BytesIO()
        start_time = time.monotonic()
        try:
            es_available = self._load_indices()
            if not es_available:
                self.log.warning("Waiting for connection to %s", self._indices_url)
                self._backoff()
                return False
            for msg in messages:
                message = json.loads(msg.decode("utf8"))
                # ISO datetime first 10 characters are equivalent to the date we need i.e. '2018-04-14'
                idx_name = f"""{self._config.index_name}-{message["timestamp"][:10]}"""
                if idx_name not in self._indices:
                    self._create_index_and_mapping(index_name=idx_name, message=message)

                self.format_message_for_es(buf=buf, header=self._message_header(idx_name), message=msg)

            # If we have messages, send them along to OpenSearch
            if buf.tell():
                buf_size = buf.tell()
                buf.seek(0)
                # Opensearch allows using _index even when posting
                # to particular index to override the index the entry
                # so this is mostly cosmetic to avoid needing to
                # expose /_bulk. We use simply the most recent index
                # name as base as it does not really matter which one
                # we use.
                res = self._session.post(
                    self._config.request_url(f"{idx_name}/_bulk"),
                    data=buf,
                    headers={
                        "content-length": str(buf_size),
                        "content-type": "application/x-ndjson",
                    },
                    timeout=self._config.request_timeout * 2,  # 2 times bigger by default 120 seconds
                )
                buf.seek(0)
                buf.truncate(0)

                self.mark_sent(messages=messages, cursor=cursor)
                self.log.info(
                    "Sent %d log events successfully: %r, took: %.2fs",
                    len(messages),
                    res.status_code in self._SUCCESS_HTTP_STATUSES,
                    time.monotonic() - start_time,
                )
        except Exception as ex:  # pylint: disable=broad-except
            self.mark_disconnected(ex)
            short_msg = str(ex)[:200]
            self.log.exception(
                "Problem sending logs to %s: %s: %s",
                self._config.sender_type,
                ex.__class__.__name__,
                short_msg,
            )
            self._backoff()
            return False

        return True

    def _message_header(self, index_name: str) -> Dict[str, Any]:
        return {
            "index": {
                "_index": index_name,
            }
        }

    def _create_index_and_mapping(self, *, index_name: str, message: Dict[str, Any]) -> None:
        try:
            self.log.info("Creating index: %r", index_name)
            res = self._session.put(
                self._config.request_url(index_name),
                json=self._create_mapping(message),
            )
            if res.status_code in self._SUCCESS_HTTP_STATUSES or "already_exists_exception" in res.text:
                self._indices.add(index_name)
            else:
                self.mark_disconnected(f"""Cannot create index "{index_name}" ({res.status_code} {res.text})""")
                self.log.warning("Could not create index mappings for: %r, %r %r", index_name, res.text, res.status_code)
        except (RequestsConnectionError, RequestsTimeout) as ex:
            self.mark_disconnected(ex)
            self.log.error("Problem creating index %r: %s: %s", index_name, ex.__class__.__name__, ex)
            self.stats.unexpected_exception(ex, where="es_pump_create_index_and_mappings")
            self._backoff()

    def _create_mapping(self, message: Dict[str, Any]) -> Dict[str, Any]:
        return {
            "mappings": {
                "properties": {
                    "SYSTEMD_SESSION": {
                        "type": "text"
                    },
                    "SESSION_ID": {
                        "type": "text"
                    },
                    **self._message_fields(message),
                },
            },
        }

    def _message_fields(self, message: Dict[str, Any]) -> Dict[str, Any]:
        addition_fields: Dict[str, Any] = {}
        unmapped_fields = {}
        for k, v in message.items():
            if k == "timestamp":  # skip timestamp
                continue
            if isinstance(v, bool):
                addition_fields[k] = {"type": "boolean"}
            elif isinstance(v, float):
                addition_fields[k] = {"type": "float"}
            elif isinstance(v, int):
                addition_fields[k] = {"type": "integer"}
            elif isinstance(v, str):
                addition_fields[k] = {"type": "text"}
            elif isinstance(v, dict):
                addition_fields[k] = {"properties": self._message_fields(v)}
            else:
                unmapped_fields[k] = type(v)
                continue
        if unmapped_fields:
            self.log.warning("Unmapped fields: %s", unmapped_fields)
        return addition_fields

class ElasticsearchSender(_EsOsLogSenderBase):

    _VERSION_WITH_MAPPING_TYPE_SUPPORT = 7

    _LEGACY_TYPE = "journal_msg"

    def __init__(self, *, config, **kwargs) -> None:
        super().__init__(
            sender_config=Config.create(sender_type=SenderType.elasticsearch, config=config),
            config=config,
            **kwargs,
        )

    def _message_header(self, index_name: str) -> Dict[str, Any]:
        header = super()._message_header(index_name)
        if not self._version:
            raise ValueError("Version has not been set")
        if self._version.major <= self._VERSION_WITH_MAPPING_TYPE_SUPPORT:
            header["index"].update({"_type": self._LEGACY_TYPE})
        return header

    def _create_mapping(self, message: Dict[str, Any]) -> Dict[str, Any]:
        mapping = super()._create_mapping(message)
        if not self._version:
            raise ValueError("Version has not been set")
        if self._version.major <= self._VERSION_WITH_MAPPING_TYPE_SUPPORT:
            mapping["mappings"].update({
                self._LEGACY_TYPE: {
                    "properties": deepcopy(mapping["mappings"]["properties"])
                },
            })
            del mapping["mappings"]["properties"]
        return mapping

class OpenSearchSender(_EsOsLogSenderBase):
    def __init__(self, *, config: Dict[str, Any], **kwargs) -> None:
        super().__init__(
            sender_config=Config.create(sender_type=SenderType.opensearch, config=config),
            config=config,
            **kwargs,
        )