text:
package edu.cmu.sv.modelinference.eventtool.charting;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.cmu.sv.modelinference.common.Util;
import edu.cmu.sv.modelinference.common.api.LogHandler;
import edu.cmu.sv.modelinference.common.api.LogProcessingException;
import edu.cmu.sv.modelinference.common.formats.DataPointCollection;
import edu.cmu.sv.modelinference.common.formats.ValueTrackerProducer;
import edu.cmu.sv.modelinference.eventtool.AvgEventGenerator;
import edu.cmu.sv.modelinference.eventtool.EWMASmoothingFilter;
import edu.cmu.sv.modelinference.eventtool.EventDetector;
import edu.cmu.sv.modelinference.eventtool.EventGenerator;
import edu.cmu.sv.modelinference.eventtool.EventVisualizer;
import edu.cmu.sv.modelinference.eventtool.FeatureExtractor;
import edu.cmu.sv.modelinference.eventtool.MovingAverageEventDetector;
import edu.cmu.sv.modelinference.eventtool.RoCExtractor;
import edu.cmu.sv.modelinference.eventtool.classification.Clusterer1D;
import edu.cmu.sv.modelinference.eventtool.classification.EventClassifier;

/**
 * @author Kasper Luckow
 */
public class Log2EventClass implements LogHandler<Void> {
  private static final Logger logger = LoggerFactory.getLogger(Log2EventClass.class.getName());

  private static final String CLASSES_ARG = "classes";
  private static final String ALARM_ARG = "alarm";
  private static final String MOVING_AVG_DETECT_SIZE_ARG = "mad";
  private static final String MOVING_AVG_FEAT_SIZE_ARG = "maf";
  private static final String HELP_ARG = "help";

  private static final int DEFAULT_CLASSES = 6;
  private static final int DEFAULT_ALARM_LEVEL = 3;
  private static final int DEFAULT_DETECT_WINDOWSIZE = 2;
  private static final int DEFAULT_FEAT_WINDOWSIZE = 3;

  private Options cmdOpts;
  private int clusterNum, alarmSize, movingAvgDetection, movingAvgSizeFeat;

  private static Log2EventClass instance = null;

  public static Log2EventClass getInstance() {
    if(instance == null) {
      instance = new Log2EventClass();
    }
    return instance;
  }

  private static Set<LogHandler<ValueTrackerProducer<?, DataPointCollection, ?>>> logHandlers = new HashSet<>();

  static {
    logHandlers.add(AREventChartHandler.getInstance());
    logHandlers.add(STEventChartHandler.getInstance());
  }

  private Log2EventClass() {
    this.cmdOpts = createCmdOptions();
  }

  @Override
  public String getHandlerName() {
    return "eventclass";
  }

  private Options createCmdOptions() {
    Options options = new Options();

    Option help = new Option(HELP_ARG, "print this message");
    Option clusters = Option.builder(CLASSES_ARG).argName("number").hasArg()
        .desc("Specify number of clusters/event classes. Default is " + DEFAULT_CLASSES).build();
    Option alarm = Option.builder(ALARM_ARG).argName("number").hasArg()
        .desc("Specify size of upper and lower control limits in terms of number of std dev from expected val. Default is " + DEFAULT_ALARM_LEVEL).build();
    Option mvRaw = Option.builder(MOVING_AVG_DETECT_SIZE_ARG).argName("number").hasArg()
        .desc("Specify size of moving average for event detection. Default is " + DEFAULT_DETECT_WINDOWSIZE).build();
    Option mvFeat = Option.builder(MOVING_AVG_FEAT_SIZE_ARG).argName("number").hasArg()
        .desc("Specify size of moving average for smoothing feat data. Default is " + DEFAULT_FEAT_WINDOWSIZE).build();
    options.addOption(clusters);
    options.addOption(alarm);
    options.addOption(mvRaw);
    options.addOption(mvFeat);
    options.addOption(help);
    return options;
  }

  @Override
  public Void process(String logFile, String logType, String[] additionalCmdArgs) throws LogProcessingException {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
      cmd = parser.parse(cmdOpts, additionalCmdArgs, true);
    } catch(ParseException exp) {
      logger.error(exp.getMessage());
      System.err.println(exp.getMessage());
      Util.printHelpAndExit(Log2EventClass.class, cmdOpts);
    }

    if(cmd.hasOption(HELP_ARG))
      Util.printHelpAndExit(Log2EventClass.class, cmdOpts, 0);

    LogHandler<ValueTrackerProducer<?, DataPointCollection, ?>> logHandler = null;
    boolean found = false;
    for(LogHandler<ValueTrackerProducer<?, DataPointCollection, ?>> lh : logHandlers) {
      if(lh.getHandlerName().equals(logType)) {
        logHandler = lh;
        found = true;
        break;
      }
    }
    if(!found) {
      StringBuilder sb = new StringBuilder();
      Iterator<LogHandler<ValueTrackerProducer<?, DataPointCollection, ?>>> logIter = logHandlers.iterator();
      while(logIter.hasNext()) {
        sb.append(logIter.next().getHandlerName());
        if(logIter.hasNext())
          sb.append(", ");
      }
      logger.error("Did not find loghandler for " + logType);
      System.err.println("Supported log handlers: " + sb.toString());
      Util.printHelpAndExit(Log2EventClass.class, cmdOpts);
    }
    logger.info("Using loghandler for logtype: " + logHandler.getHandlerName());

    this.clusterNum = (cmd.hasOption(CLASSES_ARG)) ? Integer.parseInt(cmd.getOptionValue(CLASSES_ARG)) : DEFAULT_CLASSES;
    this.alarmSize = (cmd.hasOption(ALARM_ARG)) ? Integer.parseInt(cmd.getOptionValue(ALARM_ARG)) : DEFAULT_ALARM_LEVEL;
    this.movingAvgDetection = (cmd.hasOption(MOVING_AVG_DETECT_SIZE_ARG)) ? Integer.parseInt(cmd.getOptionValue(MOVING_AVG_DETECT_SIZE_ARG)) : DEFAULT_DETECT_WINDOWSIZE;
    this.movingAvgSizeFeat = (cmd.hasOption(MOVING_AVG_FEAT_SIZE_ARG)) ? Integer.parseInt(cmd.getOptionValue(MOVING_AVG_FEAT_SIZE_ARG)) : DEFAULT_FEAT_WINDOWSIZE;

    ValueTrackerProducer<?, DataPointCollection, ?> valueExtractor = logHandler.process(logFile, logType, cmd.getArgs());

    Map<String, DataPointCollection> rawData;
    try {
      rawData = valueExtractor.computeDataSet(new File(logFile));
    } catch (IOException e) {
      throw new LogProcessingException(e);
    }

    for(Entry<String, DataPointCollection> producer : rawData.entrySet()) {
      performAnalysis(producer.getKey(), producer.getValue().toDataArray());
    }

    return null;
  }

  private void performAnalysis(String producer, double[][] rawData) {

    //Feature: slope/rate-of-change
    FeatureExtractor slopeExtractor = new RoCExtractor();

    //use event detector on features
    EventDetector movingAvg = new MovingAverageEventDetector(this.movingAvgDetection, this.alarmSize);

    EventGenerator eventGenerator = new AvgEventGenerator();

    EventClassifier classifier = new Clusterer1D(this.clusterNum, 100, 3000);

    EventVisualizer.Builder bldr = new EventVisualizer.Builder(movingAvg,
              slopeExtractor, eventGenerator, classifier);

    EWMASmoothingFilter ewmaFilter = new EWMASmoothingFilter(this.movingAvgSizeFeat, 0.1);
    EWMASmoothingFilter ewmaFilterFeature = new EWMASmoothingFilter(this.movingAvgSizeFeat, 0.1);
    EventVisualizer eventVisualizer = bldr.addRawDataSmoothingFilter(ewmaFilter)
        .addFeatureSmoothingFilter(ewmaFilterFeature)
        .build();

    eventVisualizer.visualize(producer, rawData);
  }
}


text:
<?php
namespace App\Test\TestCase\Model\Table;

use App\Model\Table\UsersTable;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;

/**
 * App\Model\Table\UsersTable Test Case
 */
class UsersTableTest extends TestCase
{

    /**
     * Fixtures
     *
     * @var array
     */
    public $fixtures = [
        'app.users',
        'app.user_types',
        'app.client_contacts',
        'app.client_infos',
        'app.client_types',
        'app.company_types',
        'app.client_alert_settings',
        'app.alert_types',
        'app.device_alerts',
        'app.client_devices',
        'app.device_infos',
        'app.device_types',
        'app.vehicle_types',
        'app.client_device_subscriptions',
        'app.account_types',
        'app.trackers',
        'app.vehicle_models',
        'app.client_contact_devices',
        'app.client_device_geofences',
        'app.geofences',
        'app.geofence_types',
        'app.client_expenses',
        'app.expense_types',
        'app.client_persons',
        'app.identification_types',
        'app.client_publicids',
        'app.client_vehicles',
        'app.fuel_types',
        'app.client_driver_assignments',
        'app.client_drivers',
        'app.client_vehicle_assignments',
        'app.client_trips',
        'app.client_notifications',
        'app.notification_types',
        'app.client_reports',
        'app.client_trip_paths',
        'app.user_logs'
    ];

    /**
     * setUp method
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $config = TableRegistry::exists('Users') ? [] : ['className' => 'App\Model\Table\UsersTable'];
        $this->Users = TableRegistry::get('Users', $config);
    }

    /**
     * tearDown method
     *
     * @return void
     */
    public function tearDown()
    {
        unset($this->Users);

        parent::tearDown();
    }

    /**
     * Test initialize method
     *
     * @return void
     */
    public function testInitialize()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test validationDefault method
     *
     * @return void
     */
    public function testValidationDefault()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }

    /**
     * Test buildRules method
     *
     * @return void
     */
    public function testBuildRules()
    {
        $this->markTestIncomplete('Not implemented yet.');
    }
}

redpajama_set_name: RedPajamaGithub


text:
import Controller from "@ember/controller";
import { get, computed } from "@ember/object";
import { inject as service } from "@ember/service";
import { chat as chatConfig, twitch as twitchConfig } from "config";
import { providers } from "data/models/settings/chat/provider/fragment";
import ChatProviderBasic from "services/chat/providers/-basic";
import { platform } from "utils/node/platform";

const { "chat-url": twitchChatUrl } = twitchConfig;
const { userArgsSubstitutions } = ChatProviderBasic;

export default Controller.extend({
	chat: service(),

	providers,
	chatConfig,
	userArgsSubstitutions,

	contentChatProvider: computed(function() {
		const list = [];
		for ( const [ id ] of providers ) {
			const { exec } = chatConfig[ id ];
			if ( exec instanceof Object && !exec[ platform ] ) { continue; }
			list.push({ id });
		}
		return list;
	}),

	contentChatUrl: computed(function() {
		return Object.keys( twitchChatUrl )
			.map( id => ({ id }) );
	}),

	// EmberData (2.9) is stupid and uses an internal Map implementation that is not iterable
	// so we can't iterate SettingsChatProvider.attributes in the template
	providerAttributes: computed(function() {
		const map = {};
		for ( const [ id, provider ] of providers ) {
			const attrs = [];
			const attributes = get( provider, "attributes" );
			attributes.forEach( attribute => attrs.push( attribute ) );
			map[ id ] = attrs;
		}
		return map;
	})
});


text:
'use strict';

const models = require('./index');

/**
 * Describes a Virtual Machine Scale Set.
 *
 * @extends models['UpdateResource']
 */
class VirtualMachineScaleSetUpdate extends models['UpdateResource'] {
  /**
   * Create a VirtualMachineScaleSetUpdate.
   * @member {object} [sku] The virtual machine scale set sku.
   * @member {string} [sku.name] The sku name.
   * @member {string} [sku.tier] Specifies the tier of virtual machines in a
   * scale set.

 Possible Values:

 **Standard**

 **Basic**
   * @member {number} [sku.capacity] Specifies the number of virtual machines
   * in the scale set.
   * @member {object} [plan] The purchase plan when deploying a virtual machine
   * scale set from VM Marketplace images.
   * @member {string} [plan.name] The plan ID.
   * @member {string} [plan.publisher] The publisher ID.
   * @member {string} [plan.product] Specifies the product of the image from
   * the marketplace. This is the same value as Offer under the imageReference
   * element.
   * @member {string} [plan.promotionCode] The promotion code.
   * @member {object} [upgradePolicy] The upgrade policy.
   * @member {string} [upgradePolicy.mode] Specifies the mode of an upgrade to
   * virtual machines in the scale set.

 Possible values are:

 **Manual** - You  control the application of updates to virtual
   * machines in the scale set. You do this by using the manualUpgrade
   * action.

 **Automatic** - All virtual machines in the scale set
   * are  automatically updated at the same time. Possible values include:
   * 'Automatic', 'Manual', 'Rolling'
   * @member {object} [upgradePolicy.rollingUpgradePolicy] The configuration
   * parameters used while performing a rolling upgrade.
   * @member {number}
   * [upgradePolicy.rollingUpgradePolicy.maxBatchInstancePercent] The maximum
   * percent of total virtual machine instances that will be upgraded
   * simultaneously by the rolling upgrade in one batch. As this is a maximum,
   * unhealthy instances in previous or future batches can cause the percentage
   * of instances in a batch to decrease to ensure higher reliability. The
   * default value for this parameter is 20%.
   * @member {number}
   * [upgradePolicy.rollingUpgradePolicy.maxUnhealthyInstancePercent] The
   * maximum percentage of the total virtual machine instances in the scale set
   * that can be simultaneously unhealthy, either as a result of being
   * upgraded, or by being found in an unhealthy state by the virtual machine
   * health checks before the rolling upgrade aborts. This constraint will be
   * checked prior to starting any batch. The default value for this parameter
   * is 20%.
   * @member {number}
   * [upgradePolicy.rollingUpgradePolicy.maxUnhealthyUpgradedInstancePercent]
   * The maximum percentage of upgraded virtual machine instances that can be
   * found to be in an unhealthy state. This check will happen after each batch
   * is upgraded. If this percentage is ever exceeded, the rolling update
   * aborts. The default value for this parameter is 20%.
   * @member {string}
   * [upgradePolicy.rollingUpgradePolicy.pauseTimeBetweenBatches] The wait time
   * between completing the update for all virtual machines in one batch and
   * starting the next batch. The time duration should be specified in ISO 8601
   * format. The default value is 0 seconds (PT0S).
   * @member {boolean} [upgradePolicy.automaticOSUpgrade] Whether OS upgrades
   * should automatically be applied to scale set instances in a rolling
   * fashion when a newer version of the image becomes available.
   * @member {object} [virtualMachineProfile] The virtual machine profile.
   * @member {object} [virtualMachineProfile.osProfile] The virtual machine
   * scale set OS profile.
   * @member {string} [virtualMachineProfile.osProfile.customData] A base-64
   * encoded string of custom data.
   * @member {object} [virtualMachineProfile.osProfile.windowsConfiguration]
   * The Windows Configuration of the OS profile.
   * @member {boolean}
   * [virtualMachineProfile.osProfile.windowsConfiguration.provisionVMAgent]
   * Indicates whether virtual machine agent should be provisioned on the
   * virtual machine.

 When this property is not specified in the
   * request body, default behavior is to set it to true.  This will ensure
   * that VM Agent is installed on the VM so that extensions can be added to
   * the VM later.
   * @member {boolean}
   * [virtualMachineProfile.osProfile.windowsConfiguration.enableAutomaticUpdates]
   * Indicates whether virtual machine is enabled for automatic updates.
   * @member {string}
   * [virtualMachineProfile.osProfile.windowsConfiguration.timeZone] Specifies
   * the time zone of the virtual machine. e.g. "Pacific Standard Time"
   * @member {array}
   * [virtualMachineProfile.osProfile.windowsConfiguration.additionalUnattendContent]
   * Specifies additional base-64 encoded XML formatted information that can be
   * included in the Unattend.xml file, which is used by Windows Setup.
   * @member {object}
   * [virtualMachineProfile.osProfile.windowsConfiguration.winRM] Specifies the
   * Windows Remote Management listeners. This enables remote Windows
   * PowerShell.
   * @member {array}
   * [virtualMachineProfile.osProfile.windowsConfiguration.winRM.listeners] The
   * list of Windows Remote Management listeners
   * @member {object} [virtualMachineProfile.osProfile.linuxConfiguration] The
   * Linux Configuration of the OS profile.
   * @member {boolean}
   * [virtualMachineProfile.osProfile.linuxConfiguration.disablePasswordAuthentication]
   * Specifies whether password authentication should be disabled.
   * @member {object} [virtualMachineProfile.osProfile.linuxConfiguration.ssh]
   * Specifies the ssh key configuration for a Linux OS.
   * @member {array}
   * [virtualMachineProfile.osProfile.linuxConfiguration.ssh.publicKeys] The
   * list of SSH public keys used to authenticate with linux based VMs.
   * @member {array} [virtualMachineProfile.osProfile.secrets] The List of
   * certificates for addition to the VM.
   * @member {object} [virtualMachineProfile.storageProfile] The virtual
   * machine scale set storage profile.
   * @member {object} [virtualMachineProfile.storageProfile.imageReference] The
   * image reference.
   * @member {string}
   * [virtualMachineProfile.storageProfile.imageReference.publisher] The image
   * publisher.
   * @member {string}
   * [virtualMachineProfile.storageProfile.imageReference.offer] Specifies the
   * offer of the platform image or marketplace image used to create the
   * virtual machine.
   * @member {string} [virtualMachineProfile.storageProfile.imageReference.sku]
   * The image SKU.
   * @member {string}
   * [virtualMachineProfile.storageProfile.imageReference.version] Specifies
   * the version of the platform image or marketplace image used to create the
   * virtual machine. The allowed formats are Major.Minor.Build or 'latest'.
   * Major, Minor, and Build are decimal numbers. Specify 'latest' to use the
   * latest version of an image available at deploy time. Even if you use
   * 'latest', the VM image will not automatically update after deploy time
   * even if a new version becomes available.
   * @member {object} [virtualMachineProfile.storageProfile.osDisk] The OS
   * disk.
   * @member {string} [virtualMachineProfile.storageProfile.osDisk.caching] The
   * caching type. Possible values include: 'None', 'ReadOnly', 'ReadWrite'
   * @member {object} [virtualMachineProfile.storageProfile.osDisk.image] The
   * Source User Image VirtualHardDisk. This VirtualHardDisk will be copied
   * before using it to attach to the Virtual Machine. If SourceImage is
   * provided, the destination VirtualHardDisk should not exist.
   * @member {string} [virtualMachineProfile.storageProfile.osDisk.image.uri]
   * Specifies the virtual hard disk's uri.
   * @member {array}
   * [virtualMachineProfile.storageProfile.osDisk.vhdContainers] The list of
   * virtual hard disk container uris.
   * @member {object} [virtualMachineProfile.storageProfile.osDisk.managedDisk]
   * The managed disk parameters.
   * @member {string}
   * [virtualMachineProfile.storageProfile.osDisk.managedDisk.storageAccountType]
   * Specifies the storage account type for the managed disk. Possible values
   * are: Standard_LRS or Premium_LRS. Possible values include: 'Standard_LRS',
   * 'Premium_LRS'
   * @member {array} [virtualMachineProfile.storageProfile.dataDisks] The data
   * disks.
   * @member {object} [virtualMachineProfile.networkProfile] The virtual
   * machine scale set network profile.
   * @member {array}
   * [virtualMachineProfile.networkProfile.networkInterfaceConfigurations] The
   * list of network configurations.
   * @member {object} [virtualMachineProfile.diagnosticsProfile] The virtual
   * machine scale set diagnostics profile.
   * @member {object}
   * [virtualMachineProfile.diagnosticsProfile.bootDiagnostics] Boot
   * Diagnostics is a debugging feature which allows you to view Console Output
   * and Screenshot to diagnose VM status.

 For Linux Virtual Machines,
   * you can easily view the output of your console log.

 For both
   * Windows and Linux virtual machines, Azure also enables you to see a
   * screenshot of the VM from the hypervisor.
   * @member {boolean}
   * [virtualMachineProfile.diagnosticsProfile.bootDiagnostics.enabled] Whether
   * boot diagnostics should be enabled on the Virtual Machine.
   * @member {string}
   * [virtualMachineProfile.diagnosticsProfile.bootDiagnostics.storageUri] Uri
   * of the storage account to use for placing the console output and
   * screenshot.
   * @member {object} [virtualMachineProfile.extensionProfile] The virtual
   * machine scale set extension profile.
   * @member {array} [virtualMachineProfile.extensionProfile.extensions] The
   * virtual machine scale set child extension resources.
   * @member {string} [virtualMachineProfile.licenseType] The license type,
   * which is for bring your own license scenario.
   * @member {boolean} [overprovision] Specifies whether the Virtual Machine
   * Scale Set should be overprovisioned.
   * @member {boolean} [singlePlacementGroup] When true this limits the scale
   * set to a single placement group, of max size 100 virtual machines.
   * @member {object} [identity] The identity of the virtual machine scale set,
   * if configured.
   * @member {string} [identity.principalId] The principal id of virtual
   * machine scale set identity.
   * @member {string} [identity.tenantId] The tenant id associated with the
   * virtual machine scale set.
   * @member {string} [identity.type] The type of identity used for the virtual
   * machine scale set. Currently, the only supported type is 'SystemAssigned',
   * which implicitly creates an identity. Possible values include:
   * 'SystemAssigned'
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of VirtualMachineScaleSetUpdate
   *
   * @returns {object} metadata of VirtualMachineScaleSetUpdate
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'VirtualMachineScaleSetUpdate',
      type: {
        name: 'Composite',
        className: 'VirtualMachineScaleSetUpdate',
        modelProperties: {
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          sku: {
            required: false,
            serializedName: 'sku',
            type: {
              name: 'Composite',
              className: 'Sku'
            }
          },
          plan: {
            required: false,
            serializedName: 'plan',
            type: {
              name: 'Composite',
              className: 'Plan'
            }
          },
          upgradePolicy: {
            required: false,
            serializedName: 'properties.upgradePolicy',
            type: {
              name: 'Composite',
              className: 'UpgradePolicy'
            }
          },
          virtualMachineProfile: {
            required: false,
            serializedName: 'properties.virtualMachineProfile',
            type: {
              name: 'Composite',
              className: 'VirtualMachineScaleSetUpdateVMProfile'
            }
          },
          overprovision: {
            required: false,
            serializedName: 'properties.overprovision',
            type: {
              name: 'Boolean'
            }
          },
          singlePlacementGroup: {
            required: false,
            serializedName: 'properties.singlePlacementGroup',
            type: {
              name: 'Boolean'
            }
          },
          identity: {
            required: false,
            serializedName: 'identity',
            type: {
              name: 'Composite',
              className: 'VirtualMachineScaleSetIdentity'
            }
          }
        }
      }
    };
  }
}

module.exports = VirtualMachineScaleSetUpdate;


text:
#include "shared-bindings/displayio/Group.h"

#include <stdint.h>

#include "shared/runtime/context_manager_helpers.h"
#include "py/binary.h"
#include "py/objproperty.h"
#include "py/objtype.h"
#include "py/runtime.h"
#include "supervisor/shared/translate/translate.h"

//| class Group:
//|     """Manage a group of sprites and groups and how they are inter-related."""
//|
//|     def __init__(self, *, scale: int = 1, x: int = 0, y: int = 0) -> None:
//|         """Create a Group of a given size and scale. Scale is in one dimension. For example, scale=2
//|         leads to a layer's pixel being 2x2 pixels when in the group.
//|
//|         :param int scale: Scale of layer pixels in one dimension.
//|         :param int x: Initial x position within the parent.
//|         :param int y: Initial y position within the parent."""
//|         ...
STATIC mp_obj_t displayio_group_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
    enum { ARG_scale, ARG_x, ARG_y };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_scale, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1} },
        { MP_QSTR_x, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} },
        { MP_QSTR_y, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} },
    };
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    mp_int_t scale = mp_arg_validate_int_min(args[ARG_scale].u_int, 1, MP_QSTR_scale);

    displayio_group_t *self = m_new_obj(displayio_group_t);
    self->base.type = &displayio_group_type;
    common_hal_displayio_group_construct(self, scale, args[ARG_x].u_int, args[ARG_y].u_int);

    return MP_OBJ_FROM_PTR(self);
}

// Helper to ensure we have the native super class instead of a subclass.
displayio_group_t *native_group(mp_obj_t group_obj) {
    mp_obj_t native_group = mp_obj_cast_to_native_base(group_obj, &displayio_group_type);
    if (native_group == MP_OBJ_NULL) {
        mp_raise_ValueError_varg(translate("Must be a %q subclass."), MP_QSTR_Group);
    }
    mp_obj_assert_native_inited(native_group);
    return MP_OBJ_TO_PTR(native_group);
}

//|     hidden: bool
//|     """True when the Group and all of it's layers are not visible. When False, the Group's layers
//|     are visible if they haven't been hidden."""
STATIC mp_obj_t displayio_group_obj_get_hidden(mp_obj_t self_in) {
    displayio_group_t *self = native_group(self_in);
    return mp_obj_new_bool(common_hal_displayio_group_get_hidden(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(displayio_group_get_hidden_obj, displayio_group_obj_get_hidden);

STATIC mp_obj_t displayio_group_obj_set_hidden(mp_obj_t self_in, mp_obj_t hidden_obj) {
    displayio_group_t *self = native_group(self_in);

    common_hal_displayio_group_set_hidden(self, mp_obj_is_true(hidden_obj));
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_set_hidden_obj, displayio_group_obj_set_hidden);

MP_PROPERTY_GETSET(displayio_group_hidden_obj,
    (mp_obj_t)&displayio_group_get_hidden_obj,
    (mp_obj_t)&displayio_group_set_hidden_obj);

//|     scale: int
//|     """Scales each pixel within the Group in both directions. For example, when scale=2 each pixel
//|     will be represented by 2x2 pixels."""
STATIC mp_obj_t displayio_group_obj_get_scale(mp_obj_t self_in) {
    displayio_group_t *self = native_group(self_in);
    return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_group_get_scale(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(displayio_group_get_scale_obj, displayio_group_obj_get_scale);

STATIC mp_obj_t displayio_group_obj_set_scale(mp_obj_t self_in, mp_obj_t scale_obj) {
    displayio_group_t *self = native_group(self_in);

    mp_int_t scale = mp_arg_validate_int_min(mp_obj_get_int(scale_obj), 1, MP_QSTR_scale);

    common_hal_displayio_group_set_scale(self, scale);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_set_scale_obj, displayio_group_obj_set_scale);

MP_PROPERTY_GETSET(displayio_group_scale_obj,
    (mp_obj_t)&displayio_group_get_scale_obj,
    (mp_obj_t)&displayio_group_set_scale_obj);

//|     x: int
//|     """X position of the Group in the parent."""
STATIC mp_obj_t displayio_group_obj_get_x(mp_obj_t self_in) {
    displayio_group_t *self = native_group(self_in);
    return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_group_get_x(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(displayio_group_get_x_obj, displayio_group_obj_get_x);

STATIC mp_obj_t displayio_group_obj_set_x(mp_obj_t self_in, mp_obj_t x_obj) {
    displayio_group_t *self = native_group(self_in);

    mp_int_t x = mp_obj_get_int(x_obj);
    common_hal_displayio_group_set_x(self, x);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_set_x_obj, displayio_group_obj_set_x);

MP_PROPERTY_GETSET(displayio_group_x_obj,
    (mp_obj_t)&displayio_group_get_x_obj,
    (mp_obj_t)&displayio_group_set_x_obj);

//|     y: int
//|     """Y position of the Group in the parent."""
STATIC mp_obj_t displayio_group_obj_get_y(mp_obj_t self_in) {
    displayio_group_t *self = native_group(self_in);
    return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_group_get_y(self));
}
MP_DEFINE_CONST_FUN_OBJ_1(displayio_group_get_y_obj, displayio_group_obj_get_y);

STATIC mp_obj_t displayio_group_obj_set_y(mp_obj_t self_in, mp_obj_t y_obj) {
    displayio_group_t *self = native_group(self_in);

    mp_int_t y = mp_obj_get_int(y_obj);
    common_hal_displayio_group_set_y(self, y);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_set_y_obj, displayio_group_obj_set_y);

MP_PROPERTY_GETSET(displayio_group_y_obj,
    (mp_obj_t)&displayio_group_get_y_obj,
    (mp_obj_t)&displayio_group_set_y_obj);

//|     def append(
//|         self,
//|         layer: Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid],
//|     ) -> None:
//|         """Append a layer to the group. It will be drawn above other layers."""
//|         ...
STATIC mp_obj_t displayio_group_obj_append(mp_obj_t self_in, mp_obj_t layer) {
    displayio_group_t *self = native_group(self_in);
    common_hal_displayio_group_insert(self, common_hal_displayio_group_get_len(self), layer);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_append_obj, displayio_group_obj_append);

//|     def insert(
//|         self,
//|         index: int,
//|         layer: Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid],
//|     ) -> None:
//|         """Insert a layer into the group."""
//|         ...
STATIC mp_obj_t displayio_group_obj_insert(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t layer) {
    displayio_group_t *self = native_group(self_in);
    if ((size_t)MP_OBJ_SMALL_INT_VALUE(index_obj) == common_hal_displayio_group_get_len(self)) {
        return displayio_group_obj_append(self_in, layer);
    }
    size_t index = mp_get_index(&displayio_group_type, common_hal_displayio_group_get_len(self), index_obj, false);
    common_hal_displayio_group_insert(self, index, layer);
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_3(displayio_group_insert_obj, displayio_group_obj_insert);

//|     def index(
//|         self,
//|         layer: Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid],
//|     ) -> int:
//|         """Returns the index of the first copy of layer. Raises ValueError if not found."""
//|         ...
STATIC mp_obj_t displayio_group_obj_index(mp_obj_t self_in, mp_obj_t layer) {
    displayio_group_t *self = native_group(self_in);
    mp_int_t index = common_hal_displayio_group_index(self, layer);
    if (index < 0) {
        mp_raise_ValueError(translate("object not in sequence"));
    }
    return MP_OBJ_NEW_SMALL_INT(index);
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_index_obj, displayio_group_obj_index);

//|     def pop(
//|         self, i: int = -1
//|     ) -> Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid]:
//|         """Remove the ith item and return it."""
//|         ...
STATIC mp_obj_t displayio_group_obj_pop(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    enum { ARG_i };
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_i, MP_ARG_INT, {.u_int = -1} },
    };
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);

    displayio_group_t *self = native_group(pos_args[0]);

    size_t index = mp_get_index(&displayio_group_type,
        common_hal_displayio_group_get_len(self),
        MP_OBJ_NEW_SMALL_INT(args[ARG_i].u_int),
        false);
    return common_hal_displayio_group_pop(self, index);
}
MP_DEFINE_CONST_FUN_OBJ_KW(displayio_group_pop_obj, 1, displayio_group_obj_pop);

//|     def remove(
//|         self,
//|         layer: Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid],
//|     ) -> None:
//|         """Remove the first copy of layer. Raises ValueError if it is not present."""
//|         ...
STATIC mp_obj_t displayio_group_obj_remove(mp_obj_t self_in, mp_obj_t layer) {
    mp_obj_t index = displayio_group_obj_index(self_in, layer);
    displayio_group_t *self = native_group(self_in);

    common_hal_displayio_group_pop(self, MP_OBJ_SMALL_INT_VALUE(index));
    return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_remove_obj, displayio_group_obj_remove);

//|     def __bool__(self) -> bool: ...
//|     def __len__(self) -> int:
//|         """Returns the number of layers in a Group"""
//|         ...
STATIC mp_obj_t group_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
    displayio_group_t *self = native_group(self_in);
    uint16_t len = common_hal_displayio_group_get_len(self);
    switch (op) {
        case MP_UNARY_OP_BOOL:
            return mp_obj_new_bool(len != 0);
        case MP_UNARY_OP_LEN:
            return MP_OBJ_NEW_SMALL_INT(len);
        default:
            return MP_OBJ_NULL;      // op not supported
    }
}

//|     def __getitem__(
//|         self, index: int
//|     ) -> Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid]:
//|         """Returns the value at the given index.
//|
//|         This allows you to::
//|
//|           print(group[0])"""
//|         ...
//|     def __setitem__(
//|         self,
//|         index: int,
//|         value: Union[vectorio.Circle, vectorio.Rectangle, vectorio.Polygon, Group, TileGrid],
//|     ) -> None:
//|         """Sets the value at the given index.
//|
//|         This allows you to::
//|
//|           group[0] = sprite"""
//|         ...
//|     def __delitem__(self, index: int) -> None:
//|         """Deletes the value at the given index.
//|
//|         This allows you to::
//|
//|           del group[0]"""
//|         ...
STATIC mp_obj_t group_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t value) {
    displayio_group_t *self = native_group(self_in);

    if (mp_obj_is_type(index_obj, &mp_type_slice)) {
        mp_raise_NotImplementedError(translate("Slices not supported"));
    } else {
        size_t index = mp_get_index(&displayio_group_type, common_hal_displayio_group_get_len(self), index_obj, false);

        if (value == MP_OBJ_SENTINEL) {
            // load
            return common_hal_displayio_group_get(self, index);
        } else if (value == MP_OBJ_NULL) {
            common_hal_displayio_group_pop(self, index);
        } else {
            common_hal_displayio_group_set(self, index, value);
        }
    }
    return mp_const_none;
}

//|     def sort(self, key: function, reverse: bool) -> None:
//|         """Sort the members of the group."""
//|         ...
//|
STATIC mp_obj_t displayio_group_obj_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    displayio_group_t *self = native_group(pos_args[0]);
    mp_obj_t *args = m_new(mp_obj_t, n_args);
    for (size_t i = 1; i < n_args; ++i) {
        args[i] = pos_args[i];
    }
    args[0] = MP_OBJ_FROM_PTR(self->members);
    return mp_obj_list_sort(n_args, args, kw_args);
}
MP_DEFINE_CONST_FUN_OBJ_KW(displayio_group_sort_obj, 1, displayio_group_obj_sort);

STATIC const mp_rom_map_elem_t displayio_group_locals_dict_table[] = {
    { MP_ROM_QSTR(MP_QSTR_hidden), MP_ROM_PTR(&displayio_group_hidden_obj) },
    { MP_ROM_QSTR(MP_QSTR_scale), MP_ROM_PTR(&displayio_group_scale_obj) },
    { MP_ROM_QSTR(MP_QSTR_x), MP_ROM_PTR(&displayio_group_x_obj) },
    { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&displayio_group_y_obj) },
    { MP_ROM_QSTR(MP_QSTR_append), MP_ROM_PTR(&displayio_group_append_obj) },
    { MP_ROM_QSTR(MP_QSTR_insert), MP_ROM_PTR(&displayio_group_insert_obj) },
    { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&displayio_group_index_obj) },
    { MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&displayio_group_pop_obj) },
    { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&displayio_group_remove_obj) },
    { MP_ROM_QSTR(MP_QSTR_sort), MP_ROM_PTR(&displayio_group_sort_obj) },
};
STATIC MP_DEFINE_CONST_DICT(displayio_group_locals_dict, displayio_group_locals_dict_table);

const mp_obj_type_t displayio_group_type = {
    { &mp_type_type },
    .flags = MP_TYPE_FLAG_EXTENDED,
    .name = MP_QSTR_Group,
    .make_new = displayio_group_make_new,
    .locals_dict = (mp_obj_dict_t *)&displayio_group_locals_dict,
    MP_TYPE_EXTENDED_FIELDS(
        .subscr = group_subscr,
        .unary_op = group_unary_op,
        .getiter = mp_obj_new_generic_iterator,
        ),
};


text:
"""Launches PODs"""
import json
import math
import time
import warnings
from contextlib import closing
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Iterable, Optional, Tuple, cast

import pendulum
import tenacity
from kubernetes import client, watch
from kubernetes.client.models.v1_pod import V1Pod
from kubernetes.client.rest import ApiException
from kubernetes.stream import stream as kubernetes_stream
from pendulum import DateTime
from pendulum.parsing.exceptions import ParserError
from urllib3.exceptions import HTTPError as BaseHTTPError

from airflow.exceptions import AirflowException
from airflow.kubernetes.kube_client import get_kube_client
from airflow.kubernetes.pod_generator import PodDefaults
from airflow.utils.log.logging_mixin import LoggingMixin

if TYPE_CHECKING:
    from kubernetes.client.models.core_v1_event_list import CoreV1EventList

class PodLaunchFailedException(AirflowException):
    """When pod launching fails in KubernetesPodOperator."""

def should_retry_start_pod(exception: BaseException) -> bool:
    """Check if an Exception indicates a transient error and warrants retrying"""
    if isinstance(exception, ApiException):
        return exception.status == 409
    return False

class PodPhase:
    """
    Possible pod phases
    See https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-phase.
    """

    PENDING = 'Pending'
    RUNNING = 'Running'
    FAILED = 'Failed'
    SUCCEEDED = 'Succeeded'

    terminal_states = {FAILED, SUCCEEDED}

def container_is_running(pod: V1Pod, container_name: str) -> bool:
    """
    Examines V1Pod ``pod`` to determine whether ``container_name`` is running.
    If that container is present and running, returns True.  Returns False otherwise.
    """
    container_statuses = pod.status.container_statuses if pod and pod.status else None
    if not container_statuses:
        return False
    container_status = next(iter([x for x in container_statuses if x.name == container_name]), None)
    if not container_status:
        return False
    return container_status.state.running is not None

def get_container_termination_message(pod: V1Pod, container_name: str):
    try:
        container_statuses = pod.status.container_statuses
        container_status = next(iter([x for x in container_statuses if x.name == container_name]), None)
        return container_status.state.terminated.message if container_status else None
    except (AttributeError, TypeError):
        return None

@dataclass
class PodLoggingStatus:
    """Used for returning the status of the pod and last log time when exiting from `fetch_container_logs`"""

    running: bool
    last_log_time: Optional[DateTime]

class PodManager(LoggingMixin):
    """
    Helper class for creating, monitoring, and otherwise interacting with Kubernetes pods
    for use with the KubernetesPodOperator
    """

    def __init__(
        self,
        kube_client: client.CoreV1Api = None,
        in_cluster: bool = True,
        cluster_context: Optional[str] = None,
    ):
        """
        Creates the launcher.

        :param kube_client: kubernetes client
        :param in_cluster: whether we are in cluster
        :param cluster_context: context of the cluster
        """
        super().__init__()
        self._client = kube_client or get_kube_client(in_cluster=in_cluster, cluster_context=cluster_context)
        self._watch = watch.Watch()

    def run_pod_async(self, pod: V1Pod, **kwargs) -> V1Pod:
        """Runs POD asynchronously"""
        sanitized_pod = self._client.api_client.sanitize_for_serialization(pod)
        json_pod = json.dumps(sanitized_pod, indent=2)

        self.log.debug('Pod Creation Request: \n%s', json_pod)
        try:
            resp = self._client.create_namespaced_pod(
                body=sanitized_pod, namespace=pod.metadata.namespace, **kwargs
            )
            self.log.debug('Pod Creation Response: %s', resp)
        except Exception as e:
            self.log.exception(
                'Exception when attempting to create Namespaced Pod: %s', str(json_pod).replace("\n", " ")
            )
            raise e
        return resp

    def delete_pod(self, pod: V1Pod) -> None:
        """Deletes POD"""
        try:
            self._client.delete_namespaced_pod(
                pod.metadata.name, pod.metadata.namespace, body=client.V1DeleteOptions()
            )
        except ApiException as e:
            # If the pod is already deleted
            if e.status != 404:
                raise

    @tenacity.retry(
        stop=tenacity.stop_after_attempt(3),
        wait=tenacity.wait_random_exponential(),
        reraise=True,
        retry=tenacity.retry_if_exception(should_retry_start_pod),
    )
    def create_pod(self, pod: V1Pod) -> V1Pod:
        """Launches the pod asynchronously."""
        return self.run_pod_async(pod)

    def await_pod_start(self, pod: V1Pod, startup_timeout: int = 120) -> None:
        """
        Waits for the pod to reach phase other than ``Pending``

        :param pod:
        :param startup_timeout: Timeout (in seconds) for startup of the pod
            (if pod is pending for too long, fails task)
        :return:
        """
        curr_time = datetime.now()
        while True:
            remote_pod = self.read_pod(pod)
            if remote_pod.status.phase != PodPhase.PENDING:
                break
            self.log.warning("Pod not yet started: %s", pod.metadata.name)
            delta = datetime.now() - curr_time
            if delta.total_seconds() >= startup_timeout:
                msg = (
                    f"Pod took longer than {startup_timeout} seconds to start. "
                    "Check the pod events in kubernetes to determine why."
                )
                raise PodLaunchFailedException(msg)
            time.sleep(1)

    def follow_container_logs(self, pod: V1Pod, container_name: str) -> PodLoggingStatus:
        warnings.warn(
            "Method `follow_container_logs` is deprecated.  Use `fetch_container_logs` instead"
            "with option `follow=True`.",
            DeprecationWarning,
        )
        return self.fetch_container_logs(pod=pod, container_name=container_name, follow=True)

    def fetch_container_logs(
        self, pod: V1Pod, container_name: str, *, follow=False, since_time: Optional[DateTime] = None
    ) -> PodLoggingStatus:
        """
        Follows the logs of container and streams to airflow logging.
        Returns when container exits.
        """

        def consume_logs(*, since_time: Optional[DateTime] = None, follow: bool = True) -> Optional[DateTime]:
            """
            Tries to follow container logs until container completes.
            For a long-running container, sometimes the log read may be interrupted
            Such errors of this kind are suppressed.

            Returns the last timestamp observed in logs.
            """
            timestamp = None
            try:
                logs = self.read_pod_logs(
                    pod=pod,
                    container_name=container_name,
                    timestamps=True,
                    since_seconds=(
                        math.ceil((pendulum.now() - since_time).total_seconds()) if since_time else None
                    ),
                    follow=follow,
                )
                for raw_line in logs:
                    line = raw_line.decode('utf-8', errors="backslashreplace")
                    timestamp, message = self.parse_log_line(line)
                    self.log.info(message)
            except BaseHTTPError as e:
                self.log.warning(
                    "Reading of logs interrupted with error %r; will retry. "
                    "Set log level to DEBUG for traceback.",
                    e,
                )
                self.log.debug(
                    "Traceback for interrupted logs read for pod %r",
                    pod.metadata.name,
                    exc_info=True,
                )
            return timestamp or since_time

        # note: `read_pod_logs` follows the logs, so we shouldn't necessarily *need* to
        # loop as we do here. But in a long-running process we might temporarily lose connectivity.
        # So the looping logic is there to let us resume following the logs.
        last_log_time = since_time
        while True:
            last_log_time = consume_logs(since_time=last_log_time, follow=follow)
            if not self.container_is_running(pod, container_name=container_name):
                return PodLoggingStatus(running=False, last_log_time=last_log_time)
            if not follow:
                return PodLoggingStatus(running=True, last_log_time=last_log_time)
            else:
                self.log.warning(
                    'Pod %s log read interrupted but container %s still running',
                    pod.metadata.name,
                    container_name,
                )
                time.sleep(1)

    def await_container_completion(self, pod: V1Pod, container_name: str) -> None:
        while not self.container_is_running(pod=pod, container_name=container_name):
            time.sleep(1)

    def await_pod_completion(self, pod: V1Pod) -> V1Pod:
        """
        Monitors a pod and returns the final state

        :param pod: pod spec that will be monitored
        :return:  Tuple[State, Optional[str]]
        """
        while True:
            remote_pod = self.read_pod(pod)
            if remote_pod.status.phase in PodPhase.terminal_states:
                break
            self.log.info('Pod %s has phase %s', pod.metadata.name, remote_pod.status.phase)
            time.sleep(2)
        return remote_pod

    def parse_log_line(self, line: str) -> Tuple[Optional[DateTime], str]:
        """
        Parse K8s log line and returns the final state

        :param line: k8s log line
        :return: timestamp and log message
        :rtype: Tuple[str, str]
        """
        split_at = line.find(' ')
        if split_at == -1:
            self.log.error(
                "Error parsing timestamp (no timestamp in message %r). "
                "Will continue execution but won't update timestamp",
                line,
            )
            return None, line
        timestamp = line[:split_at]
        message = line[split_at + 1 :].rstrip()
        try:
            last_log_time = cast(DateTime, pendulum.parse(timestamp))
        except ParserError:
            self.log.error("Error parsing timestamp. Will continue execution but won't update timestamp")
            return None, line
        return last_log_time, message

    def container_is_running(self, pod: V1Pod, container_name: str) -> bool:
        """Reads pod and checks if container is running"""
        remote_pod = self.read_pod(pod)
        return container_is_running(pod=remote_pod, container_name=container_name)

    @tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True)
    def read_pod_logs(
        self,
        pod: V1Pod,
        container_name: str,
        tail_lines: Optional[int] = None,
        timestamps: bool = False,
        since_seconds: Optional[int] = None,
        follow=True,
    ) -> Iterable[bytes]:
        """Reads log from the POD"""
        additional_kwargs = {}
        if since_seconds:
            additional_kwargs['since_seconds'] = since_seconds

        if tail_lines:
            additional_kwargs['tail_lines'] = tail_lines

        try:
            return self._client.read_namespaced_pod_log(
                name=pod.metadata.name,
                namespace=pod.metadata.namespace,
                container=container_name,
                follow=follow,
                timestamps=timestamps,
                _preload_content=False,
                **additional_kwargs,
            )
        except BaseHTTPError:
            self.log.exception('There was an error reading the kubernetes API.')
            raise

    @tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True)
    def read_pod_events(self, pod: V1Pod) -> "CoreV1EventList":
        """Reads events from the POD"""
        try:
            return self._client.list_namespaced_event(
                namespace=pod.metadata.namespace, field_selector=f"involvedObject.name={pod.metadata.name}"
            )
        except BaseHTTPError as e:
            raise AirflowException(f'There was an error reading the kubernetes API: {e}')

    @tenacity.retry(stop=tenacity.stop_after_attempt(3), wait=tenacity.wait_exponential(), reraise=True)
    def read_pod(self, pod: V1Pod) -> V1Pod:
        """Read POD information"""
        try:
            return self._client.read_namespaced_pod(pod.metadata.name, pod.metadata.namespace)
        except BaseHTTPError as e:
            raise AirflowException(f'There was an error reading the kubernetes API: {e}')

    def extract_xcom(self, pod: V1Pod) -> str:
        """Retrieves XCom value and kills xcom sidecar container"""
        with closing(
            kubernetes_stream(
                self._client.connect_get_namespaced_pod_exec,
                pod.metadata.name,
                pod.metadata.namespace,
                container=PodDefaults.SIDECAR_CONTAINER_NAME,
                command=['/bin/sh'],
                stdin=True,
                stdout=True,
                stderr=True,
                tty=False,
                _preload_content=False,
            )
        ) as resp:
            result = self._exec_pod_command(resp, f'cat {PodDefaults.XCOM_MOUNT_PATH}/return.json')
            self._exec_pod_command(resp, 'kill -s SIGINT 1')
        if result is None:
            raise AirflowException(f'Failed to extract xcom from pod: {pod.metadata.name}')
        return result

    def _exec_pod_command(self, resp, command: str) -> Optional[str]:
        res = None
        if resp.is_open():
            self.log.info('Running command... %s\n', command)
            resp.write_stdin(command + '\n')
            while resp.is_open():
                resp.update(timeout=1)
                while resp.peek_stdout():
                    res = res + resp.read_stdout() if res else resp.read_stdout()
                error_res = None
                while resp.peek_stderr():
                    error_res = error_res + resp.read_stderr() if error_res else resp.read_stderr()
                if error_res:
                    self.log.info("stderr from command: %s", error_res)
                    break
                if res:
                    return res
        return res


text:
/** \file
 * Helper functions for domain initialization -- header file.
 */
#ifndef SWIG_DATA_INITIALIZER_WRAPPER_3D_H
#define SWIG_DATA_INITIALIZER_WRAPPER_3D_H

#include "core/globalDefs.h"
#include "atomicBlock/dataProcessorWrapper3D.h"
#include "multiBlock/multiDataProcessorWrapper3D.h"
#include "core/dynamics.h"
#include "plbWrapper/block/dataInitializerFunctional3D.h"

namespace plb {

/// Initialize scalar-field with the same constant value on each cell.
template<typename T>
void setToConstant(MultiNTensorField3D<T>& field, Box3D domain, T value);

/// Initialize scalar-field with the same constant value on each cell.
template<typename T>
void maskedSetToConstant(MultiNTensorField3D<T>& field, MultiNTensorField3D<int>& mask, Box3D domain, T value);

/// Initialize tensor-field with the same constant tensor/vector on each cell.
template<typename T>
void setToConstant( MultiNTensorField3D<T>& field, Box3D domain, T* in_value, int size );

/// Initialize tensor-field with the same constant tensor/vector on each cell.
template<typename T>
void maskedSetToConstant( MultiNTensorField3D<T>& field, MultiNTensorField3D<int>& mask, Box3D domain, T* in_value, int size );

/// Assign the component "index" of its space coordinate to each cell.
template<typename T>
void setToCoordinate(MultiNTensorField3D<T>& field, Box3D domain, plint index);

/// Assign the component "index" of its space coordinate to each cell.
template<typename T>
void maskedSetToCoordinate(MultiNTensorField3D<T>& field, MultiNTensorField3D<int>& mask, Box3D domain, plint index);

/// Assign its space coordinate to each cell.
template<typename T>
void setToCoordinates(MultiNTensorField3D<T>& field,  Box3D domain);

/// Assign its space coordinate to each cell.
template<typename T>
void maskedSetToCoordinates(MultiNTensorField3D<T>& field, MultiNTensorField3D<int>& mask, Box3D domain);

/// Assign scalar-field to one component of a tensor-field.
template<typename T>
void assignComponent(MultiNTensorField3D<T>& tensorField, int whichComponent,
                     MultiNTensorField3D<T>& scalarField, Box3D domain);

/// Assign scalar-field to one component of a tensor-field.
template<typename T>
void maskedAssignComponent(MultiNTensorField3D<T>& tensorField, int whichComponent,
                           MultiNTensorField3D<T>& scalarField, MultiNTensorField3D<int>& mask, Box3D domain);

}  // namespace plb

#endif  // SWIG_DATA_INITIALIZER_WRAPPER_3D_H


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="clickListener"
            type="android.view.View.OnClickListener" />

        <variable
            name="editPlan"
            type="com.unual.inote.plan.edit.EditPlan" />
    </data>

    <android.support.constraint.ConstraintLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="0dp"
            android:layout_height="?actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent">

            <android.support.v7.widget.Toolbar
                android:id="@+id/main_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/colorPrimary">

                <TextView
                    android:id="@+id/toolbar_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="@{editPlan.plan_id==0? @string/activity_plan_edit_insert:@string/activity_plan_edit_update}"
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/main_text_title" />
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.AppBarLayout>

        <LinearLayout
            android:id="@+id/plan_date"
            android:layout_width="0dp"
            android:layout_height="?actionBarSize"
            android:orientation="horizontal"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/appbar">

            <TextView
                android:id="@+id/plan_date_start"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:hint="计划起始时间"
                android:onClick="@{clickListener}"
                android:text="@={editPlan.date_start}" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="~"
                android:textSize="30dp" />

            <TextView
                android:id="@+id/plan_date_end"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center"
                android:hint="计划结束时间"
                android:onClick="@{clickListener}"
                android:text="@={editPlan.date_end}" />
        </LinearLayout>

        <View
            android:id="@+id/plan_date_divider"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:background="@drawable/dashed_line"
            android:layerType="software"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/plan_date" />

        <TextView
            android:id="@+id/plan_quantization_before"
            android:layout_width="wrap_content"
            android:layout_height="?actionBarSize"
            android:layout_marginLeft="10dp"
            android:gravity="center"
            android:text="计划量化:"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/plan_date_divider" />

        <EditText
            android:id="@+id/plan_edit_quantization"
            android:layout_width="0dp"
            android:layout_height="?actionBarSize"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@null"
            android:gravity="center"
            android:hint="0.0"
            android:inputType="numberDecimal"
            android:text="@={editPlan.quantization}"
            app:layout_constraintLeft_toRightOf="@+id/plan_quantization_before"
            app:layout_constraintRight_toLeftOf="@+id/plan_quantization_unit_divider"
            app:layout_constraintTop_toTopOf="@+id/plan_quantization_before" />

        <View
            android:id="@+id/plan_quantization_unit_divider"
            android:layout_width="1dp"
            android:layout_height="0dp"
            android:layerType="software"
            app:layout_constraintBottom_toBottomOf="@+id/plan_quantization_before"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="@+id/plan_quantization_before" />

        <TextView
            android:id="@+id/plan_unit_before"
            android:layout_width="wrap_content"
            android:layout_height="?actionBarSize"
            android:gravity="center"
            android:text="量化单位:"
            app:layout_constraintLeft_toRightOf="@+id/plan_quantization_unit_divider"
            app:layout_constraintTop_toTopOf="@+id/plan_quantization_before" />

        <EditText
            android:id="@+id/plan_edit_unit"
            android:layout_width="0dp"
            android:layout_height="?actionBarSize"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@null"
            android:gravity="center"
            android:hint="单词"
            android:text="@={editPlan.unit}"
            app:layout_constraintLeft_toRightOf="@+id/plan_unit_before"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="@+id/plan_quantization_before" />

        <View
            android:id="@+id/plan_quan_divider"
            android:layout_width="0dp"
            android:layout_height="1dp"
            android:background="@drawable/dashed_line"
            android:layerType="software"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/plan_edit_quantization" />

        <EditText
            android:id="@+id/plan_edit_description"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@null"
            android:gravity="left|top"
            android:hint="计划描述"
            android:padding="10dp"
            android:text="@={editPlan.description}"
            android:textColor="@color/textDaily"
            android:textSize="@dimen/main_text_daily"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/plan_quantization_before" />
    </android.support.constraint.ConstraintLayout>
</layout>


text:
import argparse
import os, sys
import random
import numpy as np
from Bio import SeqIO

random.seed(42)

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description="Converts Fasta files into ascii")
    parser.add_argument("inf", type=str, help="input fasta file")
    parser.add_argument("--noshuffle", action="store_true", help="Don't shuffle the data")
    parser.add_argument("--split", action='store_true', help="Split into train, valid and test")
    parser.add_argument("--train_frac", type=float, default=0.7, help="Training data fraction")
    parser.add_argument("--valid_frac", type=float, default=0.15, help="Validation data fraction")
    parser.add_argument("--test_frac", type=float, default=0.15, help="Testing data fraction")
    parser.add_argument("--binarize", action='store_true', help="binarize output")
    args = parser.parse_args()

    AALIST= [aa for aa in "AVLIPFWMGSTCYNQDEKRH-"]
    aa_dict = dict((aa,idx) for (idx,aa) in enumerate(AALIST))
    aa_dict["X"] = len(AALIST) - 1

    base, _ = os.path.splitext(args.inf)

    aa_lines = []

    for seqr in SeqIO.parse(args.inf,"fasta"):
        line = str(seqr.seq)
        aa_line = [aa_dict[aa]*2/len(AALIST) if args.binarize else aa_dict[aa] for aa in line]
        aa_lines.append(aa_line)

    if not args.noshuffle :
        random.shuffle(aa_lines)

    if args.split:
        train_frac = args.train_frac
        valid_frac = args.valid_frac
        nseq = len(aa_lines)
        train = aa_lines[:int(nseq * train_frac)]
        valid = aa_lines[int(nseq * train_frac):int(nseq * train_frac) + int(nseq * valid_frac)]
        test = aa_lines[int(nseq * train_frac) + int(nseq * valid_frac):]

        for f in ['train','valid','test']:
            seqs = eval(f)
            seqs = np.asarray(seqs, dtype="int").squeeze()
            fout_str = base+ "_" +  f + '.npy'
            np.save(fout_str, seqs)
    else :
        with open(base + '.npy','w') as fout :
            for aa_line in aa_lines:
                print >>fout, ",".join(str(aa) for aa in aa_line)

	X = util.convert_mat_from_msa(args.inputf)
	if args.binarize:
		X = np.array(X >= 10, dtype=int)
	np.save(args.outputf, X)


text:
package org.apache.spark.mllib.regression

import org.apache.spark.SparkContext
import org.apache.spark.annotation.Since
import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.optimization._
import org.apache.spark.mllib.pmml.PMMLExportable
import org.apache.spark.mllib.regression.impl.GLMRegressionModel
import org.apache.spark.mllib.util.{Loader, Saveable}
import org.apache.spark.rdd.RDD

/**
 * Regression model trained using RidgeRegression.
 *
 * @param weights Weights computed for every feature.
 * @param intercept Intercept computed for this model.
 *
 */
@Since("0.8.0")
class RidgeRegressionModel @Since("1.1.0") (
    @Since("1.0.0") override val weights: Vector,
    @Since("0.8.0") override val intercept: Double)
  extends GeneralizedLinearModel(weights, intercept)
  with RegressionModel with Serializable with Saveable with PMMLExportable {

  override protected def predictPoint(
      dataMatrix: Vector,
      weightMatrix: Vector,
      intercept: Double): Double = {
    weightMatrix.toBreeze.dot(dataMatrix.toBreeze) + intercept
  }

  @Since("1.3.0")
  override def save(sc: SparkContext, path: String): Unit = {
    GLMRegressionModel.SaveLoadV1_0.save(sc, path, this.getClass.getName, weights, intercept)
  }

  override protected def formatVersion: String = "1.0"
}

@Since("1.3.0")
object RidgeRegressionModel extends Loader[RidgeRegressionModel] {

  @Since("1.3.0")
  override def load(sc: SparkContext, path: String): RidgeRegressionModel = {
    val (loadedClassName, version, metadata) = Loader.loadMetadata(sc, path)
    // Hard-code class name string in case it changes in the future
    val classNameV1_0 = "org.apache.spark.mllib.regression.RidgeRegressionModel"
    (loadedClassName, version) match {
      case (className, "1.0") if className == classNameV1_0 =>
        val numFeatures = RegressionModel.getNumFeatures(metadata)
        val data = GLMRegressionModel.SaveLoadV1_0.loadData(sc, path, classNameV1_0, numFeatures)
        new RidgeRegressionModel(data.weights, data.intercept)
      case _ => throw new Exception(
        s"RidgeRegressionModel.load did not recognize model with (className, format version):" +
        s"($loadedClassName, $version).  Supported:\n" +
        s"  ($classNameV1_0, 1.0)")
    }
  }
}

/**
 * Train a regression model with L2-regularization using Stochastic Gradient Descent.
 * This solves the l2-regularized least squares regression formulation
 *          f(weights) = 1/2n ||A weights-y||^2^  + regParam/2 ||weights||^2^
 * Here the data matrix has n rows, and the input RDD holds the set of rows of A, each with
 * its corresponding right hand side label y.
 * See also the documentation for the precise formulation.
 */
@Since("0.8.0")
class RidgeRegressionWithSGD private (
    private var stepSize: Double,
    private var numIterations: Int,
    private var regParam: Double,
    private var miniBatchFraction: Double)
  extends GeneralizedLinearAlgorithm[RidgeRegressionModel] with Serializable {

  private val gradient = new LeastSquaresGradient()
  private val updater = new SquaredL2Updater()
  @Since("0.8.0")
  override val optimizer = new GradientDescent(gradient, updater)
    .setStepSize(stepSize)
    .setNumIterations(numIterations)
    .setRegParam(regParam)
    .setMiniBatchFraction(miniBatchFraction)

  /**
   * Construct a RidgeRegression object with default parameters: {stepSize: 1.0, numIterations: 100,
   * regParam: 0.01, miniBatchFraction: 1.0}.
   */
  @Since("0.8.0")
  def this() = this(1.0, 100, 0.01, 1.0)

  override protected def createModel(weights: Vector, intercept: Double) = {
    new RidgeRegressionModel(weights, intercept)
  }
}

/**
 * Top-level methods for calling RidgeRegression.
 *
 */
@Since("0.8.0")
object RidgeRegressionWithSGD {

  /**
   * Train a RidgeRegression model given an RDD of (label, features) pairs. We run a fixed number
   * of iterations of gradient descent using the specified step size. Each iteration uses
   * `miniBatchFraction` fraction of the data to calculate a stochastic gradient. The weights used
   * in gradient descent are initialized using the initial weights provided.
   *
   * @param input RDD of (label, array of features) pairs.
   * @param numIterations Number of iterations of gradient descent to run.
   * @param stepSize Step size to be used for each iteration of gradient descent.
   * @param regParam Regularization parameter.
   * @param miniBatchFraction Fraction of data to be used per iteration.
   * @param initialWeights Initial set of weights to be used. Array should be equal in size to
   *        the number of features in the data.
   *
   */
  @Since("1.0.0")
  def train(
      input: RDD[LabeledPoint],
      numIterations: Int,
      stepSize: Double,
      regParam: Double,
      miniBatchFraction: Double,
      initialWeights: Vector): RidgeRegressionModel = {
    new RidgeRegressionWithSGD(stepSize, numIterations, regParam, miniBatchFraction).run(
      input, initialWeights)
  }

  /**
   * Train a RidgeRegression model given an RDD of (label, features) pairs. We run a fixed number
   * of iterations of gradient descent using the specified step size. Each iteration uses
   * `miniBatchFraction` fraction of the data to calculate a stochastic gradient.
   *
   * @param input RDD of (label, array of features) pairs.
   * @param numIterations Number of iterations of gradient descent to run.
   * @param stepSize Step size to be used for each iteration of gradient descent.
   * @param regParam Regularization parameter.
   * @param miniBatchFraction Fraction of data to be used per iteration.
   *
   */
  @Since("0.8.0")
  def train(
      input: RDD[LabeledPoint],
      numIterations: Int,
      stepSize: Double,
      regParam: Double,
      miniBatchFraction: Double): RidgeRegressionModel = {
    new RidgeRegressionWithSGD(stepSize, numIterations, regParam, miniBatchFraction).run(input)
  }

  /**
   * Train a RidgeRegression model given an RDD of (label, features) pairs. We run a fixed number
   * of iterations of gradient descent using the specified step size. We use the entire data set to
   * compute the true gradient in each iteration.
   *
   * @param input RDD of (label, array of features) pairs.
   * @param stepSize Step size to be used for each iteration of Gradient Descent.
   * @param regParam Regularization parameter.
   * @param numIterations Number of iterations of gradient descent to run.
   * @return a RidgeRegressionModel which has the weights and offset from training.
   *
   */
  @Since("0.8.0")
  def train(
      input: RDD[LabeledPoint],
      numIterations: Int,
      stepSize: Double,
      regParam: Double): RidgeRegressionModel = {
    train(input, numIterations, stepSize, regParam, 1.0)
  }

  /**
   * Train a RidgeRegression model given an RDD of (label, features) pairs. We run a fixed number
   * of iterations of gradient descent using a step size of 1.0. We use the entire data set to
   * compute the true gradient in each iteration.
   *
   * @param input RDD of (label, array of features) pairs.
   * @param numIterations Number of iterations of gradient descent to run.
   * @return a RidgeRegressionModel which has the weights and offset from training.
   *
   */
  @Since("0.8.0")
  def train(
      input: RDD[LabeledPoint],
      numIterations: Int): RidgeRegressionModel = {
    train(input, numIterations, 1.0, 0.01, 1.0)
  }
}


text:
local debug = false
--@debug@
--GAME_LOCALE = "koKR"
--debug = true
--@end-debug@

-- Libraries
local L = LibStub("AceLocale-3.0"):NewLocale("DoomShards", "enUS", true, debug)
if not L then return end

-- Translations
--@localization(locale="enUS", format="lua_additive_table", same-key-is-true=true, handle-subnamespaces="none")@

--@do-not-package@

L["Add. HoG Shards"] = true
L["Additional Doom Indicators"] = true
L["Always show borders"] = true
L["Anchor"] =  true
L["Animations"] = true
L["Background Color"] = true
L["Bar Color"] = true
L["Border Color"] = true
L["Borders"] = true
L["Cancelled Test Mode"] = "|cFF814eaaDoom Shards|r: Cancelled Test Mode!"
L["Change color of all Shards when reaching cap"] = true
L["Color of additional indicators for overcapping with Doom ticks"] = true
L["Color Shard 1"] = true
L["Color Shard 2"] = true
L["Color Shard 3"] = true
L["Color Shard 4"] = true
L["Color Shard 5"] = true
L["Color When Shard Capped"] = true
L["Colors"] = true
L["Dimensions"] = true
L["Direction"] = true
L["Display"] = true
L["Doom Shards locked!"] = "|cFF814eaaDoom Shards|r locked!"
L["Doom Shards reset!"] = "|cFF814eaaDoom Shards|r reset!"
L["Doom Shards unlocked!"] = "|cFF814eaaDoom Shards|r unlocked!"
L["Doom Tick Indicator Bars"] = true
L["Documentation"] = true
L["dragFrameTooltip"] = [=[|cFFcc0060Left mouse button|r to drag.
|cFFcc0060Right mouse button|r to lock.
|cFFcc0060Mouse wheel|r and |cFFcc0060shift + mouse wheel|r for fine adjustment.]=]
L["Enable"] = true
L["Enable bars for incoming Doom ticks"] = true
L["File to play."] = true
L["Fill indicator from right to left"] = "Fill indicator from right to left."
L["Flash on Shard Gain"] = true
L["Font"] = true
L["Font Color"] = true
L["Font Flags"] = true
L["Font Size"] = true
L["Functionality"] = true
L["General"] = true
L["Growth direction"] = true
L["Height"] = true
L["Horizontal"] = true
L["Include Doom tick indicator in Hand of Gul'dan casts. (Demonology only)"] = true
L["Indicate Shard Building"] = true
L["Indicate Shard Spending"] = true
L["Instance Type"] = true
L["Interval"] = true
L["MONOCHROMEOUTLINE"] = true
L["None"] = true
L["Offset"] = true
L["Order in which Shards get filled in"] = true
L["Orientation"] = true
L["OUTLINE"] = true
L["\"Overcap Shards\" Bar Color"] = true
L["\"Overcap Shards\" Color"] = "\"Overcap Shards\" Background Color"
L["Overcapping"] = true
L["Play Warning Sound when about to cap."] = true
L["Position"] = true
L["Regular"] = true
L["Regulate display visibility with macro conditionals"] = [=[
Regulate display visibility with macro conditionals
show - show display
hide - hide display
fade - fade out display
]=]
L["Reset Position"] = true
L["Reset to Defaults"] = true
L["Reversed"] = true
L["Reverse Direction"] = true
L["Scale"] = true
L["Shadow"] = true
L["Shard Colors"] = true
L["Shard Gain Color"] = true
L["Shard Cap Color Change"] = "Cap Color Change"
L["Shard Spend Color"] = true
L["Show prediction for gaining shards through casts"] = true
L["Show prediction for spending shards through casts"] = true
L["Shows the frame and toggles it for repositioning."] = true
L["Soul Shard Bars"] = true
L["Sound"] = true
L["Spacing"] = true
L["Starting Test Mode"] = "|cFF814eaaDoom Shards|r: Starting Test Mode"
L["Test Mode"] = true
L["Text"] = true
L["Texture"] = true
L["Textures"] = true
L["THICKOUTLINE"] = true
L["Threshold when text begins showing first decimal place"] = "Threshold when text begins showing first decimal place."
L["Time between warning sounds"] = true
L["Time Threshold"] = true
L["Toggle Lock"] = true
L["Use Texture for Shards"] = true
L["Version"] = true
L["Vertical"] = true
L["Visibility"] = true
L["Visibility Conditionals"] = true
L["WeakAurasDocumentation"] = [=[WeakAuras event
  DOOM_SHARDS_DISPLAY_UPDATE

DoomShards methods
  DoomShards:GetPrediction(index)
    arguments
      index : index of predicted tick
    return nextTick, resourceGenerationChance
      nextTick : time stamp of next tick
      resourceGenerationChance : chance to generate a Soul Shard on the next tick]=]
L["WeakAuras Example Strings"] = true
L["WeakAuras Import String 1"] = true
L["WeakAuras Import String 2"] = true
L["WeakAuras Interface"] = true
L["WeakAuras String to use when \"WeakAuras\" Display is selected. Copy & paste into WeakAuras to import."] = true
L["Width"] = true
L["X Offset"] = true
L["Y Offset"] = true
L["No Instance"] = true
L["Scenario"] = true
L["Dungeon"] = true
L["Raid"] = true
L["Arena"] = true
L["Battleground"] = true
L["Fade Duration"] = true
L["Positioning"] = true
L["X Position"] = true
L["Y Position"] = true
L["Anchor Point"] = true
L["Anchor Frame"] = true
L["Will change to UIParent when manually dragging frame."] = true

L["Consolidate individual ticks to full expected shards"] = true
L["Consolidate Ticks"] = true

L["Specializations"] = true
L["Affliction"] = true
L["Track Agony"] = true
L["Demonology"] = true
L["Destruction"] = true
L["Track Doom"] = true
L["Track Shadowburn"] = true

L["Copy string for later import"] = true
L["Doom Shards: Profile import completed"] = "|cFF814eaaDoom Shards|r: Profile import completed"
L["Export"] = true
L["Export/Import"] = true
L["Import"] = true
L["Paste import string here"] = true
L["Really import profile?"] = true

L["Color the text will change to if doom will tick before next possible Hand of Gul'dan cast."] = "Color the text will change to if prediction ends before end of the next possible filler cast (Shadow Bolt/Incinerate/2 ticks of Drain Life)."
L["Font Color for Hand of Gul'dan Prediction"] = "Font Color for low remaining time"

L["Failed to import profile: "] = true
L["not a table"] = true

L["Track Unstable Affliction"] = true

L["Show Depleted Shards"] = true
L["Color of Depleted Shards"] = true
--@end-do-not-package@


text:
package com.exp.tracker.data.entities;

public abstract class EncryptionHelper
{

    /**
     * Provide a encrypted version of a string.
     *
     * @param plainTextString
     * @return
     */
    protected String encryptString(String plainTextString) {
        return plainTextString;
    }

    /**
     * Provide a plain-text version of an encrypted string.
     *
     * @param plainTextString
     * @return
     */
    protected String decryptString(String encryptedString) {
        return encryptedString;
    }

    /**
     * Masks all but last four characters of a provided string.
     * @param originalString
     * @return
     */
    protected String maskAllButLastFourChars(String originalString) {
        return null;
    }
}


text:
package org.springmodules.so.sample.simple.annotated;

import org.springmodules.so.core.annotation.State;
import org.springmodules.so.core.annotation.Transition;

/**
 * @author janm
 */
@State(flowId = "main", id = "end", end = true)
public class StateTwo {

    @Transition(id = "1", to = "one")
    public void back() {

    }

    @Transition(id = "2", to = "end")
    public void x() {

    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Claim</title>
<meta name="date" content="2015-04-07">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

group5.trackerexpress

Class Claim

java.lang.Object

group5.trackerexpress.TModel

group5.trackerexpress.Claim

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<Claim>

public class Claim
extends TModel
implements java.lang.Comparable<Claim>

The Class Claim holds the claim's expense items and
 information about the claim like the title, author, etc.

Version:

Part 4

Author:

Peter Crinklaw, Randy Hu, Parash Rahman, Jesse Emery, Sean Baergen, Rishi Barnwal

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

static int
APPROVED

The Constant APPROVED.

static int
IN_PROGRESS

The Constant IN_PROGRESS.

static int
RETURNED

The Constant RETURNED.

static int
SUBMITTED

The Constant SUBMITTED.

Constructor Summary

Constructors

Constructor and Description

Claim(java.lang.String claimName)

Instantiates a new claim.

Method Summary

Methods

Modifier and Type
Method and Description

void
addDestination(android.content.Context context,
              java.lang.String place,
              java.lang.String reason)

Adds the destination with its parameters

void
addView(TView view)

adds view to be updated

int
compareTo(Claim arg0)

compares the claim start date with the instance's start date

java.lang.String
getApproverEmail()

Sets the approvers email.

java.lang.String
getApproverName()

Gets the user name.

java.lang.String
getClaimName()

Gets the name the user set on the claim

java.lang.String
getComments()

Gets the comments from the approver

java.lang.String
getDescription()

Gets the description.

java.util.ArrayList<Destination>
getDestinationList()

Gets the destination list.

java.util.Calendar
getEndDate()

Gets the end date.

ExpenseList
getExpenseList()

Gets the expense list.

java.util.Calendar
getStartDate()

Gets the start date.

int
getStatus()

Gets the status of the claim.

java.lang.String
getSubmitterEmail()

Gets the submitters name
 This function does not need context
 since it will not be updating views.

java.lang.String
getSubmitterName()

Gets the submitters username.

java.util.ArrayList<java.util.UUID>
getTagsIds(android.content.Context context)

Gets the list of TagIds.

java.util.UUID
getUuid()

Gets the uuid.

boolean
hasIncompleteExpense()

Checks if there are any incomplete expenses

boolean
isIncomplete()

Checks if claim is incomplete.

void
markAsSubmitted(android.content.Context context)

Updates claim status and sets comments.

void
setApproverEmail(android.content.Context context,
                java.lang.String approverEmail)

Sets the approvers email.

void
setApproverName(android.content.Context context,
               java.lang.String approverName)

Sets the submitters name.

void
setClaimName(android.content.Context context,
            java.lang.String claimName)

Sets the name the user wants on the claim

void
setComments(java.lang.String comments)

Sets the comments from the approver

void
setDescription(android.content.Context context,
              java.lang.String description)

Sets the description.

void
setDestinationList(android.content.Context context,
                  java.util.ArrayList<Destination> destination)

Sets the destination list

void
setEndDate(android.content.Context context,
          java.util.Calendar d2)

Sets the end date.

void
setExpenseList(android.content.Context context,
              ExpenseList expenseList)

Sets the expense list.

void
setIncomplete(android.content.Context context,
             boolean incomplete)

Sets the incomplete.

void
setStartDate(android.content.Context context,
            java.util.Calendar d1)

Sets the start date.

void
setStatus(android.content.Context context,
         int status)

Sets the status.

void
setStatusNoNotify(android.content.Context context,
                 int status)

Function that sets the status without notifying views.

void
setSubmitterEmail(android.content.Context context,
                 java.lang.String submitterEmail)

Sets the submitters email.

void
setSubmitterName(android.content.Context context,
                java.lang.String submitterName)

Set the submitters username.

void
setTagsIds(java.util.ArrayList<java.util.UUID> tagsIds)

Sets the list of tagIds.

void
setUuid(android.content.Context context,
       java.util.UUID uuid)

Sets the uuid.

java.lang.String
toStringDestinations()

Creates string of all destinations.

java.lang.String
toStringTags(android.content.Context context)

formats and gets a string list of the tags

Methods inherited from class group5.trackerexpress.TModel

addViews, deleteView, notifyViews

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

IN_PROGRESS

public static final int IN_PROGRESS

The Constant IN_PROGRESS.

See Also:

Constant Field Values

SUBMITTED

public static final int SUBMITTED

The Constant SUBMITTED.

See Also:

Constant Field Values

RETURNED

public static final int RETURNED

The Constant RETURNED.

See Also:

Constant Field Values

APPROVED

public static final int APPROVED

The Constant APPROVED.

See Also:

Constant Field Values

Constructor Detail

Claim

public Claim(java.lang.String claimName)

Instantiates a new claim.

Parameters:

claimName - the claim name

Method Detail

isIncomplete

public boolean isIncomplete()

Checks if claim is incomplete.

Returns:

true, if is incomplete

setIncomplete

public void setIncomplete(android.content.Context context,
                 boolean incomplete)

Sets the incomplete.

Parameters:

context - Needed for file IO

incomplete - the incompleteness indicator

hasIncompleteExpense

public boolean hasIncompleteExpense()

Checks if there are any incomplete expenses

Returns:

true if there is an incomplete expense
                        false if all expenses are complete

getComments

public java.lang.String getComments()

Gets the comments from the approver

Returns:

the comments

setComments

public void setComments(java.lang.String comments)

Sets the comments from the approver

Parameters:

the - comments

getUuid

public java.util.UUID getUuid()

Gets the uuid.

Returns:

the uuid

setUuid

public void setUuid(android.content.Context context,
           java.util.UUID uuid)

Sets the uuid.

Parameters:

context - Needed for file IO

uuid - the uuid

getSubmitterName

public java.lang.String getSubmitterName()

Gets the submitters username.
 This function does not need context
 because it will not be updating views.

Returns:

the user name

setSubmitterName

public void setSubmitterName(android.content.Context context,
                    java.lang.String submitterName)

Set the submitters username.
 This function needs context because
 it will be updating views.

Parameters:

context - Needed for file IO

submitterName - the name

getSubmitterEmail

public java.lang.String getSubmitterEmail()

Gets the submitters name
 This function does not need context
 since it will not be updating views.

Returns:

the username

setSubmitterEmail

public void setSubmitterEmail(android.content.Context context,
                     java.lang.String submitterEmail)

Sets the submitters email.
 This function needs context because
 it will be updating views.

Parameters:

context - Needed for file IO

submitterName - the name

getApproverName

public java.lang.String getApproverName()

Gets the user name.

Returns:

the user name

setApproverName

public void setApproverName(android.content.Context context,
                   java.lang.String approverName)

Sets the submitters name.
 This function needs context because
 it will be updating views.

Parameters:

context - Needed for file IO

submitterName - the name

getApproverEmail

public java.lang.String getApproverEmail()

Sets the approvers email.
 This function does not need context
 since it will not be updating views.

Returns:

the user name

setApproverEmail

public void setApproverEmail(android.content.Context context,
                    java.lang.String approverEmail)

Sets the approvers email.
 This function needs context because
 it will be updating views.

Parameters:

context - Needed for file IO

submitterName - the name

getClaimName

public java.lang.String getClaimName()

Gets the name the user set on the claim

Returns:

the claim name

setClaimName

public void setClaimName(android.content.Context context,
                java.lang.String claimName)

Sets the name the user wants on the claim

Parameters:

context - Needed for file IO

claimName - the claim name

getExpenseList

public ExpenseList getExpenseList()

Gets the expense list.

Returns:

the expense list

setExpenseList

public void setExpenseList(android.content.Context context,
                  ExpenseList expenseList)

Sets the expense list.

Parameters:

context - Needed for file IO

expenseList - the expense list

setStartDate

public void setStartDate(android.content.Context context,
                java.util.Calendar d1)

Sets the start date.

Parameters:

context - Needed for file IO

d1 - the date to use as the start date

getStartDate

public java.util.Calendar getStartDate()

Gets the start date.

Returns:

the start date

setEndDate

public void setEndDate(android.content.Context context,
              java.util.Calendar d2)

Sets the end date.

Parameters:

context - Needed for file IO

d2 - the date to use as the end date

getEndDate

public java.util.Calendar getEndDate()

Gets the end date.

Returns:

the end date

addDestination

public void addDestination(android.content.Context context,
                  java.lang.String place,
                  java.lang.String reason)

Adds the destination with its parameters

Parameters:

context - Needed for file IO

place - the location of destination

Reason - the reason for travel to destination

setDestinationList

public void setDestinationList(android.content.Context context,
                      java.util.ArrayList<Destination> destination)

Sets the destination list

Parameters:

context - Needed for file IO

destination - the destination

toStringDestinations

public java.lang.String toStringDestinations()

Creates string of all destinations.

Returns:

formatted string of all the destinations

getDestinationList

public java.util.ArrayList<Destination> getDestinationList()

Gets the destination list.

Returns:

the destination list

setDescription

public void setDescription(android.content.Context context,
                  java.lang.String description)

Sets the description.

Parameters:

context - Needed for file IO

description - the description

getDescription

public java.lang.String getDescription()

Gets the description.

Returns:

the description

setStatus

public void setStatus(android.content.Context context,
             int status)

Sets the status.

Parameters:

context - Needed for file IO

status - the status

setStatusNoNotify

public void setStatusNoNotify(android.content.Context context,
                     int status)

Function that sets the status without notifying views.
 Necessary for calling this method within an update method.

Parameters:

context -

status -

getStatus

public int getStatus()

Gets the status of the claim.

Returns:

the status

markAsSubmitted

public void markAsSubmitted(android.content.Context context)

Updates claim status and sets comments. Does NOT update views.
 Needed because this must be called from within an update method.

Parameters:

context -

comments -

compareTo

public int compareTo(Claim arg0)

compares the claim start date with the instance's start date

Specified by:

compareTo in interface java.lang.Comparable<Claim>

Parameters:

arg0 - The Claim to be compared

Returns:

the result of the comparison as an int

getTagsIds

public java.util.ArrayList<java.util.UUID> getTagsIds(android.content.Context context)

Gets the list of TagIds.

Returns:

the list of tag Ids

toStringTags

public java.lang.String toStringTags(android.content.Context context)

formats and gets a string list of the tags

Returns:

a string of tags in list form

setTagsIds

public void setTagsIds(java.util.ArrayList<java.util.UUID> tagsIds)

Sets the list of tagIds.

Parameters:

tagsIds - the list of tagIds

addView

public void addView(TView view)

adds view to be updated

Overrides:

addView in class TModel

Parameters:

view - TView to be updated

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD


text:
package nl.uva.vlet.glite.lfc.internal;
/*
 * Initial development of the original code was made for the
 * g-Eclipse project founded by European Union
 * project number: FP6-IST-034327  http://www.geclipse.eu/
 *
 * Contributors:
 *    Mateusz Pabis (PSNC) - initial API and implementation
 *    Piter T. de boer - Refactoring to standalone API and bugfixing.
 *    Spiros Koulouzis - Refactoring to standalone API and bugfixing.
 */
// source:

//package org.glite.lfc.internal;
//
//import java.io.DataInputStream;
//import java.io.DataOutputStream;
//import java.io.IOException;
//
//import org.glite.lfc.IOUtil;
//import org.glite.lfc.LFCServer;
//import org.glite.lfc.internal.AbstractCnsRequest;
//import org.glite.lfc.internal.CnsConstants;
//import org.glite.lfc.internal.CnsListReplicaResponse;
//
//
///**
// * GetReplica Request. Modified from ListReplicaRequest.
// * New request as listReplicas is an deprecated method !
// *
// * @author Piter T. de Boer
// */
//
//public class CnsGetReplicasRequest extends AbstractCnsRequest
//{
//  private int uid;
//  private int gid;
//  private long cwd;
//  private String path=null;
//  private String guid = null;
//  private String se = null; // new parameter in getReplicas()!
//  /**
//   * Creates request for list replica command
//   *
//   * @param guid Global unique ID of the file which replica information will be retrieved
// * @param isGuid
//   */
//  public CnsGetReplicasRequest( final String guidOrPath, boolean isGuid )
//  {
//    this.se=null;
//    if (isGuid)
//    {
//        this.guid = guidOrPath;
//        this.path = null;
//    }
//    else
//    {
//        this.guid = null;
//        this.path = guidOrPath;
//    }
//    this.uid = 0;
//    this.gid = 0;
//    this.cwd = 0;
//  }
//
//
//  /**
//   *
Sends prepared request to the output stream and then fetch the response

//   *
//   * @param output output stream to which request will be written
//   * @param input input stream from which response will be read
//   * @return object that encapsulates response
//   * @throws IOException in case of any I/O problem
//   * @see CnsOpenDirResponse
//   */
//  public CnsListReplicaResponse sendTo( final DataOutputStream output, final DataInputStream input )
//    throws IOException
//    {
//
//    CnsListReplicaResponse result = new CnsListReplicaResponse();
//    int bytes = 0;
//
//    LFCServer.staticLogIOMessage(  "Sending replica information request for: " + this.guid );
//    this.sendHeader( output,
//                     CnsConstants.CNS_MAGIC, // MAGIC not MAGIC2 used in listreplica
//                     CnsConstants.CNS_GETREPLICAS,
//                     IOUtil.byteSize(guid,se) + 35 );
//
//    output.writeInt( this.uid );
//    output.writeInt( this.gid );
//    // NOT IN C Code: output.writeLong( this.cwd );
//    output.writeInt( 1 );//1296 ); // size of nbguids -> Nr of GUIDS ?
//
//    IOUtil.writeString(output,se);
//    IOUtil.writeString(output,guid); // could be list of GUIDS !
//
//    // output.writeShort( 1 ); // NO BOL in GetReplica !(begin of list)
//
//    output.flush();
//    result.readFrom( input );
//    return result;
//
//  }
//}


text:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

@class CDYLocationsInput;

@interface CDYLocationManager : CLLocationManager

@property (nonatomic, assign) double playbackSpeed;

- (instancetype)initWithInput:(CDYLocationsInput *)input;

- (void)startUpdatingLocation;
- (void)stopUpdatingLocation;

@end