text:
import ServerResponse from '../commons/ServerResponse';

export default class BaseService {

  /**
   * コンストラクタ
   */
  constructor ($log, $translate, $location, $http, GlobalConstants) {
    this.$log = $log;
    this.$translate = $translate;
    this.$location = $location;
    this.$http = $http;
    this.GlobalConstants = GlobalConstants;
  }

  /**
   *
   */
  callApiService(method, fullApiUrl, sendData) {

    this.$log.debug("start to callApiService, fullApiUrl=" + fullApiUrl + ", sendData=" + angular.toJson(sendData));

    const httpCommand = {};

    httpCommand.method = method;
    httpCommand.cache = false;
    httpCommand.url = fullApiUrl;
    httpCommand.responseType = 'json';
    const methodUppercase = method.toUpperCase();
    if (methodUppercase === 'GET' ||  methodUppercase === 'DELETE' || methodUppercase === 'HEAD' ) {
      //GETまたはDELETEまたはHEADの場合はdataプロパティではなく、paramsプロパティにkey=valueオブジェクトをセットする
      //(クエリパラメータにする場合はparamsにセットするのが$httpの仕様)
      httpCommand.params = sendData;
    } else {
      //GETまたはDELETE以外の場合(=POST, PUT, PATCH想定)の場合は、dataプロパティにkey=valueオブジェクトをセット。
      httpCommand.data = sendData;
    }

    //実際に$httpサービスを使ってサーバー通信を実行。非同期的にPromiseでの結果を受け取り。
    const resultPromise = this.$http(httpCommand).then(
      //thenで一度チェーンさせている(結果データを加工し、ServerResponseを生成してそれを結果とするため)
      (resp) => {
        //resolve時、通常のServerResponseオブジェクトを結果データとしたPromiseを返す
        const response = this._createNormalServerResponse(resp);
        return response;
      },
      (resp) => {
        //reject時、HTTP応答エラーメッセージがセットされたServerResponseオブジェクトを結果データとしたPromiseを返す
        const response = this._createRejectedServerResponse(resp);
        return response;
      }
    );

    //Promiseオブジェクトを返す。
    //このPromiseは、$http()が返したPromiseではなく、.thenで一度チェーンさせた方のPromiseである
    //(結果データを加工し、ServerResponseオブジェクトを結果データとしてコントローラ側に返す構造にするため)
    return resultPromise;

  }

  /**
   * HTTPレスポンスが得られた場合で
   */
  _createNormalServerResponse(response) {

    const svrresp = new ServerResponse();

    angular.copy(response.data, svrresp);
    svrresp.httpStatus = response.status;

    return svrresp;
  }

  /**
   * HTTPレスポンスが得られなかった場合
   */
  _createRejectedServerResponse(response) {

    const svrresp = new ServerResponse();

    if (typeof(response.data) !== 'undefined' ) {
      angular.copy(response.data, svrresp);
    }

    svrresp.httpStatus = response.status;
    svrresp.result = this.GlobalConstants.RESULT_FALSE;

    return svrresp;

  }

}


text:
module SpreeDmi
  class Engine < Rails::Engine
    require 'spree/core'
    isolate_namespace Spree
    engine_name 'spree_dmi'

    # use rspec for tests
    config.generators do |g|
      g.test_framework :rspec
    end

    initializer "spree.dmi.preferences", :before => :load_config_initializers do |app|
      Spree::AppConfiguration.class_eval do
        preference :dmi_sender_id, :string
        preference :dmi_receiver_id, :string
        preference :dmi_catalog_zipcode, :string
        preference :dmi_include_confirmation_email, :boolean, default: false
        preference :dmi_capture_on_ship, :boolean, default: false
      end
    end

    def self.activate
      Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end
    end

    config.to_prepare &method(:activate).to_proc
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
   "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd" []>
<chapter id="scenarios">
   <title>Advanced testing scenarios</title>
<!--
vim:et:ts=3:sw=3:tw=120
-->
</chapter>


text:
@implementation ADJConfig

+ (ADJConfig *) configWithAppToken:(NSString *)appToken
                       environment:(NSString *)environment {
    return [[ADJConfig alloc] initWithAppToken:appToken environment:environment];
}

- (id) initWithAppToken:(NSString *)appToken
            environment:(NSString *)environment
{
    if (![self checkAppToken:appToken]) return nil;
    if (![self checkEnvironment:environment logAssert:YES]) return nil;

    return [self initWithoutCheckAppToken:appToken environment:environment];
}

- (id) initWithoutCheckAppToken:(NSString *)appToken
                    environment:(NSString *)environment
{
    self = [super init];
    if (self == nil) return nil;

    _appToken = appToken;
    _environment = environment;

    // default values
    self.logLevel = ADJLogLevelInfo;
    self.macMd5TrackingEnabled = YES;

    return self;
}

- (void) setDelegate:(NSObject<AdjustDelegate> *)delegate {
    if (delegate == nil) {
        _delegate = nil;
        self.hasDelegate = NO;
        return;
    }

    if (![delegate respondsToSelector:@selector(adjustAttributionChanged:)]) {
        id<ADJLogger> logger = ADJAdjustFactory.logger;
        [logger error:@"Delegate does not implement AdjustDelegate"];

        _delegate = nil;
        self.hasDelegate = NO;
        return;
    }

    _delegate = delegate;
    self.hasDelegate = YES;
}

- (BOOL) checkEnvironment:(NSString *)environment
                logAssert:(BOOL)logAssert
{
    id<ADJLogger> logger = ADJAdjustFactory.logger;
    if ([environment isEqualToString:ADJEnvironmentSandbox]) {
        if (logAssert) {
            [logger assert:@"SANDBOX: Adjust will run in Sandbox mode. Use this setting for testing. Don't forget to set the environment to ADJEnvironmentProduction before publishing!"];
        }
        return YES;
    } else if ([environment isEqualToString:ADJEnvironmentProduction]) {
        if (logAssert) {
            [logger assert:@"PRODUCTION: Adjust will run in Production mode. Use this setting only for the build that you want to publish. Set the environment to ADJEnvironmentSandbox if you want to test your app!"];
        }
        return YES;
    }
    [logger error:@"Malformed environment '%@'", environment];
    return NO;
}

- (BOOL)checkAppToken:(NSString *)appToken {
    if (appToken == nil) {
        [ADJAdjustFactory.logger error:@"Missing App Token"];
        return NO;
    }
    if (appToken == nil || appToken.length != 12) {
        [ADJAdjustFactory.logger error:@"Malformed App Token '%@'", appToken];
        return NO;
    }
    return YES;
}

- (BOOL) isValid {
    if (![self checkAppToken:self.appToken]) return NO;
    if (![self checkEnvironment:self.environment logAssert:NO]) return NO;
    return YES;
}

-(id)copyWithZone:(NSZone *)zone
{
    ADJConfig* copy = [[[self class] allocWithZone:zone]
                       initWithoutCheckAppToken:[self.appToken copyWithZone:zone]
                       environment:[self.environment copyWithZone:zone]];
    if (copy) {
        copy.logLevel = self.logLevel;
        copy.sdkPrefix = [self.sdkPrefix copyWithZone:zone];
        copy.defaultTracker = [self.defaultTracker copyWithZone:zone];
        copy.eventBufferingEnabled = self.eventBufferingEnabled;
        copy.macMd5TrackingEnabled = self.macMd5TrackingEnabled;
        copy.hasDelegate = self.hasDelegate;
        // adjust delegate not copied
    }

    return copy;
}

@end


text:
package org.lionsoul.jcseg.json.zip;

import java.io.IOException;

/**
 * A bitwriter is a an interface that allows for doing output at the bit level.
 * Most IO interfaces only allow for writing at the byte level or higher.
 */
public interface BitWriter {

    /**
     * Write a 1 bit.
     *
     * @throws IOException
     */
    public void one() throws IOException;

    /**
     * Pad the rest of the block with zeros and flush.
     *
     * @param width
     *            The size in bits of the block to pad. This will typically be
     *            8, 16, 32, 64, 128, 256, etc.
     * @throws IOException
     */
    public void pad(int width) throws IOException;

    /**
     * Write some bits. Up to 32 bits can be written at a time.
     *
     * @param bits
     *            The bits to be written.
     * @param width
     *            The number of bits to write. (0..32)
     * @throws IOException
     */
    public void write(int bits, int width) throws IOException;

    /**
     * Write a 0 bit.
     *
     * @throws IOException
     */
    public void zero() throws IOException;
}


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using System.ComponentModel.DataAnnotations;
using Squidex.Infrastructure.Validation;

namespace Squidex.Web;

public sealed class ErrorDto
{
    [LocalizedRequired]
    [Display(Description = "Error message.")]
    public string? Message { get; set; }

    [Display(Description = "The error code.")]
    public string? ErrorCode { get; set; }

    [Display(Description = "The optional trace id.")]
    public string? TraceId { get; set; }

    [Display(Description = "Link to the error details.")]
    public string? Type { get; set; }

    [Display(Description = "Detailed error messages.")]
    public string[]? Details { get; set; }

    [Display(Description = "Status code of the http response.")]
    public int StatusCode { get; set; } = 400;
}


text:
package com.oneops.inductor;

import java.util.Date;

public class InductorStatus {
	private boolean isRunning;
	private int queueBacklog;
	private Date lastRun;
	private String queueName;

	public String getQueueName() {
		return queueName;
	}
	public void setQueueName(String queueName) {
		this.queueName = queueName;
	}
	public boolean getIsRunning() {
		return isRunning;
	}
	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}
	public int getQueueBacklog() {
		return queueBacklog;
	}
	public void setQueueBacklog(int queueBacklog) {
		this.queueBacklog = queueBacklog;
	}
	public Date getLastRun() {
		return lastRun;
	}
	public void setLastRun(Date lastRun) {
		this.lastRun = lastRun;
	}
}


text:
<?php
/**
 * ALIPAY API: alipay.gotone.message.sms.send request
 *
 * @author auto create
 * @since 1.0, 2014-06-12 17:16:36
 */
class AlipayGotoneMessageSmsSendRequest
{
	/**
	 * 模板参数
	 **/
	private $arguments;

	/**
	 * 接收短信手机号
	 **/
	private $mobile;

	/**
	 * 短信模板对应的serviceCode
	 **/
	private $serviceCode;

	/**
	 * 用户的支付宝ID
	 **/
	private $userId;

	private $apiParas = array();
	private $terminalType;
	private $terminalInfo;
	private $prodCode;
	private $apiVersion="1.0";

	public function setArguments($arguments)
	{
		$this->arguments = $arguments;
		$this->apiParas["arguments"] = $arguments;
	}

	public function getArguments()
	{
		return $this->arguments;
	}

	public function setMobile($mobile)
	{
		$this->mobile = $mobile;
		$this->apiParas["mobile"] = $mobile;
	}

	public function getMobile()
	{
		return $this->mobile;
	}

	public function setServiceCode($serviceCode)
	{
		$this->serviceCode = $serviceCode;
		$this->apiParas["service_code"] = $serviceCode;
	}

	public function getServiceCode()
	{
		return $this->serviceCode;
	}

	public function setUserId($userId)
	{
		$this->userId = $userId;
		$this->apiParas["user_id"] = $userId;
	}

	public function getUserId()
	{
		return $this->userId;
	}

	public function getApiMethodName()
	{
		return "alipay.gotone.message.sms.send";
	}

	public function getApiParas()
	{
		return $this->apiParas;
	}

	public function getTerminalType()
	{
		return $this->terminalType;
	}

	public function setTerminalType($terminalType)
	{
		$this->terminalType = $terminalType;
	}

	public function getTerminalInfo()
	{
		return $this->terminalInfo;
	}

	public function setTerminalInfo($terminalInfo)
	{
		$this->terminalInfo = $terminalInfo;
	}

	public function getProdCode()
	{
		return $this->prodCode;
	}

	public function setProdCode($prodCode)
	{
		$this->prodCode = $prodCode;
	}

	public function setApiVersion($apiVersion)
	{
		$this->apiVersion=$apiVersion;
	}

	public function getApiVersion()
	{
		return $this->apiVersion;
	}

}


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"""
import os
from resource_management.libraries.script import Script
from resource_management.libraries.functions.version import format_hdp_stack_version, compare_versions
from resource_management.libraries.functions.format import format
from resource_management.libraries.functions.default import default

config  = Script.get_config()
tmp_dir = Script.get_tmp_dir()

stack_name = default("/hostLevelParams/stack_name", None)
version = default("/commandParams/version", None)

stack_version_unformatted = str(config['hostLevelParams']['stack_version'])
hdp_stack_version = format_hdp_stack_version(stack_version_unformatted)

stack_is_hdp23_or_further = Script.is_hdp_stack_greater_or_equal("2.3")

if stack_is_hdp23_or_further:
  kms_home = '/usr/hdp/current/ranger-kms'
  kms_conf_dir = '/usr/hdp/current/ranger-kms/conf'

kms_log_dir = default("/configurations/kms-env/kms_log_dir", "/var/log/ranger/kms")
java_home = config['hostLevelParams']['java_home']
kms_user  = default("/configurations/kms-env/kms_user", "kms")
kms_group = default("/configurations/kms-env/kms_group", "kms")

jdk_location = config['hostLevelParams']['jdk_location']
kms_log4j = config['configurations']['kms-log4j']['content']

# ranger host
ranger_admin_hosts = config['clusterHostInfo']['ranger_admin_hosts'][0]
has_ranger_admin = len(ranger_admin_hosts) > 0
kms_host = config['clusterHostInfo']['ranger_kms_server_hosts'][0]
kms_port = config['configurations']['kms-env']['kms_port']

#kms properties
db_flavor = (config['configurations']['kms-properties']['DB_FLAVOR']).lower()
db_host = config['configurations']['kms-properties']['db_host']
db_name = config['configurations']['kms-properties']['db_name']
db_user = config['configurations']['kms-properties']['db_user']
db_password = unicode(config['configurations']['kms-properties']['db_password'])
kms_master_key_password = unicode(config['configurations']['kms-properties']['KMS_MASTER_KEY_PASSWD'])
credential_provider_path = config['configurations']['dbks-site']['ranger.ks.jpa.jdbc.credential.provider.path']
jdbc_alias = config['configurations']['dbks-site']['ranger.ks.jpa.jdbc.credential.alias']
masterkey_alias = config['configurations']['dbks-site']['ranger.ks.masterkey.credential.alias']
repo_name = str(config['clusterName']) + '_kms'
cred_lib_path = os.path.join(kms_home,"cred","lib","*")
cred_setup_prefix = (format('{kms_home}/ranger_credential_helper.py'), '-l', cred_lib_path)
credential_file = format('/etc/ranger/{repo_name}/cred.jceks')

if has_ranger_admin:
  policymgr_mgr_url = config['configurations']['admin-properties']['policymgr_external_url']
  xa_audit_db_flavor = (config['configurations']['admin-properties']['DB_FLAVOR']).lower()
  xa_audit_db_name = config['configurations']['admin-properties']['audit_db_name']
  xa_audit_db_user = config['configurations']['admin-properties']['audit_db_user']
  xa_audit_db_password = config['configurations']['admin-properties']['audit_db_password']
  xa_db_host = config['configurations']['admin-properties']['db_host']

  admin_uname = config['configurations']['ranger-env']['admin_username']
  admin_password = config['configurations']['ranger-env']['admin_password']
  ambari_ranger_admin = config['configurations']['ranger-env']['ranger_admin_username']
  ambari_ranger_password = config['configurations']['ranger-env']['ranger_admin_password']
  admin_uname_password = format("{admin_uname}:{admin_password}")
  ranger_audit_solr_urls = config['configurations']['ranger-admin-site']['ranger.audit.solr.urls']

java_share_dir = '/usr/share/java'

if db_flavor == 'mysql':
  jdbc_symlink_name = "mysql-jdbc-driver.jar"
  jdbc_jar_name = "mysql-connector-java.jar"
  db_jdbc_url = format('jdbc:log4jdbc:mysql://{db_host}/{db_name}')
  db_jdbc_driver = "net.sf.log4jdbc.DriverSpy"
  jdbc_dialect = "org.eclipse.persistence.platform.database.MySQLPlatform"
elif db_flavor == 'oracle':
  jdbc_jar_name = "ojdbc6.jar"
  jdbc_symlink_name = "oracle-jdbc-driver.jar"
  db_jdbc_url = format('jdbc:oracle:thin:@//{db_host}')
  db_jdbc_driver = "oracle.jdbc.OracleDriver"
  jdbc_dialect = "org.eclipse.persistence.platform.database.OraclePlatform"
elif db_flavor == 'postgres':
  jdbc_jar_name = "postgresql.jar"
  jdbc_symlink_name = "postgres-jdbc-driver.jar"
  db_jdbc_url = format('jdbc:postgresql://{db_host}/{db_name}')
  db_jdbc_driver = "org.postgresql.Driver"
  jdbc_dialect = "org.eclipse.persistence.platform.database.PostgreSQLPlatform"
elif db_flavor == 'mssql':
  jdbc_jar_name = "sqljdbc4.jar"
  jdbc_symlink_name = "mssql-jdbc-driver.jar"
  db_jdbc_url = format('jdbc:sqlserver://{db_host};databaseName={db_name}')
  db_jdbc_driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
  jdbc_dialect = "org.eclipse.persistence.platform.database.SQLServerPlatform"
elif db_flavor == 'sqla':
  jdbc_jar_name = "sajdbc4.jar"
  jdbc_symlink_name = "sqlanywhere-jdbc-driver.tar.gz"
  db_jdbc_url = format('jdbc:sqlanywhere:database={db_name};host={db_host}')
  db_jdbc_driver = "sap.jdbc4.sqlanywhere.IDriver"
  jdbc_dialect = "org.eclipse.persistence.platform.database.SQLAnywherePlatform"

downloaded_custom_connector = format("{tmp_dir}/{jdbc_jar_name}")

driver_curl_source = format("{jdk_location}/{jdbc_symlink_name}")
driver_curl_target = format("{java_share_dir}/{jdbc_jar_name}")

if db_flavor == 'sqla':
  downloaded_custom_connector = format("{tmp_dir}/sqla-client-jdbc.tar.gz")
  jar_path_in_archive = format("{tmp_dir}/sqla-client-jdbc/java/{jdbc_jar_name}")
  libs_path_in_archive = format("{tmp_dir}/sqla-client-jdbc/native/lib64/*")
  jdbc_libs_dir = format("{kms_home}/native/lib64")
  ld_library_path = format("{jdbc_libs_dir}")

if has_ranger_admin:
  if xa_audit_db_flavor == 'mysql':
    jdbc_symlink = "mysql-jdbc-driver.jar"
    jdbc_jar = "mysql-connector-java.jar"
    audit_jdbc_url = format('jdbc:mysql://{xa_db_host}/{xa_audit_db_name}')
    jdbc_driver = "com.mysql.jdbc.Driver"
  elif xa_audit_db_flavor == 'oracle':
    jdbc_jar = "ojdbc6.jar"
    jdbc_symlink = "oracle-jdbc-driver.jar"
    audit_jdbc_url = format('jdbc:oracle:thin:\@//{xa_db_host}')
    jdbc_driver = "oracle.jdbc.OracleDriver"
  elif xa_audit_db_flavor == 'postgres':
    jdbc_jar = "postgresql.jar"
    jdbc_symlink = "postgres-jdbc-driver.jar"
    audit_jdbc_url = format('jdbc:postgresql://{xa_db_host}/{xa_audit_db_name}')
    jdbc_driver = "org.postgresql.Driver"
  elif xa_audit_db_flavor == 'mssql':
    jdbc_jar = "sqljdbc4.jar"
    jdbc_symlink = "mssql-jdbc-driver.jar"
    audit_jdbc_url = format('jdbc:sqlserver://{xa_db_host};databaseName={xa_audit_db_name}')
    jdbc_driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"
  elif xa_audit_db_flavor == 'sqla':
    jdbc_jar = "sajdbc4.jar"
    jdbc_symlink = "sqlanywhere-jdbc-driver.tar.gz"
    audit_jdbc_url = format('jdbc:sqlanywhere:database={xa_audit_db_name};host={xa_db_host}')
    jdbc_driver = "sap.jdbc4.sqlanywhere.IDriver"

  downloaded_connector_path = format("{tmp_dir}/{jdbc_jar}")

  driver_source = format("{jdk_location}/{jdbc_symlink}")
  driver_target = format("{java_share_dir}/{jdbc_jar}")

repo_config_username = config['configurations']['kms-properties']['REPOSITORY_CONFIG_USERNAME']
repo_config_password = unicode(config['configurations']['kms-properties']['REPOSITORY_CONFIG_PASSWORD'])

kms_plugin_config = {
  'username' : repo_config_username,
  'password' : repo_config_password,
  'provider' : format('kms://http@{kms_host}:{kms_port}/kms')
}

kms_ranger_plugin_repo = {
  'isEnabled' : 'true',
  'configs' : kms_plugin_config,
  'description' : 'kms repo',
  'name' : repo_name,
  'type' : 'kms'
}

xa_audit_db_is_enabled = config['configurations']['ranger-kms-audit']['xasecure.audit.destination.db']
ssl_keystore_password = unicode(config['configurations']['ranger-kms-policymgr-ssl']['xasecure.policymgr.clientssl.keystore.password'])
ssl_truststore_password = unicode(config['configurations']['ranger-kms-policymgr-ssl']['xasecure.policymgr.clientssl.truststore.password'])

#For SQLA explicitly disable audit to DB for Ranger
if xa_audit_db_flavor == 'sqla':
  xa_audit_db_is_enabled = False


text:
import synthtool as s
from synthtool.languages import java

for library in s.get_staging_dirs():
    # put any special-case replacements here

    # Ensure backwards-compat for Java-microgenerator migration
    # Details: https://github.com/googleapis/synthtool/pull/883
    java.remove_method('owl-bot-staging/v1/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/DataSourceName.java', 'public static List<DataSourceName> parseList(List<String> formattedStrings)')
    java.remove_method('owl-bot-staging/v1/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/DataSourceName.java', 'public static List<String> toStringList(List<DataSourceName> values)')
    java.remove_method('owl-bot-staging/v1/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/TransferConfigName.java', 'public static List<TransferConfigName> parseList(List<String> formattedStrings)')
    java.remove_method('owl-bot-staging/v1/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/TransferConfigName.java', 'public static List<String> toStringList(List<TransferConfigName> values)')
    java.remove_method('owl-bot-staging/v1/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/RunName.java', 'public static List<RunName> parseList(List<String> formattedStrings)')
    java.remove_method('owl-bot-staging/v1/proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/RunName.java', 'public static List<String> toStringList(List<RunName> values)')

    s.move(library)

s.remove_staging_dirs()
java.common_templates(monorepo=True, excludes=[
    ".github/*",
    ".kokoro/*",
    "samples/*",
    "CODE_OF_CONDUCT.md",
    "CONTRIBUTING.md",
    "LICENSE",
    "SECURITY.md",
    "java.header",
    "license-checks.xml",
    "renovate.json",
    ".gitignore"
])


text:
import time

from django.conf import settings
from django.db import models
from django.dispatch import receiver
from django.utils import translation
from django.utils.http import urlencode

from translations.fields import TranslatedField

import amo
import amo.models
from amo.urlresolvers import reverse
from stats.models import Contribution
from users.models import UserProfile

from babel import Locale, numbers
import commonware.log
from jinja2.filters import do_dictsort
import jwt
import paypal

log = commonware.log.getLogger('z.market')

class PriceManager(amo.models.ManagerBase):

    def active(self):
        return self.filter(active=True)

class Price(amo.models.ModelBase):
    active = models.BooleanField(default=True)
    name = TranslatedField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    objects = PriceManager()
    currency = 'USD'

    class Meta:
        db_table = 'prices'

    def __unicode__(self):
        return u'%s - $%s' % (self.name, self.price)

    def _price(self):
        """Return the price and currency for the current locale."""
        lang = translation.get_language()
        locale = Locale(translation.to_locale(lang))
        currency = amo.LOCALE_CURRENCY.get(locale.language)
        if currency:
            price_currency = self.pricecurrency_set.filter(currency=currency)
            if price_currency:
                return price_currency[0].price, currency, locale

        return self.price, self.currency, locale

    def get_price(self):
        """Return the price as a decimal for the current locale."""
        return self._price()[0]

    def get_price_locale(self):
        """Return the price as a nicely localised string for the locale."""
        price, currency, locale = self._price()
        return numbers.format_currency(price, currency, locale=locale)

class PriceCurrency(amo.models.ModelBase):
    currency = models.CharField(max_length=10,
                                choices=do_dictsort(amo.OTHER_CURRENCIES))
    price = models.DecimalField(max_digits=5, decimal_places=2)
    tier = models.ForeignKey(Price)

    class Meta:
        db_table = 'price_currency'
        verbose_name = 'Price currencies'

    def __unicode__(self):
        return u'%s, %s: %s' % (self.tier, self.currency, self.price)

class AddonPurchase(amo.models.ModelBase):
    addon = models.ForeignKey('addons.Addon')
    user = models.ForeignKey(UserProfile)
    receipt = models.TextField(default='')

    class Meta:
        db_table = 'addon_purchase'

    def __unicode__(self):
        return u'%s: %s' % (self.addon, self.user)

    def create_receipt(self):
        verify = reverse('api.market.verify', args=[self.addon.pk])
        hsh = self.addon.get_watermark_hash(self.user)
        url = urlencode({amo.WATERMARK_KEY: self.user.email,
                         amo.WATERMARK_KEY_HASH: hsh})
        verify = '%s?%s' % (verify, url)
        receipt = dict(typ='purchase-receipt',
                       product=self.addon.origin,
                       user={'type': 'email',
                             'value': self.user.email},
                       iss=settings.SITE_URL,
                       nbf=time.time(),
                       iat=time.time(),
                       detail=reverse('users.purchases.receipt',
                                      args=[self.addon.pk]),
                       verify=verify)
        self.receipt = jwt.encode(receipt, get_key())

def get_key():
    """Return a key for using with encode."""
    return jwt.rsa_load(settings.WEBAPPS_RECEIPT_KEY)

@receiver(models.signals.post_save, sender=AddonPurchase,
          dispatch_uid='create_receipt')
def create_receipt(sender, instance, **kw):
    """
    When the AddonPurchase gets created, see if we need to create a receipt.
    """
    if (kw.get('raw') or instance.addon.type != amo.ADDON_WEBAPP
        or instance.receipt):
        return

    log.debug('Creating receipt for: addon %s, user %s'
              % (instance.addon.pk, instance.user.pk))
    instance.create_receipt()
    instance.save()

@receiver(models.signals.post_save, sender=Contribution,
          dispatch_uid='create_addon_purchase')
def create_addon_purchase(sender, instance, **kw):
    """
    When the contribution table is updated with the data from PayPal,
    update the addon purchase table. Will figure out if we need to add to or
    delete from the AddonPurchase table.
    """
    if (kw.get('raw') or
        instance.type not in [amo.CONTRIB_PURCHASE, amo.CONTRIB_REFUND,
                              amo.CONTRIB_CHARGEBACK]):
        # Whitelist the types we care about. Forget about the rest.
        return

    log.debug('Processing addon purchase type: %s, addon %s, user %s'
              % (amo.CONTRIB_TYPES[instance.type], instance.addon.pk,
                 instance.user.pk))

    if instance.type == amo.CONTRIB_PURCHASE:
        log.debug('Creating addon purchase: addon %s, user %s'
                  % (instance.addon.pk, instance.user.pk))
        AddonPurchase.objects.get_or_create(addon=instance.addon,
                                            user=instance.user)

    elif instance.type in [amo.CONTRIB_REFUND, amo.CONTRIB_CHARGEBACK]:
        purchases = AddonPurchase.objects.filter(addon=instance.addon,
                                                 user=instance.user)
        for p in purchases:
            log.debug('Deleting addon purchase: %s, addon %s, user %s'
                      % (p.pk, instance.addon.pk, instance.user.pk))
            p.delete()

class AddonPremium(amo.models.ModelBase):
    """Additions to the Addon model that only apply to Premium add-ons."""
    addon = models.OneToOneField('addons.Addon')
    price = models.ForeignKey(Price, blank=True, null=True)
    paypal_permissions_token = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = 'addons_premium'

    def __unicode__(self):
        return u'Premium %s: %s' % (self.addon, self.price)

    def get_price(self):
        return self.price.get_price()

    def get_price_locale(self):
        return self.price.get_price_locale()

    def is_complete(self):
        return bool(self.addon and self.price and
                    self.addon.paypal_id and self.addon.support_email)

    def has_permissions_token(self):
        """
        Have we got a permissions token. If you've got 'should_ignore_paypal'
        enabled, then it will just happily return True.
        """
        return bool(paypal.should_ignore_paypal() or
                    self.paypal_permissions_token)

    def has_valid_permissions_token(self):
        """
        Have we got a valid permissions token by ping paypal. If you've got
        'should_ignore_paypal', then it will just happily return True.
        """
        if paypal.should_ignore_paypal():
            return True
        if not self.paypal_permissions_token:
            return False
        return paypal.check_refund_permission(self.paypal_permissions_token)


text:
var fs = require('fs'),
    path = require('path'),
    wrench = require('wrench'),
    os = require('os'),
    conf = require("./conf"),
    childProcess = require('child_process'),
    cordovaUtils = require(path.join(conf.NODE_MODULES_DIR,'cordova/src/util')),
    CORDOVA_DIR = '.cordova',
    _self;

_self = {
    findHomePath : function () {
        return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
    },

    getCordovaDir: function () {
        var cordovaPath = path.join(_self.findHomePath(), CORDOVA_DIR);

        if (!fs.existsSync(cordovaPath)) {
            fs.mkdirSync(cordovaPath);
        }

        return cordovaPath;
    },

    quotify : function (property) {
        //wrap in quotes if it's not already wrapped
        if (property.indexOf("\"") === -1) {
            return "\"" + property + "\"";
        } else {
            return property;
        }
    },

    fetchBlackBerry: function () {
        var cli_platforms = require(path.join(conf.NODE_MODULES_DIR, 'cordova/platforms')),
            bbVersion = cli_platforms.blackberry10.version,
            wwwVersion = cli_platforms.www.version,
            cliBBLib = path.join(_self.getCordovaDir(), "lib", "blackberry10", "cordova", bbVersion ),
            cliWWWLib = path.join(_self.getCordovaDir(), "lib", "www", "cordova", wwwVersion );

        if (!fs.existsSync(cliBBLib)) {
            wrench.mkdirSyncRecursive(cliBBLib, 0775);
            wrench.copyDirSyncRecursive(conf.CORDOVA_BB_DIR, cliBBLib);

            //Re-Adding execution permissions
            wrench.chmodSyncRecursive(path.join(cliBBLib, "bin"), 0775);
        }

        if (!fs.existsSync(cliWWWLib)) {
            wrench.mkdirSyncRecursive(cliWWWLib, 0775);
            wrench.copyDirSyncRecursive(conf.CORDOVA_HELLO_WORLD_DIR, cliWWWLib);
        }
    },

    isWindows: function () {
        return os.type().toLowerCase().indexOf("windows") >= 0;
    },

    spawn : function (command, args, options, callback) {
        //Optional params handling [args, options]
        if (typeof args === "Object" && !Array.isArray(args)) {
            callback = options;
            options = args;
            args = [];
        } else if (typeof args === "function"){
            callback = args;
            options = {};
            args = [];
        } else if (typeof options === "function"){
            callback = options;
            options = {};
        }

        var customOptions = options._customOptions || {},
            feedback = function (data) { console.log(data.toString());},
            proc,
            i;

        //delete _customOptions from options object before sending to exec
        delete options._customOptions;
        //Use the process env by default
        options.env = options.env || process.env;

        proc = childProcess.spawn(command, args, options);

        if (!customOptions.silent) {
            proc.stdout.on("data", feedback);
            proc.stderr.on("data", feedback);
        }
        proc.on("close", callback);
    },

    preProcessOptions: function (inputOptions, callback, commandDefaultOptions) {
        var projectRoot = cordovaUtils.isCordova(process.cwd()),
            options,
            platforms,
            DEFAULT_OPTIONS = {verbose: false, platforms : [], options: []};

        if (!projectRoot) {
            err = new Error('Current working directory is not a WebWorks-based project.');
            if (callback)  {
                return callback(err);
            } else {
                throw err;
            }
        } else {

            platforms = cordovaUtils.listPlatforms(projectRoot);

            //We came from the CLI
            if (Array.isArray(inputOptions)) {
                options = commandDefaultOptions || DEFAULT_OPTIONS;
                // Filter all non-platforms into options
                inputOptions.forEach(function(option) {
                    if (platforms.indexOf(option) !== -1) {
                        options.platforms.push(option);
                    } else {
                        if (option === "--verbose" && !options.verbose) {
                            options.verbose = true;
                        } else {
                            options.options.push(option);
                        }
                    }
                });

            } else {
                options = inputOptions || commandDefaultOptions  || DEFAULT_OPTIONS;
                if (inputOptions && commandDefaultOptions) {
                    options.options = options.options.concat(commandDefaultOptions.options);
                }
            }

            if (!options.platforms || options.platforms.length === 0) {
                options.platforms = platforms;
            }

            if (callback && typeof callback === "function") {
                options.callback = callback;
            }

            return options;
        }
    }
};

module.exports = _self;


text:
package scouter.client.group.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.csstudio.swt.xygraph.dataprovider.CircularBufferDataProvider;
import org.csstudio.swt.xygraph.dataprovider.IDataProvider;
import org.csstudio.swt.xygraph.dataprovider.Sample;
import org.csstudio.swt.xygraph.figures.Trace;
import org.csstudio.swt.xygraph.figures.Trace.PointStyle;
import org.csstudio.swt.xygraph.figures.Trace.TraceType;
import org.csstudio.swt.xygraph.figures.XYGraph;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import scouter.client.Images;
import scouter.client.group.GroupManager;
import scouter.client.model.AgentModelThread;
import scouter.client.model.AgentObject;
import scouter.client.net.INetReader;
import scouter.client.net.TcpProxy;
import scouter.client.popup.CalendarDialog;
import scouter.client.preferences.PManager;
import scouter.client.preferences.PreferenceConstants;
import scouter.client.server.Server;
import scouter.client.server.ServerManager;
import scouter.client.util.ChartUtil;
import scouter.client.util.ColorUtil;
import scouter.client.util.CounterUtil;
import scouter.client.util.ExUtil;
import scouter.client.util.ImageUtil;
import scouter.client.util.ScouterUtil;
import scouter.client.util.TimeUtil;
import scouter.client.util.UIUtil;
import scouter.client.views.ScouterViewPart;
import scouter.lang.TimeTypeEnum;
import scouter.lang.pack.MapPack;
import scouter.lang.pack.Pack;
import scouter.lang.value.ListValue;
import scouter.io.DataInputX;
import scouter.net.RequestCmd;
import scouter.util.CastUtil;
import scouter.util.DateUtil;
import scouter.util.StringUtil;

public class CounterPastTimeGroupTotalView extends ScouterViewPart implements CalendarDialog.ILoadCounterDialog {

	public static final String ID = CounterPastTimeGroupTotalView.class.getName();

	private String grpName;
	private String objType;
	private String counter;
	private String mode;
	private long etime = TimeUtil.getCurrentTime();
	private long stime = etime - DateUtil.MILLIS_PER_FIVE_MINUTE;
	private Server defaultServer = ServerManager.getInstance().getDefaultServer();
	protected XYGraph xyGraph;
	IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
	protected List<Trace> traces = new ArrayList<Trace>();
	private Map<Integer, ListValue> serverObjMap = new HashMap<Integer, ListValue>();
	protected FigureCanvas canvas;

	public void init(IViewSite site) throws PartInitException {
		super.init(site);
		String secId = site.getSecondaryId();
		String[] datas = secId.split("&");
		grpName = datas[0];
		objType = datas[1];
		counter = datas[2];
	}

	public void createPartControl(Composite parent) {
		String displayCounter = defaultServer.getCounterEngine().getCounterDisplayName(objType, counter);
		setPartName(grpName + " - " + displayCounter);
		setTitleImage(Images.getCounterImage(objType, counter, defaultServer.getId()));
		String unit = defaultServer.getCounterEngine().getCounterUnit(objType, counter);
		mode = CounterUtil.getTotalMode(objType, counter);
		statusMessage = grpName + " | (PastTime) Total " + displayCounter + (StringUtil.isNotEmpty(unit) ? "(" + unit + ")" : "");
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout gLayout = new GridLayout(1, true);
		gLayout.horizontalSpacing = 0;
		gLayout.marginHeight = 0;
		gLayout.marginWidth = 0;
		composite.setLayout(gLayout);
		createUpperMenu(composite);

		Composite chartComposite = new Composite(composite, SWT.NONE);
		chartComposite.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
		chartComposite.setLayout(UIUtil.formLayout(0, 0));
		chartComposite.setBackground(ColorUtil.getInstance().getColor(SWT.COLOR_WHITE));
		canvas = new FigureCanvas(chartComposite);
		canvas.setScrollBarVisibility(FigureCanvas.NEVER);
		canvas.setBackground(ColorUtil.getInstance().getColor(SWT.COLOR_WHITE));
		canvas.setLayoutData(UIUtil.formData(0, 0, 0, 0, 100, 0, 100, 0));
		canvas.addControlListener(new ControlListener() {
			boolean lock = false;
			public void controlResized(ControlEvent e) {
				org.eclipse.swt.graphics.Rectangle r = canvas.getClientArea();
				if (!lock) {
					lock = true;
					xyGraph.setSize(r.width, r.height);
					lock = false;
				}
			}
			public void controlMoved(ControlEvent e) {
			}
		});
		canvas.addKeyListener(new KeyListener() {
			public void keyReleased(KeyEvent e) {
			}
			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					forceRefresh();
				}
			}
		});
		xyGraph = new XYGraph();
		xyGraph.setShowTitle(false);
		xyGraph.setShowLegend(false);
		canvas.setContents(xyGraph);
		xyGraph.primaryXAxis.setDateEnabled(true);
		xyGraph.primaryXAxis.setShowMajorGrid(true);
		xyGraph.primaryYAxis.setAutoScale(true);
		xyGraph.primaryYAxis.setShowMajorGrid(true);
		xyGraph.primaryXAxis.setTitle("");
		xyGraph.primaryYAxis.setTitle("");

		ScouterUtil.addShowTotalValueListener(canvas, xyGraph);

		IToolBarManager man = getViewSite().getActionBars().getToolBarManager();
		man.add(new Action("Reload", ImageUtil.getImageDescriptor(Images.refresh)) {
			public void run() {
				forceRefresh();
			}
		});
		man.add(new Separator());
		man.add(new Action("Duplicate", ImageUtil.getImageDescriptor(Images.copy)) {
			public void run() {
				ExUtil.exec(new Runnable() {
					public void run() {
						try {
							window.getActivePage().showView(
									CounterPastTimeGroupTotalView.ID, grpName + "&" + objType + "&" + counter + "&" + TimeUtil.getCurrentTime(),
									IWorkbenchPage.VIEW_ACTIVATE);
						} catch (PartInitException e) {
							e.printStackTrace();
						}
					}
				});
			}
		});
		forceRefresh();
	}

	Label serverText, sDateText, sTimeText, eTimeText;
	CalendarDialog calDialog;
	Composite headerComp;
	private void createUpperMenu(Composite composite) {
		headerComp = new Composite(composite, SWT.NONE);
		headerComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
		headerComp.setLayout(UIUtil.formLayout(0, 0));

		Button manualBtn = new Button(headerComp, SWT.PUSH);
		manualBtn.setImage(Images.CTXMENU_RDC);
		manualBtn.setText("Manual");
		manualBtn.setLayoutData(UIUtil.formData(null, -1, 0, 2, 100, -5, null, -1));
		manualBtn.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event event) {
				switch (event.type) {
				case SWT.Selection:
					Display display = Display.getCurrent();
					if (display == null) {
						display = Display.getDefault();
					}

					calDialog = new CalendarDialog(display, CounterPastTimeGroupTotalView.this);
					calDialog.showWithTime(UIUtil.getMousePosition(), stime);
					break;
				}
			}
		});

		eTimeText = new Label(headerComp, SWT.NONE);
		eTimeText.setLayoutData(UIUtil.labelFormData(manualBtn));

		Label label = new Label(headerComp, SWT.NONE);
		label.setLayoutData(UIUtil.labelFormData(eTimeText));
        label.setText("~");

		sTimeText = new Label(headerComp, SWT.NONE);
		sTimeText.setLayoutData(UIUtil.labelFormData(label));

        sDateText = new Label(headerComp, SWT.NONE);
		sDateText.setLayoutData(UIUtil.labelFormData(sTimeText));

		serverText = new Label(headerComp, SWT.NONE | SWT.RIGHT);
		serverText.setLayoutData(UIUtil.formData(0, 0, 0, 7, sDateText, -5, null, -1));

		setHeadText();
	}

	private void setHeadText() {
		serverText.setText(grpName + " |");
		sDateText.setText(DateUtil.format(stime, "yyyy-MM-dd"));
		sTimeText.setText(DateUtil.format(stime, "hh:mm a", Locale.ENGLISH));
		eTimeText.setText(DateUtil.format(etime, "hh:mm a", Locale.ENGLISH));
	}

	public void onPressedOk(long startTime, long endTime) {
		stime = startTime;
		etime = endTime;
		forceRefresh();
		setHeadText();
	}
	public void onPressedOk(String date) {}
	public void onPressedCancel() {}

	public void setFocus() {
		super.setFocus();
	}

	private IDataProvider getDataProvider() {
		CircularBufferDataProvider provider = new CircularBufferDataProvider(true);
		provider.setBufferSize((int) ((etime - stime) / 2000) + 1);
		Trace trace = new Trace(grpName, xyGraph.primaryXAxis, xyGraph.primaryYAxis, provider);
		trace.setPointStyle(PointStyle.NONE);
		trace.getXAxis().setFormatPattern("HH:mm:ss");
		trace.getYAxis().setFormatPattern("#,##0");
		trace.setLineWidth(PManager.getInstance().getInt(PreferenceConstants.P_CHART_LINE_WIDTH));
		trace.setTraceType(TraceType.AREA);
		trace.setTraceColor(ColorUtil.getInstance().TOTAL_CHART_COLOR);
		xyGraph.addTrace(trace);
		Trace lineTrace = ChartUtil.addSolidLine(xyGraph, provider, ColorUtil.getInstance().TOTAL_CHART_COLOR);
		traces.add(trace);
		traces.add(lineTrace);
		return provider;
	}

	private void forceRefresh() {
		for (Trace t : traces) {
			xyGraph.removeTrace(t);
		}
		traces.clear();
		ExUtil.asyncRun(new Runnable() {
			public void run() {
				load();
			}
		});
	}

	private GroupManager manager = GroupManager.getInstance();

	private void collectObj() {
		serverObjMap.clear();
		Set<Integer> objHashs = manager.getObjectsByGroup(grpName);
		for (int objHash : objHashs) {
			AgentObject agentObj = AgentModelThread.getInstance().getAgentObject(objHash);
			if (agentObj == null || agentObj.isAlive() == false) {
				continue;
			}
			int serverId = agentObj.getServerId();
			ListValue lv = serverObjMap.get(serverId);
			if (lv == null) {
				lv = new ListValue();
				serverObjMap.put(serverId, lv);
			}
			lv.add(objHash);
		}
	}

	private void load() {
		collectObj();
		Iterator<Integer> serverIds = serverObjMap.keySet().iterator();
		final List<Pack> result = new ArrayList<Pack>();
		while (serverIds.hasNext()) {
			int serverId = serverIds.next();
			TcpProxy tcp = TcpProxy.getTcpProxy(serverId);
			try {
				MapPack param = new MapPack();
				param.put("stime", stime);
				param.put("etime", etime);
				param.put("counter", counter);
				param.put("objHash", serverObjMap.get(serverId));
				tcp.process(RequestCmd.COUNTER_PAST_TIME_GROUP, param, new INetReader() {
					public void process(DataInputX in) throws IOException {
						Pack p = in.readPack();
						result.add(p);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				TcpProxy.putTcpProxy(tcp);
			}
		}
		final Map<Long, Double> valueMap = ScouterUtil.getLoadTotalMap(counter, result, mode, TimeTypeEnum.REALTIME);
		ExUtil.exec(canvas, new Runnable() {
			public void run() {
				xyGraph.primaryXAxis.setRange(stime, etime);
				CircularBufferDataProvider provider = (CircularBufferDataProvider) getDataProvider();
				provider.clearTrace();
				Set<Long> timeSet = valueMap.keySet();
				for (long time : timeSet) {
					provider.addSample(new Sample(time, CastUtil.cdouble(valueMap.get(time))));
				}
				if (CounterUtil.isPercentValue(objType, counter)) {
					xyGraph.primaryYAxis.setRange(0, 100);
				} else {
					double max = ChartUtil.getMax(provider.iterator());
						xyGraph.primaryYAxis.setRange(0, max);
				}
			}
		});
	}
}


text: <unf-selection-list [stix]="dataSources$ | async" [formCtrl]="formCtrl"></unf-selection-list>


text:
package org.apache.samoa.moa.classifiers;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.apache.samoa.instances.Instance;
import org.apache.samoa.instances.InstancesHeader;
import org.apache.samoa.moa.MOAObject;
import org.apache.samoa.moa.core.Example;
import org.apache.samoa.moa.core.Measurement;
import org.apache.samoa.moa.core.ObjectRepository;
import org.apache.samoa.moa.core.StringUtils;
import org.apache.samoa.moa.core.Utils;
import org.apache.samoa.moa.learners.Learner;
import org.apache.samoa.moa.options.AbstractOptionHandler;
import org.apache.samoa.moa.tasks.TaskMonitor;

import com.github.javacliparser.IntOption;

public abstract class AbstractClassifier extends AbstractOptionHandler implements Classifier {

  @Override
  public String getPurposeString() {
    return "MOA Classifier: " + getClass().getCanonicalName();
  }

  /** Header of the instances of the data stream */
  protected InstancesHeader modelContext;

  /** Sum of the weights of the instances trained by this model */
  protected double trainingWeightSeenByModel = 0.0;

  /** Random seed used in randomizable learners */
  protected int randomSeed = 1;

  /** Option for randomizable learners to change the random seed */
  protected IntOption randomSeedOption;

  /** Random Generator used in randomizable learners */
  public Random classifierRandom;

  /**
   * Creates an classifier and setups the random seed option if the classifier is randomizable.
   */
  public AbstractClassifier() {
    if (isRandomizable()) {
      this.randomSeedOption = new IntOption("randomSeed", 'r',
          "Seed for random behaviour of the classifier.", 1);
    }
  }

  @Override
  public void prepareForUseImpl(TaskMonitor monitor,
      ObjectRepository repository) {
    if (this.randomSeedOption != null) {
      this.randomSeed = this.randomSeedOption.getValue();
    }
    if (!trainingHasStarted()) {
      resetLearning();
    }
  }

  @Override
  public double[] getVotesForInstance(Example<Instance> example) {
    return getVotesForInstance(example.getData());
  }

  @Override
  public abstract double[] getVotesForInstance(Instance inst);

  @Override
  public void setModelContext(InstancesHeader ih) {
    if ((ih != null) && (ih.classIndex() < 0)) {
      throw new IllegalArgumentException(
          "Context for a classifier must include a class to learn");
    }
    if (trainingHasStarted()
        && (this.modelContext != null)
        && ((ih == null) || !contextIsCompatible(this.modelContext, ih))) {
      throw new IllegalArgumentException(
          "New context is not compatible with existing model");
    }
    this.modelContext = ih;
  }

  @Override
  public InstancesHeader getModelContext() {
    return this.modelContext;
  }

  @Override
  public void setRandomSeed(int s) {
    this.randomSeed = s;
    if (this.randomSeedOption != null) {
      // keep option consistent
      this.randomSeedOption.setValue(s);
    }
  }

  @Override
  public boolean trainingHasStarted() {
    return this.trainingWeightSeenByModel > 0.0;
  }

  @Override
  public double trainingWeightSeenByModel() {
    return this.trainingWeightSeenByModel;
  }

  @Override
  public void resetLearning() {
    this.trainingWeightSeenByModel = 0.0;
    if (isRandomizable()) {
      this.classifierRandom = new Random(this.randomSeed);
    }
    resetLearningImpl();
  }

  @Override
  public void trainOnInstance(Instance inst) {
    if (inst.weight() > 0.0) {
      this.trainingWeightSeenByModel += inst.weight();
      trainOnInstanceImpl(inst);
    }
  }

  @Override
  public Measurement[] getModelMeasurements() {
    List<Measurement> measurementList = new LinkedList<>();
    measurementList.add(new Measurement("model training instances",
        trainingWeightSeenByModel()));
    measurementList.add(new Measurement("model serialized size (bytes)",
        measureByteSize()));
    Measurement[] modelMeasurements = getModelMeasurementsImpl();
    if (modelMeasurements != null) {
      measurementList.addAll(Arrays.asList(modelMeasurements));
    }
    // add average of sub-model measurements
    Learner[] subModels = getSublearners();
    if ((subModels != null) && (subModels.length > 0)) {
      List<Measurement[]> subMeasurements = new LinkedList<>();
      for (Learner subModel : subModels) {
        if (subModel != null) {
          subMeasurements.add(subModel.getModelMeasurements());
        }
      }
      Measurement[] avgMeasurements = Measurement.averageMeasurements(subMeasurements
          .toArray(new Measurement[subMeasurements.size()][]));
      measurementList.addAll(Arrays.asList(avgMeasurements));
    }
    return measurementList.toArray(new Measurement[measurementList.size()]);
  }

  @Override
  public void getDescription(StringBuilder out, int indent) {
    StringUtils.appendIndented(out, indent, "Model type: ");
    out.append(this.getClass().getName());
    StringUtils.appendNewline(out);
    Measurement.getMeasurementsDescription(getModelMeasurements(), out,
        indent);
    StringUtils.appendNewlineIndented(out, indent, "Model description:");
    StringUtils.appendNewline(out);
    if (trainingHasStarted()) {
      getModelDescription(out, indent);
    } else {
      StringUtils.appendIndented(out, indent,
          "Model has not been trained.");
    }
  }

  @Override
  public Learner[] getSublearners() {
    return null;
  }

  @Override
  public Classifier[] getSubClassifiers() {
    return null;
  }

  @Override
  public Classifier copy() {
    return (Classifier) super.copy();
  }

  @Override
  public MOAObject getModel() {
    return this;
  }

  @Override
  public void trainOnInstance(Example<Instance> example) {
    trainOnInstance(example.getData());
  }

  @Override
  public boolean correctlyClassifies(Instance inst) {
    return Utils.maxIndex(getVotesForInstance(inst)) == (int) inst.classValue();
  }

  /**
   * Gets the name of the attribute of the class from the header.
   *
   * @return the string with name of the attribute of the class
   */
  public String getClassNameString() {
    return InstancesHeader.getClassNameString(this.modelContext);
  }

  /**
   * Gets the name of a label of the class from the header.
   *
   * @param classLabelIndex
   *          the label index
   * @return the name of the label of the class
   */
  public String getClassLabelString(int classLabelIndex) {
    return InstancesHeader.getClassLabelString(this.modelContext,
        classLabelIndex);
  }

  /**
   * Gets the name of an attribute from the header.
   *
   * @param attIndex
   *          the attribute index
   * @return the name of the attribute
   */
  public String getAttributeNameString(int attIndex) {
    return InstancesHeader.getAttributeNameString(this.modelContext, attIndex);
  }

  /**
   * Gets the name of a value of an attribute from the header.
   *
   * @param attIndex
   *          the attribute index
   * @param valIndex
   *          the value of the attribute
   * @return the name of the value of the attribute
   */
  public String getNominalValueString(int attIndex, int valIndex) {
    return InstancesHeader.getNominalValueString(this.modelContext, attIndex, valIndex);
  }

  /**
   * Returns if two contexts or headers of instances are compatible.

   *

   *
   * Two contexts are compatible if they follow the following rules:

   * Rule 1: num classes can increase but never decrease

   * Rule 2: num attributes can increase but never decrease

   * Rule 3: num nominal attribute values can increase but never decrease

   * Rule 4: attribute types must stay in the same order (although class can move; is always skipped over)

   *

   *
   * Attribute names are free to change, but should always still represent the original attributes.
   *
   * @param originalContext
   *          the first context to compare
   * @param newContext
   *          the second context to compare
   * @return true if the two contexts are compatible.
   */
  public static boolean contextIsCompatible(InstancesHeader originalContext,
      InstancesHeader newContext) {

    if (newContext.numClasses() < originalContext.numClasses()) {
      return false; // rule 1
    }
    if (newContext.numAttributes() < originalContext.numAttributes()) {
      return false; // rule 2
    }
    int oPos = 0;
    int nPos = 0;
    while (oPos < originalContext.numAttributes()) {
      if (oPos == originalContext.classIndex()) {
        oPos++;
        if (!(oPos < originalContext.numAttributes())) {
          break;
        }
      }
      if (nPos == newContext.classIndex()) {
        nPos++;
      }
      if (originalContext.attribute(oPos).isNominal()) {
        if (!newContext.attribute(nPos).isNominal()) {
          return false; // rule 4
        }
        if (newContext.attribute(nPos).numValues() < originalContext.attribute(oPos).numValues()) {
          return false; // rule 3
        }
      } else {
        assert (originalContext.attribute(oPos).isNumeric());
        if (!newContext.attribute(nPos).isNumeric()) {
          return false; // rule 4
        }
      }
      oPos++;
      nPos++;
    }
    return true; // all checks clear
  }

  /**
   * Resets this classifier. It must be similar to starting a new classifier from scratch.

   *

   *
   * The reason for ...Impl methods: ease programmer burden by not requiring them to remember calls to super in
   * overridden methods. Note that this will produce compiler errors if not overridden.
   */
  public abstract void resetLearningImpl();

  /**
   * Trains this classifier incrementally using the given instance.

   *

   *
   * The reason for ...Impl methods: ease programmer burden by not requiring them to remember calls to super in
   * overridden methods. Note that this will produce compiler errors if not overridden.
   *
   * @param inst
   *          the instance to be used for training
   */
  public abstract void trainOnInstanceImpl(Instance inst);

  /**
   * Gets the current measurements of this classifier.

   *

   *
   * The reason for ...Impl methods: ease programmer burden by not requiring them to remember calls to super in
   * overridden methods. Note that this will produce compiler errors if not overridden.
   *
   * @return an array of measurements to be used in evaluation tasks
   */
  protected abstract Measurement[] getModelMeasurementsImpl();

  /**
   * Returns a string representation of the model.
   *
   * @param out
   *          the stringbuilder to add the description
   * @param indent
   *          the number of characters to indent
   */
  public abstract void getModelDescription(StringBuilder out, int indent);

  /**
   * Gets the index of the attribute in the instance, given the index of the attribute in the learner.
   *
   * @param index
   *          the index of the attribute in the learner
   * @return the index in the instance
   */
  protected static int modelAttIndexToInstanceAttIndex(int index) {
    return index; // inst.classIndex() > index ? index : index + 1;
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="generator" content="rustdoc">
    <title>Welcome to Rust</title>

    <link rel="stylesheet" href="http://doc.rust-lang.org/rust.css">
<link rel="stylesheet" href="sliderust.css">

Welcome to Rust

@steveklabnik

Meta

Rust is a new programming language from Mozilla (and friends).

Rust is a low-level programming language that often feels like a high level
one.

Rust makes low-level programming accessible to those who haven't done it, and
safer for those who have.

Safety and Ownership

Here's some Ruby:

v = [];

v.push("Hello");

x = v[0];

v.push("world");

puts x

Safety and Ownership

Here's some C++:

#include<iostream>
#include<vector>
#include<string>

int main() {
    std::vector<std::string> v;

    v.push_back("Hello");

    std::string& x = v[0];

    v.push_back("world");

    std::cout << x;
}

Safety and Ownership

$ g++ hello.cpp -Wall -Werror
$ ./a.out
Segmentation fault (core dumped)

Safety and Ownership

int main() {
    std::vector<std::string> v;

location
name
value

0x30
v

Safety and Ownership

v.push_back("Hello");

location
name
value

0x30
v
0x18

0x18

"Hello"

Safety and Ownership

std::string& x = v[0];

location
name
value

0x30
v
0x18

0x18

"Hello"

0x14
x
0x18

Safety and Ownership

v.push_back("world");

location
name
value

0x30
v
0x08

0x18

GARBAGE

0x14
x
0x18

0x08

"Hello"

0x04

"world"

Safety and Ownership

If the new size() is greater than capacity() then all iterators and
references (including the past-the-end iterator) are invalidated.

Safety and Ownership

fn main() {
    let mut v = vec![];

    v.push("Hello");

    let x = &v[0];

    v.push("world");

    println!("{}", x);
}

Safety and Ownership

error: cannot borrow `v` as mutable because it is also borrowed as immutable
v.push("world");
^

Safety and Ownership

note: previous borrow of `v` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `v` until the borrow ends
let x = &v[0];
^

Safety and Ownership

fn main() {
    let mut v = vec![];

    v.push("Hello");

    let x = v[0].clone();

    v.push("world");

    println!("{}", x);
}

Zero Cost Abstraction

fn main() {
    let xs = [1, 2, 3, 4, 5];

    let mut xs = xs.iter()
               .map(|x| x + 1 )
               .filter(|x| x % 2i == 0 );

    let xs: Vec<int> = xs.collect();
}

Cargo

$ cargo new hello_world --bin
$ cd hello_world
$ tree .
.
├── Cargo.toml
└── src
    └── main.rs

1 directory, 2 files

Cargo

[package]

name = "hello_world"
version = "0.0.1"
authors = ["Your Name <you@example.com>"]

fn main() {
    println!("Hello, world!")
}

Cargo

$ cargo run
   Compiling hello_world v0.0.1 (file:///Users/you/src/hello_world)
     Running `target/hello_world`
Hello, world!

Cargo

[package]

name = "hello_world"
version = "0.0.1"
authors = ["Your Name <someone@example.com>"]

[dependencies.semver]

git = "https://github.com/rust-lang/semver.git"

$ cargo run
    Updating git repository `https://github.com/rust-lang/semver.git`
   Compiling semver v0.0.1 (https://github.com/rust-lang/semver.git#bf739419)
   Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
     Running `target/hello_world`
Hello, world!

Thanks!

Rust makes low-level programming accessible to those who haven't done it, and
safer for those who have.

@steveklabnik


text:
require_relative '../../spec_helper.rb'

describe Commerce::Store::Inventory do

  context "structure" do
    let (:inventory) {described_class.new}

    it "has all fields" do
      [:id, :sku, :color, :size, :returnable, :price, :remaining, :tax, :tax_title].each { |name| inventory_responds_to(name)}
    end

    def inventory_responds_to(attribute)
      expect(inventory).to respond_to attribute
    end

  end

end


text:
<?php

namespace App\Modules\DummyModule\Services;

use App\Modules\Core\BaseClasses\Contracts\BaseServiceInterface;

interface DummyServiceInterface extends BaseServiceInterface
{
}


text:
ComponentNotPresentException::ComponentNotPresentException() :
	CustomMessageException(
		"The specified component could not be found within this genome."
	) {}

ComponentNotPresentException::ComponentNotPresentException(
	std::string message
) : CustomMessageException(message) {}


text:
package cern.colt;

/**
 * Interface for an object that knows how to swap elements at two positions (a,b).
 *
 * @see cern.colt.GenericSorting
 *
 * @author wolfgang.hoschek@cern.ch
 * @version 1.0, 03-Jul-99
 */
public interface Swapper {
/**
 * Swaps the generic data g[a] with g[b].
 */
public abstract void swap(int a, int b);
}


text:
require File.expand_path('spec_helper', File.dirname(__FILE__))

describe 'stats', :type => :search do
  it 'returns field name for facet' do
    #stub_stat(:visibility)
    result = session.search Content do
      stat :visibility, :facet => :published_at
    end

    result.stat(:visibility).field_name.should == :visibility
  end

end


text:
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.0.xsd">

	<changeSet id="change_32" author="aakil">
		<comment>logbook entity</comment>
		<sqlFile path="db/scripts/script_32.sql" splitStatements="false" />
		<rollback>
            <sqlFile  path="db/scripts/script_32_rollback.sql"/>
        </rollback>

	</changeSet>
</databaseChangeLog>


text:
"""
Serializable models for the `SignaliQ`.
"""


text:
<?php

/**
 * Subclass for performing query and update operations on the 'app_user_role_access' table.
 *
 *
 *
 * @package lib.model
 */
class AppUserRoleAccessPeer extends BaseAppUserRoleAccessPeer
{
}


text:
package blogapp;

import javax.sql.DataSource;

import logic.model.User;

public class BlogAppContext
{
    public BlogAppConfiguration configuration;
    public DataSource dataSource;
    public BlogAppDatabase db;

    public User user;
}


text:
/* See LICENSE for licensing information */

/**
 * \file voting_schedule.h
 * \brief Header file for voting_schedule.c.
 **/

#ifndef TOR_VOTING_SCHEDULE_H
#define TOR_VOTING_SCHEDULE_H

#include "core/or/or.h"

/** Scheduling information for a voting interval. */
typedef struct {
  /** When do we generate and distribute our vote for this interval? */
  time_t voting_starts;
  /** When do we send an HTTP request for any votes that we haven't
   * been posted yet?*/
  time_t fetch_missing_votes;
  /** When do we give up on getting more votes and generate a consensus? */
  time_t voting_ends;
  /** When do we send an HTTP request for any signatures we're expecting to
   * see on the consensus? */
  time_t fetch_missing_signatures;
  /** When do we publish the consensus? */
  time_t interval_starts;

  /** True iff we have generated and distributed our vote. */
  int have_voted;
  /** True iff we've requested missing votes. */
  int have_fetched_missing_votes;
  /** True iff we have built a consensus and sent the signatures around. */
  int have_built_consensus;
  /** True iff we've fetched missing signatures. */
  int have_fetched_missing_signatures;
  /** True iff we have published our consensus. */
  int have_published_consensus;

  /* True iff this voting schedule was set on demand meaning not through the
   * normal vote operation of a dirauth or when a consensus is set. This only
   * applies to a directory authority that needs to recalculate the voting
   * timings only for the first vote even though this object was initilized
   * prior to voting. */
  int created_on_demand;

  /** The valid-after time of the last live consensus that filled this voting
   *  schedule.  It's used to detect outdated voting schedules. */
  time_t live_consensus_valid_after;
} voting_schedule_t;

/* Public API. */

extern voting_schedule_t voting_schedule;

void voting_schedule_recalculate_timing(const or_options_t *options,
                                        time_t now);

time_t voting_schedule_get_start_of_next_interval(time_t now,
                                                  int interval,
                                                  int offset);
time_t voting_schedule_get_next_valid_after_time(void);

#endif /* !defined(TOR_VOTING_SCHEDULE_H) */


text:
#pragma once

#include <time.h>
#include <iostream>
#include <signal.h>
#include <cstring>
#include <functional>

using namespace std;

/*
 * public types
 *
 */
typedef function<void()> timer_callback_t;

/*
 * public class
 *
 */

class timer
{
private:
	bool mRunning;
	pthread_t mThreadId;
	long mRefreshPeriod;
	timer_t mTimer;
	timer_callback_t mCallback;
public:
	timer(long pPeriod, const timer_callback_t& pCallback);
	virtual ~timer();

	static void handler_wrapper(sigval_t pVal);
	void handler();

	void run(void);
};


text:
/*
 * This source file is based on code taken from SQLLine 1.0.2
 * See SQLLine notice in LICENSE
 */
package org.apache.hive.beeline;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * Rows implementation which buffers all rows in a linked list.
 */
class BufferedRows extends Rows {
  private final LinkedList<Row> list;
  private final Iterator<Row> iterator;

  BufferedRows(BeeLine beeLine, ResultSet rs) throws SQLException {
    super(beeLine, rs);
    list = new LinkedList<Row>();
    int count = rsMeta.getColumnCount();
    list.add(new Row(count));
    while (rs.next()) {
      list.add(new Row(count, rs));
    }
    iterator = list.iterator();
  }

  public boolean hasNext() {
    return iterator.hasNext();
  }

  public Object next() {
    return iterator.next();
  }

  @Override
  public String toString(){
    return list.toString();
  }

  @Override
  void normalizeWidths() {
    int[] max = null;
    for (Row row : list) {
      if (max == null) {
        max = new int[row.values.length];
      }
      for (int j = 0; j < max.length; j++) {
        max[j] = Math.max(max[j], row.sizes[j] + 1);
      }
    }
    for (Row row : list) {
      row.sizes = max;
    }
  }

}


text:
require.config({
    paths: {
        'dataStore': 'src/tb/component/datastore/DataStore'
    }
});
define(['dataStore'], function (DataStore) {
    'use strict';
    return DataStore;
});


text:
This library implements [Nganluong](http://www.nganluong.vn/) payment gateway for [Payum](http://payum.org).

## License

Nganluong is released under the [MIT License](LICENSE).


text:
<?php

class Extensionmanager_UpdateController extends Pimcore_Controller_Action_Admin {

    public function getUpdateInformationAction () {

        $id = $this->_getParam("id");
        $type = $this->_getParam("type");

        if($type == "plugin") {
            $extensionPath = PIMCORE_PLUGINS_PATH . "/" . $id;
        } else if ($type = "brick") {
            $extensionPath = PIMCORE_WEBSITE_PATH . "/var/areas/" . $id;
        }

        $remoteConfig = array(
            "token" => Pimcore_Liveconnect::getToken(),
            "id" => $id,
            "type" => $type,
            "revision" => trim(file_get_contents($extensionPath."/.pimcore_extension_revision"))
        );

        $rawData = Pimcore_Tool::getHttpData("http://extensions.pimcore.org/update/getUpdateInformation.php", null, array("data" => base64_encode(Pimcore_Tool_Serialize::serialize($remoteConfig))));

        if(!$rawData) {
            header('HTTP/1.1 403 Forbidden');
            exit;
        }

        $steps = array();
        $numberOfFiles = 0;
        $data = Zend_Json::decode($rawData);
        foreach ($data["revisions"] as $revision) {

            foreach ($revision["files"] as $file) {
                $steps[] = array(
                    "action" => $file["action"],
                    "controller" => "download",
                    "params" => array(
                        "id" => $id,
                        "type" => $type,
                        "path" => $file["path"],
                        "revision" => $file["revision"]
                    )
                );
                $numberOfFiles++;
            }

            $steps[] = array(
                "action" => "check-update-script",
                "controller" => "update",
                "params" => array(
                    "id" => $id,
                    "type" => $type,
                    "revision" => $revision["revision"]
                )
            );
        }

        $this->_helper->json(array("steps" => $steps, "fileAmount" => $numberOfFiles));
    }

    public function checkUpdateScriptAction () {

        $id = $this->_getParam("id");
        $type = $this->_getParam("type");
        $revision = $this->_getParam("revision");

        if($type == "plugin") {
            $extensionPath = PIMCORE_PLUGINS_PATH . "/" . $id;
        } else if ($type = "brick") {
            $extensionPath = PIMCORE_WEBSITE_PATH . "/var/areas/" . $id;
        }

        $maxExecutionTime = 900;
        @ini_set("max_execution_time", $maxExecutionTime);
        set_time_limit($maxExecutionTime);

        $updateFile = $extensionPath."/"."update.php";
        if(is_file($updateFile)) {
            ob_start();
            include($updateFile);
            $message = ob_get_clean();

            unlink($updateFile);
        }

        $this->_helper->json(array("success" => true, "message" => $message));
    }
}


text:
def largestContiguousSum(listOfNumbers: List[Int]): Int = {
  var largestSum = 0
  listOfNumbers.foldLeft(0)((accum, num) => {
    val currentSum = if ((accum + num) < 0) (0) else (accum + num)
    largestSum = if (currentSum > largestSum) (currentSum) else largestSum
    currentSum
  })
  largestSum
}

@scala.annotation.tailrec
def tailRecursiveLargestContiguousSum(listOfNumbers: List[Int], currentSum: Int = 0, largestSum: Int = 0): Int = {
  if (listOfNumbers.isEmpty) return largestSum
  val newCurrentSum = List((currentSum + listOfNumbers.head), 0).max
  tailRecursiveLargestContiguousSum(listOfNumbers.tail, newCurrentSum, List(newCurrentSum, largestSum).max)
}


text:
package io.quarkus.bootstrap.model;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import io.quarkus.bootstrap.util.IoUtils;
import io.quarkus.maven.dependency.ArtifactCoords;
import io.quarkus.maven.dependency.GACTV;

public class PlatformImportsTest {

    private final List<PlatformProps> platformProps = new ArrayList<>();

    @AfterEach
    public void cleanUp() {
        for (PlatformProps p : platformProps) {
            p.delete();
        }
    }

    @Test
    public void singlePlatformReleaseInfo() throws Exception {
        final PlatformProps props = newPlatformProps();
        props.setProperty("platform.quarkus.native.builder-image", "url");
        props.setRelease(new PlatformReleaseInfo("io.playground", "1.1", "1",
                "io.playground:playground-bom::pom:1.1.1,io.playground:acme-bom::pom:2.2.2,io.playground:foo-bom::pom:3.3.3"));

        final PlatformImportsImpl pi = new PlatformImportsImpl();
        props.importRelease(pi);

        final PlatformInfo platform = pi.getPlatform("io.playground");
        assertNotNull(platform);
        assertEquals("io.playground", platform.getPlatformKey());
        final PlatformStreamInfo stream = platform.getStream("1.1");
        assertNotNull(stream);
        final PlatformReleaseInfo release = stream.getRelease("1");
        assertEquals("io.playground", release.getPlatformKey());
        assertEquals("1.1", release.getStream());
        assertEquals("1", release.getVersion());
        final List<ArtifactCoords> boms = release.getBoms();
        assertEquals(Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.1"),
                GACTV.fromString("io.playground:acme-bom::pom:2.2.2"),
                GACTV.fromString("io.playground:foo-bom::pom:3.3.3")), boms);
        assertEquals(1, stream.getReleases().size());
        assertEquals(1, platform.getStreams().size());
        assertEquals(1, pi.getPlatforms().size());

        assertTrue(pi.isAligned(Collections.singletonMap("io.playground",
                Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.1"),
                        GACTV.fromString("io.playground:acme-bom::pom:2.2.2")))));
        assertFalse(pi.isAligned(Collections.singletonMap("io.playground",
                Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.2"),
                        GACTV.fromString("io.playground:acme-bom::pom:2.2.2")))));
    }

    @Test
    public void multiplePlatformReleaseInTheSameStream() throws Exception {
        final PlatformProps member1 = newPlatformProps();
        member1.setProperty("platform.quarkus.native.builder-image", "url");
        member1.setRelease(new PlatformReleaseInfo("io.playground", "1.1", "1",
                "io.playground:playground-bom::pom:1.1.1,io.playground:acme-bom::pom:2.2.2,io.playground:foo-bom::pom:3.3.3"));

        final PlatformProps member2 = newPlatformProps();
        member2.setProperty("platform.quarkus.native.builder-image", "url");
        member2.setRelease(new PlatformReleaseInfo("io.playground", "1.1", "2",
                "io.playground:playground-bom::pom:1.1.2,io.playground:acme-bom::pom:2.2.3,io.playground:foo-bom::pom:3.3.3"));

        final PlatformImportsImpl pi = new PlatformImportsImpl();
        member1.importRelease(pi);
        member2.importRelease(pi);

        final PlatformInfo platform = pi.getPlatform("io.playground");
        assertNotNull(platform);
        assertEquals("io.playground", platform.getPlatformKey());
        final PlatformStreamInfo stream = platform.getStream("1.1");
        assertNotNull(stream);
        final PlatformReleaseInfo release = stream.getRelease("1");
        assertEquals("io.playground", release.getPlatformKey());
        assertEquals("1.1", release.getStream());
        assertEquals("1", release.getVersion());
        final List<ArtifactCoords> boms = release.getBoms();
        assertEquals(Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.1"),
                GACTV.fromString("io.playground:acme-bom::pom:2.2.2"),
                GACTV.fromString("io.playground:foo-bom::pom:3.3.3")), boms);
        assertEquals(2, stream.getReleases().size());
        assertEquals(1, platform.getStreams().size());
        assertEquals(1, pi.getPlatforms().size());

        assertTrue(pi.isAligned(Collections.singletonMap("io.playground",
                Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.1"),
                        GACTV.fromString("io.playground:acme-bom::pom:2.2.2")))));
        assertTrue(pi.isAligned(Collections.singletonMap("io.playground",
                Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.2"),
                        GACTV.fromString("io.playground:acme-bom::pom:2.2.3")))));
        assertFalse(pi.isAligned(Collections.singletonMap("io.playground",
                Arrays.asList(GACTV.fromString("io.playground:playground-bom::pom:1.1.2"),
                        GACTV.fromString("io.playground:acme-bom::pom:2.2.2")))));
    }

    private PlatformProps newPlatformProps() throws IOException {
        final PlatformProps p = new PlatformProps();
        platformProps.add(p);
        return p;
    }

    private static class PlatformProps {

        private final Path path;
        private Properties props = new Properties();

        private PlatformProps() throws IOException {
            path = Files.createTempFile("quarkus", "platform-imports");
        }

        private void setRelease(PlatformReleaseInfo release) {
            props.setProperty(release.getPropertyName(), release.getPropertyValue());
        }

        private void setProperty(String name, String value) {
            props.setProperty(name, value);
        }

        private void importRelease(PlatformImportsImpl pi) throws IOException {
            try (BufferedWriter w = Files.newBufferedWriter(path)) {
                props.store(w, "test playground platform props");
            }
            props = new Properties();
            try (BufferedReader reader = Files.newBufferedReader(path)) {
                props.load(reader);
            }
            for (Map.Entry<?, ?> prop : props.entrySet()) {
                if (PlatformImportsImpl.isPlatformReleaseInfo(prop.getKey().toString())) {
                    pi.addPlatformRelease(prop.getKey().toString(), prop.getValue().toString());
                }
            }
        }

        private void delete() {
            IoUtils.recursiveDelete(path);
        }
    }
}


text:
$LOAD_PATH << File.expand_path(__FILE__, '../lib')

require 'que'
require 'rspec'
require 'active_record'

require_relative "./helpers/create_user"
require_relative "./helpers/exceptional_job"
require_relative "./helpers/fake_job"
require_relative "./helpers/que_job"
require_relative "./helpers/sleep_job"
require_relative "./helpers/user"

def postgres_now
  now = ActiveRecord::Base.connection.execute("SELECT NOW();")[0]["now"]
  Time.parse(now)
end

def establish_database_connection
  ActiveRecord::Base.establish_connection(
    adapter: 'postgresql',
    host: ENV.fetch('PGHOST', 'localhost'),
    user: ENV.fetch('PGUSER', 'postgres'),
    password: ENV.fetch('PGPASSWORD', ''),
    database: ENV.fetch('PGDATABASE', 'que-test')
  )
end

establish_database_connection

# Make sure our test database is prepared to run Que
Que.connection = ActiveRecord
Que.migrate!

# Ensure we have a logger, so that we can test the code paths that log
Que.logger = Logger.new("/dev/null")

RSpec.configure do |config|
  config.before(:each) do
    QueJob.delete_all
    FakeJob.log = []
    ExceptionalJob.log = []
    ExceptionalJob::WithFailureHandler.log = []

    # In normal runtime we'll new-up metrics with consistent labels, but in tests we'll
    # create workers with all sorts of configurations. Ensure we clear the registry to
    # prevent mis-matched metric labels from raising exceptions from the incompatible
    # configurations.
    Prometheus::Client.registry.instance_eval { @metrics.clear }
  end
end


text:
#include <vector>
#include <tuple>
#include <collection.h>
#include "ID3TagParser.h"
#include "HLSID3MetadataPayload.h"
#include "HLSID3TagFrame.h"

using namespace Microsoft::HLSClient;
using namespace Microsoft::HLSClient::Private;

HLSID3MetadataPayload::HLSID3MetadataPayload(unsigned long long timestamp, vector<tuple<const BYTE*, unsigned int>>& payloadchunks) :_timestamp(timestamp), _parsedFrames(nullptr)
{
  for (auto itr = payloadchunks.begin(); itr != payloadchunks.end(); itr++)
  {
    auto data = std::get<0>(*itr);
    auto len = std::get<1>(*itr);
    if (len == 0)
      continue;

    auto oldsize = _payload.size();
    _payload.resize(_payload.size() + len);
    memcpy_s(&(*(_payload.begin() + oldsize)), len, data, len);
  }

  //validate for  ID3 and readjust
  ULONG correctsize = 0;
  ULONG startat = 0;
  bool valid = ID3TagParser::AdjustPayloadToID3Tag(&(*(this->_payload.begin())), (ULONG)this->_payload.size(), startat, correctsize);
  if (!valid)
    throw ref new Platform::InvalidArgumentException();

  if (startat > 0)
  {
    for (ULONG i = 0; i < startat; i++)
      this->_payload.erase(this->_payload.begin());
  }
  if (correctsize > _payload.size())
    throw ref new Platform::InvalidArgumentException();
  else if (correctsize < _payload.size())
    _payload.resize(correctsize);
}

Windows::Foundation::Collections::IVector<IHLSID3TagFrame^>^ HLSID3MetadataPayload::ParseFrames()
{
  if (_parsedFrames == nullptr && _payload.size() > 0)
  {
    auto frames = ID3TagParser::Parse(&(*(_payload.begin())), (ULONG) _payload.size());
    if (frames.size() > 0)
    {
      _parsedFrames = ref new Platform::Collections::Vector<IHLSID3TagFrame^>((unsigned int)frames.size());

      std::transform(begin(frames), end(frames), begin(_parsedFrames), [](std::shared_ptr<std::tuple<string, vector<BYTE>>> frame)
      {
        string frameid = std::get<0>(*(frame.get()));
        unique_ptr<wchar_t[]> wzframeid(new wchar_t[9]);
        ZeroMemory(wzframeid.get(), 9);
        ::MultiByteToWideChar(CP_UTF8, 0, frameid.c_str(), (int) frameid.size() + 1/*for null term*/, wzframeid.get(), 9);

        return ref new HLSID3TagFrame(wstring(wzframeid.get()), std::get<1>(*(frame.get())));
      });
    }
  }

  return _parsedFrames;
}


text:
class ChangeTagIdToTopicId < ActiveRecord::Migration[5.0]
  def change
    rename_column :resource_topics, :tag_id, :topic_id
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZyGames.Framework.Common.Log;
using ZyGames.Framework.Game.Com;
using ZyGames.Framework.Game.Com.Rank;
using ZyGames.Tianjiexing.Model.Config;
using ZyGames.Framework.Data;
using ZyGames.Tianjiexing.Model;
using System.Data;
using ZyGames.Framework.Common;
using ZyGames.Framework.Game.Cache;

namespace ZyGames.Tianjiexing.Component
{
    /// <summary>
    /// 竞技场排行
    /// </summary>
    public class CombatRanking : Ranking<UserRank>
    {
        public const string RankingKey = "CombatRanking";
        public List<UserRank> rankList = new List<UserRank>();

        public CombatRanking()
            : base(RankingKey, int.MaxValue)
        {
        }

        protected override int ComparerTo(UserRank x, UserRank y)
        {
            int result = 0;
            if (x == null && y == null)
            {
                return 0;
            }
            if (x != null && y == null)
            {
                return 1;
            }
            if (x == null)
            {
                return -1;
            }
            result = x.RankId.CompareTo(y.RankId);
            if (result == 0)
            {
                result = y.UserLv.CompareTo(x.UserLv);
                if (result == 0)
                {
                    result = x.UserID.CompareTo(y.UserID);
                }
            }
            return result;
        }

        /// <summary>
        /// 获取前5名玩家
        /// </summary>
        /// <returns></returns>
        public List<UserRank> GetRanking(GameUser user)
        {
            List<UserRank> userRankList = new List<UserRank>();
            int currRankId;
            if (TryGetRankNo(m => m.UserID == user.UserID, out currRankId))
            {
                //user.RankID = currRankId;
                int rankIncrice;
                int length = 5;
                if (currRankId < 51) rankIncrice = 1;
                else if (currRankId < 101) rankIncrice = 2;
                else if (currRankId < 501) rankIncrice = 5;
                else rankIncrice = 10;
                int pagesize;
                int pageIndex;
                if (currRankId > 5)
                {
                    pagesize = currRankId;
                    pageIndex = currRankId - (length + 1) * rankIncrice;
                }
                else
                {
                    pagesize = 6;
                    pageIndex = 0;
                }
                int pagecount;
                IList<UserRank> list = this.GetRange(1, pagesize, out pagecount);
                while (pageIndex < pagesize && pageIndex < list.Count)
                {
                    if (list.Count <= pageIndex)
                    {
                        break;
                    }
                    if (list[pageIndex].UserID == user.UserID)
                    {
                        pageIndex = MathUtils.Addition(pageIndex, rankIncrice);
                        continue;
                    }
                    userRankList.Add(list[pageIndex]);
                    pageIndex = MathUtils.Addition(pageIndex, rankIncrice);
                }
            }
            return userRankList;
        }

        protected override IList<UserRank> GetCacheList()
        {
            if (rankList.Count > 0)
            {
                return rankList;
            }
            var dbProvider = DbConnectionProvider.CreateDbProvider(DbConfig.Data);
            string sql = "SELECT UserID,NickName,CombatNum,VictoryNum,RankID,UserLv,ObtainNum,GameCoin,VipLv,CountryID,SportsIntegral,RankDate FROM GameUser where RankID>0 order by RankID";
            using (IDataReader reader = dbProvider.ExecuteReader(CommandType.Text, sql))
            {
                while (reader.Read())
                {
                    UserRank rankInfo = new UserRank();
                    rankInfo.UserID = reader["UserID"].ToString();
                    rankInfo.NickName = reader["NickName"].ToString();
                    rankInfo.UserLv = Convert.ToInt16(reader["UserLv"]);
                    rankInfo.ObtainNum = Convert.ToInt32(reader["ObtainNum"]);
                    rankInfo.TotalCombatNum = Convert.ToInt32(reader["CombatNum"]);
                    rankInfo.VictoryNum = Convert.ToInt32(reader["VictoryNum"]);
                    rankInfo.GameCoin = Convert.ToInt32(reader["GameCoin"]);
                    rankInfo.CountryID = reader["CountryID"].ToEnum<CountryType>();
                    rankInfo.VipLv = Convert.ToInt16(reader["VipLv"]);
                    //rankInfo.HeadID = reader["HeadID"].ToString();
                    rankInfo.RankId = Convert.ToInt32(reader["RankID"]);
                    rankInfo.SportsIntegral = Convert.ToInt32(reader["SportsIntegral"]);
                    rankInfo.RankDate = reader["RankDate"].ToDateTime();
                    rankList.Add(rankInfo);
                }
            }
            return rankList;
        }
        protected override void ChangeRankNo(UserRank item)
        {
            var gameUser = new GameDataCacheSet<GameUser>().FindKey(item.UserID);
            if (gameUser == null)
            {
                return;
            }
            gameUser.RankID = item.RankId;
            gameUser.RankDate = DateTime.Now;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//NetBeans//DTD Module Status 1.0//EN"
                        "http://www.netbeans.org/dtds/module-status-1_0.dtd">
<module name="org.eclipse.equinox.registry">
    <param name="autoload">true</param>
    <param name="eager">false</param>
    <param name="jar">modules/org-eclipse-equinox-registry.jar</param>
    <param name="reloadable">false</param>
</module>


text:
package com.amazonaws.services.mediaconvert.model;

import javax.annotation.Generated;

/**
 * Optional. Choose a specific entropy encoding mode only when you want to override XAVC recommendations. If you choose
 * the value auto, MediaConvert uses the mode that the XAVC file format specifies given this output's operating point.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum XavcEntropyEncoding {

    AUTO("AUTO"),
    CABAC("CABAC"),
    CAVLC("CAVLC");

    private String value;

    private XavcEntropyEncoding(String value) {
        this.value = value;
    }

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

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return XavcEntropyEncoding corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static XavcEntropyEncoding fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (XavcEntropyEncoding enumEntry : XavcEntropyEncoding.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}