text:
<?php
namespace Geekhub\DreamBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Geekhub\DreamBundle\Entity\Dream;
use Geekhub\DreamBundle\Entity\Work;
use Geekhub\DreamBundle\Entity\Financial;
use Geekhub\DreamBundle\Entity\Equipment;

class LoadContributionData extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        for ($i = 0; $i < 100; $i++) {
            $currentDream = 'dream' . rand(0, 29);

            /** @var $dream Dream */
            $dream = $this->getReference($currentDream);
            $workDreamPoints = $dream->getWork();
            $financialDreamPoints = $dream->getFinancial();
            $equipmentDreamPoints = $dream->getEquipment();

            if ($workDreamPoints) {
                //get 100%
                $planQuantity = 0;
                foreach ($workDreamPoints as $workPoint) {
                    $planQuantity = $planQuantity + $workPoint->getQuantity();
                }
                /** @var $workPoint Work */
                foreach ($workDreamPoints as $workPoint) {
                    $user = $this->getReference('user' . rand(1, 17));

                    if (rand(1, 3) == 2) {
                        continue;
                    }
                    elseif ($user->getId() == $dream->getOwner()->getId()) {
                        continue;
                    }

                    $work = new Work();

                    $work->setQuantity(1);
                    $work->setName($workPoint->getName());
                    $work->setDream($dream);
                    $work->setHide(rand(0, 1));
                    $work->setUser($user);
                    $work->setParent($workPoint);
                    $work->setIsDonate(true);

                    $partPlan = $work->getQuantity()/$planQuantity;
                    $progressBar = $dream->getProgressBar();
                    $progressBar->addWork($partPlan);

                    $manager->persist($progressBar);
                    $manager->persist($work);
                    $manager->flush();
                }
            }

            if ($financialDreamPoints) {
                //get 100%
                $planQuantity = 0;
                foreach ($financialDreamPoints as $financialPoint) {
                    $planQuantity = $planQuantity + $financialPoint->getQuantity();
                }
                /** @var $financialPoint Financial */
                foreach ($financialDreamPoints as $financialPoint) {
                    $user = $this->getReference('user' . rand(1, 17));

                    if (rand(1, 3) == 2) {
                        continue;
                    }
                    elseif ($user->getId() == $dream->getOwner()->getId()) {
                        continue;
                    }

                    $financial = new Financial();

                    $financial->setName($financialPoint->getName());
                    $financial->setQuantity(rand(10, $planQuantity/4));
                    $financial->setDream($dream);
                    $financial->setHide(rand(0, 1));
                    $financial->setUser($user);
                    $financial->setParent($financialPoint);
                    $financial->setIsDonate(true);

                    $partPlan = $financial->getQuantity()/$planQuantity;
                    $progressBar = $dream->getProgressBar();
                    $progressBar->addFinance($partPlan);

                    $manager->persist($progressBar);
                    $manager->persist($financial);
                    $manager->flush();
                }
            }

            if ($equipmentDreamPoints) {
                //get 100%
                $planQuantity = 0;
                foreach ($equipmentDreamPoints as $equipmentPoint) {
                    $planQuantity = $planQuantity + $equipmentPoint->getQuantity();
                }
                /** @var $equipmentPoint Equipment */
                foreach ($equipmentDreamPoints as $equipmentPoint) {
                    $user = $this->getReference('user' . rand(1, 17));

                    if (rand(1, 3) == 2) {
                        continue;
                    }
                    elseif ($user->getId() == $dream->getOwner()->getId()) {
                        continue;
                    }

                    $equipment = new Equipment();

                    $equipment->setDream($dream);
                    $equipment->setName($equipmentPoint->getName());
                    $equipment->setQuantity(rand(1, $planQuantity/5));
                    $equipment->setHide(rand(0, 1));
                    $equipment->setUser($user);
                    $equipment->setParent($equipmentPoint);
                    $equipment->setIsDonate(true);

                    $partPlan = $equipment->getQuantity()/$planQuantity;
                    $progressBar = $dream->getProgressBar();
                    $progressBar->addEquipment($partPlan);

                    $manager->persist($progressBar);
                    $manager->persist($equipment);
                    $manager->flush();
                }
            }
        }
    }

    /**
     * Get the order of this fixture
     *
     * @return integer
     */
    function getOrder()
    {
        return 32;
    }

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Envelope.java
 *
 * Created on 12. februar 2007, 13:07
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.rometools.modules.georss.geometries;

/**
 * Envelope, a bounding box spanned by an upper right and lower left corner point. Note that if the
 * box spans the -180 180 degree meridian the numerical value of the minLongitude may be greater
 * than the maxLongitude.
 *
 * @author runaas
 */
public class Envelope extends AbstractGeometry {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    protected double minLatitude, minLongitude, maxLatitude, maxLongitude;

    /** Creates a new instance of Envelope */
    public Envelope() {
        minLatitude = minLongitude = maxLatitude = maxLongitude = Double.NaN;
    }

    /**
     * Construct object from coordinate values
     *
     * @param minLatitude
     * @param minLongitude
     * @param maxLatitude
     * @param maxLongitude
     */
    public Envelope(final double minLatitude, final double minLongitude, final double maxLatitude, final double maxLongitude) {
        this.minLatitude = minLatitude;
        this.minLongitude = minLongitude;
        this.maxLatitude = maxLatitude;
        this.maxLongitude = maxLongitude;
    }

    /**
     * @return the minimum longitude
     */
    public double getMinLongitude() {
        return minLongitude;
    }

    /**
     * @return the minimum latitude
     */
    public double getMinLatitude() {
        return minLatitude;
    }

    /**
     * @return the maximum longitude
     */
    public double getMaxLongitude() {
        return maxLongitude;
    }

    /**
     * @return the maximum latitude
     */
    public double getMaxLatitude() {
        return maxLatitude;
    }

    /**
     * @param v minimum longitude
     */
    public void setMinLongitude(final double v) {
        minLongitude = v;
    }

    /**
     * @param v minimum latitude
     */
    public void setMinLatitude(final double v) {
        minLatitude = v;
    }

    /**
     * @param v maximum longitude
     */
    public void setMaxLongitude(final double v) {
        maxLongitude = v;
    }

    /**
     * @param v maximum latitude
     */
    public void setMaxLatitude(final double v) {
        maxLatitude = v;
    }
}


text:
module Locomotive
  module PluginsModule

    DEFAULT_PATH = File.join(Merb.root, 'vendor','plugins','locomotive')

    class << self
      attr_accessor :discovered

      # Accessor to query plugins by their name
      # Returns the plugin with plugin_name if it is known
      def [](plugin_name)
        discovered[plugin_name]
      end
    end

    self.discovered = {}

    # Find and include all Locomotive plugins
    def self.discover

      discovered.clear

      puts "finding plugins"

      installed_plugins.each do |p|
        puts "\t#{p}"

        path = File.join(DEFAULT_PATH, p, 'lib', 'locomotive', 'plugins', p)

        $LOAD_PATH << path
        ActiveSupport::Dependencies.load_paths      << path
        ActiveSupport::Dependencies.load_once_paths << path
        require_dependency path

        discovered[p] = Locomotive::Plugins.const_get(p.camelize)
      end

    end

    def self.find_all
      discovered.values
    end

    # Generates a list of installed plugins from the directory structure
    # in vendor/plugins/locomotive.
    def self.installed_plugins
      base_path = Locomotive::Plugins::DEFAULT_PATH
      plugin_paths = Dir[File.join(base_path, '*')].select {|d| File.directory?(d)}
      plugin_names = plugin_paths.map {|d| File.basename(d)}
    end
  end
end


text:
namespace v8 {
namespace internal {

static const int kDaysIn4Years = 4 * 365 + 1;
static const int kDaysIn100Years = 25 * kDaysIn4Years - 1;
static const int kDaysIn400Years = 4 * kDaysIn100Years + 1;
static const int kDays1970to2000 = 30 * 365 + 7;
static const int kDaysOffset =
    1000 * kDaysIn400Years + 5 * kDaysIn400Years - kDays1970to2000;
static const int kYearsOffset = 400000;
static const char kDaysInMonths[] = {31, 28, 31, 30, 31, 30,
                                     31, 31, 30, 31, 30, 31};

DateCache::DateCache()
    : stamp_(kNullAddress),
      tz_cache_(
#ifdef V8_INTL_SUPPORT
          Intl::CreateTimeZoneCache()
#else
          base::OS::CreateTimezoneCache()
#endif
      ) {
  ResetDateCache(base::TimezoneCache::TimeZoneDetection::kSkip);
}

void DateCache::ResetDateCache(
    base::TimezoneCache::TimeZoneDetection time_zone_detection) {
  if (stamp_.value() >= Smi::kMaxValue) {
    stamp_ = Smi::zero();
  } else {
    stamp_ = Smi::FromInt(stamp_.value() + 1);
  }
  DCHECK(stamp_ != Smi::FromInt(kInvalidStamp));
  for (int i = 0; i < kDSTSize; ++i) {
    ClearSegment(&dst_[i]);
  }
  dst_usage_counter_ = 0;
  before_ = &dst_[0];
  after_ = &dst_[1];
  ymd_valid_ = false;
#ifdef V8_INTL_SUPPORT
  if (!FLAG_icu_timezone_data) {
#endif
    local_offset_ms_ = kInvalidLocalOffsetInMs;
#ifdef V8_INTL_SUPPORT
  }
#endif
  tz_cache_->Clear(time_zone_detection);
  tz_name_ = nullptr;
  dst_tz_name_ = nullptr;
}

// ECMA 262 - ES#sec-timeclip TimeClip (time)
double DateCache::TimeClip(double time) {
  if (-kMaxTimeInMs <= time && time <= kMaxTimeInMs) {
    return DoubleToInteger(time) + 0.0;
  }
  return std::numeric_limits<double>::quiet_NaN();
}

void DateCache::ClearSegment(DST* segment) {
  segment->start_sec = kMaxEpochTimeInSec;
  segment->end_sec = -kMaxEpochTimeInSec;
  segment->offset_ms = 0;
  segment->last_used = 0;
}

void DateCache::YearMonthDayFromDays(int days, int* year, int* month,
                                     int* day) {
  if (ymd_valid_) {
    // Check conservatively if the given 'days' has
    // the same year and month as the cached 'days'.
    int new_day = ymd_day_ + (days - ymd_days_);
    if (new_day >= 1 && new_day <= 28) {
      ymd_day_ = new_day;
      ymd_days_ = days;
      *year = ymd_year_;
      *month = ymd_month_;
      *day = new_day;
      return;
    }
  }
  int save_days = days;

  days += kDaysOffset;
  *year = 400 * (days / kDaysIn400Years) - kYearsOffset;
  days %= kDaysIn400Years;

  DCHECK_EQ(save_days, DaysFromYearMonth(*year, 0) + days);

  days--;
  int yd1 = days / kDaysIn100Years;
  days %= kDaysIn100Years;
  *year += 100 * yd1;

  days++;
  int yd2 = days / kDaysIn4Years;
  days %= kDaysIn4Years;
  *year += 4 * yd2;

  days--;
  int yd3 = days / 365;
  days %= 365;
  *year += yd3;

  bool is_leap = (!yd1 || yd2) && !yd3;

  DCHECK_GE(days, -1);
  DCHECK(is_leap || (days >= 0));
  DCHECK((days < 365) || (is_leap && (days < 366)));
  DCHECK(is_leap == ((*year % 4 == 0) && (*year % 100 || (*year % 400 == 0))));
  DCHECK(is_leap || ((DaysFromYearMonth(*year, 0) + days) == save_days));
  DCHECK(!is_leap || ((DaysFromYearMonth(*year, 0) + days + 1) == save_days));

  days += is_leap;

  // Check if the date is after February.
  if (days >= 31 + 28 + BoolToInt(is_leap)) {
    days -= 31 + 28 + BoolToInt(is_leap);
    // Find the date starting from March.
    for (int i = 2; i < 12; i++) {
      if (days < kDaysInMonths[i]) {
        *month = i;
        *day = days + 1;
        break;
      }
      days -= kDaysInMonths[i];
    }
  } else {
    // Check January and February.
    if (days < 31) {
      *month = 0;
      *day = days + 1;
    } else {
      *month = 1;
      *day = days - 31 + 1;
    }
  }
  DCHECK(DaysFromYearMonth(*year, *month) + *day - 1 == save_days);
  ymd_valid_ = true;
  ymd_year_ = *year;
  ymd_month_ = *month;
  ymd_day_ = *day;
  ymd_days_ = save_days;
}

int DateCache::DaysFromYearMonth(int year, int month) {
  static const int day_from_month[] = {0,   31,  59,  90,  120, 151,
                                       181, 212, 243, 273, 304, 334};
  static const int day_from_month_leap[] = {0,   31,  60,  91,  121, 152,
                                            182, 213, 244, 274, 305, 335};

  year += month / 12;
  month %= 12;
  if (month < 0) {
    year--;
    month += 12;
  }

  DCHECK_GE(month, 0);
  DCHECK_LT(month, 12);

  // year_delta is an arbitrary number such that:
  // a) year_delta = -1 (mod 400)
  // b) year + year_delta > 0 for years in the range defined by
  //    ECMA 262 - 15.9.1.1, i.e. upto 100,000,000 days on either side of
  //    Jan 1 1970. This is required so that we don't run into integer
  //    division of negative numbers.
  // c) there shouldn't be an overflow for 32-bit integers in the following
  //    operations.
  static const int year_delta = 399999;
  static const int base_day =
      365 * (1970 + year_delta) + (1970 + year_delta) / 4 -
      (1970 + year_delta) / 100 + (1970 + year_delta) / 400;

  int year1 = year + year_delta;
  int day_from_year =
      365 * year1 + year1 / 4 - year1 / 100 + year1 / 400 - base_day;

  if ((year % 4 != 0) || (year % 100 == 0 && year % 400 != 0)) {
    return day_from_year + day_from_month[month];
  }
  return day_from_year + day_from_month_leap[month];
}

void DateCache::BreakDownTime(int64_t time_ms, int* year, int* month, int* day,
                              int* weekday, int* hour, int* min, int* sec,
                              int* ms) {
  int const days = DaysFromTime(time_ms);
  int const time_in_day_ms = TimeInDay(time_ms, days);
  YearMonthDayFromDays(days, year, month, day);
  *weekday = Weekday(days);
  *hour = time_in_day_ms / (60 * 60 * 1000);
  *min = (time_in_day_ms / (60 * 1000)) % 60;
  *sec = (time_in_day_ms / 1000) % 60;
  *ms = time_in_day_ms % 1000;
}

// Implements LocalTimeZonedjustment(t, isUTC)
// ECMA 262 - ES#sec-local-time-zone-adjustment
int DateCache::GetLocalOffsetFromOS(int64_t time_ms, bool is_utc) {
  double offset;
#ifdef V8_INTL_SUPPORT
  if (FLAG_icu_timezone_data) {
    offset = tz_cache_->LocalTimeOffset(static_cast<double>(time_ms), is_utc);
  } else {
#endif
    // When ICU timezone data is not used, we need to compute the timezone
    // offset for a given local time.
    //
    // The following shows that using DST for (t - LocalTZA - hour) produces
    // correct conversion where LocalTZA is the timezone offset in winter (no
    // DST) and the timezone offset is assumed to have no historical change.
    // Note that it does not work for the past and the future if LocalTZA (no
    // DST) is different from the current LocalTZA (no DST). For instance,
    // this will break for Europe/Moscow in 2012 ~ 2013 because LocalTZA was
    // 4h instead of the current 3h (as of 2018).
    //
    // Consider transition to DST at local time L1.
    // Let L0 = L1 - hour, L2 = L1 + hour,
    //     U1 = UTC time that corresponds to L1,
    //     U0 = U1 - hour.
    // Transitioning to DST moves local clock one hour forward L1 => L2, so
    // U0 = UTC time that corresponds to L0 = L0 - LocalTZA,
    // U1 = UTC time that corresponds to L1 = L1 - LocalTZA,
    // U1 = UTC time that corresponds to L2 = L2 - LocalTZA - hour.
    // Note that DST(U0 - hour) = 0, DST(U0) = 0, DST(U1) = 1.
    // U0 = L0 - LocalTZA - DST(L0 - LocalTZA - hour),
    // U1 = L1 - LocalTZA - DST(L1 - LocalTZA - hour),
    // U1 = L2 - LocalTZA - DST(L2 - LocalTZA - hour).
    //
    // Consider transition from DST at local time L1.
    // Let L0 = L1 - hour,
    //     U1 = UTC time that corresponds to L1,
    //     U0 = U1 - hour, U2 = U1 + hour.
    // Transitioning from DST moves local clock one hour back L1 => L0, so
    // U0 = UTC time that corresponds to L0 (before transition)
    //    = L0 - LocalTZA - hour.
    // U1 = UTC time that corresponds to L0 (after transition)
    //    = L0 - LocalTZA = L1 - LocalTZA - hour
    // U2 = UTC time that corresponds to L1 = L1 - LocalTZA.
    // Note that DST(U0) = 1, DST(U1) = 0, DST(U2) = 0.
    // U0 = L0 - LocalTZA - DST(L0 - LocalTZA - hour) = L0 - LocalTZA - DST(U0).
    // U2 = L1 - LocalTZA - DST(L1 - LocalTZA - hour) = L1 - LocalTZA - DST(U1).
    // It is impossible to get U1 from local time.
    if (local_offset_ms_ == kInvalidLocalOffsetInMs) {
      // This gets the constant LocalTZA (arguments are ignored).
      local_offset_ms_ =
          tz_cache_->LocalTimeOffset(static_cast<double>(time_ms), is_utc);
    }
    offset = local_offset_ms_;
    if (!is_utc) {
      const int kMsPerHour = 3600 * 1000;
      time_ms -= (offset + kMsPerHour);
    }
    offset += DaylightSavingsOffsetInMs(time_ms);
#ifdef V8_INTL_SUPPORT
  }
#endif
  DCHECK_LT(offset, kInvalidLocalOffsetInMs);
  return static_cast<int>(offset);
}

void DateCache::ExtendTheAfterSegment(int time_sec, int offset_ms) {
  if (after_->offset_ms == offset_ms &&
      after_->start_sec - kDefaultDSTDeltaInSec <= time_sec &&
      time_sec <= after_->end_sec) {
    // Extend the after_ segment.
    after_->start_sec = time_sec;
  } else {
    // The after_ segment is either invalid or starts too late.
    if (!InvalidSegment(after_)) {
      // If the after_ segment is valid, replace it with a new segment.
      after_ = LeastRecentlyUsedDST(before_);
    }
    after_->start_sec = time_sec;
    after_->end_sec = time_sec;
    after_->offset_ms = offset_ms;
    after_->last_used = ++dst_usage_counter_;
  }
}

int DateCache::DaylightSavingsOffsetInMs(int64_t time_ms) {
  int time_sec = (time_ms >= 0 && time_ms <= kMaxEpochTimeInMs)
                     ? static_cast<int>(time_ms / 1000)
                     : static_cast<int>(EquivalentTime(time_ms) / 1000);

  // Invalidate cache if the usage counter is close to overflow.
  // Note that dst_usage_counter is incremented less than ten times
  // in this function.
  if (dst_usage_counter_ >= kMaxInt - 10) {
    dst_usage_counter_ = 0;
    for (int i = 0; i < kDSTSize; ++i) {
      ClearSegment(&dst_[i]);
    }
  }

  // Optimistic fast check.
  if (before_->start_sec <= time_sec && time_sec <= before_->end_sec) {
    // Cache hit.
    before_->last_used = ++dst_usage_counter_;
    return before_->offset_ms;
  }

  ProbeDST(time_sec);

  DCHECK(InvalidSegment(before_) || before_->start_sec <= time_sec);
  DCHECK(InvalidSegment(after_) || time_sec < after_->start_sec);

  if (InvalidSegment(before_)) {
    // Cache miss.
    before_->start_sec = time_sec;
    before_->end_sec = time_sec;
    before_->offset_ms = GetDaylightSavingsOffsetFromOS(time_sec);
    before_->last_used = ++dst_usage_counter_;
    return before_->offset_ms;
  }

  if (time_sec <= before_->end_sec) {
    // Cache hit.
    before_->last_used = ++dst_usage_counter_;
    return before_->offset_ms;
  }

  if (time_sec - kDefaultDSTDeltaInSec > before_->end_sec) {
    // If the before_ segment ends too early, then just
    // query for the offset of the time_sec
    int offset_ms = GetDaylightSavingsOffsetFromOS(time_sec);
    ExtendTheAfterSegment(time_sec, offset_ms);
    // This swap helps the optimistic fast check in subsequent invocations.
    DST* temp = before_;
    before_ = after_;
    after_ = temp;
    return offset_ms;
  }

  // Now the time_sec is between
  // before_->end_sec and before_->end_sec + default DST delta.
  // Update the usage counter of before_ since it is going to be used.
  before_->last_used = ++dst_usage_counter_;

  // Check if after_ segment is invalid or starts too late.
  // Note that start_sec of invalid segments is kMaxEpochTimeInSec.
  int new_after_start_sec =
      before_->end_sec < kMaxEpochTimeInSec - kDefaultDSTDeltaInSec
          ? before_->end_sec + kDefaultDSTDeltaInSec
          : kMaxEpochTimeInSec;
  if (new_after_start_sec <= after_->start_sec) {
    int new_offset_ms = GetDaylightSavingsOffsetFromOS(new_after_start_sec);
    ExtendTheAfterSegment(new_after_start_sec, new_offset_ms);
  } else {
    DCHECK(!InvalidSegment(after_));
    // Update the usage counter of after_ since it is going to be used.
    after_->last_used = ++dst_usage_counter_;
  }

  // Now the time_sec is between before_->end_sec and after_->start_sec.
  // Only one daylight savings offset change can occur in this interval.

  if (before_->offset_ms == after_->offset_ms) {
    // Merge two segments if they have the same offset.
    before_->end_sec = after_->end_sec;
    ClearSegment(after_);
    return before_->offset_ms;
  }

  // Binary search for daylight savings offset change point,
  // but give up if we don't find it in five iterations.
  for (int i = 4; i >= 0; --i) {
    int delta = after_->start_sec - before_->end_sec;
    int middle_sec = (i == 0) ? time_sec : before_->end_sec + delta / 2;
    int offset_ms = GetDaylightSavingsOffsetFromOS(middle_sec);
    if (before_->offset_ms == offset_ms) {
      before_->end_sec = middle_sec;
      if (time_sec <= before_->end_sec) {
        return offset_ms;
      }
    } else {
      DCHECK(after_->offset_ms == offset_ms);
      after_->start_sec = middle_sec;
      if (time_sec >= after_->start_sec) {
        // This swap helps the optimistic fast check in subsequent invocations.
        DST* temp = before_;
        before_ = after_;
        after_ = temp;
        return offset_ms;
      }
    }
  }
  return 0;
}

void DateCache::ProbeDST(int time_sec) {
  DST* before = nullptr;
  DST* after = nullptr;
  DCHECK(before_ != after_);

  for (int i = 0; i < kDSTSize; ++i) {
    if (dst_[i].start_sec <= time_sec) {
      if (before == nullptr || before->start_sec < dst_[i].start_sec) {
        before = &dst_[i];
      }
    } else if (time_sec < dst_[i].end_sec) {
      if (after == nullptr || after->end_sec > dst_[i].end_sec) {
        after = &dst_[i];
      }
    }
  }

  // If before or after segments were not found,
  // then set them to any invalid segment.
  if (before == nullptr) {
    before = InvalidSegment(before_) ? before_ : LeastRecentlyUsedDST(after);
  }
  if (after == nullptr) {
    after = InvalidSegment(after_) && before != after_
                ? after_
                : LeastRecentlyUsedDST(before);
  }

  DCHECK_NOT_NULL(before);
  DCHECK_NOT_NULL(after);
  DCHECK(before != after);
  DCHECK(InvalidSegment(before) || before->start_sec <= time_sec);
  DCHECK(InvalidSegment(after) || time_sec < after->start_sec);
  DCHECK(InvalidSegment(before) || InvalidSegment(after) ||
         before->end_sec < after->start_sec);

  before_ = before;
  after_ = after;
}

DateCache::DST* DateCache::LeastRecentlyUsedDST(DST* skip) {
  DST* result = nullptr;
  for (int i = 0; i < kDSTSize; ++i) {
    if (&dst_[i] == skip) continue;
    if (result == nullptr || result->last_used > dst_[i].last_used) {
      result = &dst_[i];
    }
  }
  ClearSegment(result);
  return result;
}

}  // namespace internal
}  // namespace v8


text:
package com.amazonaws.services.connectcampaign.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;

import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.connectcampaign.model.*;
import com.amazonaws.transform.Marshaller;

import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * StopCampaignRequest Marshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class StopCampaignRequestProtocolMarshaller implements Marshaller<Request<StopCampaignRequest>, StopCampaignRequest> {

    private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/campaigns/{id}/stop")
            .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AmazonConnectCampaign").build();

    private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;

    public StopCampaignRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
        this.protocolFactory = protocolFactory;
    }

    public Request<StopCampaignRequest> marshall(StopCampaignRequest stopCampaignRequest) {

        if (stopCampaignRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            final ProtocolRequestMarshaller<StopCampaignRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
                    stopCampaignRequest);

            protocolMarshaller.startMarshalling();
            StopCampaignRequestMarshaller.getInstance().marshall(stopCampaignRequest, protocolMarshaller);
            return protocolMarshaller.finishMarshalling();
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
Simple MIPS Simulator in JavaScript (Experimental)
==================================================
<!---
This is an experimental project after taking the computer architecture course during my undergraduate study. Basically it provides a basic playground for MIPS assembly. However, only a limited set of instructions are available due to limited time:
-->
[![Build Status](https://travis-ci.org/jfmherokiller/SimpleMIPS.js.svg?branch=master)](https://travis-ci.org/jfmherokiller/SimpleMIPS.js)[![codecov](https://codecov.io/gh/jfmherokiller/SimpleMIPS.js/branch/master/graph/badge.svg)](https://codecov.io/gh/jfmherokiller/SimpleMIPS.js)

List of Currently Implemented instructions:
- **Memory access**: lb, lbu, lh, lhu, lui, lw, sb, sh, sw, mfhi, mflo, mthi, mtlo
- **Arithmetic operations**: addi, addiu, add, addu, sub, subu, slt, slti, sltu, sltiu, mult, multu, div, divu
- **Logical operations**: and, andi, or, ori, xor, xori, nor, sll, sllv, srl, sra, srlv, srav
- **Jump**: j, jr,jal,
- **Conditional branch**: beq, bne, blez, bgtz, bltz, bgez,bltzal,bgezal
- **Misc/Pseudo instructions**: nop, break, print prints, printm,b,la,popr,pushr,li
<!---
It should be noted that the detailed 5-stage pipeline implementation does not reflect any real MIPS processor. It is my own implantation for my course project, where the branching logic was put in the instruction decoding stage. The memory model is also ideal so there is no additional delay in the writeback stage.

I have implemented both the functional simulator and the pipeline simulator, both of which can be found in SimpleMIPS.js. A mini-assembler is also included. While the basic "to upper case" program works well, it is not guaranteed to be bug-free (probably lots of bugs). [jQuery](http://jquery.com/) and [Normalize.css](http://necolas.github.io/normalize.css/) was used when implementing the interface.

**IMPORTANT: Unfortunately, since I no longer work in this area, I will no longer maintain this project (so please no pull request). I released it here for anyone interested. Feel free to check the code and modify it as you wish. Have fun :)**
-->


text:
require "uri"
require "pg"

module Elefant
  class ConnectionAdapter

    attr_accessor :connection

    def initialize(connection=nil)
      @connection = connection.nil? ? establish_new : validate!(connection)
    end

    def execute(stmt, params = [])
      begin
        params = nil if params.empty?
        r = @connection.exec(stmt, params)
        result = []
        r.each do |t|
          result << t
        end
        result
      rescue PGError => e
        @connection.reset
        raise e
      end
    end

    def disconnect
      begin
        if active_record?
          @connection = nil
          ActiveRecord::Base.clear_active_connections!
        else
          @connection.close
        end
      rescue => e
        # TODO: log something and do sensible stuff
        raise e
      end
    end

    def alive?
      @connection.query "SELECT 1"
      true
    rescue PGError
      false
    end

    def info
      @info ||= {
          db_name: @connection.db,
          server_version: version_str(connection.server_version),
          client_version: (PG.respond_to?( :library_version ) ? version_str(PG.library_version) : 'unknown')
      }
    end

    def db_name
      @connection.db
    end

    def active_record?
      defined?(ActiveRecord::Base) == "constant" && ActiveRecord::Base.class == Class && !Elefant.configuration.disable_ar
    end

    private

    def version_str(number)
      number.to_s.tr('0','.').gsub(/(\.)+\z/, '')
    end

    def validate!(c)
      return c if c.is_a?(PG::Connection)
      err = "connection must be an instance of PG::Connection, but was #{c.class}"
      raise(ArgumentError, err)
    end

    def establish_new
      #QC.log(:at => "establish_conn")
      connection = if active_record?
                     establish_ar
                   else
                     establish_pg
                   end
      connection.exec("SET application_name = 'Elefant Stats #{Elefant::VERSION}'")
      connection
    end

    def establish_pg
      PGconn.connect(*normalize_db_url(db_url))
      # if conn.status != PGconn::CONNECTION_OK
      #   log(:error => conn.error)
      # end
    end

    def establish_ar
      ActiveRecord::Base.connection.raw_connection
    end

    def normalize_db_url(url)
      host = url.host
      host = host.gsub(/%2F/i, '/') if host

      [
          host, # host or percent-encoded socket path
          url.port || 5432,
          nil, "", #opts, tty
          url.path.gsub('/', ''), # database name
          url.user,
          url.password
      ]
    end

    def db_url
      return @db_url if defined?(@db_url) && @db_url

      url = ENV["ELEFANT_DATABASE_URL"] ||
          ENV["DATABASE_URL"] ||
          raise(ArgumentError, "missing ELEFANT_DATABASE_URL or DATABASE_URL")
      @db_url = URI.parse(url)
    end
  end
end


text: throw new Error('This file should be ignored');


text:
using System;

namespace CheckBitAtGivenPosition

    //Problem 13. Check a Bit at Given Position
    //Write a Boolean expression that returns if the bit at position p (counting from 0, starting from the right)
    //in given integer number n, has value of 1.

{
    class CheckBitAtGivenPosition
    {
        static void Main()
        {
            string number = null;
            string bit = null;

            Console.Write("Enter number: ");
            int intNumber = int.Parse(Console.ReadLine());

            Console.Write("Check witch bit?: ");
            int intBit = int.Parse (Console.ReadLine());

            int mask = 1 << intBit;
            int result = intNumber & mask;
            result >>= intBit;

            bool isItOne = result == 1 ? true : false;
            Console.WriteLine("Is the bit {0} of the number {1}[{2}] is 1? {3}", intBit, intNumber, Convert.ToString(intNumber, 2).PadLeft(32, '0'), isItOne);
        }

    }
}


text:
<?php
class Signup extends CI_Controller
{
	function __construct(){
		parent::__construct();
		//varify_user();
	}

	function index(){

		//testing sendy
        /*$sendy_subscribe = $this->subscribe_model->subscribe_sendy();
        echo $sendy_subscribe;exit;*/

		if($this->session->userdata('user_id'))
		    redirect('agent-profile-menu/upgrade-account');

		$data['class']	= 'signup';
		$data['title']  =  'Sign Up';

		if($this->session->userdata('user_id') != ''){
            redirect('agent-profile-menu/upgrade-account');
        } else {

            $result['user_type'] = $this->user_model->select_all('*', 'user_type');
            $result['youtube_video_link'] = get_config_data('config_realty_youtube_video');
            $result['thumbnail'] = get_config_data('config_realty_youtube_thumbnail');
            $data['content'] = $this->load->view('front/signup/signup',$result,true);
            $this->load->view('front/template',$data);
        }
	}

	function success(){
		$data['class']	= 'signup';
		$data['title']  =  'Sign Up Success';
		$result['user_type'] = "";
		$data['content'] = $this->load->view('front/signup/signup_success',$result,true);
		$this->load->view('front/template',$data);
	}

	/*function mautic_testing(){

		$data['first_name'] = 'ali';
		$data['last_name'] = 'ali';
		$email = 'ali@yahoo.com';

        $mautic_subscribe = $this->subscribe_model->subscribe_mautic($data['first_name'], $data['last_name'], $email);
        echo $mautic_subscribe;exit;
	}*/

}


text:
package org.openkilda.northbound.dto.v2.switches;

import org.openkilda.model.SwitchId;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Value;

@Value
@AllArgsConstructor
@Builder
@JsonInclude(Include.NON_EMPTY)
@JsonNaming(value = SnakeCaseStrategy.class)
public class PortPropertiesResponse {

    SwitchId switchId;
    int portNumber;
    boolean discoveryEnabled;
}


text:
set -o xtrace -o errexit

if [[ "${TRAVIS_SUDO}" == "true" && -n "${ZULU_JDK}" ]]
then
    # Install OpenJDK Zulu from repository
    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 0x219BD9C9
    sudo apt-add-repository 'deb http://repos.azulsystems.com/ubuntu stable main'
    sudo apt-get update -qq && sudo apt-get install zulu-${ZULU_JDK} -y
fi


text:
.. _add_data:

Datasets
========

For a list of currently available datasets and usage instructions, see the
:ref:`datasets page <datasets>`.

License
-------

To be considered for inclusion in `statsmodels`, a dataset must be in the
public domain, distributed under a BSD-compatible license, or we must obtain
permission from the original author.

Adding a dataset: An example
----------------------------

The Nile River data measures the volume of the discharge of the Nile River at
Aswan for the years 1871 to 1970. The data are copied from the paper of Cobb
(1978).

**Step 1**: Create a directory `datasets/nile/`

**Step 2**: Add `datasets/nile/nile.csv` and  a new file `datasets/__init__.py` which contains ::

    from data import *

**Step 3**: If `nile.csv` is a transformed/cleaned version of the original data, create a `nile/src` directory and include the original raw data there. In the `nile` case, this step is not necessary.

**Step 4**: Copy `datasets/template_data.py` to `nile/data.py`. Edit `nile/data.py` by filling-in strings for COPYRIGHT, TITLE, SOURCE, DESCRSHORT, DESCLONG, and NOTE. ::

    COPYRIGHT   = """This is public domain."""
    TITLE       = """Nile River Data"""
    SOURCE      = """
    Cobb, G.W. 1978. The Problem of the Nile: Conditional Solution to a Changepoint
        Problem. Biometrika. 65.2, 243-251,
    """

    DESCRSHORT  = """Annual Nile River Volume at Aswan, 1871-1970""

    DESCRLONG   = """AAnnual Nile River Volume at Aswan, 1871-1970. The units of
    measurement are 1e9 m^{3}, and there is an apparent changepoint near 1898."""

    NOTE        = """
    Number of observations: 100
    Number of variables: 2
    Variable name definitions:
        year - Year of observation
        volume - Nile River volume at Aswan

    The data were originally used in Cobb (1987, See SOURCE). The author
    acknowledges that the data were originally compiled from various sources by
    Dr. Barbara Bell, Center for Astrophysics, Cambridge, Massachusetts. The data
    set is also used as an example in many textbooks and software packages.
    """

**Step 5:** Edit the docstring of the `load` function in `data.py` to specify
which dataset will be loaded. Also edit the path and the indices for the
`endog` and `exog` attributes. In the `nile` case, there is no `exog`, so
everything referencing `exog` is not used. The `year` variable is also not
used.

**Step 6:** Edit the `datasets/__init__.py` to import the directory.

That's it! The result can be found `here
<https://github.com/statsmodels/statsmodels/tree/master/statsmodels/datasets/nile>`_
for reference.


text:
:title: Base commands
:description: Common usage and commands
:keywords: Examples, Usage

The basics
=============

Starting Docker
---------------

If you have used one of the quick install paths', Docker may have been installed with upstart, Ubuntu's
system for starting processes at boot time. You should be able to run ``docker help`` and get output.

If you get ``docker: command not found`` or something like ``/var/lib/docker/repositories: permission denied``
you will need to specify the path to it and manually start it.

.. code-block:: bash

    # Run docker in daemon mode
    sudo <path to>/docker -d &

Running an interactive shell
----------------------------

.. code-block:: bash

  # Download a base image
  docker pull base

  # Run an interactive shell in the base image,
  # allocate a tty, attach stdin and stdout
  docker run -i -t base /bin/bash

Starting a long-running worker process
--------------------------------------

.. code-block:: bash

  # Start a very useful long-running process
  JOB=$(docker run -d base /bin/sh -c "while true; do echo Hello world; sleep 1; done")

  # Collect the output of the job so far
  docker logs $JOB

  # Kill the job
  docker kill $JOB

Listing all running containers
------------------------------

.. code-block:: bash

  docker ps

Expose a service on a TCP port
------------------------------

.. code-block:: bash

  # Expose port 4444 of this container, and tell netcat to listen on it
  JOB=$(docker run -d -p 4444 base /bin/nc -l -p 4444)

  # Which public port is NATed to my container?
  PORT=$(docker port $JOB 4444)

  # Connect to the public port via the host's public address
  # Please note that because of how routing works connecting to localhost or 127.0.0.1 $PORT will not work.
  echo hello world | nc $(hostname) $PORT

  # Verify that the network connection worked
  echo "Daemon received: $(docker logs $JOB)"

Committing (saving) an image
-----------------------------

Save your containers state to a container image, so the state can be re-used.

When you commit your container only the differences between the image the container was created from
and the current state of the container will be stored (as a diff). See which images you already have
using ``docker images``

.. code-block:: bash

    # Commit your container to a new named image
    docker commit <container_id> <some_name>

    # List your containers
    docker images

You now have a image state from which you can create new instances.

Read more about :ref:`working_with_the_repository` or continue to the complete :ref:`cli`


text:
package com.couchbase.lite;

import com.couchbase.lite.util.Log;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hideki on 8/13/15.
 */
public class SimpleCRUDTest extends LiteTestCaseWithDB {
    public static final String TAG = SimpleCRUDTest.class.getSimpleName();

    public void testHelloWorld() throws Exception{

        Log.w(TAG, "Create a document");

        // get the current date and time
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = GregorianCalendar.getInstance();
        String currentTimeString = dateFormatter.format(calendar.getTime());

        // create an object that contains data for a document
        Map<String, Object> docContent = new HashMap<String, Object>();
        docContent.put("message", "Hello Couchbase Lite");
        docContent.put("creationDate", currentTimeString);

        // display the data for the new document
        Log.w(TAG, "new docContent=" + String.valueOf(docContent));

        // create an empty document
        Document document = database.createDocument();
        assertNotNull(document);

        // write the document to the database
        try {
            document.putProperties(docContent);
            Log.w(TAG, "Document written to database named " + database.getName() + " with ID = " + document.getId());
        } catch (CouchbaseLiteException e) {
            Log.e(TAG, "Cannot write document to database", e);
        }

        // save the ID of the new document
        String docID = document.getId();
        assertNotNull(docID);
        assertNotSame("", docID);

        Log.w(TAG, "Retrieve a document");

        // retrieve the document from the database
        Document retrievedDocument = database.getDocument(docID);
        assertNotNull(retrievedDocument);

        // display the retrieved document
        Log.w(TAG, "retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));

        Log.w(TAG, "Update a document");

        // update the document
        Map<String, Object> updatedProperties = new HashMap<String, Object>();
        updatedProperties.putAll(retrievedDocument.getProperties());
        updatedProperties.put ("message", "We're having a heat wave!");
        updatedProperties.put ("temperature", "95");

        // display the data for the update document
        Log.w(TAG, "update docContent=" + String.valueOf(updatedProperties));

        try {
            retrievedDocument.putProperties(updatedProperties);
            Log.w(TAG, "updated retrievedDocument=" + String.valueOf(retrievedDocument.getProperties()));
        } catch (CouchbaseLiteException e) {
            Log.e (TAG, "Cannot update document", e);
        }

        Log.w(TAG, "Delete a document");

        // delete the document
        try {
            retrievedDocument.delete();
            Log.w (TAG, "Deleted document, deletion status = " + retrievedDocument.isDeleted());
        } catch (CouchbaseLiteException e) {
            Log.e (TAG, "Cannot delete document", e);
        }
    }
}


text:
package org.apache.kafka.streams.kstream.internals.foreignkeyjoin;

import org.apache.kafka.common.errors.UnsupportedVersionException;

import java.util.Arrays;
import java.util.Objects;

public class SubscriptionWrapper<K> {
    static final byte CURRENT_VERSION = 0;

    private final long[] hash;
    private final Instruction instruction;
    private final byte version;
    private final K primaryKey;

    public enum Instruction {
        //Send nothing. Do not propagate.
        DELETE_KEY_NO_PROPAGATE((byte) 0x00),

        //Send (k, null)
        DELETE_KEY_AND_PROPAGATE((byte) 0x01),

        //(changing foreign key, but FK+Val may not exist)
        //Send (k, fk-val) OR
        //Send (k, null) if fk-val does not exist
        PROPAGATE_NULL_IF_NO_FK_VAL_AVAILABLE((byte) 0x02),

        //(first time ever sending key)
        //Send (k, fk-val) only if fk-val exists.
        PROPAGATE_ONLY_IF_FK_VAL_AVAILABLE((byte) 0x03);

        private final byte value;
        Instruction(final byte value) {
            this.value = value;
        }

        public byte getValue() {
            return value;
        }

        public static Instruction fromValue(final byte value) {
            for (final Instruction i: values()) {
                if (i.value == value) {
                    return i;
                }
            }
            throw new IllegalArgumentException("Unknown instruction byte value = " + value);
        }
    }

    public SubscriptionWrapper(final long[] hash, final Instruction instruction, final K primaryKey) {
        this(hash, instruction, primaryKey, CURRENT_VERSION);
    }

    public SubscriptionWrapper(final long[] hash, final Instruction instruction, final K primaryKey, final byte version) {
        Objects.requireNonNull(instruction, "instruction cannot be null. Required by downstream processor.");
        Objects.requireNonNull(primaryKey, "primaryKey cannot be null. Required by downstream processor.");
        if (version != CURRENT_VERSION) {
            throw new UnsupportedVersionException("SubscriptionWrapper does not support version " + version);
        }

        this.instruction = instruction;
        this.hash = hash;
        this.primaryKey = primaryKey;
        this.version = version;
    }

    public Instruction getInstruction() {
        return instruction;
    }

    public long[] getHash() {
        return hash;
    }

    public K getPrimaryKey() {
        return primaryKey;
    }

    public byte getVersion() {
        return version;
    }

    @Override
    public String toString() {
        return "SubscriptionWrapper{" +
            "version=" + version +
            ", primaryKey=" + primaryKey +
            ", instruction=" + instruction +
            ", hash=" + Arrays.toString(hash) +
            '}';
    }
}


text:
package org.jetbrains.sbt

import java.io.File

import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IconLoader

/**
 * @author Pavel Fatin
 */
object Sbt {
  val Name = "SBT"

  val FileExtension = "sbt"

  val FileDescription = "SBT files"

  val BuildFile = "build.sbt"

  val PluginsFile = "plugins.sbt"

  val PropertiesFile = "build.properties"

  val ProjectDirectory = "project"

  val TargetDirectory = "target"

  val ModulesDirectory = ".idea/modules"

  val ProjectDescription = "SBT project"

  val ProjectLongDescription = "Project backed by SBT"

  val BuildModuleSuffix = "-build"

  val BuildModuleName = "SBT module"

  val BuildModuleDescription = "SBT modules are used to mark content roots and to provide libraries for SBT project definitions"

  val BuildLibraryName = "sbt-and-plugins"

  val UnmanagedLibraryName = "unmanaged-jars"

  val UnmanagedSourcesAndDocsName = "unmanaged-sources-and-docs"

  val DefinitionHolderClasses = Seq("sbt.Plugin", "sbt.Build")

  val DefaultImplicitImports = Seq("sbt._", "Process._", "Keys._")

  val LatestVersion = "0.13.9"

  lazy val Icon = IconLoader.getIcon("/sbt.png")

  lazy val FileIcon = IconLoader.getIcon("/sbt-file.png")

  def isProjectDefinitionFile(project: Project, file: File): Boolean = {
    val baseDir = new File(project.getBasePath)
    val projectDir = baseDir / Sbt.ProjectDirectory
    file.getName == Sbt.BuildFile && file.isUnder(baseDir) ||
      file.getName.endsWith(s".${Sbt.FileExtension}") && file.isUnder(baseDir) ||
      file.getName.endsWith(".scala") && file.isUnder(projectDir)
  }
}


text:
name: "\U0001F41E Bug report"
about: Report an issue with Gesture Handler
title: ''
labels: 'bug'
assignees: ''
---

<!--
NOTE: please submit only bug reports here, any new questions or feature requests should be submitted in Discussions:
https://github.com/software-mansion/react-native-gesture-handler/discussions
 -->

## Description

<!--
Tell us what's happening here.
-->

### Screenshots

## Steps To Reproduce

1.

### Expected behavior

### Actual behavior

## Snack or minimal code example

<!--
Please provide a Snack ([https://snack.expo.io/](https://snack.expo.io/)) or provide a minimal code example that reproduces the problem.
Please provide code that can be copied and ran (with imports, please don't use pseudocode if possible).
Here are some tips for providing a minimal example: [https://stackoverflow.com/help/mcve](https://stackoverflow.com/help/mcve).
-->

## Package versions

<!--
Fill in your Gesture Handler and React Native versions below.

List other libraries if relevant.
-->

- React:
- React Native:
- React Native Gesture Handler:


text:
<!doctype html>

	<meta charset="utf-8">
	<title>jQuery UI Effects - Easing demo</title>
	<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">

	<link rel="stylesheet" href="../demos.css">

All easings provided by jQuery UI are drawn above, using a HTML canvas element. Click a diagram to see the easing in action.


text:
<?php

namespace Kanboard\Pagination;

use Kanboard\Core\Base;
use Kanboard\Core\Paginator;
use Kanboard\Model\TaskModel;

/**
 * Class SubtaskPagination
 *
 * @package Kanboard\Pagination
 * @author  Frederic Guillot
 */
class SubtaskPagination extends Base
{
    /**
     * Get dashboard pagination
     *
     * @access public
     * @param  integer $userId
     * @return Paginator
     */
    public function getDashboardPaginator($userId)
    {
        return $this->paginator
            ->setUrl('DashboardController', 'subtasks', array('user_id' => $userId))
            ->setMax(50)
            ->setOrder(TaskModel::TABLE.'.priority')
            ->setDirection('DESC')
            ->setFormatter($this->taskListSubtaskAssigneeFormatter->withUserId($userId)->withoutEmptyTasks())
            ->setQuery($this->taskFinderModel->getUserQuery($userId))
            ->calculate();
    }
}


text:
'use strict';

describe("InLine", function () {

  var Creative = require('ads/vast/Creative');
  var InLine = require('ads/vast/InLine');

  var xml = require('utils/xml');

  var inlineXML;

  beforeEach(function () {
    inlineXML = '<?xml version="1.0" encoding="UTF-8"?>' +
      '<InLine>' +
      '<AdSystem>GDFP</AdSystem>' +
      '<AdTitle>41683 Hof Christmas</AdTitle>' +
      '<Impression><![CDATA[]]></Impression>' +
      '<Creatives>' +
      '<Creative id="8454" sequence="1"></Creative>' +
      '</Creatives>' +
      '</InLine>';

  });

  it("must return an instance of InLine", function () {
    assert.instanceOf(new InLine(xml.toJXONTree(inlineXML)), InLine);
  });

  describe("required fields", function () {
    var inline;

    beforeEach(function () {
      inline = new InLine(xml.toJXONTree(inlineXML));
    });

    it("must publish the adTitle", function () {
      assert.equal(inline.adTitle, '41683 Hof Christmas');
    });

    it("must publish the adSystem", function () {
      assert.equal(inline.adSystem, 'GDFP');
    });

    describe("impressions", function () {
      it("must be an array", function () {
        assert.isArray(inline.impressions);
      });

      it("must be empty if there is no real impression", function () {
        inlineXML = '<InLine>' +
          '<Impression><![CDATA[]]></Impression>' +
          '</InLine>';
        inline = new InLine(xml.toJXONTree(inlineXML));
        assert.equal(inline.impressions.length, 0);
      });

      it("must contain the defined impression", function () {
        inlineXML = '<InLine>' +
          '<Impression id="DART">' +
          '<![CDATA[http://ad.doubleclick.net/imp;v7;x;223626102;0-0;0;47414672;0/0;30477563/30495440/1;;~aopt=0/0/ff/0;~cs=j%3fhttp://s0.2mdn.net/dot.gif]]>' +
          '</Impression>' +
          '</InLine>';
        inline = new InLine(xml.toJXONTree(inlineXML));

        assert.deepEqual(inline.impressions, [
          'http://ad.doubleclick.net/imp;v7;x;223626102;0-0;0;47414672;0/0;30477563/30495440/1;;~aopt=0/0/ff/0;~cs=j%3fhttp://s0.2mdn.net/dot.gif'
        ]);
      });

      it("must be possible to contain more than one impression", function () {
        inlineXML = '<InLine>' +
          '<Impression id="DART">' +
          '<![CDATA[http://ad.doubleclick.net/imp;v7;x;223626102;0-0;0;47414672;0/0;30477563/30495440/1;;~aopt=0/0/ff/0;~cs=j%3fhttp://s0.2mdn.net/dot.gif]]>' +
          '</Impression>' +
          '<Impression id="ThirdParty">' +
          '<![CDATA[http://ad.doubleclick.net/ad/N270.Process_Other/B3473145;sz=1x1;ord=6212269?]]>' +
          '</Impression>' +
          '<Impression>' +
          '<![CDATA[]]>' +
          '</Impression>' +
          '</InLine>';
        inline = new InLine(xml.toJXONTree(inlineXML));

        assert.deepEqual(inline.impressions, [
          'http://ad.doubleclick.net/imp;v7;x;223626102;0-0;0;47414672;0/0;30477563/30495440/1;;~aopt=0/0/ff/0;~cs=j%3fhttp://s0.2mdn.net/dot.gif',
          'http://ad.doubleclick.net/ad/N270.Process_Other/B3473145;sz=1x1;ord=6212269?'
        ]);
      });
    });

    describe("creatives", function () {

      beforeEach(function () {
        inlineXML = '<InLine>' +
          '<Creatives>' +
          '<Creative id="8454" sequence="1"></Creative>' +
          '<Creative id="8455" sequence="2"></Creative>' +
          '</Creatives>' +
          '</InLine>';
        inline = new InLine(xml.toJXONTree(inlineXML));
      });

      it("must be an array or creatives", function () {
        assert.isArray(inline.creatives);
        assert.instanceOf(inline.creatives[0], Creative);
        assert.equal(inline.creatives[0].id, 8454);
        assert.instanceOf(inline.creatives[1], Creative);
        assert.equal(inline.creatives[1].id, 8455);

      });
    });
  });

  describe("optional fields", function () {
    describe("description", function () {
      it("must be undefined if not set", function () {
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.isUndefined(inline.description);
      });

      it("must contain the description of the ad", function () {
        inlineXML = '<?xml version="1.0" encoding="UTF-8"?>' +
          '<InLine>' +
          '<Description>41683 Hof Christmas ad</Description>' +
          '</InLine>';
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.equal(inline.description, '41683 Hof Christmas ad');
      });
    });

    describe("advertiser", function () {
      it("must be undefined if not set", function () {
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.equal(inline.advertiser, undefined);
      });

      it("must contain the name of the advertiser", function () {
        inlineXML = '<?xml version="1.0" encoding="UTF-8"?>' +
          '<InLine>' +
          '<Advertiser>AdvertiserName</Advertiser>' +
          '</InLine>';
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.equal(inline.advertiser, 'AdvertiserName');
      });
    });

    describe("surveys", function () {
      it("must be an empty array if not surveys are set", function () {
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.deepEqual(inline.surveys, []);
      });

      it("must contain must array with the survey objects an object with a uri and an optional type attr", function () {
        inlineXML = '<InLine>' +
          '<Survey type="text/javascript">' +
          '<![CDATA[http://pubads.g.doubleclick.net/pagead/survey]]>' +
          '</Survey>' +
          '<Survey>' +
          '<![CDATA[http://pubads.g.doubleclick.net/pagead/survey]]>' +
          '</Survey>' +
          '</InLine>';
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.deepEqual(inline.surveys, [
          {
            uri: 'http://pubads.g.doubleclick.net/pagead/survey',
            type: 'text/javascript'
          },
          {
            uri: 'http://pubads.g.doubleclick.net/pagead/survey',
            type: undefined
          }
        ]);
      });
    });

    describe("pricing", function () {
      it("must be undefined if not set", function () {
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.isUndefined(inline.pricing);
      });

      it("must contain the price of the ad if set", function () {
        inlineXML = '<InLine>' +
          '<Pricing>price</Pricing>' +
          '</InLine>';
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.equal(inline.pricing, 'price');
      });
    });

    describe("error", function () {
      it("must be undefined if not set", function () {
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.isUndefined(inline.error);
      });

      /*jshint maxlen: 700 */
      it("must contain the tracking error uri if set", function () {
        inlineXML = '<InLine>' +
          '<Error><![CDATA[http://pubads.g.doubleclick.net/pagead/conversion/?ai=Bc4roEKqOVIzhJqPi7ga7y4G4CrjOsO4FAAAAEAEgyJaWHDgAWNiN_Je3AWC7rquD0AqyARN3d3cuZGFpbHltYWlsLmNvLnVrugENOHg4X3htbF92YXN0M8gBBdoBqAFodHRwOi8vd3d3LmRhaWx5bWFpbC5jby51ay90dnNob3diaXovYXJ0aWNsZS0yODU2OTEyL1BhcnR5LWdpcmwtUmloYW5uYS1sZXRzLWxvb3NlLWRhbmNlZmxvb3Itc2hvd3MtcmF1bmNoeS1tb3Zlcy1zZW1pLXNoZWVyLWdvd24tQnJpdGlzaC1GYXNoaW9uLUF3YXJkcy1hZnRlcnBhcnR5Lmh0bWyYAuiEAakCPN_bpEVluj7AAgLgAgDqAiEvNTc2NS9kbS52aWRlby9kbV92aWRlb190dnNob3diaXr4AvnRHpAD0AWYA9AFqAMB4AQBoAYj&sigh=fy3coLR3uPk&label=videoplayfailed[ERRORCODE]]]></Error>' +
          '</InLine>';
        var inline = new InLine(xml.toJXONTree(inlineXML));

        assert.equal(inline.error, 'http://pubads.g.doubleclick.net/pagead/conversion/?ai=Bc4roEKqOVIzhJqPi7ga7y4G4CrjOsO4FAAAAEAEgyJaWHDgAWNiN_Je3AWC7rquD0AqyARN3d3cuZGFpbHltYWlsLmNvLnVrugENOHg4X3htbF92YXN0M8gBBdoBqAFodHRwOi8vd3d3LmRhaWx5bWFpbC5jby51ay90dnNob3diaXovYXJ0aWNsZS0yODU2OTEyL1BhcnR5LWdpcmwtUmloYW5uYS1sZXRzLWxvb3NlLWRhbmNlZmxvb3Itc2hvd3MtcmF1bmNoeS1tb3Zlcy1zZW1pLXNoZWVyLWdvd24tQnJpdGlzaC1GYXNoaW9uLUF3YXJkcy1hZnRlcnBhcnR5Lmh0bWyYAuiEAakCPN_bpEVluj7AAgLgAgDqAiEvNTc2NS9kbS52aWRlby9kbV92aWRlb190dnNob3diaXr4AvnRHpAD0AWYA9AFqAMB4AQBoAYj&sigh=fy3coLR3uPk&label=videoplayfailed[ERRORCODE]');
      });
    });

    describe("extensions", function () {
      it("must be undefined if not set", function () {
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.isUndefined(inline.extensions);
      });

      it("must be contain the JXONTree of the extension element if set", function () {
        inlineXML = '<InLine>' +
          '<Extensions>price</Extensions>' +
          '</InLine>';
        var inline = new InLine(xml.toJXONTree(inlineXML));
        assert.isDefined(inline.extensions);
        assert.deepEqual(inline.extensions, xml.toJXONTree(inlineXML).extensions);
      });
    });
  });

  describe("isSupported", function () {
    var inLine;

    beforeEach(function () {
      inLine = new InLine(xml.toJXONTree(inlineXML));
    });

    it("must return false if the inLine has no creatives", function () {
      inLine.creatives.length = 0;
      assert.isFalse(inLine.isSupported());
    });

    it("must return true if all the creatives of the inline are supported", function () {
      var spy = sinon.spy();
      inLine.creatives = [
        {
          isSupported: function () {
            spy();
            return true;
          }
        },
        {
          isSupported: function () {
            spy();
            return true;
          }
        }
      ];
      assert.isTrue(inLine.isSupported());
      sinon.assert.calledTwice(spy);
    });

    it("must return false if at least one the creatives of the inline is not supported", function () {
      var spy = sinon.spy();
      inLine.creatives = [
        {
          isSupported: function () {
            spy();
            return false;
          }
        },
        {
          isSupported: function () {
            spy();
            return true;
          }
        }
      ];
      assert.isFalse(inLine.isSupported());
      sinon.assert.calledOnce(spy);
    });

  });
});


text:
/* eslint-disable no-console */
/* eslint-disable no-underscore-dangle */
import {
  Component,
  ElementRef,
  EventEmitter,
  HostBinding,
  HostListener,
  Input,
  Output,
  ViewChild,
} from '@angular/core';

export const exportedConstant = 'An exported constant';

export type ButtonSize = 'small' | 'medium' | 'large' | 'xlarge';

export interface ISomeInterface {
  one: string;
  two: boolean;
  three: any[];
}

export enum ButtonAccent {
  'Normal' = 'Normal',
  'High' = 'High',
}

/**
 * This is a simple button that demonstrates various JSDoc handling in Storybook Docs for Angular.
 *
 * It supports [markdown](https://en.wikipedia.org/wiki/Markdown), so you can embed formatted text,
 * like **bold**, _italic_, and `inline code`.
 *
 * > How you like dem apples?! It's never been easier to document all your components.
 *
 * @string Hello world
 * @link [Example](http://example.com)
 * @code `ThingThing`
 * @html aaa
 */
@Component({
  selector: 'my-button',
  templateUrl: './doc-button.component.html',
  styleUrls: ['./doc-button.component.scss'],
})
export class DocButtonComponent<T> {
  @ViewChild('buttonRef', { static: false }) buttonRef: ElementRef;

  /** Appearance style of the button. */
  @Input()
  public appearance: 'primary' | 'secondary' = 'secondary';

  /** Sets the button to a disabled state. */
  @Input()
  public isDisabled = false;

  /** Specify the accent-type of the button */
  @Input()
  public accent: ButtonAccent = ButtonAccent.Normal;

  /** Specifies some arbitrary object */
  @Input() public someDataObject: ISomeInterface;

  /**
   * The inner text of the button.
   *
   * @required
   */
  @Input()
  public label: string;

  /** Size of the button. */
  @Input()
  public size?: ButtonSize = 'medium';

  /**
   * Some input you shouldn't use.
   *
   * @deprecated
   */
  @Input()
  public somethingYouShouldNotUse = false;

  /**
   * Handler to be called when the button is clicked by a user.
   *
   * Will also block the emission of the event if `isDisabled` is true.
   */
  @Output()
  public onClick = new EventEmitter<Event>();

  /**
   * This is an internal method that we don't want to document and have added the `ignore` annotation to.
   *
   * @ignore
   */
  public handleClick(event: Event) {
    event.stopPropagation();

    if (!this.isDisabled) {
      this.onClick.emit(event);
    }
  }

  private _inputValue = 'some value';

  /** Setter for `inputValue` that is also an `@Input`. */
  @Input()
  public set inputValue(value: string) {
    this._inputValue = value;
  }

  /** Getter for `inputValue`. */
  public get inputValue() {
    return this._inputValue;
  }

  @HostListener('click', ['$event.target'])
  onClickListener(btn) {
    console.log('button', btn);
  }

  @HostBinding('class.focused') focus = false;

  /**
   * Returns all the CSS classes for the button.
   *
   * @ignore
   */
  public get classes(): string[] {
    return [this.appearance, this.size]
      .filter((_class) => !!_class)
      .map((_class) => `btn-${_class}`);
  }

  /**
   * @ignore
   */
  public ignoredProperty = 'Ignore me';

  /** Public value. */
  public internalProperty = 'Public hello';

  /** Private value. */
  private _value = 'Private hello';

  /** Set the private value. */
  public set value(value: string | number) {
    this._value = `${value}`;
  }

  /** Get the private value. */
  public get value(): string | number {
    return this._value;
  }

  /**
   * An internal calculation method which adds `x` and `y` together.
   *
   * @param x Some number you'd like to use.
   * @param y Some other number or string you'd like to use, will have `parseInt()` applied before calculation.
   */
  public calc(x: number, y: string | number): number {
    return x + parseInt(`${y}`, 10);
  }

  /** A public method using an interface. */
  public publicMethod(things: ISomeInterface) {
    console.log(things);
  }

  /**
   * A protected method.
   *
   * @param id Some `id`.
   */
  protected protectedMethod(id?: number) {
    console.log(id);
  }

  /**
   * A private method.
   *
   * @param password Some `password`.
   */
  private privateMethod(password: string) {
    console.log(password);
  }

  @Input('showKeyAlias')
  public showKey: keyof T;

  @Input()
  public set item(item: T[]) {
    this.processedItem = item;
  }

  public processedItem: T[];
}


text:
"""Tests for Bijector."""

# Dependency imports

from absl.testing import parameterized
import numpy as np
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import bijector_test_util
from tensorflow_probability.python.bijectors import softplus
from tensorflow_probability.python.internal import test_util
from tensorflow_probability.python.math import gradient

rng = np.random.RandomState(42)

@test_util.test_all_tf_execution_regimes
class SoftplusBijectorTest(test_util.TestCase):
  """Tests the correctness of the Y = g(X) = Log[1 + exp(X)] transformation."""

  def _softplus(self, x):
    return np.log(1 + np.exp(x))

  def _softplus_inverse(self, y):
    return np.log(np.exp(y) - 1)

  def _softplus_ildj_before_reduction(self, y):
    """Inverse log det jacobian, before being reduced."""
    return -np.log(1 - np.exp(-y))

  def testHingeSoftnessZeroRaises(self):
    with self.assertRaisesOpError(
        'Argument `hinge_softness` must be non-zero.'):
      self.evaluate(
          softplus.Softplus(hinge_softness=0., validate_args=True).forward(1.))

  def testBijectorForwardInverseEventDimsZero(self):
    bijector = softplus.Softplus()
    self.assertStartsWith(bijector.name, 'softplus')
    x = 2 * rng.randn(2, 10)
    y = self._softplus(x)

    self.assertAllClose(y, self.evaluate(bijector.forward(x)))
    self.assertAllClose(x, self.evaluate(bijector.inverse(y)))

  def testBijectorForwardInverseWithHingeSoftnessEventDimsZero(self):
    bijector = softplus.Softplus(hinge_softness=np.float64(1.5))
    x = 2 * rng.randn(2, 10)
    y = 1.5 * self._softplus(x / 1.5)

    self.assertAllClose(y, self.evaluate(bijector.forward(x)))
    self.assertAllClose(x, self.evaluate(bijector.inverse(y)))

  def testBijectorLogDetJacobianEventDimsZero(self):
    bijector = softplus.Softplus()
    y = 2 * rng.rand(2, 10)
    # No reduction needed if event_dims = 0.
    ildj = self._softplus_ildj_before_reduction(y)

    self.assertAllClose(
        ildj,
        self.evaluate(bijector.inverse_log_det_jacobian(
            y, event_ndims=0)))

  def testBijectorForwardInverseEventDimsOne(self):
    bijector = softplus.Softplus()
    self.assertStartsWith(bijector.name, 'softplus')
    x = 2 * rng.randn(2, 10)
    y = self._softplus(x)

    self.assertAllClose(y, self.evaluate(bijector.forward(x)))
    self.assertAllClose(x, self.evaluate(bijector.inverse(y)))

  def testBijectorLogDetJacobianEventDimsOne(self):
    bijector = softplus.Softplus()
    y = 2 * rng.rand(2, 10)
    ildj_before = self._softplus_ildj_before_reduction(y)
    ildj = np.sum(ildj_before, axis=1)

    self.assertAllClose(
        ildj,
        self.evaluate(
            bijector.inverse_log_det_jacobian(
                y, event_ndims=1)))

  def testScalarCongruency(self):
    bijector = softplus.Softplus()
    bijector_test_util.assert_scalar_congruency(
        bijector, lower_x=-2., upper_x=2., eval_func=self.evaluate, rtol=.02)

  def testScalarCongruencyWithPositiveHingeSoftness(self):
    bijector = softplus.Softplus(hinge_softness=1.3)
    bijector_test_util.assert_scalar_congruency(
        bijector, lower_x=-2., upper_x=2., eval_func=self.evaluate, rtol=.02)

  def testScalarCongruencyWithNegativeHingeSoftness(self):
    bijector = softplus.Softplus(hinge_softness=-1.3)
    bijector_test_util.assert_scalar_congruency(
        bijector, lower_x=-2., upper_x=2., eval_func=self.evaluate, rtol=.02)

  def testScalarCongruencyWithLowerBound(self):
    bijector = softplus.Softplus(low=1.6)
    bijector_test_util.assert_scalar_congruency(
        bijector, lower_x=-2., upper_x=2., eval_func=self.evaluate, rtol=.02)

  def testScalarCongruencyWithHingeSoftnessAndLowerBound(self):
    bijector = softplus.Softplus(hinge_softness=1.3, low=1.6)
    bijector_test_util.assert_scalar_congruency(
        bijector, lower_x=-2., upper_x=2., eval_func=self.evaluate, rtol=.02)

  def testBijectiveAndFinite32bit(self):
    bijector = softplus.Softplus()
    x = np.linspace(-20., 20., 100).astype(np.float32)
    y = np.logspace(-10, 10, 100).astype(np.float32)
    bijector_test_util.assert_bijective_and_finite(
        bijector, x, y, eval_func=self.evaluate, event_ndims=0, rtol=1e-2,
        atol=1e-2)

  def testBijectiveAndFiniteWithPositiveHingeSoftness32Bit(self):
    bijector = softplus.Softplus(hinge_softness=1.23)
    x = np.linspace(-20., 20., 100).astype(np.float32)
    y = np.logspace(-10, 10, 100).astype(np.float32)
    bijector_test_util.assert_bijective_and_finite(
        bijector, x, y, eval_func=self.evaluate, event_ndims=0, rtol=1e-2,
        atol=1e-2)

  def testBijectiveAndFiniteWithNegativeHingeSoftness32Bit(self):
    bijector = softplus.Softplus(hinge_softness=-0.7)
    x = np.linspace(-20., 20., 100).astype(np.float32)
    y = -np.logspace(-10, 10, 100).astype(np.float32)
    bijector_test_util.assert_bijective_and_finite(
        bijector, x, y, eval_func=self.evaluate, event_ndims=0, rtol=1e-2,
        atol=1e-2)

  def testVariableHingeSoftness(self):
    hinge_softness = tf.Variable(1.)
    b = softplus.Softplus(hinge_softness=hinge_softness, validate_args=True)
    self.evaluate(hinge_softness.initializer)
    self.assertIs(hinge_softness, b.hinge_softness)
    self.assertEqual((), self.evaluate(b.forward(0.5)).shape)
    with self.assertRaisesOpError(
        'Argument `hinge_softness` must be non-zero.'):
      with tf.control_dependencies([hinge_softness.assign(0.)]):
        self.evaluate(b.forward(0.5))

  def testDtype(self):
    b = softplus.Softplus()
    self.assertIsNone(b.dtype)

    b = softplus.Softplus(low=1.75)
    self.assertEqual(tf.float32, b.dtype)

    b = softplus.Softplus(hinge_softness=tf.constant(0.5, dtype=tf.float64))
    self.assertEqual(tf.float64, b.dtype)

  @parameterized.named_parameters(
      ('32bitGraph', np.float32, False),
      ('64bitGraph', np.float64, False),
      ('32bitXLA', np.float32, True),
      ('64bitXLA', np.float64, True),
  )
  @test_util.numpy_disable_gradient_test
  def testLeftTailGrad(self, dtype, do_compile):
    x = np.linspace(-50., -8., 1000).astype(dtype)

    @tf.function(autograph=False, jit_compile=do_compile)
    def fn(x):
      return tf.math.log(softplus.Softplus().forward(x))

    _, grad = gradient.value_and_gradient(fn, x)

    true_grad = 1 / (1 + np.exp(-x)) / np.log1p(np.exp(x))
    self.assertAllClose(true_grad, self.evaluate(grad), atol=1e-3)

if __name__ == '__main__':
  test_util.main()


text:
@implementation ResendAuthorizedSmsCmd
-(VIHOME_CMD)cmd
{
    return VIHOME_CMD_RSAS;
}

-(NSDictionary *)payload
{
    [sendDic setObject:self.deviceId forKey:@"deviceId"];
    [sendDic setObject:self.phone forKey:@"phone"];
    return sendDic;
}
@end


text:
A solution to the [n-queens puzzle](https://en.wikipedia.org/wiki/Eight_queens_puzzle).

Casting the puzzle as a [set cover problem](https://en.wikipedia.org/wiki/Set_cover_problem), it is solved using [the DLX algorithm](http://arxiv.org/abs/cs/0011047v1).
This project is a stepping-stone to a better algorithm for [my sudoku project](http://github.com/jeffseif/sudoku).

## Development

    > git clone git@github.com:jeffseif/queens.git
    > cd queens
    > make test

## Example invocation

    > ./cli --help
    usage: __main__.py [-h] [--version] [size]

    N-queens solver

    positional arguments:
      size        Number of queens (e.g., 8)

    optional arguments:
      -h, --help  show this help message and exit
      --version   show program's version number and exit

    Version 1.0.0 | Jeffrey Seifried 2016

    > ./cli 4
    0
    +---------+
    | . ♕ . . |
    | . . . ♕ |
    | ♕ . . . |
    | . . ♕ . |
    +---------+
    1
    +---------+
    | . . ♕ . |
    | ♕ . . . |
    | . . . ♕ |
    | . ♕ . . |
    +---------+


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.network.models.P2SVpnConnectionRequest;
import java.util.Arrays;

/** Samples for VirtualNetworkGateways DisconnectVirtualNetworkGatewayVpnConnections. */
public final class VirtualNetworkGatewaysDisconnectVirtualNetworkGatewayVpnConnectionsSamples {
    /*
     * x-ms-original-file: specification/network/resource-manager/Microsoft.Network/stable/2022-05-01/examples/VirtualNetworkGatewaysDisconnectP2sVpnConnections.json
     */
    /**
     * Sample code: Disconnect VpnConnections from Virtual Network Gateway.
     *
     * @param azure The entry point for accessing resource management APIs in Azure.
     */
    public static void disconnectVpnConnectionsFromVirtualNetworkGateway(
        com.azure.resourcemanager.AzureResourceManager azure) {
        azure
            .networks()
            .manager()
            .serviceClient()
            .getVirtualNetworkGateways()
            .disconnectVirtualNetworkGatewayVpnConnections(
                "vpn-gateway-test",
                "vpngateway",
                new P2SVpnConnectionRequest().withVpnConnectionIds(Arrays.asList("vpnconnId1", "vpnconnId2")),
                Context.NONE);
    }
}


text:
// appease the jshint gods
/* eslint no-console:0 */
var mongoscope = window.mongoscopeClient;
var AsciiTable = window.asciiTable;
var $ = window.$;

mongoscope.configure({
  endpoint: 'http://scope.mongodb.land'
});

var deltas = {};
var namespaces = [];
var operations = ['queries', 'inserts', 'removes', 'updates', 'getmore'];

function loop() {
  mongoscope().top().on('data', function(data) {
    deltas = data.deltas;
  });

  setInterval(function() {
    var table = new AsciiTable('top: ' + new Date());
    var columns = ['namespace'];

    columns.push.apply(columns, operations);
    table.setHeading(columns);

    namespaces.map(function(namespace) {
      var row = [namespace];
      row.push.apply(row, operations.map(function(op) {
        return deltas[namespace + '.' + op + '.count'] || 0;
      }));
      table.addRow(row);
    });
    $('.container').append('

'
      + table.toString() + '

');
    document.body.scrollTop = document.body.scrollHeight;
    deltas = {};
  }, 1000);
}

mongoscope().top(function(err, data) {
  if (err) return console.error(err);
  namespaces = data.namespaces;
  deltas = data.deltas;
  loop();
});


text:
module OneCfg

    module Exception

        # Generic OneCfg exception
        class Generic < RuntimeError

            attr_reader :text

            def initialize(text = nil)
                @text = text
                super(text)
            end

        end

        # OneCfg config exception when file not found
        class FileNotFound < Generic

            def initialize(text = 'File not found')
                super(text)
            end

        end

        # OneCfg config exception on file read
        # rubocop:disable Lint/UselessMethodDefinition
        class FileReadError < Generic

        end

        # OneCfg config exception on file write
        class FileWriteError < Generic

        end
        # rubocop:enable Lint/UselessMethodDefinition

        # OneCfg parser exception on file
        # rubocop:disable Lint/UselessMethodDefinition
        class FileParseError < Generic

        end
        # rubocop:enable Lint/UselessMethodDefinition

    end

end


text:
const test = require('ava');
const micro = require('micro');
const listen = require('test-listen');
const rp = require('request-promise');
const pkg = require('./package.json');

const makeService = require('.');

const MockBackend = ({input}) =>
  Promise.resolve({name: input.name, body: input.body, message: 'testing'});

/**
 * Thin wrapper around request-promise
 * that always resolves to a full response
 * object rather than just the response body
 * and automatically parses JSON respones.
 *
 * @param {object} options: Options passed to request-promise.
 * @returns {Promise} The response.
 */
const request = options => {
  const defaults = {
    resolveWithFullResponse: true,
    json: true,
  };
  const opts = {...defaults, ...options};
  return rp(opts);
};

/**
 * Make a mocked service.
 *
 * @param {object} backend: MicroFeedback backend.
 * @returns {object} service and service URL.
 */
const maketestService = async backend => {
  const handler = makeService(backend || MockBackend, {
    name: 'test-backend',
    version: '0.1.0',
  });
  const service = micro(handler);
  const url = await listen(service);
  return {service, url};
};

test('GET: success', async t => {
  const {url} = await maketestService();
  const {body, statusCode} = await request({uri: url});
  t.is(statusCode, 200);
  t.is(body.core.version, pkg.version);
});

test('GET: returns backend attributes', async t => {
  const {url} = await maketestService();
  const {body} = await request({uri: url});
  t.deepEqual(body.backend, {name: 'test-backend', version: '0.1.0'});
});

test('POST: success', async t => {
  const {url} = await maketestService();
  const body = {name: 'steve', body: 'wat'};
  const response = await request({uri: url, method: 'POST', body});
  t.is(response.statusCode, 201);
});

test('POST: response format', async t => {
  const {url} = await maketestService();
  const payload = {name: 'steve', body: 'wat'};
  const {body} = await request({uri: url, method: 'POST', body: payload});
  t.deepEqual(body.result, {name: 'steve', body: 'wat', message: 'testing'});
  t.deepEqual(body.backend, {name: 'test-backend', version: '0.1.0'});
});

test('POST: no issue body given', async t => {
  const {url} = await maketestService();
  const body = {name: 'steve'};
  const response = await request({
    uri: url,
    method: 'POST',
    body,
    simple: false,
  });
  t.is(response.statusCode, 422);
});

test('POST: error thrown by backend', async t => {
  const ErrorBackend = () => {
    throw micro.createError(400, 'Error thrown by backend');
  };
  const {url} = await maketestService(ErrorBackend);
  const payload = {name: 'steve', body: 'wat'};
  const {body, statusCode} = await request({
    uri: url,
    method: 'POST',
    body: payload,
    simple: false,
  });
  t.is(statusCode, 400);
  t.deepEqual(body, {status: 400, message: 'Error thrown by backend'});
});

test('PUT not supported', async t => {
  const {url} = await maketestService();
  const body = {name: 'steve', body: 'wat'};
  const response = await request({
    uri: url,
    method: 'PUT',
    body,
    simple: false,
  });
  t.is(response.statusCode, 405);
});


text:
import type { CompilerOptions, ParsedConfiguration } from '@angular/compiler-cli';
import ts from 'typescript';
import { BuildGraph } from '../graph/build-graph';
import { EntryPointNode, PackageNode, isEntryPointInProgress, isPackage } from '../ng-package/nodes';
import { StylesheetProcessor } from '../styles/stylesheet-processor';
import { augmentProgramWithVersioning, cacheCompilerHost } from '../ts/cache-compiler-host';
import { ngccTransformCompilerHost } from '../ts/ngcc-transform-compiler-host';
import * as log from '../utils/log';
import { ngCompilerCli } from '../utils/ng-compiler-cli';
import { NgccProcessor } from './ngcc-processor';

export async function compileSourceFiles(
  graph: BuildGraph,
  tsConfig: ParsedConfiguration,
  moduleResolutionCache: ts.ModuleResolutionCache,
  extraOptions?: Partial<CompilerOptions>,
  stylesheetProcessor?: StylesheetProcessor,
  ngccProcessor?: NgccProcessor,
  watch?: boolean,
) {
  const { NgtscProgram, formatDiagnostics } = await ngCompilerCli();

  const tsConfigOptions: CompilerOptions = { ...tsConfig.options, ...extraOptions };
  const entryPoint: EntryPointNode = graph.find(isEntryPointInProgress());
  const ngPackageNode: PackageNode = graph.find(isPackage);
  const inlineStyleLanguage = ngPackageNode.data.inlineStyleLanguage;

  const tsCompilerHost = ngccTransformCompilerHost(
    cacheCompilerHost(
      graph,
      entryPoint,
      tsConfigOptions,
      moduleResolutionCache,
      stylesheetProcessor,
      inlineStyleLanguage,
    ),
    tsConfigOptions,
    ngccProcessor,
    moduleResolutionCache,
  );

  const cache = entryPoint.cache;
  const sourceFileCache = cache.sourcesFileCache;

  // Create the Angular specific program that contains the Angular compiler
  const angularProgram = new NgtscProgram(tsConfig.rootNames, tsConfigOptions, tsCompilerHost, cache.oldNgtscProgram);

  const angularCompiler = angularProgram.compiler;
  const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler;

  // SourceFile versions are required for builder programs.
  // The wrapped host inside NgtscProgram adds additional files that will not have versions.
  const typeScriptProgram = angularProgram.getTsProgram();
  augmentProgramWithVersioning(typeScriptProgram);

  let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram;
  if (watch) {
    builder = cache.oldBuilder = ts.createEmitAndSemanticDiagnosticsBuilderProgram(
      typeScriptProgram,
      tsCompilerHost,
      cache.oldBuilder,
    );
    cache.oldNgtscProgram = angularProgram;
  } else {
    // When not in watch mode, the startup cost of the incremental analysis can be avoided by
    // using an abstract builder that only wraps a TypeScript program.
    builder = ts.createAbstractBuilder(typeScriptProgram, tsCompilerHost);
  }

  // Update semantic diagnostics cache
  const affectedFiles = new Set<ts.SourceFile>();

  // Analyze affected files when in watch mode for incremental type checking
  if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) {
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, sourceFile => {
        // If the affected file is a TTC shim, add the shim's original source file.
        // This ensures that changes that affect TTC are typechecked even when the changes
        // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes.
        // For example, changing @Input property types of a directive used in another component's
        // template.
        if (ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts')) {
          // This file name conversion relies on internal compiler logic and should be converted
          // to an official method when available. 15 is length of `.ngtypecheck.ts`
          const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts';
          const originalSourceFile = builder.getSourceFile(originalFilename);
          if (originalSourceFile) {
            affectedFiles.add(originalSourceFile);
          }

          return true;
        }

        return false;
      });

      if (!result) {
        break;
      }

      affectedFiles.add(result.affected as ts.SourceFile);
    }
  }

  // Collect program level diagnostics
  const allDiagnostics: ts.Diagnostic[] = [
    ...angularCompiler.getOptionDiagnostics(),
    ...builder.getOptionsDiagnostics(),
    ...builder.getGlobalDiagnostics(),
  ];

  // Required to support asynchronous resource loading
  // Must be done before creating transformers or getting template diagnostics
  await angularCompiler.analyzeAsync();

  // Collect source file specific diagnostics
  for (const sourceFile of builder.getSourceFiles()) {
    if (!ignoreForDiagnostics.has(sourceFile)) {
      allDiagnostics.push(
        ...builder.getSyntacticDiagnostics(sourceFile),
        ...builder.getSemanticDiagnostics(sourceFile),
      );
    }

    if (sourceFile.isDeclarationFile) {
      continue;
    }

    // Collect sources that are required to be emitted
    if (!ignoreForEmit.has(sourceFile) && !angularCompiler.incrementalDriver.safeToSkipEmit(sourceFile)) {
      // If required to emit, diagnostics may have also changed
      if (!ignoreForDiagnostics.has(sourceFile)) {
        affectedFiles.add(sourceFile);
      }
    } else if (sourceFileCache && !affectedFiles.has(sourceFile) && !ignoreForDiagnostics.has(sourceFile)) {
      // Use cached Angular diagnostics for unchanged and unaffected files
      const angularDiagnostics = sourceFileCache.getAngularDiagnostics(sourceFile);
      if (angularDiagnostics?.length) {
        allDiagnostics.push(...angularDiagnostics);
      }
    }
  }

  // Collect new Angular diagnostics for files affected by changes
  for (const affectedFile of affectedFiles) {
    const angularDiagnostics = angularCompiler.getDiagnosticsForFile(affectedFile, /** OptimizeFor.WholeProgram */ 1);

    allDiagnostics.push(...angularDiagnostics);
    sourceFileCache.updateAngularDiagnostics(affectedFile, angularDiagnostics);
  }

  const otherDiagnostics = [];
  const errorDiagnostics = [];
  for (const diagnostic of allDiagnostics) {
    if (diagnostic.category === ts.DiagnosticCategory.Error) {
      errorDiagnostics.push(diagnostic);
    } else {
      otherDiagnostics.push(diagnostic);
    }
  }

  if (otherDiagnostics.length) {
    log.msg(formatDiagnostics(errorDiagnostics));
  }

  if (errorDiagnostics.length) {
    throw new Error(formatDiagnostics(errorDiagnostics));
  }

  const transformers = angularCompiler.prepareEmit().transformers;
  for (const sourceFile of builder.getSourceFiles()) {
    if (!ignoreForEmit.has(sourceFile)) {
      builder.emit(sourceFile, undefined, undefined, undefined, transformers);
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <issue id="UnusedResources">
        <ignore regexp="library_vntfontlistpreference_strings.xml"/>
    </issue>

    <issue id="ResourceName">
        <ignore regexp="library_vntfontlistpreference_strings.xml"/>
    </issue>
</lint>


text:
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@android:color/transparent" android:state_checked="true" android:state_window_focused="false"/>
    <item android:drawable="@drawable/shopping_species_normal" android:state_checked="false" android:state_window_focused="false"/>
    <item android:drawable="@android:color/transparent" android:state_checked="true" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent" android:state_checked="false" android:state_pressed="true"/>
    <item android:drawable="@android:color/transparent" android:state_checked="true" android:state_focused="true"/>
    <item android:drawable="@android:color/transparent" android:state_checked="false" android:state_focused="true"/>
    <item android:drawable="@drawable/shopping_species_normal" android:state_checked="false"/>
    <item android:drawable="@android:color/transparent" android:state_checked="true"/>

</selector>


text:
package com.asakusafw.lang.compiler.api.reference;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Represents a task in runtime.
 * @since 0.3.0
 */
public interface TaskReference extends BlockingReference<TaskReference> {

    /**
     * Returns the module name for processing this task.
     * The module name must consist of lower-case alphabets or digits.
     * @return the module name
     */
    String getModuleName();

    /**
     * Returns the acceptable extension names for this task.
     * @return the acceptable extension names
     * @since 0.3.0
     */
    Set<String> getExtensions();

    /**
     * Returns tasks which must be executed before this task.
     * @return the blocker tasks
     */
    @Override
    Collection<? extends TaskReference> getBlockers();

    /**
     * Phases each task replies on.
     */
    enum Phase {

        /**
         * Initialization.
         */
        INITIALIZE,

        /**
         * Importing input data.
         */
        IMPORT,

        /**
         * Pre-processing input data.
         */
        PROLOGUE,

        /**
         * Processing data.
         */
        MAIN,

        /**
         * Post-processing output data.
         */
        EPILOGUE,

        /**
         * Exporting output data.
         */
        EXPORT,

        /**
         * Finalization.
         */
        FINALIZE,
        ;

        /**
         * Returns the symbol of this phase.
         * @return the symbol of this phase
         */
        public String getSymbol() {
            return name().toLowerCase();
        }

        /**
         * Returns an {@link Phase} corresponded to the symbol.
         * @param symbol target symbol
         * @return the corresponding phase, or {@code null} if not found
         * @throws IllegalArgumentException if some parameters were {@code null}
         */
        public static Phase findFromSymbol(String symbol) {
            Objects.requireNonNull(symbol, "symbol must not be null"); //$NON-NLS-1$
            return Lazy.SYMBOLS.get(symbol);
        }

        @Override
        public String toString() {
            return getSymbol();
        }

        private static final class Lazy {

            static final Map<String, Phase> SYMBOLS;
            static {
                Map<String, Phase> map = new HashMap<>();
                for (Phase phase : values()) {
                    map.put(phase.getSymbol(), phase);
                }
                SYMBOLS = Collections.unmodifiableMap(map);
            }

            private Lazy() {
                return;
            }
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>skml.problem_transformation.binary_relevance — skml 0.1.0b documentation</title>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="stylesheet" href="../../../_static/gallery.css" type="text/css" />

        <link rel="index" title="Index"
              href="../../../genindex.html"/>
        <link rel="search" title="Search" href="../../../search.html"/>
    <link rel="top" title="skml 0.1.0b documentation" href="../../../index.html"/>
        <link rel="up" title="Module code" href="../../index.html"/>

             skml

                0.1

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

API Documentation

Multi-label Classification Examples

User Guide

          skml

Docs »

Module code »

skml.problem_transformation.binary_relevance

Source code for skml.problem_transformation.binary_relevance

import random
import numpy as np
from sklearn.base import clone
from sklearn.base import BaseEstimator, MetaEstimatorMixin, ClassifierMixin
from sklearn.utils import validation

[docs]class BinaryRelevance(
        BaseEstimator, MetaEstimatorMixin, ClassifierMixin):
    """Implements the binary relevance problem transformation strategy,
    where for each label a distinct binary classifier is trained to
    classify whether label should be assigned to an instance or not.
    """

[docs]    def __init__(self, estimator):
        """
        Constructs a classifier for each single label, thus having n_labels
        estimators predicting a single label for an instance.

        Parameters
        ----------
        estimator :
            scikit-learn compatible classifier instance. Will be
            copied (with all hyperparameters) before use, hence
            original will be left untouched.

        Returns
        -------
        Binary relevance problem transformed MLC classifier
        """
        # get's cloned later on
        self.estimator = estimator

        self.estimators_ = []

[docs]    def fit(self, X, y):
        """Fit underlying estimators.

        Parameters
        ----------
        X : (sparse) array-like, shape = [n_samples, n_features]
            Data
        y : (sparse) array-like, shape = [n_samples, ], [n_samples, n_classes]
            Multi-label targets
        """

        validation.check_X_y(X, y, multi_output=True)
        y = validation.check_array(y, accept_sparse=True)

        self.estimators_ = [clone(self.estimator).fit(X, y[:, i])

                            for i in range(y.shape[1])]

[docs]    def predict(self, X):
        """
        Predicts the labels for the given instances.

        Parameters
        ----------
        X : (sparse) array-like, shape = [n_samples, n_features]
            Data.

        Returns
        -------
        array-like, shape = [n_samples, n_labels]
            Estimated labels
        """
        validation.check_is_fitted(self, 'estimators_')

        return np.array([e.predict(X) for e in self.estimators_]).T

        © Copyright 2016, Christian Schulze.

  Built with Sphinx using a theme provided by Read the Docs.


text:
define([], function () {

  'use strict';

  // TODO
  // It was based NPAPI, a deprecated API !
  // need a workaround now...
  // maybe I should take a look at pointer events, or extended touch events
  var Tablet = {
    useOnRadius: true, // the pen pressure acts on the tool's radius
    useOnIntensity: false // the pen pressure acts on the tool's intensity
  };

  /** Returns the pressure of pen: [0, 1] **/
  Tablet.pressure = function () {
    if (!Tablet.plugin)
      return 1.0;
  };

  Tablet.getPressureIntensity = function () {
    return Tablet.useOnIntensity === true ? 0.25 + Tablet.pressure() * 0.75 : 1.0;
  };

  Tablet.getPressureRadius = function () {
    return Tablet.useOnRadius === true ? 0.25 + Tablet.pressure() * 0.75 : 1.0;
  };

  return Tablet;
});


text:
{{<layout}}

{{$pageTitle}}
	State Pension Activation
{{/pageTitle}}

{{$content}}

      		ALPHA
      		This is a new service – your feedback will help us to improve it.

Get your State Pension

You can choose to claim or defer your State Pension if you're within 4 months and 4 days of State Pension age.

To do this you will need your:

Unique reference number (on your pension activation letter)

Surname

Date of birth

Bank account / building society account details

		    	Start now

{{/content}}

{{/layout}}


text:
package in.zaidi.engineering.auctions.resource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.text.StrSubstitutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import in.zaidi.engineering.auctions.client.GeoSaleResource;
import in.zaidi.engineering.auctions.client.SaleResource;
import in.zaidi.engineering.auctions.client.SalesSearchResponse;
import in.zaidi.engineering.auctions.repository.SaleWithBidRepository;

import in.zaidi.engineering.auctions.api.Sale;

@Path("/saleswithbid")
public class SaleWithBidResource {

	@Autowired
	private SaleResource resource;

	@Autowired
	private GeoSaleResource saleSearch;

	@Autowired
	private SaleWithBidRepository repository;

	private static final Logger LOGGER = LoggerFactory.getLogger(SaleWithBidResource.class);

	/*
	 * @GET
	 *
	 * @Consumes(MediaType.APPLICATION_JSON)
	 *
	 * @Produces(MediaType.APPLICATION_JSON) public Response
	 * getSales(@QueryParam("createdBy") String userId) { List<Sale> sales;
	 * sales = resource.getSales(userId); return
	 * Response.ok().entity(sales).build(); }
	 */

	String geoQueryTemplate = "{\"query\": {\"bool\": {\"must\": {\"match_all\": {}},\"filter\": {\"geo_distance\": "
			+ "{\"distance\": \"${distance}km\",\"doc.saleLocation\": {\"lat\": ${lat},\"lon\": ${lon}}}}}}}";

	@GET
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response getSalesWithMaxBid(@QueryParam("createdBy") String userId, @QueryParam("lat") Float lat,
			@QueryParam("lon") Float lon, @QueryParam("dist") int km) {
		List<Sale> sales;
		List<String> saleIds = new ArrayList<String>();
		if (lat != null && lon != null) {
			sales = getSalesGeolocated(lat, lon, km);
		} else {
			sales = resource.getSales(userId);
		}

		for(Sale sale : sales){
			 saleIds.add(sale.getId());

		}

		LOGGER.info("sale ids " + saleIds.toString());

		Map<String, Double> saleWithMaxBid = repository.getSaleMaxBidUsingN1QL(userId, saleIds);

		for (Sale sale : sales) {
			if (saleWithMaxBid.containsKey(sale.getId()))
				sale.setMaxBidAmount(saleWithMaxBid.get(sale.getId()));
			else
				sale.setMaxBidAmount(sale.getStartPrice());
		}

		return Response.ok().entity(sales).build();
	}

	private List<Sale> getSalesGeolocated(Float lat, Float lon, int km) {
		List<Sale> sales;
		int distance;
		// Geolocated listing
		if (km < 1) {
			distance = 1;
		} else {
			distance = km;
		}
		Map<String, Object> data = new HashMap<>();
		data.put("distance", distance);
		data.put("lat", lat);
		data.put("lon", lon);
		SalesSearchResponse response = saleSearch.getSales(StrSubstitutor.replace(geoQueryTemplate, data));
		sales = response.getSales();
		return sales;
	}

}