text:
// Copyright (c) 2014, Smart Projects Holdings Ltd
// All rights reserved.
// See LICENSE file for license details.

/**
 * @file ardrone_vehicle_manager.h
 */
#ifndef _ARDRONE_VEHICLE_MANAGER_H_
#define _ARDRONE_VEHICLE_MANAGER_H_

#include <mavlink_vehicle_manager.h>
#include <ugcs/vsm/text_stream_filter.h>

class Ardrone_vehicle_manager: public Mavlink_vehicle_manager {
    DEFINE_COMMON_CLASS(Ardrone_vehicle_manager, Mavlink_vehicle_manager)

public:

    /** Constructor. */
    Ardrone_vehicle_manager();

    /** Handler for a new transport connection. */
    void
    On_connection_detected(
    		std::string,
    		int,
    		ugcs::vsm::Socket_address::Ptr,
    		ugcs::vsm::Io_stream::Ref);

private:

    /** ArDrone specific detection context used for reading network SSID and
     * drone name from TCP connection. */
    class Detection_ctx: public std::enable_shared_from_this<Detection_ctx> {
    	DEFINE_COMMON_CLASS(Detection_ctx, Detection_ctx)
    public:
		/** Construct using Mavlink stream, port name and drone address. */
    	Detection_ctx(
    			ugcs::vsm::Io_stream::Ref,
    			const std::string&,
    			ugcs::vsm::Socket_address::Ptr);

    	/** Close all. */
    	~Detection_ctx();

    	/** TCP stream for receiving configuration data. */
    	ugcs::vsm::Io_stream::Ref config_stream;

    	/** UDP steam for sending AT commands. */
    	ugcs::vsm::Socket_processor::Stream::Ref at_stream;

    	/** Mavlink stream from the detector. */
    	ugcs::vsm::Io_stream::Ref mav_stream;

    	/** Connection operation waiter. */
    	ugcs::vsm::Operation_waiter connect_waiter;

    	/** Mavlink data waiter. */
    	ugcs::vsm::Operation_waiter mav_waiter;

    	/** Drone UDP address from transport detector. */
    	ugcs::vsm::Socket_address::Ptr drone_addr;

    	/** Drone UDP address. */
    	ugcs::vsm::Socket_address::Ptr drone_udp_addr;

    	/** Drone TCP address. */
    	ugcs::vsm::Socket_address::Ptr drone_tcp_addr;

    	/** Configuration TCP stream filter. */
    	ugcs::vsm::Text_stream_filter::Ptr filter;

    	/** Configuration read retry timer. */
    	ugcs::vsm::Timer_processor::Timer::Ptr config_timer;

    	/** Port name from the detector. */
    	std::string port_name;

    	/** Attempts for TCP connection establishments. */
    	size_t connect_attempts_left = 3;

    	/** Attempts for configuration reading. */
    	size_t read_attempts_left = 3;

    	/** AT command sequence number to use next. */
    	uint32_t at_seq = 1;

    	/** Drone SSID, when received. */
    	ugcs::vsm::Optional<std::string> ssid;

    	/** Drone name, when received. */
    	ugcs::vsm::Optional<std::string> name;
    };

    /** UDP port for AT commands. */
    constexpr static unsigned AT_PORT = 5556;

    /** TCP port for configuration reading. */
    constexpr static unsigned CONFIG_PORT = 5559;

    /** Timeout for waiting for any data from Mavlink stream. Configuration
     * reading is started only after some data is read from the Mavlink
     * stream. This is to avoid TCP SYN flooding when drone is absent.
     */
    constexpr static std::chrono::seconds MAVLINK_TIMEOUT = std::chrono::seconds(2);

    /** Configuration reading retry timeout. */
    constexpr static std::chrono::seconds CONFIG_RETRY_TIMEOUT = std::chrono::seconds(3);

    /** TCP connection timeout. */
    constexpr static std::chrono::seconds TCP_TIMEOUT = std::chrono::seconds(5);

    /** Start detection by waiting some data from Mavlink stream first. */
    void
    Start_detection(Detection_ctx::Ptr);

    /** TCP connection handler. */
    void
    On_tcp_connected(
    		ugcs::vsm::Socket_processor::Stream::Ref,
    		ugcs::vsm::Io_result,
    		Detection_ctx::Weak_ptr);

    /** Send AT command to request full drone config from TCP stream and
     * schedule retry timer. */
    bool
    Request_config(Detection_ctx::Weak_ptr);

    /** Reading from Mavlink stream. */
    void
    On_mavlink_read(
    		ugcs::vsm::Io_buffer::Ptr,
    		ugcs::vsm::Io_result,
    		Detection_ctx::Weak_ptr);

    /** Reconnect TCP stream for configuration reading. */
    void
    Reconnect_tcp(Detection_ctx::Ptr);

    /** Finishes detection when both SSID and drone name are recieved. */
    void
    Try_finish_detecton(Detection_ctx::Ptr);

    /** Send AT command. */
    void
    Send_at(
    		Detection_ctx::Ptr,
    		const std::string& prefix,
    		const std::string& args);

    /** Handler for reading string parameter from TCP. */
    bool
    String_param_read_cb(
    		regex::smatch* match,
    		ugcs::vsm::Text_stream_filter::Lines_list*,
    		ugcs::vsm::Io_result,
    		Detection_ctx::Weak_ptr,
    		ugcs::vsm::Optional<std::string>*);

    virtual Mavlink_vehicle::Ptr
    Create_mavlink_vehicle(
            ugcs::vsm::Mavlink_demuxer::System_id system_id,
            ugcs::vsm::Mavlink_demuxer::Component_id component_id,
            ugcs::vsm::mavlink::MAV_TYPE type,
            ugcs::vsm::Io_stream::Ref stream,
            ugcs::vsm::Socket_address::Ptr peer_addr,
            ugcs::vsm::Optional<std::string> mission_dump_path,
            std::string serial_number,
            std::string model_name,
            bool id_overridden) override;

    virtual void
    Register_detectors() override;

    /** Detection ended (successfully or not), do cleanup. */
    void
    Detection_ended(Detection_ctx::Ptr);

    /** Disable handler. */
    virtual void
    On_manager_disable() override;

    /** Currently ongoing detections. */
    std::unordered_set<Detection_ctx::Ptr> detectors;

};

#endif /* _ARDRONE_VEHICLE_MANAGER_H_ */


text:
namespace {

using i18n::addressinput::BuildCallback;
using i18n::addressinput::NullStorage;
using i18n::addressinput::Retriever;
using i18n::addressinput::Rule;
using i18n::addressinput::RuleRetriever;
using i18n::addressinput::TestdataSource;

// Tests for RuleRetriever object.
class RuleRetrieverTest : public testing::Test {
 public:
  RuleRetrieverTest(const RuleRetrieverTest&) = delete;
  RuleRetrieverTest& operator=(const RuleRetrieverTest&) = delete;

 protected:
  RuleRetrieverTest()
      : rule_retriever_(
            new Retriever(new TestdataSource(false), new NullStorage)),
        success_(false),
        key_(),
        rule_(),
        rule_ready_(BuildCallback(this, &RuleRetrieverTest::OnRuleReady)) {}

  RuleRetriever rule_retriever_;
  bool success_;
  std::string key_;
  Rule rule_;
  const std::unique_ptr<const RuleRetriever::Callback> rule_ready_;

 private:
  void OnRuleReady(bool success,
                   const std::string& key,
                   const Rule& rule) {
    success_ = success;
    key_ = key;
    rule_.CopyFrom(rule);
  }
};

TEST_F(RuleRetrieverTest, ExistingRule) {
  static const char kExistingKey[] = "data/CA";

  rule_retriever_.RetrieveRule(kExistingKey, *rule_ready_);

  EXPECT_TRUE(success_);
  EXPECT_EQ(kExistingKey, key_);
  EXPECT_FALSE(rule_.GetFormat().empty());
}

TEST_F(RuleRetrieverTest, MissingRule) {
  static const char kMissingKey[] = "junk";

  rule_retriever_.RetrieveRule(kMissingKey, *rule_ready_);

  EXPECT_TRUE(success_);  // The server returns "{}" for bad keys.
  EXPECT_EQ(kMissingKey, key_);
  EXPECT_TRUE(rule_.GetFormat().empty());
}

}  // namespace

redpajama_set_name: RedPajamaGithub


text:
@interface ELBarButton ()

- (void)animateAlpha:(CGFloat)alpha withRemove:(BOOL)remove;

@end

@implementation ELBarButton
@synthesize holder = _holder;
@synthesize selfOffset = _selfOffset;
@synthesize mode;

- (id)initWithImage:(UIImage *)image asBackground:(BOOL)background andHolder:(id)holder {
    self = [super initWithFrame:YSRectMakeFromSize(30, 30)];
    if (self) {
        _holder = holder;
        [self setTitleShadowColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.titleLabel.textColor = [UIColor whiteColor];
        self.titleLabel.font = ELFontGetHelveticaNeue(12, ELFontStyleBold);
        self.titleLabel.shadowOffset = CGSizeMake(0, -1);
        if (background) {
            [self setBackgroundImage:image forState:UIControlStateNormal];
        } else {
            [self setImage:image forState:UIControlStateNormal];
        }
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
    }
    return self;
}

- (void)show {
    [self animateAlpha:1.0 withRemove:NO];
}

- (void)hideWithRemove:(BOOL)remove {
    [self animateAlpha:0.0 withRemove:remove];
}

- (void)animateAlpha:(CGFloat)alpha withRemove:(BOOL)remove {
    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionAllowAnimatedContent animations:^{

        if (!remove) {
            self.alpha = alpha;
        } else {
            [self removeFromSuperview];
        }

    } completion:NULL];
}

@end


text:
#include <harfbuzz/hb.h>

#if !HB_VERSION_ATLEAST(0, 9, 31)
#  error "This version of harfbuzz is too old."
#endif

int main(int, char **)
{
    hb_buffer_t *buffer = hb_buffer_create();

    const uint16_t string[] = { 'A', 'b', 'c' };
    hb_buffer_add_utf16(buffer, string, 3, 0, 3);
    hb_buffer_guess_segment_properties(buffer);
    hb_buffer_set_flags(buffer, hb_buffer_flags_t(HB_BUFFER_FLAG_PRESERVE_DEFAULT_IGNORABLES));

    hb_buffer_destroy(buffer);

    return 0;
}


text:
[Redis](https://redis.io/) is an in-memory key-value store which NetBox employs for caching and queuing. This section entails the installation and configuration of a local Redis instance. If you already have a Redis service in place, skip to [the next section](3-netbox.md).

!!! warning "Redis v4.0 or later required"
    NetBox v2.9.0 and later require Redis v4.0 or higher. If your distribution does not offer a recent enough release, you will need to build Redis from source. Please see [the Redis installation documentation](https://github.com/redis/redis) for further details.

=== "Ubuntu"

    ```no-highlight
    sudo apt install -y redis-server
    ```

=== "CentOS"

    ```no-highlight
    sudo yum install -y redis
    sudo systemctl start redis
    sudo systemctl enable redis
    ```

Before continuing, verify that your installed version of Redis is at least v4.0:

```no-highlight
redis-server -v
```

You may wish to modify the Redis configuration at `/etc/redis.conf` or `/etc/redis/redis.conf`, however in most cases the default configuration is sufficient.

## Verify Service Status

Use the `redis-cli` utility to ensure the Redis service is functional:

```no-highlight
redis-cli ping
```

If successful, you should receive a `PONG` response from the server.


text:
package annotations.tests.classfile.cases;

import java.util.Set;

public class TestLocalVariable<T> extends Object {
  public int i;

  public Set<Set> s;

  public TestLocalVariable() {
    int t = 0;
    i = 0;
  }

  public TestLocalVariable(int i) {
    this.i = i;
  }

  public TestLocalVariable(Integer j) {
    int k = 1;
    k++;
    this.i = j;
    k--;
    this.i = k;
  }

  public int i() {
    return i;
  }

  public int j() {
    int temp = 1;
    return j();
  }

  public static void someMethod() {
    TestLocalVariable t = new TestLocalVariable();
    String s = new String();
    Double d = Double.valueOf(2);
  }

  public static void main(String[] args) {
    boolean b = true;
    boolean b1 = Boolean.TRUE;
    boolean b2 = (boolean) Boolean.FALSE;
    b = b1 && b2;
    if (b || b2) {
      b1 = b;
    }
    if (b1) {
      System.out.println("Message");
    }
  }
}


text:
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;

namespace S11Context
{

    /// <summary>
    /// VIEW
    /// </summary>
    [Table(Name = @"s11.vHospitalBed")]
    public partial class VHospitalBed : INotifyPropertyChanging, INotifyPropertyChanged
    {

        private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(System.String.Empty);

        private int _Id;

        private int _MasterId;

        private int _Idx;

        private string _Code;

        private string _Name;

        private bool _IsPermanent;

        private System.Nullable<int> _TypeId;

        private System.Nullable<int> _ProfileId;

        private int _Relief;

        private System.Nullable<int> _ScheduleId;

        private System.Nullable<System.DateTime> _BegDate;

        private System.Nullable<System.DateTime> _EndDate;

        private sbyte _Sex;

        private string _Age;

        private int _Involution;

        private System.Nullable<System.DateTime> _BegDateInvolute;

        private System.Nullable<System.DateTime> _EndDateInvolute;

        private System.Nullable<int> _IsBusy;

        #region Extensibility Method Definitions
        partial void OnLoaded();
        partial void OnValidate(System.Data.Linq.ChangeAction action);
        partial void OnCreated();
        partial void OnIdChanging(int value);
        partial void OnIdChanged();
        partial void OnMasterIdChanging(int value);
        partial void OnMasterIdChanged();
        partial void OnIdxChanging(int value);
        partial void OnIdxChanged();
        partial void OnCodeChanging(string value);
        partial void OnCodeChanged();
        partial void OnNameChanging(string value);
        partial void OnNameChanged();
        partial void OnIsPermanentChanging(bool value);
        partial void OnIsPermanentChanged();
        partial void OnTypeIdChanging(System.Nullable<int> value);
        partial void OnTypeIdChanged();
        partial void OnProfileIdChanging(System.Nullable<int> value);
        partial void OnProfileIdChanged();
        partial void OnReliefChanging(int value);
        partial void OnReliefChanged();
        partial void OnScheduleIdChanging(System.Nullable<int> value);
        partial void OnScheduleIdChanged();
        partial void OnBegDateChanging(System.Nullable<System.DateTime> value);
        partial void OnBegDateChanged();
        partial void OnEndDateChanging(System.Nullable<System.DateTime> value);
        partial void OnEndDateChanged();
        partial void OnSexChanging(sbyte value);
        partial void OnSexChanged();
        partial void OnAgeChanging(string value);
        partial void OnAgeChanged();
        partial void OnInvolutionChanging(int value);
        partial void OnInvolutionChanged();
        partial void OnBegDateInvoluteChanging(System.Nullable<System.DateTime> value);
        partial void OnBegDateInvoluteChanged();
        partial void OnEndDateInvoluteChanging(System.Nullable<System.DateTime> value);
        partial void OnEndDateInvoluteChanged();
        partial void OnIsBusyChanging(System.Nullable<int> value);
        partial void OnIsBusyChanged();
        #endregion

        public VHospitalBed()
        {
            OnCreated();
        }

        /// <summary>
        /// There are no comments for Id in the schema.
        /// </summary>
        [Column(Name = @"id", Storage = "_Id", CanBeNull = false, DbType = "INT(10) NOT NULL")]
        public int Id
        {
            get
            {
                return this._Id;
            }
            set
            {
                if (this._Id != value)
                {
                    this.OnIdChanging(value);
                    this.SendPropertyChanging();
                    this._Id = value;
                    this.SendPropertyChanged("Id");
                    this.OnIdChanged();
                }
            }
        }

        /// <summary>
        /// Подразделение к которому относится койка {OrgStructure}
        /// </summary>
        [Column(Name = @"master_id", Storage = "_MasterId", CanBeNull = false, DbType = "INT(10) NOT NULL")]
        public int MasterId
        {
            get
            {
                return this._MasterId;
            }
            set
            {
                if (this._MasterId != value)
                {
                    this.OnMasterIdChanging(value);
                    this.SendPropertyChanging();
                    this._MasterId = value;
                    this.SendPropertyChanged("MasterId");
                    this.OnMasterIdChanged();
                }
            }
        }

        /// <summary>
        /// относительный индекс (для сортировки в списке)
        /// </summary>
        [Column(Name = @"idx", Storage = "_Idx", CanBeNull = false, DbType = "INT(10) NOT NULL")]
        public int Idx
        {
            get
            {
                return this._Idx;
            }
            set
            {
                if (this._Idx != value)
                {
                    this.OnIdxChanging(value);
                    this.SendPropertyChanging();
                    this._Idx = value;
                    this.SendPropertyChanged("Idx");
                    this.OnIdxChanged();
                }
            }
        }

        /// <summary>
        /// Идентификатор (место)
        /// </summary>
        [Column(Name = @"code", Storage = "_Code", CanBeNull = false, DbType = "VARCHAR(16) NOT NULL")]
        public string Code
        {
            get
            {
                return this._Code;
            }
            set
            {
                if (this._Code != value)
                {
                    this.OnCodeChanging(value);
                    this.SendPropertyChanging();
                    this._Code = value;
                    this.SendPropertyChanged("Code");
                    this.OnCodeChanged();
                }
            }
        }

        /// <summary>
        /// Расшифровка
        /// </summary>
        [Column(Name = @"name", Storage = "_Name", CanBeNull = false, DbType = "VARCHAR(64) NOT NULL")]
        public string Name
        {
            get
            {
                return this._Name;
            }
            set
            {
                if (this._Name != value)
                {
                    this.OnNameChanging(value);
                    this.SendPropertyChanging();
                    this._Name = value;
                    this.SendPropertyChanged("Name");
                    this.OnNameChanged();
                }
            }
        }

        /// <summary>
        /// флаг является/не является штатной
        /// </summary>
        [Column(Name = @"isPermanent", Storage = "_IsPermanent", CanBeNull = false, DbType = "TINYINT(1) NOT NULL")]
        public bool IsPermanent
        {
            get
            {
                return this._IsPermanent;
            }
            set
            {
                if (this._IsPermanent != value)
                {
                    this.OnIsPermanentChanging(value);
                    this.SendPropertyChanging();
                    this._IsPermanent = value;
                    this.SendPropertyChanged("IsPermanent");
                    this.OnIsPermanentChanged();
                }
            }
        }

        /// <summary>
        /// Тип {rbHospitalBedType}
        /// </summary>
        [Column(Name = @"type_id", Storage = "_TypeId", DbType = "INT(10)")]
        public System.Nullable<int> TypeId
        {
            get
            {
                return this._TypeId;
            }
            set
            {
                if (this._TypeId != value)
                {
                    this.OnTypeIdChanging(value);
                    this.SendPropertyChanging();
                    this._TypeId = value;
                    this.SendPropertyChanged("TypeId");
                    this.OnTypeIdChanged();
                }
            }
        }

        /// <summary>
        /// Профиль {rbHospitalBedProfile}
        /// </summary>
        [Column(Name = @"profile_id", Storage = "_ProfileId", DbType = "INT(10)")]
        public System.Nullable<int> ProfileId
        {
            get
            {
                return this._ProfileId;
            }
            set
            {
                if (this._ProfileId != value)
                {
                    this.OnProfileIdChanging(value);
                    this.SendPropertyChanging();
                    this._ProfileId = value;
                    this.SendPropertyChanged("ProfileId");
                    this.OnProfileIdChanged();
                }
            }
        }

        /// <summary>
        /// Смены
        /// </summary>
        [Column(Name = @"relief", Storage = "_Relief", CanBeNull = false, DbType = "INT(10) NOT NULL")]
        public int Relief
        {
            get
            {
                return this._Relief;
            }
            set
            {
                if (this._Relief != value)
                {
                    this.OnReliefChanging(value);
                    this.SendPropertyChanging();
                    this._Relief = value;
                    this.SendPropertyChanged("Relief");
                    this.OnReliefChanged();
                }
            }
        }

        /// <summary>
        /// Режим {rbHospitalBedShedule}
        /// </summary>
        [Column(Name = @"schedule_id", Storage = "_ScheduleId", DbType = "INT(10)")]
        public System.Nullable<int> ScheduleId
        {
            get
            {
                return this._ScheduleId;
            }
            set
            {
                if (this._ScheduleId != value)
                {
                    this.OnScheduleIdChanging(value);
                    this.SendPropertyChanging();
                    this._ScheduleId = value;
                    this.SendPropertyChanged("ScheduleId");
                    this.OnScheduleIdChanged();
                }
            }
        }

        /// <summary>
        /// начало периода действия
        /// </summary>
        [Column(Name = @"begDate", Storage = "_BegDate", DbType = "DATE")]
        public System.Nullable<System.DateTime> BegDate
        {
            get
            {
                return this._BegDate;
            }
            set
            {
                if (this._BegDate != value)
                {
                    this.OnBegDateChanging(value);
                    this.SendPropertyChanging();
                    this._BegDate = value;
                    this.SendPropertyChanged("BegDate");
                    this.OnBegDateChanged();
                }
            }
        }

        /// <summary>
        /// окончание периода действия
        /// </summary>
        [Column(Name = @"endDate", Storage = "_EndDate", DbType = "DATE")]
        public System.Nullable<System.DateTime> EndDate
        {
            get
            {
                return this._EndDate;
            }
            set
            {
                if (this._EndDate != value)
                {
                    this.OnEndDateChanging(value);
                    this.SendPropertyChanging();
                    this._EndDate = value;
                    this.SendPropertyChanged("EndDate");
                    this.OnEndDateChanged();
                }
            }
        }

        /// <summary>
        /// Применимо для указанного пола (0-любой, 1-М, 2-Ж)
        /// </summary>
        [Column(Name = @"sex", Storage = "_Sex", CanBeNull = false, DbType = "TINYINT(4) NOT NULL")]
        public sbyte Sex
        {
            get
            {
                return this._Sex;
            }
            set
            {
                if (this._Sex != value)
                {
                    this.OnSexChanging(value);
                    this.SendPropertyChanging();
                    this._Sex = value;
                    this.SendPropertyChanged("Sex");
                    this.OnSexChanged();
                }
            }
        }

        /// <summary>
        /// Применимо для указанного интервала возрастов пусто-нет ограничения, "{NNN{д|н|м|г}-{MMM{д|н|м|г}}" - с NNN дней/недель/месяцев/лет по MMM дней/недель/месяцев/лет; пустая нижняя или верхняя граница - нет ограничения снизу или сверху
        /// </summary>
        [Column(Name = @"age", Storage = "_Age", CanBeNull = false, DbType = "VARCHAR(9) NOT NULL")]
        public string Age
        {
            get
            {
                return this._Age;
            }
            set
            {
                if (this._Age != value)
                {
                    this.OnAgeChanging(value);
                    this.SendPropertyChanging();
                    this._Age = value;
                    this.SendPropertyChanged("Age");
                    this.OnAgeChanged();
                }
            }
        }

        /// <summary>
        /// There are no comments for Involution in the schema.
        /// </summary>
        [Column(Name = @"involution", Storage = "_Involution", CanBeNull = false, DbType = "INT(10) NOT NULL")]
        public int Involution
        {
            get
            {
                return this._Involution;
            }
            set
            {
                if (this._Involution != value)
                {
                    this.OnInvolutionChanging(value);
                    this.SendPropertyChanging();
                    this._Involution = value;
                    this.SendPropertyChanged("Involution");
                    this.OnInvolutionChanged();
                }
            }
        }

        /// <summary>
        /// Дата начала сворачивания
        /// </summary>
        [Column(Name = @"begDateInvolute", Storage = "_BegDateInvolute", DbType = "DATE")]
        public System.Nullable<System.DateTime> BegDateInvolute
        {
            get
            {
                return this._BegDateInvolute;
            }
            set
            {
                if (this._BegDateInvolute != value)
                {
                    this.OnBegDateInvoluteChanging(value);
                    this.SendPropertyChanging();
                    this._BegDateInvolute = value;
                    this.SendPropertyChanged("BegDateInvolute");
                    this.OnBegDateInvoluteChanged();
                }
            }
        }

        /// <summary>
        /// Дата окончания сворачивания
        /// </summary>
        [Column(Name = @"endDateInvolute", Storage = "_EndDateInvolute", DbType = "DATE")]
        public System.Nullable<System.DateTime> EndDateInvolute
        {
            get
            {
                return this._EndDateInvolute;
            }
            set
            {
                if (this._EndDateInvolute != value)
                {
                    this.OnEndDateInvoluteChanging(value);
                    this.SendPropertyChanging();
                    this._EndDateInvolute = value;
                    this.SendPropertyChanged("EndDateInvolute");
                    this.OnEndDateInvoluteChanged();
                }
            }
        }

        /// <summary>
        /// There are no comments for IsBusy in the schema.
        /// </summary>
        [Column(Name = @"isBusy", Storage = "_IsBusy", DbType = "INT(10)")]
        public System.Nullable<int> IsBusy
        {
            get
            {
                return this._IsBusy;
            }
            set
            {
                if (this._IsBusy != value)
                {
                    this.OnIsBusyChanging(value);
                    this.SendPropertyChanging();
                    this._IsBusy = value;
                    this.SendPropertyChanged("IsBusy");
                    this.OnIsBusyChanged();
                }
            }
        }

        public event PropertyChangingEventHandler PropertyChanging;

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void SendPropertyChanging()
        {
            if (this.PropertyChanging != null)
                this.PropertyChanging(this, emptyChangingEventArgs);
        }

        protected virtual void SendPropertyChanging(System.String propertyName)
        {
            if (this.PropertyChanging != null)
                this.PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
        }

        protected virtual void SendPropertyChanged(System.String propertyName)
        {
             if (this.PropertyChanged != null)
                 this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}


text:
package mts

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// AsrText is a nested struct in mts response
type AsrText struct {
	StartTime  int    `json:"StartTime" xml:"StartTime"`
	EndTime    string `json:"EndTime" xml:"EndTime"`
	ChannelId  string `json:"ChannelId" xml:"ChannelId"`
	SpeechRate string `json:"SpeechRate" xml:"SpeechRate"`
	Text       string `json:"Text" xml:"Text"`
}


text:
<?php

/**
 * Redux Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * any later version.
 *
 * Redux Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Redux Framework. If not, see <http://www.gnu.org/licenses/>.
 *
 * @package     ReduxFramework
 * @subpackage  field_import_export
 * @author      Dovy Paukstys
 * @author      Kevin Provance (kprovance)
 * @version     3.1.8
 */

// Exit if accessed directly
if( !defined( 'ABSPATH' ) ) exit;

if( !class_exists( 'ReduxFramework_import_export' ) ) {
    /**
     * Main ReduxFramework_import_export class
     *
     * @since       1.0.0
     */
    class ReduxFramework_import_export {

        /**
         * Field Constructor.
         *
         * Required - must call the parent constructor, then assign field and value to vars, and obviously call the render field function
         *
         * @since       1.0.0
         * @access      public
         * @return      void
         */
        public function __construct( $field = array(), $value ='', $parent ) {
            $this->parent = $parent;
            $this->field = $field;
            $this->value = $value;

            if (!isset($this->field['full_width'])) {
                $this->field['full_width'] = true;
            }

            $args = array(
                'full_width' => $this->field['full_width']
            );

            $this->parent->import_export->field_args = $args;
        }

        /**
         * Field Render Function.
         *
         * Takes the vars and outputs the HTML for the field in the settings
         *
         * @since       1.0.0
         * @access      public
         * @return      void
         */
        public function render() {
            $this->parent->import_export->render();
        }

        /**
         * Enqueue Function.
         *
         * If this field requires any scripts, or css define this function and register/enqueue the scripts/css
         *
         * @since       1.0.0
         * @access      public
         * @return      void
         */
        public function enqueue() {
            $this->parent->import_export->enqueue();
        }
    }
}


text:
gaf.TimeLine = gaf.Object.extend
({
    _className: "GAFTimeLine",
    _objects: null,
    _container: null,
    _animationStartedNextLoopDelegate: null,
    _animationFinishedPlayDelegate: null,
    _framePlayedDelegate: null,
    _sequenceDelegate: null,
    _fps: 60,
    _frameTime: 1/60,
    _currentSequenceStart: gaf.FIRST_FRAME_INDEX,
    _currentSequenceEnd: gaf.FIRST_FRAME_INDEX,
    _totalFrameCount: 0,
    _isRunning: false,
    _isLooped: false,
    _isReversed: false,
    _timeDelta: 0,
    _animationsSelectorScheduled: false,
    _currentFrame: gaf.FIRST_FRAME_INDEX,

    setAnimationStartedNextLoopDelegate: function (delegate)
    {
        this._animationStartedNextLoopDelegate = delegate;
    },
    setAnimationFinishedPlayDelegate: function (delegate)
    {
        this._animationFinishedPlayDelegate = delegate;
    },
    setLooped: function (looped, recursively)
    {
        this._isLooped = looped;
        if (recursively)
        {
            this._objects.forEach(function (item)
            {
                item.setLooped(looped, recursively);
            });
        }
    },
    getBoundingBoxForCurrentFrame: function ()
    {
        var result = null;//cc.rect();
        var isFirstObj = true;
        this._objects.forEach(function (item) {
            if(item.isVisibleInCurrentFrame() && item.isVisible())
            {
                var bb = item.getBoundingBoxForCurrentFrame();
                if(!bb)
                {
                    bb = item.getBoundingBox();
                }
                if (isFirstObj)
                {
                    isFirstObj = false;
                    result = bb;
                }
                else
                {
                    result = cc.rectUnion(result, bb);
                }
            }
        });
        return cc._rectApplyAffineTransformIn(result, this._container.getNodeToParentTransform());
    },
    setFps: function (fps)
    {
        cc.assert(fps !== 0, 'Error! Fps is set to zero.');
        this._fps = fps;
        this._frameTime = 1/fps;
    },
    getObjectByName: function (name)
    {
        var elements = name.split('.');
        var result = null;
        var retId = -1;
        var timeLine = this;
        var BreakException = {};
        try
        {
            elements.forEach(function(element)
            {
                var parts = timeLine._gafproto.getNamedParts();
                if(parts.hasOwnProperty(element))
                {
                    retId = parts[element];
                }
                else
                {
                    // Sequence is incorrect
                    BreakException.lastElement = element;
                    throw BreakException;
                }
                result = timeLine._objects[retId];
                timeLine = result;
            });
        }
        catch (e)
        {
            if (e!==BreakException)
            {
                throw e;
            }
            cc.log("Sequence incorrect: `" + name + "` At: `" + BreakException.lastElement + "`");
            return null;
        }
        return result;
    },
    clearSequence: function ()
    {
        this._currentSequenceStart = gaf.FIRST_FRAME_INDEX;
        this._currentSequenceEnd = this._gafproto.getTotalFrames();
    },
    getIsAnimationRunning: function ()
    {
        return this._isRunning;
    },
    gotoAndStop: function (value)
    {
        var frame = 0;
        if (typeof value === 'string')
        {
            frame = this.getStartFrame(value);
        }
        else
        {
            frame = value;
        }
        if (this.setFrame(frame))
        {
            this.setAnimationRunning(false, false);
            return true;
        }
        return false;
    },
    gotoAndPlay: function (value)
    {
        var frame = 0;
        if (typeof value === 'string')
        {
            frame = this.getStartFrame(value);
        }
        else
        {
            frame = value;
        }
        if (this.setFrame(frame))
        {
            this.setAnimationRunning(true, false);
            return true;
        }
        return false;
    },
    getStartFrame: function (frameLabel)
    {
        var seq = this._gafproto.getSequences()[frameLabel];
        if (seq)
        {
            return seq.start;
        }
        return gaf.IDNONE;
    },
    getEndFrame: function (frameLabel)
    {
        var seq = this._gafproto.getSequences()[frameLabel];
        if (seq)
        {
            return seq.end;
        }
        return gaf.IDNONE;
    },
    setFramePlayedDelegate: function (delegate)
    {
        this._framePlayedDelegate = delegate;
    },
    getCurrentFrameIndex: function ()
    {
        return this._showingFrame;
    },
    getTotalFrameCount: function ()
    {
        return this._gafproto.getTotalFrames();
    },
    start: function ()
    {
        this._enableTick(true);
        if (!this._isRunning)
        {
            this._currentFrame = gaf.FIRST_FRAME_INDEX;
            this.setAnimationRunning(true, true);
        }
    },
    stop: function ()
    {
        this._enableTick(false);
        if (this._isRunning)
        {
            this._currentFrame = gaf.FIRST_FRAME_INDEX;
            this.setAnimationRunning(false, true);
        }
    },
    isDone: function ()
    {
        if (this._isLooped)
        {
            return false;
        }
        else
        {
            if (!this._isReversed)
            {
                return this._currentFrame > this._totalFrameCount;
            }
            else
            {
                return this._currentFrame < gaf.FIRST_FRAME_INDEX - 1;
            }
        }
    },
    getSequences: function()
    {
        return this._gafproto.getSequences();
    },
    playSequence: function (name, looped)
    {
        var s = this.getStartFrame(name);
        var e = this.getEndFrame(name);
        if (gaf.IDNONE === s || gaf.IDNONE === e)
        {
            return false;
        }
        this._currentSequenceStart = s;
        this._currentSequenceEnd = e;
        if (this._currentFrame < this._currentSequenceStart || this._currentFrame > this._currentSequenceEnd)
        {
            this._currentFrame = this._currentSequenceStart;
        }
        else
        {
            this._currentFrame = this._currentSequenceStart;
        }
        this.setLooped(looped, false);
        this.resumeAnimation();
        return true;
    },
    isReversed: function ()
    {
        return this._isReversed;
    },
    setSequenceDelegate: function (delegate)
    {
        this._sequenceDelegate = delegate;
    },
    setFrame: function (index)
    {
        if (index >= gaf.FIRST_FRAME_INDEX && index < this._totalFrameCount)
        {
            this._showingFrame = index;
            this._currentFrame = index;
            this._processAnimation();
            return true;
        }
        return false;
    },

    pauseAnimation: function ()
    {
        if (this._isRunning)
        {
            this.setAnimationRunning(false, false);
        }
    },
    isLooped: function ()
    {
        return this._isLooped;
    },
    resumeAnimation: function ()
    {
        if (!this._isRunning)
        {
            this.setAnimationRunning(true, false);
        }
    },
    setReversed: function (reversed)
    {
        this._isReversed = reversed;
    },
    hasSequences: function ()
    {
        return this._gafproto.getSequences().length > 0;
    },
    getFps: function ()
    {
        return this._fps;
    },

    // Private

    ctor: function(gafTimeLineProto, scale)
    {
        this._super(scale);
        this._objects = [];
        cc.assert(gafTimeLineProto,  "Error! Missing mandatory parameter.");
        this._gafproto = gafTimeLineProto;
    },

    setExternalTransform: function(affineTransform)
    {
        if(!cc.affineTransformEqualToTransform(this._container._additionalTransform, affineTransform))
        {
           this._container.setAdditionalTransform(affineTransform);
        }
    },

    _init: function()
    {
        this.setContentSize(this._gafproto.getBoundingBox());
        this._currentSequenceEnd = this._gafproto.getTotalFrames();
        this._totalFrameCount = this._currentSequenceEnd;
        this.setFps(this._gafproto.getFps());
        this._container = new cc.Node();
        this.addChild(this._container);

        var self = this;
        var asset = this._gafproto.getAsset();

        // Construct objects for current time line
        this._gafproto.getObjects().forEach(function(object)
        {
            var objectProto = asset._getProtos()[object];
            cc.assert(objectProto, "Error. GAF proto for type: " + object.type + " and reference id: " + object + " not found.");
            self._objects[object] = objectProto._gafConstruct();
        });
    },

    _enableTick: function(val)
    {
        if (!this._animationsSelectorScheduled && val)
        {
            this.schedule(this._processAnimations);
            this._animationsSelectorScheduled = true;
        }
        else if (this._animationsSelectorScheduled && !val)
        {
            this.unschedule(this._processAnimations);
            this._animationsSelectorScheduled = false;
        }
    },

    _processAnimations: function (dt)
    {
        this._timeDelta += dt;
        while (this._timeDelta >= this._frameTime)
        {
            this._timeDelta -= this._frameTime;
            this._step();
        }
    },

    _step: function ()
    {
        this._showingFrame = this._currentFrame;

        if(!this.getIsAnimationRunning())
        {
            this._processAnimation();
            return;
        }

        if(this._sequenceDelegate)
        {
            var seq;
            if(!this._isReversed)
            {
                seq = this._getSequenceByLastFrame(this._currentFrame);
            }
            else
            {
                seq = this._getSequenceByFirstFrame(this._currentFrame + 1);
            }

            if (seq)
            {
                this._sequenceDelegate(this, seq);
            }
        }
        if (this._isCurrentFrameLastInSequence())
        {
            if(this._isLooped)
            {
                if(this._animationStartedNextLoopDelegate)
                    this._animationStartedNextLoopDelegate(this);
            }
            else
            {
                this.setAnimationRunning(false, false);
                if(this._animationFinishedPlayDelegate)
                    this._animationFinishedPlayDelegate(this);
            }
        }
        this._processAnimation();
        this._currentFrame = this._nextFrame();
    },

    _isCurrentFrameLastInSequence: function()
    {
        if (this._isReversed)
            return this._currentFrame == this._currentSequenceStart;
        return this._currentFrame == this._currentSequenceEnd - 1;
    },

    _nextFrame: function()
    {
        if (this._isCurrentFrameLastInSequence())
        {
            if (!this._isLooped)
                return this._currentFrame;

            if (this._isReversed)
                return this._currentSequenceEnd - 1;
            else
                return this._currentSequenceStart;
        }

        return this._currentFrame + (this._isReversed ? -1 : 1);
    },

    _processAnimation: function ()
    {
        //var id = this._gafproto.getId();
        this._realizeFrame(this._container, this._currentFrame);
        if (this._framePlayedDelegate)
        {
            this._framePlayedDelegate(this, this._currentFrame);
        }
    },
    _realizeFrame: function(out, frameIndex)
    {
        var self = this;
        var objects = self._objects;
        var frames = self._gafproto.getFrames();
        if(frameIndex > frames.length)
        {
            return;
        }
        var currentFrame = frames[frameIndex];
        if(!currentFrame)
        {
            return;
        }
        var states = currentFrame.states;
        for(var stateIdx = 0, total = states.length; stateIdx < total; ++stateIdx)
        {
            var state = states[stateIdx];
            var object = objects[state.objectIdRef];
            if(!object)
            {
                return;
            }
            if(state.alpha < 0)
            {
                object._resetState();
            }
            object._updateVisibility(state, self);
            if(!object.isVisible())
            {
                continue;
            }
            object._applyState(state, self);
            var parent = out;
            if(state.hasMask)
            {
                parent = objects[state.maskObjectIdRef]._getNode();
                cc.assert(parent, "Error! Mask not found.");
            }
            object._lastVisibleInFrame = 1 + frameIndex;
            gaf.TimeLine.rearrangeSubobject(parent, object, state.depth);
            if(object._step)
            {
                object._step();
            }
        }
    },
    setAnimationRunning: function (value, recursively)
    {
        this._isRunning = value;
        if(recursively)
        {
            this._objects.forEach(function (obj)
            {
                if (obj && obj.setAnimationRunning)
                {
                    obj.setAnimationRunning(value, recursively);
                }
            });
        }
    },

    _getSequenceByLastFrame: function(){
        var sequences = this._gafproto.getSequences();
        for(var item in sequences){
            if(sequences.hasOwnProperty(item)){
                if(sequences[item].end === frame + 1)
                {
                    return item;
                }
            }
        }
        return "";
    },

    _resetState : function()
    {
        this._super();
        this._currentFrame = this._currentSequenceStart;
    },

    _getSequenceByFirstFrame: function(){
        var sequences = this._gafproto.getSequences();
        for(var item in sequences){
            if(sequences.hasOwnProperty(item)){
                if(sequences[item].start === frame)
                {
                    return item;
                }
            }
        }
        return "";
    }
});

gaf.TimeLine.rearrangeSubobject = function(out, object, depth)
{
    var parent = object.getParent();
    if (parent !== out)
    {
        object.removeFromParent(false);
        out.addChild(object, depth);
    }
    else
    {
        object.setLocalZOrder(depth);
    }
};


text:
package cf.rachlinski.cryspscript.runtime.dataStructs.stack;

import cf.rachlinski.cryspscript.runtime.dataStructs.variable.Variable;

import java.util.Arrays;
import java.util.Iterator;

/**
 * Superclass for all stack data structures
 *
 */
public class Stack<E>	implements Iterable<E>
{
	/**
	 * Stack of E to store
	 */
	protected E[] contents;

	/**
	 * Construct a new Stack object given contents
	 * @param contents
	 */
	public Stack(E[] contents)
	{
		this.contents = contents;
	}

	/**
	 * Return the size of the stack
	 * @return the size of the stack
	 */
	public int size()
	{
		return contents.length;
	}

	/**
	 * Return the size of the stack
	 * Alias of the size method
	 * @return the size of the stack
	 */
	public int length()
	{
		return contents.length;
	}

	/**
	 * Return the entire stack of E
	 * @return the entire stack of E
	 */
	public E[] getContents()
	{
		return contents;
	}

	/**
	 * Return the E at the specified index
	 * @param index the index of the E
	 * @return the variable at specified index
	 */
	public E get(int index)
	{
		return contents[index];
	}

	@Override
	public String toString()
	{
		StringBuilder sb = new StringBuilder();

		for(E c : contents)
		{
			sb.append(c.toString() + ", ");
		}
		return "Stack [" + sb.toString() + "]";
	}

	/**
	 * Return the types of all of the contents of the stack as a string
	 * @return the types of the contents of teh stack as a string
	 */
	public String typesToString()
	{
		StringBuilder sb = new StringBuilder();

		if(contents instanceof Variable<?>[])
		{
			for(E c : contents)
			{
				sb.append(((Variable<?>) c).getType().toString() + ", ");
			}
		}
		else
		{
			for(E c : contents)
			{
				sb.append(c.getClass().toString() + ", ");
			}
		}

		return "StackTypes [" + sb.toString() + "]";
	}

	public Iterator<E> iterator()
	{
		return Arrays.asList(contents).iterator();
	}
}


text:
using PocoGenerator.ValueGenerators.Literals;
using System.Collections.Generic;
using System.Text;

namespace PocoGenerator.ValueGenerators.RandomValueGenerators
{
    /// <summary>
    /// An IValueGenerator for generating random strings.
    /// </summary>
    public class StringGenerator : RandomValueGenerator, IValueGenerator<string>
    {
        private IValueGenerator<string> wordSelector;
        private IValueGenerator<int> sizeSelector;

        /// <summary>
        /// Creates a new instances.
        /// </summary>
        /// <param name="size">The length of the strings to be generated.</param>
        /// <param name="wordSelector">An IValueGenerator to generate segments of the random string.</param>
        public StringGenerator(int size, IValueGenerator<string> wordSelector) {
            sizeSelector = new LiteralValueGenerator<int>(size);
            this.wordSelector = wordSelector;
        }

        /// <summary>
        /// Creates a new instance.
        /// </summary>
        /// <param name="sizeSelector">An IValueGenerator used to determine the length of the string to generate.</param>
        /// <param name="wordSelector">An IValueGenerator to generate segments of the random string.</param>
        public StringGenerator(IValueGenerator<int> sizeSelector, IValueGenerator<string> wordSelector) {
            this.sizeSelector = sizeSelector;
            this.wordSelector = wordSelector;
        }

        /// <summary>
        /// Gets all the valueGenerators used.
        /// </summary>
        /// <returns>The generators used to select values and size.</returns>
        public override IEnumerable<object> getGenerators() {
            return new List<object>() { wordSelector, sizeSelector };
        }

        /// <summary>
        /// Creates a new value.
        /// </summary>
        /// <returns>The generated value.</returns>
        public string MakeOne() {
            int curSize = 0;
            var size = sizeSelector.MakeOne();

            var builder = new StringBuilder();
            while (curSize < size)
            {
                var curWord = wordSelector.MakeOne();
                builder.Append(curWord).Append(" ");
                curSize += (curWord.Length + 1);
            }

            if (size > 0)
                return builder.ToString().Substring(0, size);
            else
                return "";
        }
    }
}


text:
/* eslint-disable no-undef, max-nested-callbacks */
jest.mock('path');
const {createPages, onCreateNode} = require('../gatsby-node');

describe('gatsby-node', () => {
  const boundActionCreators = {};

  describe('createPages', () => {
    let graphql;

    beforeEach(() => {
      boundActionCreators.createPage = jest.fn();
      graphql = jest.fn();
    });

    it('should create blog posts', () => {
      graphql.mockReturnValueOnce(
        Promise.resolve(
          {
            data: {
              posts: {
                edges: [
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-04-18--welcoming/'
                      }
                    }
                  },
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-05-02--article-2/'
                      }
                    }
                  },
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-05-02--article-1/'
                      }
                    }
                  },
                  {
                    node: {
                      fields: {
                        slug: '/docs/dont-take-me/'
                      }
                    }
                  }
                ]
              }
            }
          }
        )
      );

      return createPages({graphql, boundActionCreators})
        .then(() => {
          expect(boundActionCreators.createPage.mock.calls).toMatchSnapshot();
        });
    });

    it('should throw an error on graphql error', () => {
      graphql.mockReturnValueOnce(
        Promise.resolve({errors: 'something wrong!'})
      );

      expect(createPages({graphql, boundActionCreators}))
        .toThrow();
    });

    it('should create tags pages', () => {
      graphql.mockReturnValueOnce(
        Promise.resolve(
          {
            data: {
              posts: {
                edges: [
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-04-18--welcoming/'
                      },
                      frontmatter: {
                        tags: [
                          'starter',
                          'gatsby'
                        ]
                      }
                    }
                  },
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-05-02--article-2/'
                      },
                      frontmatter: {
                        tags: [
                          'test'
                        ]
                      }
                    }
                  },
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-05-02--article-1/'
                      },
                      frontmatter: {
                        tags: [
                          'test'
                        ]
                      }
                    }
                  },
                  {
                    node: {
                      fields: {
                        slug: '/blog/2017-05-02--article-0/'
                      },
                      frontmatter: {
                        tags: null
                      }
                    }
                  }
                ]
              }
            }
          }
        )
      );

      return createPages({graphql, boundActionCreators})
        .then(() => {
          expect(boundActionCreators.createPage.mock.calls).toMatchSnapshot();
        });
    });

    describe('pagination', () => {
      const generateData = n => {
        const edges = [...new Array(n)].map((val, i) => ({
          node: {
            fields: {
              slug: `/blog/2017-04-18--article-${i + 1}/`
            }
          }
        }));

        return {data: {posts: {edges}}};
      };

      it('should create 1 page with 5 posts', () => {
        graphql.mockReturnValueOnce(Promise.resolve(generateData(5)));
        return createPages({graphql, boundActionCreators})
          .then(() => {
            const pages = boundActionCreators.createPage.mock.calls
              .filter(d => d[0].path && d[0].path.startsWith('/blog/page/'));
            expect(pages).toMatchSnapshot();
          });
      });

      it('should create 2 pages with 15 posts', () => {
        graphql.mockReturnValueOnce(Promise.resolve(generateData(15)));
        return createPages({graphql, boundActionCreators})
          .then(() => {
            const pages = boundActionCreators.createPage.mock.calls
              .filter(d => d[0].path && d[0].path.startsWith('/blog/page/'));
            expect(pages).toMatchSnapshot();
          });
      });

      it('should create 3 pages with 30 posts', () => {
        graphql.mockReturnValueOnce(Promise.resolve(generateData(30)));
        return createPages({graphql, boundActionCreators})
          .then(() => {
            const pages = boundActionCreators.createPage.mock.calls
              .filter(d => d[0].path && d[0].path.startsWith('/blog/page/'));
            expect(pages).toMatchSnapshot();
          });
      });
    });
  });

  describe('onCreateNode', () => {
    let getNode;

    beforeEach(() => {
      boundActionCreators.createNodeField = jest.fn();
      getNode = jest.fn();
    });

    it('should create slugs for MarkdownRemark file', () => {
      getNode.mockReturnValue(
        {
          relativePath: 'blog/2017-04-18--welcoming/index.md'
        }
      );
      const node = {
        internal: {
          type: 'MarkdownRemark'
        },
        parent: 'parent'
      };
      onCreateNode({node, boundActionCreators, getNode});

      expect(boundActionCreators.createNodeField.mock.calls).toMatchSnapshot();
    });

    it('should do nothing on unknown type', () => {
      getNode.mockReturnValue(
        {
          relativePath: 'blog/2017-04-18--welcoming/index.md'
        }
      );
      const node = {
        internal: {
          type: 'unknown'
        },
        parent: 'parent'
      };
      onCreateNode({node, boundActionCreators, getNode});

      expect(boundActionCreators.createNodeField.mock.calls.length).toBe(0);
    });
  });
});


text:
<?php
namespace Phwoolcon\Queue\Adapter\Beanstalkd;

use Pheanstalk\Pheanstalk;
use Pheanstalk\Job as PheanstalkJob;
use Phwoolcon\Queue\Adapter\Beanstalkd;
use Phwoolcon\Queue\Adapter\JobInterface;
use Phwoolcon\Queue\Adapter\JobTrait;

/**
 * Class Job
 * @package Phwoolcon\Queue\Adapter\Beanstalkd
 *
 * @property Pheanstalk    $connection
 * @property Beanstalkd    $queue
 * @property PheanstalkJob $rawJob
 * @method  PheanstalkJob getRawJob()
 */
class Job implements JobInterface
{
    use JobTrait;

    protected function _delete()
    {
        $this->connection->delete($this->rawJob);
    }

    protected function _release($delay = 0)
    {
        $priority = Pheanstalk::DEFAULT_PRIORITY;
        $this->connection->release($this->rawJob, $priority, $delay);
    }

    public function attempts()
    {
        $stats = $this->connection->statsJob($this->rawJob);
        return (int)$stats->reserves;
    }

    /**
     * Bury the job in the queue.
     *
     * @return void
     */
    public function bury()
    {
        $this->connection->bury($this->rawJob);
    }

    /**
     * Get the job identifier.
     *
     * @return integer
     */
    public function getJobId()
    {
        return $this->rawJob->getId();
    }

    public function getRawBody()
    {
        return $this->rawJob->getData();
    }
}


text:
import logging as mod_logging
import math as mod_math

from . import utils as mod_utils

log = mod_logging.getLogger(__name__)

# Generic geo related function and class(es)

# latitude/longitude in GPX files is always in WGS84 datum
# WGS84 defined the Earth semi-major axis with 6378.137 km
EARTH_RADIUS = 6378.137 * 1000

# One degree in meters:
ONE_DEGREE = (2*mod_math.pi*EARTH_RADIUS) / 360  # ==> 111.319 km

def to_rad(x):
    return x / 180. * mod_math.pi

def haversine_distance(latitude_1, longitude_1, latitude_2, longitude_2):
    """
    Haversine distance between two points, expressed in meters.

    Implemented from http://www.movable-type.co.uk/scripts/latlong.html
    """
    d_lat = to_rad(latitude_1 - latitude_2)
    d_lon = to_rad(longitude_1 - longitude_2)
    lat1 = to_rad(latitude_1)
    lat2 = to_rad(latitude_2)

    a = mod_math.sin(d_lat/2) * mod_math.sin(d_lat/2) + \
        mod_math.sin(d_lon/2) * mod_math.sin(d_lon/2) * mod_math.cos(lat1) * mod_math.cos(lat2)
    c = 2 * mod_math.atan2(mod_math.sqrt(a), mod_math.sqrt(1-a))
    d = EARTH_RADIUS * c

    return d

def length(locations=None, _3d=None):
    locations = locations or []
    if not locations:
        return 0
    length = 0
    for i in range(len(locations)):
        if i > 0:
            previous_location = locations[i - 1]
            location = locations[i]

            if _3d:
                d = location.distance_3d(previous_location)
            else:
                d = location.distance_2d(previous_location)
            if d:
                length += d
    return length

def length_2d(locations=None):
    """ 2-dimensional length (meters) of locations (only latitude and longitude, no elevation). """
    locations = locations or []
    return length(locations, False)

def length_3d(locations=None):
    """ 3-dimensional length (meters) of locations (it uses latitude, longitude, and elevation). """
    locations = locations or []
    return length(locations, True)

def calculate_max_speed(speeds_and_distances):
    """
    Compute average distance and standard deviation for distance. Extremes
    in distances are usually extremes in speeds, so we will ignore them,
    here.

    speeds_and_distances must be a list containing pairs of (speed, distance)
    for every point in a track segment.
    """
    assert speeds_and_distances
    if len(speeds_and_distances) > 0:
        assert len(speeds_and_distances[0]) == 2
        # ...
        assert len(speeds_and_distances[-1]) == 2

    size = len(speeds_and_distances)

    if size < 20:
        log.debug('Segment too small to compute speed, size=%s', size)
        return None

    distances = list(map(lambda x: x[1], speeds_and_distances))
    average_distance = sum(distances) / float(size)
    standard_distance_deviation = mod_math.sqrt(sum(map(lambda distance: (distance-average_distance)**2, distances))/float(size))

    # Ignore items where the distance is too big:
    filtered_speeds_and_distances = filter(lambda speed_and_distance: abs(speed_and_distance[1] - average_distance) <= standard_distance_deviation * 1.5, speeds_and_distances)

    # sort by speed:
    speeds = list(map(lambda speed_and_distance: speed_and_distance[0], filtered_speeds_and_distances))
    if not isinstance(speeds, list):  # python3
        speeds = list(speeds)
    if not speeds:
        return None
    speeds.sort()

    # Even here there may be some extremes => ignore the last 5%:
    index = int(len(speeds) * 0.95)
    if index >= len(speeds):
        index = -1

    return speeds[index]

def calculate_uphill_downhill(elevations):
    if not elevations:
        return 0, 0

    size = len(elevations)

    def __filter(n):
        current_ele = elevations[n]
        if current_ele is None:
            return False
        if 0 < n < size - 1:
            previous_ele = elevations[n-1]
            next_ele = elevations[n+1]
            if previous_ele is not None and current_ele is not None and next_ele is not None:
                return previous_ele*.3 + current_ele*.4 + next_ele*.3
        return current_ele

    smoothed_elevations = list(map(__filter, range(size)))

    uphill, downhill = 0., 0.

    for n, elevation in enumerate(smoothed_elevations):
        if n > 0 and elevation is not None and smoothed_elevations is not None:
            d = elevation - smoothed_elevations[n-1]
            if d > 0:
                uphill += d
            else:
                downhill -= d

    return uphill, downhill

def distance(latitude_1, longitude_1, elevation_1, latitude_2, longitude_2, elevation_2,
             haversine=None):
    """
    Distance between two points. If elevation is None compute a 2d distance

    if haversine==True -- haversine will be used for every computations,
    otherwise...

    Haversine distance will be used for distant points where elevation makes a
    small difference, so it is ignored. That's because haversine is 5-6 times
    slower than the dummy distance algorithm (which is OK for most GPS tracks).
    """

    # If points too distant -- compute haversine distance:
    if haversine or (abs(latitude_1 - latitude_2) > .2 or abs(longitude_1 - longitude_2) > .2):
        return haversine_distance(latitude_1, longitude_1, latitude_2, longitude_2)

    coef = mod_math.cos(latitude_1 / 180. * mod_math.pi)
    x = latitude_1 - latitude_2
    y = (longitude_1 - longitude_2) * coef

    distance_2d = mod_math.sqrt(x * x + y * y) * ONE_DEGREE

    if elevation_1 is None or elevation_2 is None or elevation_1 == elevation_2:
        return distance_2d

    return mod_math.sqrt(distance_2d ** 2 + (elevation_1 - elevation_2) ** 2)

def elevation_angle(location1, location2, radians=False):
    """ Uphill/downhill angle between two locations. """
    if location1.elevation is None or location2.elevation is None:
        return None

    b = float(location2.elevation - location1.elevation)
    a = location2.distance_2d(location1)

    if a == 0:
        return 0

    angle = mod_math.atan(b / a)

    if radians:
        return angle

    return 180 * angle / mod_math.pi

def distance_from_line(point, line_point_1, line_point_2):
    """ Distance of point from a line given with two points. """
    assert point, point
    assert line_point_1, line_point_1
    assert line_point_2, line_point_2

    a = line_point_1.distance_2d(line_point_2)

    if a == 0:
        return line_point_1.distance_2d(point)

    b = line_point_1.distance_2d(point)
    c = line_point_2.distance_2d(point)

    s = (a + b + c) / 2.

    return 2. * mod_math.sqrt(abs(s * (s - a) * (s - b) * (s - c))) / a

def get_line_equation_coefficients(location1, location2):
    """
    Get line equation coefficients for:
        latitude * a + longitude * b + c = 0

    This is a normal cartesian line (not spherical!)
    """
    if location1.longitude == location2.longitude:
        # Vertical line:
        return float(0), float(1), float(-location1.longitude)
    else:
        a = float(location1.latitude - location2.latitude) / (location1.longitude - location2.longitude)
        b = location1.latitude - location1.longitude * a
        return float(1), float(-a), float(-b)

def simplify_polyline(points, max_distance):
    """Does Ramer-Douglas-Peucker algorithm for simplification of polyline """

    if len(points) < 3:
        return points

    begin, end = points[0], points[-1]

    # Use a "normal" line just to detect the most distant point (not its real distance)
    # this is because this is faster to compute than calling distance_from_line() for
    # every point.
    #
    # This is an approximation and may have some errors near the poles and if
    # the points are too distant, but it should be good enough for most use
    # cases...
    a, b, c = get_line_equation_coefficients(begin, end)

    # Initialize to safe values
    tmp_max_distance = 0
    tmp_max_distance_position = 1

    # Check distance of all points between begin and end, exclusive
    for point_no in range(1,len(points)-1):
        point = points[point_no]
        d = abs(a * point.latitude + b * point.longitude + c)
        if d > tmp_max_distance:
            tmp_max_distance = d
            tmp_max_distance_position = point_no

    # Now that we have the most distance point, compute its real distance:
    real_max_distance = distance_from_line(points[tmp_max_distance_position], begin, end)

    # If furthest point is less than max_distance, remove all points between begin and end
    if real_max_distance < max_distance:
        return [begin, end]

    # If furthest point is more than max_distance, use it as anchor and run
    # function again using (begin to anchor) and (anchor to end), remove extra anchor
    return (simplify_polyline(points[:tmp_max_distance_position + 1], max_distance) +
            simplify_polyline(points[tmp_max_distance_position:], max_distance)[1:])

class Location:
    """ Generic geographical location """

    latitude = None
    longitude = None
    elevation = None

    def __init__(self, latitude, longitude, elevation=None):
        self.latitude = latitude
        self.longitude = longitude
        self.elevation = elevation

    def has_elevation(self):
        return self.elevation or self.elevation == 0

    def remove_elevation(self):
        self.elevation = None

    def distance_2d(self, location):
        if not location:
            return None

        return distance(self.latitude, self.longitude, None, location.latitude, location.longitude, None)

    def distance_3d(self, location):
        if not location:
            return None

        return distance(self.latitude, self.longitude, self.elevation, location.latitude, location.longitude, location.elevation)

    def elevation_angle(self, location, radians=False):
        return elevation_angle(self, location, radians)

    def move(self, location_delta):
        self.latitude, self.longitude = location_delta.move(self)

    def __add__(self, location_delta):
        latitude, longitude = location_delta.move(self)
        return Location(latitude, longitude)

    def __str__(self):
        return '[loc:%s,%s@%s]' % (self.latitude, self.longitude, self.elevation)

    def __repr__(self):
        if self.elevation is None:
            return 'Location(%s, %s)' % (self.latitude, self.longitude)
        else:
            return 'Location(%s, %s, %s)' % (self.latitude, self.longitude, self.elevation)

    def __hash__(self):
        return mod_utils.hash_object(self, ('latitude', 'longitude', 'elevation'))

class LocationDelta:
    """
    Intended to use similar to timestamp.timedelta, but for Locations.
    """

    NORTH = 0
    EAST = 90
    SOUTH = 180
    WEST = 270

    def __init__(self, distance=None, angle=None, latitude_diff=None, longitude_diff=None):
        """
        Version 1:
            Distance (in meters).
            angle_from_north *clockwise*.
            ...must be given
        Version 2:
            latitude_diff and longitude_diff
            ...must be given
        """
        if (distance is not None) and (angle is not None):
            if (latitude_diff is not None) or (longitude_diff is not None):
                raise Exception('No lat/lon diff if using distance and angle!')
            self.distance = distance
            self.angle_from_north = angle
            self.move_function = self.move_by_angle_and_distance
        elif (latitude_diff is not None) and (longitude_diff is not None):
            if (distance is not None) or (angle is not None):
                raise Exception('No distance/angle if using lat/lon diff!')
            self.latitude_diff  = latitude_diff
            self.longitude_diff = longitude_diff
            self.move_function = self.move_by_lat_lon_diff

    def move(self, location):
        """
        Move location by this timedelta.
        """
        return self.move_function(location)

    def move_by_angle_and_distance(self, location):
        coef = mod_math.cos(location.latitude / 180. * mod_math.pi)
        vertical_distance_diff   = mod_math.sin((90 - self.angle_from_north) / 180. * mod_math.pi) / ONE_DEGREE
        horizontal_distance_diff = mod_math.cos((90 - self.angle_from_north) / 180. * mod_math.pi) / ONE_DEGREE
        lat_diff = self.distance * vertical_distance_diff
        lon_diff = self.distance * horizontal_distance_diff / coef
        return location.latitude + lat_diff, location.longitude + lon_diff

    def move_by_lat_lon_diff(self, location):
        return location.latitude + self.latitude_diff, location.longitude + self.longitude_diff


text:
"""Helper to help coordinating calls."""
import asyncio
import functools
from typing import Awaitable, Callable, TypeVar, cast

from homeassistant.core import HomeAssistant
from homeassistant.loader import bind_hass

T = TypeVar("T")

FUNC = Callable[[HomeAssistant], Awaitable[T]]

def singleton(data_key: str) -> Callable[[FUNC], FUNC]:
    """Decorate a function that should be called once per instance.

    Result will be cached and simultaneous calls will be handled.
    """

    def wrapper(func: FUNC) -> FUNC:
        """Wrap a function with caching logic."""

        @bind_hass
        @functools.wraps(func)
        async def wrapped(hass: HomeAssistant) -> T:
            obj_or_evt = hass.data.get(data_key)

            if not obj_or_evt:
                evt = hass.data[data_key] = asyncio.Event()

                result = await func(hass)

                hass.data[data_key] = result
                evt.set()
                return cast(T, result)

            if isinstance(obj_or_evt, asyncio.Event):
                evt = obj_or_evt
                await evt.wait()
                return cast(T, hass.data.get(data_key))

            return cast(T, obj_or_evt)

        return wrapped

    return wrapper


text:
from datetime import date, timedelta

import os
import settings

from django.core.management.base import BaseCommand
from django.db import connection
from django.utils.encoding import force_str

import olympia.core.logger

from olympia.amo.utils import send_mail
from olympia.constants.reviewers import (
    POST_REVIEW_WEIGHT_HIGHEST_RISK,
    POST_REVIEW_WEIGHT_HIGH_RISK,
    POST_REVIEW_WEIGHT_MEDIUM_RISK,
)

from premailer import transform

SQL_DIR = os.path.join(
    settings.ROOT, 'src/olympia/reviewers/management/commands/review_reports_sql/'
)

REPORTS = {
    'addon': [
        (
            'Weekly Add-on Reviews, 5 Reviews or More',
            os.path.join(SQL_DIR, 'addon/weekly.sql'),
        ),
        (
            'Weekly Volunteer Contribution Ratio',
            os.path.join(SQL_DIR, 'addon/breakdown.sql'),
        ),
        (
            'Weekly Add-on Reviews by Risk Profiles',
            os.path.join(SQL_DIR, 'addon/risk.sql'),
        ),
        ('Quarterly contributions', os.path.join(SQL_DIR, 'addon/quarterly.sql')),
    ],
    'content': [
        (
            'Weekly Content Reviews, 10 Reviews or More',
            os.path.join(SQL_DIR, 'content/weekly.sql'),
        ),
        (
            'Weekly Volunteer Contribution Ratio',
            os.path.join(SQL_DIR, 'content/breakdown.sql'),
        ),
        ('Quarterly contributions', os.path.join(SQL_DIR, 'content/quarterly.sql')),
    ],
}

log = olympia.core.logger.getLogger('z.reviewers.review_report')

class Command(BaseCommand):
    help = 'Generate and send the review report'

    def handle(self, *args, **options):
        log.info('Generating add-on reviews report...')

        addon_report_data = self.fetch_report_data('addon')
        addon_report_html = self.generate_report_html('addon', addon_report_data)
        addon_report_subject = '%s %s-%s' % (
            'Weekly Add-on Reviews Report',
            self.week_begin,
            self.week_end,
        )
        self.mail_report(
            'addon-reviewers@mozilla.org', addon_report_subject, addon_report_html
        )

        log.info('Generating content reviews report...')
        content_report_data = self.fetch_report_data('content')
        content_report_html = self.generate_report_html('content', content_report_data)
        content_report_subject = '%s %s-%s' % (
            'Weekly Add-on Content Reviews Report',
            self.week_begin,
            self.week_end,
        )
        self.mail_report(
            'addon-content-reviewers@mozilla.com',
            content_report_subject,
            content_report_html,
        )

    def fetch_report_data(self, group):
        today = date.today()
        with connection.cursor() as cursor:
            # Set variables that are being used in the review report,
            # as well as the email output.
            cursor.execute(
                """
                SET @WEEK_BEGIN=%s;
                SET @WEEK_END=%s;
                SET @QUARTER_BEGIN=%s;
                SET @RISK_HIGHEST=%s;
                SET @RISK_HIGH=%s;
                SET @RISK_MEDIUM=%s;
                """,
                [
                    today - timedelta(days=today.weekday() + 7),
                    today - timedelta(days=today.weekday() + 1),
                    date(today.year, (today.month - 1) // 3 * 3 + 1, 1),
                    POST_REVIEW_WEIGHT_HIGHEST_RISK,
                    POST_REVIEW_WEIGHT_HIGH_RISK,
                    POST_REVIEW_WEIGHT_MEDIUM_RISK,
                ],
            )

            # Read the beginning/end of the week
            # in order to put it in the email.
            cursor.execute('SELECT @WEEK_BEGIN, @WEEK_END;')
            data = cursor.fetchone()
            self.week_begin = data[0]
            self.week_end = data[1]

            report_data = []

            for header, query_file in REPORTS.get(group):
                with open(query_file) as report_query:
                    query_string = report_query.read().replace('\n', ' ')
                    cursor.execute(query_string)

                    table_header = []
                    for descr in cursor.description:
                        table_header.append(descr[0])
                    table_content = cursor.fetchall()
                    table_content = tuple(
                        (
                            tuple((force_str(item) for item in row))
                            for row in table_content
                        )
                    )
                    report_data.append((header, table_header, table_content))

            return report_data

    def generate_report_html(self, group, report_data):
        # Pre-set email with style information and header
        all_html = """

Weekly Add-on %sReviews Report

%s - %s

            """ % (
            ('Content ' if group == 'content' else ''),
            self.week_begin,
            self.week_end,
        )

        # For each group, execute the individual SQL reports
        # and build the HTML email.

        for section in report_data:
            all_html += '
%s
\n' % section[0]

            table_html = '
\n'
            table_html += (
                '
'
                + '	'.join([header for header in section[1]])
                + '
\n'
            )
            for row in section[2]:
                table_html += (
                    '
'
                    + '	'.join([entry for entry in row])
                    + '
\n'
                )
            table_html += '
\n'
            all_html += table_html

        # Some email clients (e.g. GMail) require all styles to be inline.
        # 'transform' takes the file-wide styles defined above and transforms
        # them to be inline styles.
        return transform(all_html)

    def mail_report(self, recipient, subject, content):
        log.info("Sending report '%s' to %s." % (subject, recipient))

        send_mail(
            subject,
            content,
            from_email='nobody@mozilla.org',
            recipient_list=[recipient],
            html_message=content,
            reply_to=[recipient],
        )


text:
@interface ActionSheetStringPicker()
@property (nonatomic,strong) NSArray *data;
@property (nonatomic,assign) NSInteger selectedIndex;
@end

@implementation ActionSheetStringPicker

+ (instancetype)showPickerWithTitle:(NSString *)title rows:(NSArray *)strings initialSelection:(NSInteger)index doneBlock:(ActionStringDoneBlock)doneBlock cancelBlock:(ActionStringCancelBlock)cancelBlockOrNil origin:(id)origin {
    ActionSheetStringPicker * picker = [[ActionSheetStringPicker alloc] initWithTitle:title rows:strings initialSelection:index doneBlock:doneBlock cancelBlock:cancelBlockOrNil origin:origin];
    [picker showActionSheetPicker];
    return picker;
}

- (instancetype)initWithTitle:(NSString *)title rows:(NSArray *)strings initialSelection:(NSInteger)index doneBlock:(ActionStringDoneBlock)doneBlock cancelBlock:(ActionStringCancelBlock)cancelBlockOrNil origin:(id)origin {
    self = [self initWithTitle:title rows:strings initialSelection:index target:nil successAction:nil cancelAction:nil origin:origin];
    if (self) {
        self.onActionSheetDone = doneBlock;
        self.onActionSheetCancel = cancelBlockOrNil;
    }
    return self;
}

+ (instancetype)showPickerWithTitle:(NSString *)title rows:(NSArray *)data initialSelection:(NSInteger)index target:(id)target successAction:(SEL)successAction cancelAction:(SEL)cancelActionOrNil origin:(id)origin {
    ActionSheetStringPicker *picker = [[ActionSheetStringPicker alloc] initWithTitle:title rows:data initialSelection:index target:target successAction:successAction cancelAction:cancelActionOrNil origin:origin];
    [picker showActionSheetPicker];
    return picker;
}

- (instancetype)initWithTitle:(NSString *)title rows:(NSArray *)data initialSelection:(NSInteger)index target:(id)target successAction:(SEL)successAction cancelAction:(SEL)cancelActionOrNil origin:(id)origin {
    self = [self initWithTarget:target successAction:successAction cancelAction:cancelActionOrNil origin:origin];
    if (self) {
        self.data = data;
        self.selectedIndex = index;
        self.title = title;
    }
    return self;
}

- (UIView *)configuredPickerView {
    if (!self.data)
        return nil;
    CGRect pickerFrame = CGRectMake(0, 40, self.viewSize.width, 216);
    UIPickerView *stringPicker = [[UIPickerView alloc] initWithFrame:pickerFrame];
    stringPicker.delegate = self;
    stringPicker.dataSource = self;

    [stringPicker selectRow:self.selectedIndex inComponent:0 animated:NO];
    if (self.data.count == 0) {
        stringPicker.showsSelectionIndicator = NO;
        stringPicker.userInteractionEnabled = NO;
    } else {
        stringPicker.showsSelectionIndicator = YES;
        stringPicker.userInteractionEnabled = YES;
    }

    //need to keep a reference to the picker so we can clear the DataSource / Delegate when dismissing
    self.pickerView = stringPicker;

    return stringPicker;
}

- (void)notifyTarget:(id)target didSucceedWithAction:(SEL)successAction origin:(id)origin {
    if (self.onActionSheetDone) {
        id selectedObject = (self.data.count > 0) ? (self.data)[(NSUInteger) self.selectedIndex] : nil;
        _onActionSheetDone(self, self.selectedIndex, selectedObject);
        return;
    }
    else if (target && [target respondsToSelector:successAction]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [target performSelector:successAction withObject:@(self.selectedIndex) withObject:origin];
#pragma clang diagnostic pop
        return;
    }
    NSLog(@"Invalid target/action ( %s / %s ) combination used for ActionSheetPicker", object_getClassName(target), sel_getName(successAction));
}

- (void)notifyTarget:(id)target didCancelWithAction:(SEL)cancelAction origin:(id)origin {
    if (self.onActionSheetCancel) {
        _onActionSheetCancel(self);
        return;
    }
    else if (target && cancelAction && [target respondsToSelector:cancelAction]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [target performSelector:cancelAction withObject:origin];
#pragma clang diagnostic pop
    }
}

#pragma mark - UIPickerViewDelegate / DataSource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    self.selectedIndex = row;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.data.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    id obj = (self.data)[(NSUInteger) row];

    // return the object if it is already a NSString,
    // otherwise, return the description, just like the toString() method in Java
    // else, return nil to prevent exception

    if ([obj isKindOfClass:[NSString class]])
        return obj;

    if ([obj respondsToSelector:@selector(description)])
        return [obj performSelector:@selector(description)];

    return nil;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return pickerView.frame.size.width - 50;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{

     NSString *str_lbl = (self.data)[(NSUInteger) row];

    //NSLog(@"////////%@",obj);

    UILabel *label = (UILabel*) view;
    if (label == nil)
    {
        label = [[UILabel alloc] init];
    }
    [label setText:str_lbl];
    [label setTextColor:[UIColor blackColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
    [label setAdjustsFontSizeToFitWidth:true];

   // [label setBackgroundColor:[UIColor blackColor]];
//    CGSize rowSize = [pickerView rowSizeForComponent:component];
//    CGRect labelRect = CGRectMake (0, 0, rowSize.width, rowSize.height);
//    [label setFrame:labelRect];

    return label;
}
@end


text: spinner


text:
#import "ElasticLoadBalancingInstance.h"

#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequestConfig.h>
#else
#import "../AmazonServiceRequestConfig.h"
#endif

/**
 * Register Instances With Load Balancer Request
 */

@interface ElasticLoadBalancingRegisterInstancesWithLoadBalancerRequest:AmazonServiceRequestConfig

{
    NSString       *loadBalancerName;
    NSMutableArray *instances;
}

/**
 * The name associated with the LoadBalancer. The name must be unique
 * within the client AWS account.
 */
@property (nonatomic, retain) NSString *loadBalancerName;

/**
 * A list of instance IDs that should be registered with the
 * LoadBalancer. <note>If you stop and then restart the instance, the
 * instance ID changes. Elastic Load Balancing cannot recognize the new
 * ID, which prevents it from routing traffic to your instance. We
 * recommend you de-register and then register your the new instance ID
 * with the load balancer after you restart your instance. To de-register
 * your instances from load balancer, use
 * DeregisterInstancesFromLoadBalancer action.</note>
 */
@property (nonatomic, retain) NSMutableArray *instances;

/**
 * Default constructor for a new RegisterInstancesWithLoadBalancerRequest object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * Constructs a new RegisterInstancesWithLoadBalancerRequest object.
 * Callers should use properties to initialize any additional object members.
 *
 * @param theLoadBalancerName The name associated with the LoadBalancer.
 * The name must be unique within the client AWS account.
 * @param theInstances A list of instance IDs that should be registered
 * with the LoadBalancer. <note>If you stop and then restart the
 * instance, the instance ID changes. Elastic Load Balancing cannot
 * recognize the new ID, which prevents it from routing traffic to your
 * instance. We recommend you de-register and then register your the new
 * instance ID with the load balancer after you restart your instance. To
 * de-register your instances from load balancer, use
 * DeregisterInstancesFromLoadBalancer action.</note>
 */
-(id)initWithLoadBalancerName:(NSString *)theLoadBalancerName andInstances:(NSMutableArray *)theInstances;

/**
 * Adds a single object to instances.
 * This function will alloc and init instances if not already done.
 */
-(void)addInstance:(ElasticLoadBalancingInstance *)instanceObject;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
"""Attributes:

    module_level_variable1 (int): Module level variables may be documented in
        <ref>
        either the ``Attributes`` section of the module docstring, or in an
        inline docstring immediately following the variable.

"""

module_level_variable1 = 12345


text:
<?php declare(strict_types = 1);

namespace Algatux\MongoDB\Tests\QueryBuilder\functional;

use Algatux\MongoDB\QueryBuilder\QueryBuilder;
use MongoDB\Client;
use MongoDB\Collection;
use MongoDB\Database;

/**
 * Class TestCase
 */
class TestCase extends \PHPUnit_Framework_TestCase
{
    const TEST_DATABASE = 'test_execution_database';
    const TEST_COLLECTION = 'test_execution_collection';

    /** @var Database */
    private $database;
    /** @var Collection */
    private $collection;

    protected function setUp()
    {
        $client = new Client();
        $this->database = $client->selectDatabase(self::TEST_DATABASE);
        $this->collection = $this->database->selectCollection(self::TEST_COLLECTION);
        $this->prepareFixtures();
    }

    protected function tearDown()
    {
        $this->database->dropCollection(self::TEST_COLLECTION);
    }

    /**
     * @return Collection
     */
    protected function getCollection(): Collection
    {
        return $this->collection;
    }

    /**
     * @return QueryBuilder
     */
    public function getQueryBuilder(): QueryBuilder
    {
        return new QueryBuilder($this->collection);
    }

    protected function prepareFixtures()
    {
        $this->collection->insertMany([
            // Doc1
            [
                'name' => 'Alessandro',
                'surname' => 'Galli',
                'age' => 31,
                'type' => 'Developer'
            ],
            // Doc2
            [
                'name' => 'John',
                'surname' => 'Snow',
                'age' => 24,
                'type' => 'Fantasy Character'
            ],
            // Doc3
            [
                'name' => 'James',
                'surname' => 'Hetfield',
                'age' => 45,
                'type' => 'Musician'
            ],
        ]);
    }
}


text:
ENV['RACK_ENV'] ||= 'development'

require 'bundler/setup'
Bundler.require :default, ENV.fetch('RACK_ENV', nil)

Dir[File.expand_path('config/initializers', __dir__) + '/**/*.rb'].each do |file|
  require file
end

Mongoid.load! File.expand_path('config/mongoid.yml', __dir__), ENV.fetch('RACK_ENV', nil)

require 'slack-gamebot/error'
require 'slack-gamebot/version'
require 'slack-gamebot/info'
require 'slack-gamebot/models'
require 'slack-gamebot/api'
require 'slack-gamebot/app'
require 'slack-gamebot/server'
require 'slack-gamebot/service'
require 'slack-gamebot/commands'


text:
package fr.tolc.jahia.intellij.plugin.cnd.enums;

public enum ResourcesTypeEnum {
    CSS("css"),
    JAVASCRIPT("javascript");

    private String value;

    ResourcesTypeEnum(String value) {
        this.value = value;
    }

    public static ResourcesTypeEnum fromValue(String value) throws IllegalArgumentException {
        for (ResourcesTypeEnum type : ResourcesTypeEnum.values()) {
            if (type.value.equalsIgnoreCase(value)) {
                return type;
            }
        }
        throw new IllegalArgumentException("Unknown resources type [" + value + "]");
    }

    public static ResourcesTypeEnum fromAnything(String value) {
        for (ResourcesTypeEnum type : ResourcesTypeEnum.values()) {
            if (type.value.equalsIgnoreCase(value)) {
                return type;
            }
        }
        return null;
    }

    public String toString() {
        return this.value;
    }
}