text:
class Sponsor < ActiveRecord::Base
  has_many :prizes

  def image=(upload)
    @uploaded_file = upload
    @filename = sanitize_filename(@uploaded_file.original_filename)
    write_attribute("image","/uploads/sponsors/#{@filename}")
  end

  def after_create
    # make the uploads/sponsors folder if it doesn't exist
    if !File.exists?(File.dirname(image_file_path))
      Dir.mkdir(File.dirname(image_file_path))
    end
    if @uploaded_file.instance_of?(Tempfile)
      FileUtils.copy(@uploaded_file.local_path, image_file_path)
    else
      File.open(self.image_file_path, "wb") { |f| f.write(@uploaded_file.read) }
    end
  end

  def after_destroy
    if File.exists?(self.image)
      File.delete(self.image)
      Dir.rmdir(File.dirname(self.file))
    end
  end

  def public_image_tag
    "<img src=\"#{self.image}\" border=\"0\" alt=\"#{self.name}\"/>" rescue ""
  end

  def image_file_path
    File.expand_path("#{RAILS_ROOT}/public/uploads/sponsors/#{@filename}")
  end

private
  def sanitize_filename(file_name)
    # get only the filename, not the whole path (from IE)
    just_filename = File.basename(file_name)
    # replace all none alphanumeric, underscore or perioids with underscore
    just_filename.gsub(/[^\w\.\_]/,'_')
  end
end

redpajama_set_name: RedPajamaGithub


text:
class CreatePreregistrants < ActiveRecord::Migration
  def self.up
    create_table :preregistrants do |t|
      t.string :firstname, :null => false
      t.string :lastname, :null => false
      t.date :preregdate, :null => false
      t.string :ranktype, :null => false
      t.integer :rank, :null => false
      t.string :country, :null => false
      t.string :email, :null => false
      t.boolean :anonymous, :null => false

      t.timestamps
    end
  end

  def self.down
    drop_table :preregistrants
  end
end


text:
package co.cask.cdap.internal.app.runtime.distributed;

import co.cask.cdap.api.app.ApplicationSpecification;
import co.cask.cdap.app.program.Program;
import co.cask.cdap.app.runtime.ProgramController;
import co.cask.cdap.app.runtime.ProgramOptions;
import co.cask.cdap.common.app.RunIds;
import co.cask.cdap.common.conf.CConfiguration;
import co.cask.cdap.internal.app.runtime.ProgramOptionConstants;
import co.cask.cdap.proto.ProgramType;
import co.cask.cdap.security.TokenSecureStoreUpdater;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.twill.api.RunId;
import org.apache.twill.api.TwillController;
import org.apache.twill.api.TwillRunner;
import org.apache.twill.filesystem.LocationFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Map;

/**
 * Distributed program runner for webapp.
 */
public final class DistributedWebappProgramRunner extends AbstractDistributedProgramRunner {

  private static final Logger LOG = LoggerFactory.getLogger(DistributedWebappProgramRunner.class);

  @Inject
  public DistributedWebappProgramRunner(TwillRunner twillRunner, LocationFactory locationFactory,
                                        YarnConfiguration hConf, CConfiguration cConf,
                                        TokenSecureStoreUpdater tokenSecureStoreUpdater) {
    super(twillRunner, locationFactory, hConf, cConf, tokenSecureStoreUpdater);
  }

  @Override
  protected ProgramController launch(Program program, ProgramOptions options,
                                     Map<String, LocalizeResource> localizeResources,
                                     File tempDir, ApplicationLauncher launcher) {
    // Extract and verify parameters
    ApplicationSpecification appSpec = program.getApplicationSpecification();
    Preconditions.checkNotNull(appSpec, "Missing application specification.");

    ProgramType processorType = program.getType();
    Preconditions.checkNotNull(processorType, "Missing processor type.");
    Preconditions.checkArgument(processorType == ProgramType.WEBAPP, "Only WEBAPP process type is supported.");

    LOG.info("Launching distributed webapp: " + program.getName());
    TwillController controller = launcher.launch(new WebappTwillApplication(program, localizeResources, eventHandler));
    RunId runId = RunIds.fromString(options.getArguments().getOption(ProgramOptionConstants.RUN_ID));
    return new WebappTwillProgramController(program.getId(), controller, runId).startListen();
  }
}


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * @property int id The model ID
 */
class Artist extends Model
{
    const UNKNOWN_ID = 1;
    const UNKNOWN_NAME = 'Unknown Artist';

    protected $guarded = ['id'];

    protected $hidden = ['created_at', 'updated_at'];

    public function albums()
    {
        return $this->hasMany(Album::class);
    }

    public function getNameAttribute($value)
    {
        return $value ?: self::UNKNOWN_NAME;
    }

    /**
     * Get an Artist object from their name.
     * If such is not found, a new artist will be created.
     *
     * @param string $name
     *
     * @return Artist
     */
    public static function get($name)
    {
        $name = trim($name) ?: self::UNKNOWN_NAME;

        return self::firstOrCreate(compact('name'), compact('name'));
    }

    /**
     * Sometimes the tags extracted from getID3 are HTML entity encoded.
     * This makes sure they are always sane.
     *
     * @param $value
     */
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = html_entity_decode($value);
    }
}


text:
package com.revo.display.views.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;

import com.revo.display.R;

public class RSpeedometer extends View implements ValueChangeListener {
    public static final float DEFAULT_MAX_SPEED = 100; // Assuming this is km/h and you drive a super-car
    final RectF oval = new RectF();

    // Speedometer internal state
    private float mMaxSpeed;
    private float mCurrentSpeed;

    // Scale drawing tools
    private Paint onMarkPaint;
    private Paint offMarkPaint;
    private Paint scalePaint;
    private Paint readingPaint;
    private Path onPath;
    private Path offPath;
    private int ON_COLOR = Color.argb(255, 0xff, 0xA5, 0x00);
    private int OFF_COLOR = Color.argb(255, 0x3e, 0x3e, 0x3e);
    private int SCALE_COLOR = Color.argb(255, 255, 255, 255);
    private float SCALE_SIZE = 60f;

    // Scale configuration
    private float centerX;
    private float centerY;
    private float radius;

    public RSpeedometer(Context context) {
        super(context);
    }

    public RSpeedometer(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                R.styleable.RSpeedometer,
                0, 0);
        try {
            mMaxSpeed = a.getFloat(R.styleable.RSpeedometer_maxSpeed, DEFAULT_MAX_SPEED);
            mCurrentSpeed = a.getFloat(R.styleable.RSpeedometer_currentSpeed, 0);
            ON_COLOR = a.getColor(R.styleable.RSpeedometer_onColor, ON_COLOR);
            OFF_COLOR = a.getColor(R.styleable.RSpeedometer_offColor, OFF_COLOR);
            SCALE_COLOR = a.getColor(R.styleable.RSpeedometer_scaleColor, SCALE_COLOR);
            SCALE_SIZE = a.getDimension(R.styleable.RSpeedometer_scaleTextSize, SCALE_SIZE);
        } finally {
            a.recycle();
        }
        initDrawingTools();
    }

    private void initDrawingTools() {
        onMarkPaint = new Paint();
        onMarkPaint.setStyle(Paint.Style.STROKE);
        onMarkPaint.setColor(ON_COLOR);
        onMarkPaint.setStrokeWidth(35f);
        onMarkPaint.setShadowLayer(5f, 0f, 0f, ON_COLOR);
        onMarkPaint.setAntiAlias(true);

        offMarkPaint = new Paint(onMarkPaint);
        offMarkPaint.setColor(OFF_COLOR);
        offMarkPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        offMarkPaint.setShadowLayer(0f, 0f, 0f, OFF_COLOR);

        scalePaint = new Paint(offMarkPaint);
        scalePaint.setStrokeWidth(2f);
        scalePaint.setTextSize(SCALE_SIZE);
        scalePaint.setShadowLayer(5f, 0f, 0f, Color.RED);
        scalePaint.setColor(SCALE_COLOR);

        readingPaint = new Paint(scalePaint);
        readingPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        offMarkPaint.setShadowLayer(3f, 0f, 0f, Color.WHITE);
        readingPaint.setTextSize(200f);
        readingPaint.setTypeface(Typeface.SANS_SERIF);
        readingPaint.setColor(Color.WHITE);

        onPath = new Path();
        offPath = new Path();
    }

    @Override
    protected void onSizeChanged(int width, int height, int oldw, int oldh) {
        // Setting up the oval area in which the arc will be drawn
        if (width > height) {
            radius = height / 2;
        } else {
            radius = width / 2;
        }
        oval.set(centerX - radius,
                centerY - radius,
                centerX + radius,
                centerY + radius);
    }

    @Override
    public void onDraw(Canvas canvas) {
        drawScaleBackground(canvas);
        drawScale(canvas);

        drawReading(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        centerX = width / 2;
        centerY = 2 * height / 3;
        setMeasuredDimension(width, height);
    }

    /**
     * Draws the segments in their OFF state
     *
     * @param canvas
     */
    private void drawScaleBackground(Canvas canvas) {
        canvas.drawARGB(0, 0, 0, 0);
        offPath.reset();
        for (int i = -180; i < 0; i += 8) {
            offPath.addArc(oval, i, 6f);
        }
        canvas.drawPath(offPath, offMarkPaint);
    }

    private void drawScale(Canvas canvas) {
        onPath.reset();
        for (int i = -180; i < (mCurrentSpeed / mMaxSpeed) * 180 - 180; i += 4) {
            onPath.addArc(oval, i, 3f);
        }
        canvas.drawPath(onPath, onMarkPaint);
    }

    private void drawReading(Canvas canvas) {
        Path path = new Path();
        String message = String.format("%d", (int) this.mCurrentSpeed);
        float[] widths = new float[message.length()];
        readingPaint.getTextWidths(message, widths);
        float advance = 0;
        for (double width : widths)
            advance += width;
        //Log.d(TAG,"advance: "+advance);
        path.moveTo(centerX - advance / 2, centerY);
        path.lineTo(centerX + advance / 2, centerY);
        canvas.drawTextOnPath(message, path, 0f, 0f, readingPaint);
    }

    private void drawLegend(Canvas canvas) {
        canvas.save(Canvas.MATRIX_SAVE_FLAG);
        canvas.rotate(-180, centerX, centerY);
        Path circle = new Path();
        double halfCircumference = radius * Math.PI;
        double increments = 20;
        circle.addCircle(centerX, centerY, radius, Path.Direction.CW);
        for (int i = 0; i <= this.mMaxSpeed; i += increments) {
            canvas.drawTextOnPath(String.format("%d", i),
                    circle,
                    (float) ((i * halfCircumference / this.mMaxSpeed) - (halfCircumference * .06)),
                    -30f,
                    scalePaint);
        }

        canvas.restore();
    }

    @Override
    public void onValueChanged(float newSpeedValue) {
        this.setCurrentSpeed(newSpeedValue);
        this.invalidate();
    }

    public void setCurrentSpeed(float mCurrentSpeed) {
        if (mCurrentSpeed > this.mMaxSpeed)
            this.mCurrentSpeed = mMaxSpeed;
        else if (mCurrentSpeed < 0)
            this.mCurrentSpeed = 0;
        else
            this.mCurrentSpeed = mCurrentSpeed;
    }

    public float getCurrentSpeed() {
        return this.mCurrentSpeed;
    }
}


text:
//------------------------------------------------------------------------------
// <copyright file="DataTableMappingCollection.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------

namespace System.Data.Common {

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;

    [
    Editor("Microsoft.VSDesigner.Data.Design.DataTableMappingCollectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
    ListBindable(false)
    ]
    public sealed class DataTableMappingCollection : MarshalByRefObject, ITableMappingCollection {
        private List<DataTableMapping> items; // delay creation until AddWithoutEvents, Insert, CopyTo, GetEnumerator

        public DataTableMappingCollection() {
        }

        // explicit ICollection implementation
        bool System.Collections.ICollection.IsSynchronized {
            get { return false;}
        }
        object System.Collections.ICollection.SyncRoot {
            get { return this;}
        }

        // explicit IList implementation
        bool System.Collections.IList.IsReadOnly {
            get { return false;}
        }
         bool System.Collections.IList.IsFixedSize {
            get { return false;}
        }
        object System.Collections.IList.this[int index] {
            get {
                return this[index];
            }
            set {
                ValidateType(value);
                this[index] = (DataTableMapping) value;
            }
        }

        object ITableMappingCollection.this[string index] {
            get {
                return this[index];
            }
            set {
                ValidateType(value);
                this[index] = (DataTableMapping) value;
            }
        }
        ITableMapping ITableMappingCollection.Add(string sourceTableName, string dataSetTableName) {
            return Add(sourceTableName, dataSetTableName);
        }
        ITableMapping ITableMappingCollection.GetByDataSetTable(string dataSetTableName) {
            return GetByDataSetTable(dataSetTableName);
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.DataTableMappings_Count),
        ]
        public int Count {
            get {
                return ((null != items) ? items.Count : 0);
            }
        }

        private Type ItemType {
            get { return typeof(DataTableMapping); }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.DataTableMappings_Item),
        ]
        public DataTableMapping this[int index] {
            get {
                RangeCheck(index);
                return items[index];
            }
            set {
                RangeCheck(index);
                Replace(index, value);
            }
        }

        [
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        ResDescriptionAttribute(Res.DataTableMappings_Item),
        ]
        public DataTableMapping this[string sourceTable] {
            get {
                int index = RangeCheck(sourceTable);
                return items[index];
            }
            set {
                int index = RangeCheck(sourceTable);
                Replace(index, value);
            }
        }

        public int Add(object value) {
            ValidateType(value);
            Add((DataTableMapping) value);
            return Count-1;
        }

        private DataTableMapping Add(DataTableMapping value) {
            AddWithoutEvents(value);
            return value;
        }

        public void AddRange(DataTableMapping[] values) { // V1.0.3300
            AddEnumerableRange(values, false);
        }

        public void AddRange(System.Array values) { // V1.2.3300
            AddEnumerableRange(values, false);
        }

        private void AddEnumerableRange(IEnumerable values, bool doClone) {
            if (null == values) {
                throw ADP.ArgumentNull("values");
            }
            foreach(object value in values) {
                ValidateType(value);
            }
            if (doClone) {
                foreach(ICloneable value in values) {
                    AddWithoutEvents(value.Clone() as DataTableMapping);
                }
            }
            else {
                foreach(DataTableMapping value in values) {
                    AddWithoutEvents(value);
                }
            }
        }

        /*/// <include file='doc\DataTableMappingCollection.uex' path='docs/doc[@for="DataTableMappingCollection.AddCloneOfRange"]/*' />
        public void AddCloneOfRange(IEnumerable values) {
            AddEnumerableRange(values, true);
        }*/

        public DataTableMapping Add(string sourceTable, string dataSetTable) {
            return Add(new DataTableMapping(sourceTable, dataSetTable));
        }

        private void AddWithoutEvents(DataTableMapping value) {
            Validate(-1, value);
            value.Parent = this;
            ArrayList().Add(value);
        }

        // implemented as a method, not as a property because the VS7 debugger
        // object browser calls properties to display their value, and we want this delayed
        private List<DataTableMapping> ArrayList() {
            if (null == this.items) {
                this.items = new List<DataTableMapping>();
            }
            return this.items;
        }

        public void Clear() {
            if (0 < Count) {
                ClearWithoutEvents();
            }
        }

        private void ClearWithoutEvents() {
            if (null != items) {
                foreach(DataTableMapping item in items) {
                    item.Parent = null;
                }
                items.Clear();
            }
        }

        public bool Contains(string value) {
            return (-1 != IndexOf(value));
        }

        public bool Contains(object value) {
            return (-1 != IndexOf(value));
        }

        public void CopyTo(Array array, int index) {
            ((ICollection)ArrayList()).CopyTo(array, index);
        }

        public void CopyTo(DataTableMapping[] array, int index) {
            ArrayList().CopyTo(array, index);
        }

        public DataTableMapping GetByDataSetTable(string dataSetTable) {
            int index = IndexOfDataSetTable(dataSetTable);
            if (0 > index) {
                throw ADP.TablesDataSetTable(dataSetTable);
            }
            return items[index];
        }

        public IEnumerator GetEnumerator() {
            return ArrayList().GetEnumerator();
        }

        public int IndexOf(object value) {
            if (null != value) {
                ValidateType(value);
                for (int i = 0; i < Count; ++i) {
                    if (items[i] == value) {
                        return i;
                    }
                }
            }
            return -1;
        }

        public int IndexOf(string sourceTable) {
            if (!ADP.IsEmpty(sourceTable)) {
                for (int i = 0; i < Count; ++i) {
                    string value = items[i].SourceTable;
                    if ((null != value) && (0 == ADP.SrcCompare(sourceTable, value))) {
                        return i;
                    }
                }
            }
            return -1;
        }

        public int IndexOfDataSetTable(string dataSetTable) {
            if (!ADP.IsEmpty(dataSetTable)) {
                for (int i = 0; i < Count; ++i) {
                    string value = items[i].DataSetTable;
                    if ((null != value) && (0 == ADP.DstCompare(dataSetTable, value))) {
                        return i;
                    }
                }
            }
            return -1;
        }

        public void Insert(int index, Object value) {
            ValidateType(value);
            Insert(index, (DataTableMapping) value);
        }

        public void Insert(int index, DataTableMapping value) {
            if (null == value) {
                throw ADP.TablesAddNullAttempt("value");
            }
            Validate(-1, value);
            value.Parent = this;
            ArrayList().Insert(index, value);
        }

        private void RangeCheck(int index) {
            if ((index < 0) || (Count <= index)) {
                throw ADP.TablesIndexInt32(index, this);
            }
        }

        private int RangeCheck(string sourceTable) {
            int index = IndexOf(sourceTable);
            if (index < 0) {
                throw ADP.TablesSourceIndex(sourceTable);
            }
            return index;
        }

        public void RemoveAt(int index) {
            RangeCheck(index);
            RemoveIndex(index);
        }

        public void RemoveAt(string sourceTable) {
            int index = RangeCheck(sourceTable);
            RemoveIndex(index);
        }

        private void RemoveIndex(int index) {
            Debug.Assert((null != items) && (0 <= index) && (index < Count), "RemoveIndex, invalid");
            items[index].Parent = null;
            items.RemoveAt(index);
        }

        public void Remove(object value) {
            ValidateType(value);
            Remove((DataTableMapping) value);
        }

        public void Remove (DataTableMapping value) {
            if (null == value) {
                throw ADP.TablesAddNullAttempt ("value");
            }
            int index = IndexOf (value);

            if (-1 != index) {
                RemoveIndex (index);
            }
            else {
                throw ADP.CollectionRemoveInvalidObject (ItemType, this);
            }
        }

        private void Replace (int index, DataTableMapping newValue) {
            Validate(index, newValue);
            items[index].Parent = null;
            newValue.Parent = this;
            items[index] = newValue;
        }

        private void ValidateType(object value) {
            if (null == value) {
                throw ADP.TablesAddNullAttempt("value");
            }
            else if (!ItemType.IsInstanceOfType(value)) {
                throw ADP.NotADataTableMapping(value);
            }
        }

        private void Validate(int index, DataTableMapping value) {
            if (null == value) {
                throw ADP.TablesAddNullAttempt("value");
            }
            if (null != value.Parent) {
                if (this != value.Parent) {
                    throw ADP.TablesIsNotParent(this);
                }
                else if (index != IndexOf(value)) {
                    throw ADP.TablesIsParent(this);
                }
            }
            String name = value.SourceTable;
            if (ADP.IsEmpty(name)) {
                index = 1;
                do {
                    name = ADP.SourceTable + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
                    index++;
                } while (-1 != IndexOf(name));
                value.SourceTable = name;
            }
            else {
                ValidateSourceTable(index, name);
            }
        }

        internal void ValidateSourceTable(int index, string value) {
            int pindex = IndexOf(value);
            if ((-1 != pindex) && (index != pindex)) { // must be non-null and unique
                throw ADP.TablesUniqueSourceTable(value);
            }
        }

        [ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
        static public DataTableMapping GetTableMappingBySchemaAction(DataTableMappingCollection tableMappings, string sourceTable, string dataSetTable, MissingMappingAction mappingAction) {
            if (null != tableMappings) {
                int index = tableMappings.IndexOf(sourceTable);
                if (-1 != index) {
#if DEBUG
                    if (AdapterSwitches.DataSchema.TraceWarning) {
                        Debug.WriteLine("mapping match on SourceTable \"" + sourceTable + "\"");
                    }
#endif
                    return tableMappings.items[index];
                }
            }
            if (ADP.IsEmpty(sourceTable)) {
                throw ADP.InvalidSourceTable("sourceTable");
            }
            switch (mappingAction) {
                case MissingMappingAction.Passthrough:
#if DEBUG
                    if (AdapterSwitches.DataSchema.TraceInfo) {
                        Debug.WriteLine("mapping passthrough of SourceTable \"" + sourceTable + "\" -> \"" + dataSetTable + "\"");
                    }
#endif
                    return new DataTableMapping(sourceTable, dataSetTable);

                case MissingMappingAction.Ignore:
#if DEBUG
                    if (AdapterSwitches.DataSchema.TraceWarning) {
                        Debug.WriteLine("mapping filter of SourceTable \"" + sourceTable + "\"");
                    }
#endif
                    return null;

                case MissingMappingAction.Error:
#if DEBUG
                    if (AdapterSwitches.DataSchema.TraceError) {
                        Debug.WriteLine("mapping error on SourceTable \"" + sourceTable + "\"");
                    }
#endif
                    throw ADP.MissingTableMapping(sourceTable);

                default:
                    throw ADP.InvalidMissingMappingAction(mappingAction);
            }
        }
    }
}


text:
arr = [1, 3, 9]

arr.any?(&:even?)  # => false
arr.none?(&:even?) # => true

# Filtering elements
data = [1, 0, 3]

data.select(&:zero?) # => [0]

# Sorting
countries = %w(Spain Germany Greece)

countries.sort # => ['Germany', 'Greece, 'Spain']

# The lazy enumerator is useful in playing with infinite sequences
seq = (0..Float::INFINITY).lazy

# Including the Enumerable mixin
class Car
  include Enumerable

  def initialize
    @parts = %w(seats engine software)
  end

  def each
    @parts.each { |part| yield "The coolest part: #{part}" }
  end
end

my_car = Car.new
my_car.first # => 'software'


text:
cask 'powershell' do
  version '6.0.0-rc.2'
  sha256 'dd6c73c55cf34190cba7e9f955d70fa383c616b9a8e3db99a1e3167e5c646558'

  url "https://github.com/PowerShell/PowerShell/releases/download/v#{version}/powershell-#{version}-osx.10.12-x64.pkg"
  appcast 'https://github.com/PowerShell/PowerShell/releases.atom',
          checkpoint: '1045202e4de4f3e5a6f158be6e563ffaf1f8f10ac1952b812d49ade823f67a10'
  name 'PowerShell'
  homepage 'https://github.com/PowerShell/PowerShell'

  depends_on formula: 'openssl'
  depends_on macos: '>= :sierra'

  pkg "powershell-#{version}-osx.10.12-x64.pkg"

  uninstall pkgutil: 'com.microsoft.powershell'

  zap trash: [
               '~/.cache/powershell',
               '~/.config/PowerShell',
               '~/.local/share/powershell',
             ],
      rmdir: [
               '~/.cache',
               '~/.config',
               '~/.local/share',
               '~/.local',
             ]

  caveats <<~EOS
    A OpenSSL-backed libcurl with GSSAPI is required for custom handling
    of certificates and default credentials for web requests.
    This is rarely needed, but you can install it with
      brew install curl --with-openssl --with-gssapi
    See https://github.com/PowerShell/PowerShell/issues/5638
  EOS
end


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
		"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
		"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

	<class name="com.sc2geeks.replay.model.MapEntity" table="rep_map" schema="" catalog="sc2geeks">
		<id name="mapId" column="MapId">
			<generator class="identity"/>
		</id>
		<property name="name" column="Name"/>
		<property name="bnetUrl" column="BnetUrl"/>
		<property name="imageFile" column="ImageFile"/>
		<property name="width" column="Width"/>
		<property name="height" column="Height"/>
		<property name="lastEditDate" column="LastEditDate"></property>
	</class>
</hibernate-mapping>


text:
What's AST?
===========

Python AST is the Abstract Syntax Tree, or the internal
representation of python code, in python.

![AST Image](http://www.codeproject.com/KB/codegen/astdlrtest/astdlrtest2.png)

At a high level, this image shows what an AST represents.

[AST Docs](https://docs.python.org/2/library/ast.html)

Lets use the ast:

```bash
$ python
>>> import ast
>>> module = ast.parse("print('hello')")
>>> exec compile(module, 'string', 'exec')
hello
>>> import astor
>>> astor.dump(module)
"Module(body=[Print(dest=None, values=[Str(s='hello')], nl=True)])"
>>> astor.dump(ast.parse("def hi(): print('hi')"))
"Module(\n    body=[\n        FunctionDef(name='hi',\n            args=arguments(args=[], vararg=None, kwarg=None, defaults=[]),\n            body=[Print(dest=None, values=[Str(s='hi')], nl=True)],\n            decorator_list=[])])"
>>> module.body
[<_ast.Print at 0x21224d0>]
>>> astor.codegen.to_source(module.body[0])
"print 'hello'"
```

Typing strings into _ast.parse_ is no fun, so:

```bash
>>> def x(): print 'hi'
>>> inspected = inspect.getsource(x)
>>> module = ast.parse(inspected)
>>> module.body
[<_ast.FunctionDef at 0x244c110>]
```

Cool. Now lets see how hylang works. If you still have your _myfile.hy_ from before:

```bash
$ hy2py --with-ast myfile.hy
```

Nice. What about doing this from the REPL?

```hy
=> (disassemble `(print "Hello"))
Module(body=[Expr(value=Call(func=Name(id='print'), args=[Str(s=u'Hello')], keywords=[], starargs=None, kwargs=None))])
```

You can also get the python equivalent:

```hy
=> (disassemble `(print "Hello") true)
print('Hello')
```

Exercises:

* Check out what python code is generated for _if_, _even?_, _for_, and any other expressions and macros you want.
* Whats the ast look like for more complex functions?


text:
package com.monsanto.data.goldengate;

import com.goldengate.atg.datasource.*;
import com.goldengate.atg.datasource.adapt.Op;
import com.goldengate.atg.datasource.adapt.Tx;
import com.goldengate.atg.datasource.meta.DsMetaData;
import com.monsanto.data.goldengate.config.Conf;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.util.Arrays;
import java.util.Collections;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Tx.class, DsEvent.class, Op.class, DsTransaction.class, DsOperation.class, EventHandler.class, AbstractHandler.class})
public class EventHandler_UT {
    @Mock
    private MessageEncoder messageEncoder;
    @Mock
    private MessageProducer messageProducer;
    @Mock
    private DsEvent mockEvent;
    @Mock
    private Tx mockTx;
    @Mock
    private Op mockOp;
    @Mock
    private DsMetaData dsMetaData;
    @Mock
    private DsConfiguration dsConfiguration;
    @Mock
    private DsTransaction mockDsTx;
    @Mock
    private DsOperation mockDsOp;
    @Mock
    private Conf configuration;
    @Mock
    private Tx tx;
    @Mock
    private Op op;
    @Mock
    private TxFactory txFactory;

    private byte[] encodedBytes = new byte[1];

    private EventHandler eventHandler;

    @Before
    public void setUp() {
        eventHandler = spy(new EventHandler(configuration, messageEncoder, messageProducer, txFactory));
        eventHandler.setState(DataSourceListener.State.READY);
        when(eventHandler.isOperationMode()).thenReturn(false);

        when(txFactory.createAdapterTx(Matchers.any(DsTransaction.class), Matchers.any(DsMetaData.class),
                Matchers.any(DsConfiguration.class))).thenReturn(tx);

        when(tx.iterator()).thenReturn(Collections.singletonList(op).listIterator());
        when(messageEncoder.encode(tx, op)).thenReturn(encodedBytes);
    }

    @Test
    public void transactionCommit_publishesMessageForTransaction() {
        GGDataSource.Status status = eventHandler.transactionCommit(mockEvent, mockDsTx);

        assertThat(status, equalTo(GGDataSource.Status.OK));
        verify(messageProducer).produce(encodedBytes);
    }

    @Test
    public void transactionCommit_publishesMessagesForAllOpsInaTransaction() {
        Op op2 = mock(Op.class);
        when(tx.iterator()).thenReturn(Arrays.asList(op, op2).listIterator());

        byte[] secondOpByteArray = new byte[2];
        when(messageEncoder.encode(tx, op2)).thenReturn(secondOpByteArray);

        eventHandler.transactionCommit(mockEvent, mockDsTx);

        verify(messageProducer).produce(encodedBytes);
        verify(messageProducer).produce(secondOpByteArray);
    }

    @Test
    public void transactionCommit_returnsAbendWhenEncoderFails() {
        when(messageEncoder.encode(tx, op)).thenThrow(new RuntimeException());

        GGDataSource.Status status = eventHandler.transactionCommit(mockEvent, mockDsTx);

        assertThat(status, equalTo(GGDataSource.Status.ABEND));
    }

    @Test
    public void transactionCommit_returnsAbendWhenProducerFails() {
        doThrow(new RuntimeException()).when(messageProducer).produce(encodedBytes);

        GGDataSource.Status status = eventHandler.transactionCommit(mockEvent, mockDsTx);

        assertThat(status, equalTo(GGDataSource.Status.ABEND));
    }

}


text:
package com.google.walkaround.wave.client;

import com.google.common.base.Preconditions;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Window;
import com.google.walkaround.wave.client.WalkaroundOperationChannel.SavedStateListener;
import com.google.walkaround.wave.client.rpc.Rpc.ConnectionState;
import com.google.walkaround.wave.client.rpc.Rpc.ConnectionStateListener;

import org.waveprotocol.wave.client.common.safehtml.EscapeUtils;
import org.waveprotocol.wave.client.scheduler.Scheduler;
import org.waveprotocol.wave.client.scheduler.SchedulerInstance;
import org.waveprotocol.wave.client.scheduler.TimerService;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.StringSet;

/**
 * Simple saved state indicator.
 *
 * @author danilatos@google.com (Daniel Danilatos)
 */
// TODO(danilatos): Make the UI pretty
public class SavedStateIndicator implements SavedStateListener, ConnectionStateListener {

  private enum SavedState {
    SAVED("Saved"),
    UNSAVED("Unsaved..."),
    TURBULENCE("Unable to save");

    final String message;
    private SavedState(String message) {
      this.message = message;
    }
  }

  private static final int UPDATE_DELAY_MS = 300;

  private final Scheduler.Task updateTask = new Scheduler.Task() {
    @Override public void execute() {
      updateDisplay();
    }
  };

  private final Element element;
  private final TimerService scheduler;

  private final StringSet channels = CollectionUtils.createStringSet();
  private boolean turbulenced = false;
  private ConnectionState connectionState = ConnectionState.CONNECTED;

  private SavedState visibleSavedState = SavedState.SAVED;

  public SavedStateIndicator(Element element) {
    this.element = element;
    this.scheduler = SchedulerInstance.getLowPriorityTimer();
  }

  @Override
  public void saved(String channelId) {
    Preconditions.checkState(channels.contains(channelId), "Already saved channel %s", channelId);
    channels.remove(channelId);
    maybeUpdateDisplay();
  }

  @Override
  public void unsaved(String channelId) {
    channels.add(channelId);
    maybeUpdateDisplay();
  }

  @Override
  public void turbulenced() {
    turbulenced = true;
    maybeUpdateDisplay();
  }

  @Override
  public void connectionStateChanged(ConnectionState newConnectionState) {
    this.connectionState = newConnectionState;
    updateDisplay();
  }

  private void maybeUpdateDisplay() {
    if (needsUpdating()) {
      switch (currentSavedState()) {
        case SAVED:
          scheduler.scheduleDelayed(updateTask, UPDATE_DELAY_MS);
          break;
        case TURBULENCE:
        case UNSAVED:
          updateDisplay();
          break;
        default:
          throw new AssertionError("unknown " + currentSavedState());
      }
    } else {
      scheduler.cancel(updateTask);
    }
  }

  private boolean needsUpdating() {
    return visibleSavedState != currentSavedState();
  }

  private SavedState currentSavedState() {
    return turbulenced ? SavedState.TURBULENCE
        : channels.isEmpty() ? SavedState.SAVED : SavedState.UNSAVED;
  }

  private void updateDisplay() {
    visibleSavedState = currentSavedState();
    element.setInnerHTML(visibleSavedState.message + htmlForConnectionState());
  }

  private String htmlForConnectionState() {
    switch (connectionState) {
      case CONNECTED: return "";
      case LOGGED_OUT: {
        String self = Window.Location.getHref();
        return "
You are logged out. Reload " + " the page to log in again
";
      }
      case OFFLINE: return "
You are not connected
";
      case SOFT_RELOAD:
      case HARD_RELOAD: {
        // TODO(danilatos): Refresh automatically (perhaps not here) if there are no
        // unsaved changes.
        String self = Window.Location.getHref();
        return "
Please reload "
            + " the page to recover
";
      }
      default:
        throw new AssertionError("unknown " + connectionState);
    }
  }
}


text:
'use strict';

describe('Controller: MainCtrl', function () {

    // load the controller's module
    beforeEach(module('nycCampaignFinanceApp'));

    var MainCtrl,
        scope,
        $httpBackend;

    // Initialize the controller and a mock scope
    beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
        $httpBackend = _$httpBackend_;
        $httpBackend.expectGET('/api/awesomeThings')
            .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
        scope = $rootScope.$new();
        MainCtrl = $controller('MainCtrl', {
            $scope: scope
          });
      }));

    it('should attach a list of awesomeThings to the scope', function () {
        expect(scope.awesomeThings).toBeUndefined();
        $httpBackend.flush();
        expect(scope.awesomeThings.length).toBe(4);
      });
  });

describe('Controller: CandidateListCtrl', function() {

    // load the controller's module
    beforeEach(module('nycCampaignFinanceApp'));

    var candidateListCtrl,
        scope,
        $httpBackend;

    // Initialize the controller and a mock scope
    beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
        $httpBackend = _$httpBackend_;
        $httpBackend.expectGET('/api/candidates')
            .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
        scope = $rootScope.$new();
        candidateListCtrl = $controller('CandidateListCtrl', {
            $scope: scope
          });
      }));

    it('should attach a list of candidates to the scope', function () {
        expect(scope.candidates).toBeUndefined();
        $httpBackend.flush();
        expect(scope.candidates.length).toBe(4);
      });

  });


text:
package com.google.security.zynamics.binnavi.Gui.GraphWindows.BottomPanel.RegisterTracker;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.ZyGraph.Implementations.ZyZoomHelpers;
import com.google.security.zynamics.zylib.general.comparators.LexicalComparator;
import com.google.security.zynamics.zylib.gui.tables.CMonospaceRenderer;

/**
 * In this table, the results of a register tracking operation are shown.
 */
public final class CTrackingResultsTable extends JTable {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = -1286932901902302435L;

  /**
   * This column shows quick status information about the instruction and its effect on the register
   * tracking process.
   */
  public static final int STATUS_COLUMN = 0;

  /**
   * This column shows the address of the instruction.
   */
  public static final int ADDRESS_COLUMN = 1;

  /**
   * This column shows the instruction.
   */
  public static final int INSTRUCTION_COLUMN = 2;

  /**
   * This column shows what registers the instruction uses.
   */
  public static final int READS_COLUMN = 3;

  /**
   * This column shows what registers the instruction updates.
   */
  public static final int UPDATES_COLUMN = 4;

  /**
   * This column shows what registers the instruction defines.
   */
  public static final int DEFINES_COLUMN = 5;

  /**
   * This column shows what registers the instruction undefines.
   */
  public static final int UNDEFINES_COLUMN = 6;

  /**
   * This column shows what registers are defined after the instruction is executed.
   */
  public static final int TAINTED_COLUMN = 7;

  /**
   * Results container from where the results can be read.
   */
  private final CTrackingResultContainer m_container;

  /**
   * The table model.
   */
  private final CTrackingResultsTableModel m_model;

  /**
   * The row sorter for this table.
   */
  private final TableRowSorter<TableModel> m_sorter;

  /**
   * Creates a new results tracking table.
   *
   * @param container Results container from where the results can be read.
   */
  public CTrackingResultsTable(final CTrackingResultContainer container) {
    m_container =
        Preconditions.checkNotNull(container, "IE01691: Container argument can not be null");

    m_model = new CTrackingResultsTableModel(container);
    setModel(m_model);

    m_sorter = new TableRowSorter<TableModel>(m_model);
    setRowSorter(m_sorter);
    m_sorter.setComparator(ADDRESS_COLUMN, new LexicalComparator());

    // Make sure that the status cells are colored.
    getColumnModel().getColumn(STATUS_COLUMN).setCellRenderer(new CStatusColumnRenderer());
    getColumnModel().getColumn(INSTRUCTION_COLUMN).setCellRenderer(new CMonospaceRenderer());

    final InternalSelectionListener listener = new InternalSelectionListener();

    getSelectionModel().addListSelectionListener(listener);
    addMouseListener(listener);
  }

  /**
   * Returns the instruction results associated with a given list of table rows.
   *
   * @param result The tracking result that contains all individual instruction results.
   * @param normalizedRows A list of normalized row indices.
   *
   * @return The instruction results associated with the given row indices.
   */
  private static List<CInstructionResult> getInstructionResults(
      final CTrackingResult result, final int[] normalizedRows) {
    final List<CInstructionResult> results = new ArrayList<CInstructionResult>();

    for (final int row : normalizedRows) {
      results.add(result.getResults().get(row));
    }

    return results;
  }

  public void dispose() {
    m_model.dispose();
  }

  /**
   * Listener that updates on selection changes in the table and updates the graph accordingly when
   * a selection change happens.
   */
  private class InternalSelectionListener extends MouseAdapter implements ListSelectionListener {
    private int[] normalizeRows(final int[] sortedRows) {
      final int[] rawRows = new int[sortedRows.length];

      for (int i = 0; i < sortedRows.length; i++) {
        rawRows[i] = convertRowIndexToModel(sortedRows[i]);
      }

      return rawRows;
    }

    @Override
    public void mouseClicked(final MouseEvent event) {
      if ((event.getButton() == MouseEvent.BUTTON1) && (event.getClickCount() == 2)) {
        final int sortedRow = rowAtPoint(event.getPoint());

        if (sortedRow == -1) {
          return;
        }

        final int row = convertRowIndexToModel(sortedRow);

        ZyZoomHelpers.zoomToInstruction(
            m_container.getGraph(), m_container.getResult().getResults().get(row).getInstruction());
      }
    }

    @Override
    public void valueChanged(final ListSelectionEvent event) {
      if (event.getValueIsAdjusting()) {
        return;
      }

      // When the selection of the table changes, clear the previous
      // register tracking highlighting and highlight the instructions
      // which are selected now.

      final int[] normalizedRows = normalizeRows(getSelectedRows());

      final List<CInstructionResult> instructionResults = getInstructionResults(
          m_container.getResult(), normalizedRows);

      CTrackingResultsHighlighter.updateHighlighting(m_container.getGraph(),
          m_container.getResult().getStartInstruction(),
          m_container.getResult().getTrackedRegister(), instructionResults);
    }
  }
}


text:
package org.rlcommunity.btanner.agentLib.learningModules.sarsaLambda;

import org.rlcommunity.btanner.agentLib.learningModules.LearningModuleInterface;
import java.util.Vector;

import org.rlcommunity.btanner.agentLib.functionApproximators.CMAC.FeatureBasedFunctionApproximatorInterface;
import org.rlcommunity.btanner.agentLib.functionApproximators.FunctionApproximatorFactoryInterface;
import org.rlcommunity.btanner.agentLib.functionApproximators.FunctionApproximatorInterface;
import org.rlcommunity.btanner.agentLib.normalizers.AutoRangeTransplantNormalizerFactory;
import org.rlcommunity.btanner.agentLib.normalizers.ObservationScalerFactoryInterface;
import org.rlcommunity.btanner.agentLib.normalizers.ObservationScalerInterface;
import org.rlcommunity.btanner.agentLib.normalizers.TaskSpecObservationNormalizerFactory;
import rlVizLib.general.ParameterHolder;
import org.rlcommunity.rlglue.codec.taskspec.TaskSpec;
import org.rlcommunity.rlglue.codec.types.Observation;

/**
 * Don't use Lambda=1.0 - if you do no traces will ever decay far enought to be
 * culled and memory will fill up.
 *
 * If you use lambda=1.0, we will change it to 1.0d-1.0e-15.
 *
 * @author btanner
 */
public class SarsaLambdaLearningModule implements LearningModuleInterface {

    public static void addToParameterHolder(ParameterHolder p) {
        p.addDoubleParam("sarsalambda-alpha", .25);
        p.addDoubleParam("sarsalambda-lambda", .25);
    }
    private int lastAction;
    private Observation lastObservation;
    private Vector<FeatureBasedFunctionApproximatorInterface> theFAVector = null;
    private ObservationScalerInterface theObsScaler = null;
    private double alpha = .1d;
    private double lambda = .1d;
    private final static double MAX_LAMBDA = 1.0d - 1.0e-12;

    /*trace code variables*/
    private int maxNonZeroTraces;
    //Lets hope that this is a linearized multi-dimensional matrix
    //IE: It is spit into separate areas for each action
    private float traces[];
    /*trace code requirements*/
    private int nonZeroTraces[];
    private int numNonZeroTraces;
    private int nonZeroTracesInverse[];
    private float minimumTrace;
    private int tempFeatures[][];								// sets of features, one set per action

    private int maxActiveFeatures=0;
    private int maxCoderMemorySize=0;
    private final double gamma;

    public SarsaLambdaLearningModule(TaskSpec theTaskObject, ParameterHolder p, FunctionApproximatorFactoryInterface FAF) {
        this(theTaskObject, p, FAF, new TaskSpecObservationNormalizerFactory());
    }

    public SarsaLambdaLearningModule(TaskSpec theTaskObject, ParameterHolder p, FunctionApproximatorFactoryInterface FAF, ObservationScalerFactoryInterface OSF) {
        this.alpha = p.getDoubleParam("sarsalambda-alpha");
        this.lambda = Math.min(p.getDoubleParam("sarsalambda-lambda"), MAX_LAMBDA);
        this.gamma=theTaskObject.getDiscountFactor();

        int actionCount = 1 + theTaskObject.getDiscreteActionRange(0).getMax() - theTaskObject.getDiscreteActionRange(0).getMin();
        assert (actionCount > 0);

        //here we're asserting there IS only one discrete action variable.
        assert (theTaskObject.getNumDiscreteActionDims() == 1); //check the number of discrete actions is only 1
        assert (theTaskObject.getNumContinuousActionDims() == 0); //check that there is no continuous actions

        //One FA per action
        theFAVector = new Vector<FeatureBasedFunctionApproximatorInterface>();

        //Todo: Fix so this isn't an unsafe cast
        for (int i = 0; i < actionCount; i++) {
            theFAVector.add((FeatureBasedFunctionApproximatorInterface) FAF.makeFunctionApproximator(theTaskObject, p));
        }
        //This is a HACK
        if(OSF instanceof AutoRangeTransplantNormalizerFactory){
            AutoRangeTransplantNormalizerFactory transplantOSF=(AutoRangeTransplantNormalizerFactory)OSF;
            theObsScaler=transplantOSF.makeObservationScaler(theTaskObject, p, theFAVector);
        }else{
            theObsScaler = OSF.makeObservationScaler(theTaskObject, p);
        }

        for (FeatureBasedFunctionApproximatorInterface featureBasedFunctionApproximatorInterface : theFAVector) {
            if(featureBasedFunctionApproximatorInterface.getActiveFeatureCount()>maxActiveFeatures){
                maxActiveFeatures=featureBasedFunctionApproximatorInterface.getActiveFeatureCount();
            }
            if(featureBasedFunctionApproximatorInterface.getMemorySize()>maxCoderMemorySize){
                maxCoderMemorySize=featureBasedFunctionApproximatorInterface.getMemorySize();
            }

        }
        this.tempFeatures = new int[actionCount][maxActiveFeatures];

        /* Setup Traces Stuff, Copied from GenericSarsaLambda */
        this.maxNonZeroTraces = 2000000;
        /*Set up the variables which are consistent in all the constructors*/

        nonZeroTraces = new int[maxNonZeroTraces];
        numNonZeroTraces = 0;
        //For now, we'll assume that all the function approximator (for each action) have the same memory size
        traces = new float[actionCount * maxCoderMemorySize];
        nonZeroTracesInverse = new int[traces.length];
        minimumTrace = 0.01f;

        clearTraces();
    }

    private void clearTraces() {
        /*Initialize the traces being used for the value function*/
        for (int i = 0; i < traces.length; i++) {
            traces[i] = 0.0f;                            // clear all traces
            nonZeroTracesInverse[i] = 0;
        }

        for (int i = 0; i < maxNonZeroTraces; i++) {
            nonZeroTraces[i] = 0;
        }
    }

    public void init() {
        clearTraces();
    }

    public void start(Observation theObservation, int theAction) {
        assert (theObsScaler != null);
        theObsScaler.notifyOfValues(theObservation);
        lastObservation = theObservation;
        lastAction = theAction;

        DecayTraces(0.0);  // clear all traces
    }

    private int linearize(int multiArrayIndex, int elementNumber) {
        return multiArrayIndex + elementNumber * maxCoderMemorySize;
    }

//    private void clearTracesOtherThan(int actionToNotClear) {
//        for (int a = 0; a < theFAVector.size(); a++) {
//            if (a != actionToNotClear) {
//                for (int j = 0; j < tempFeatures[a].length; j++) {
//                    ClearTrace(linearize(tempFeatures[a][j], a));
//                }
//            }
//        }
//    }
    private void setTracesForAction(int whichAction) {
        for (int j = 0; j < tempFeatures[whichAction].length; j++) {
            SetTrace(linearize(tempFeatures[whichAction][j], whichAction), 1.0f);
        }
    }

    public void step(Observation rawObservation, double r, int theAction) {
        assert (theObsScaler != null);
        theObsScaler.notifyOfValues(rawObservation);

        DecayTraces(gamma * lambda);  // let traces fall
        loadF(tempFeatures, lastObservation);      // compute features
//        clearTracesOtherThan(lastAction);
        setTracesForAction(lastAction);
//        System.out.printf("The 3 values: %.2f %.2f %.2f\n",query(lastObservation, 0),query(lastObservation, 1),query(lastObservation, 2));

        //Original Sarsa code
        double lastValue = query(lastObservation, lastAction);
        double thisValue = query(rawObservation, theAction);

        double target = r + gamma*thisValue;
        double delta = target - lastValue;

        update(delta);

        lastObservation = rawObservation;
        lastAction = theAction;
    }

    public void end(double r) {
        DecayTraces(gamma * lambda);  // let traces fall
        loadF(tempFeatures, lastObservation);      // compute features
//        clearTracesOtherThan(lastAction);
        setTracesForAction(lastAction);

        double target = r;
        double lastValue = query(lastObservation, lastAction);

        double delta = target - lastValue;
        update(delta);
    }

    public void update(double delta) {
        double deltaToUse = delta * alpha;
        int coderMemorySize = maxCoderMemorySize;

//        System.out.printf("Nonzero traces %d ",numNonZeroTraces);

        for (int i = 0; i < numNonZeroTraces; i++) // update theta (learn)
        {
            int f = nonZeroTraces[i];
            //f is a linear index into traces[] which has the traces for ALL actions
            //so we need to figure out which action it's really for to update the
            //appropriate function approximator

            int whichAction = f / coderMemorySize;
            int whichFeature = f % coderMemorySize;

//            System.out.printf("%d [%d] -> (%.2f,%.2f) ",whichFeature,whichAction,deltaToUse,traces[f]);

            theFAVector.get(whichAction).incrementFeatureByAmount(whichFeature, deltaToUse * traces[f]);
        }

    }

    public double queryNoSideEffect(Observation theObservation, int theAction) {
        assert (theObsScaler != null);
        Observation scaledObservation = theObsScaler.scaleObservation(theObservation);
//        System.out.printf("Query called with %.2f %.2f (original is %.2f %.2f)\n",scaledObservation.doubleArray[0],scaledObservation.doubleArray[1],theObservation.doubleArray[0],theObservation.doubleArray[1]);
        return theFAVector.get(theAction).query(scaledObservation);
    }

    public double query(Observation theObservation, int theAction, long uniqueId) {
        return queryNoSideEffect(theObservation, theAction);
//        assert (theObsScaler != null);
//        theObsScaler.notifyOfValues(theObservation);
//        Observation scaledObservation = theObsScaler.scaleObservation(theObservation);
//        return theFAVector.get(theAction).query(scaledObservation, uniqueId);
    }

    public double query(Observation theObservation, int theAction) {
//        return query(theObservation, theAction, -1);
        return queryNoSideEffect(theObservation, theAction);
    }

    /*
     *
     *
     * Traces Support Code Below
     *
     *
     */
    private void ClearTrace(int f) // Clear any trace for feature f
    {
        if (!(traces[f] == 0.0)) {
            ClearExistentTrace(f, nonZeroTracesInverse[f]);
        }
    }

    private void loadF(int F[][], Observation theObservation) {
        assert (theObsScaler != null);
        Observation scaledObservation = theObsScaler.scaleObservation(theObservation);
//        System.out.printf("LoadF called with %.2f %.2f (original is %.2f %.2f)\n",scaledObservation.doubleArray[0],scaledObservation.doubleArray[1],theObservation.doubleArray[0],theObservation.doubleArray[1]);

        for (int a = 0; a < theFAVector.size(); a++) {
            theFAVector.get(a).setActiveFeatures(scaledObservation, F[a]);
        }
    }

    private void SetTrace(int f, float new_trace_value) // Manually Set the trace for feature f to the given value, which must be positive
    {
        if (traces[f] >= minimumTrace) {
            traces[f] = new_trace_value;
        } // trace already exists
        else {
            while (numNonZeroTraces >= maxNonZeroTraces) {
                IncreaseMinTrace();
            } // ensure room for new trace
            traces[f] = new_trace_value;
            nonZeroTraces[numNonZeroTraces] = f;
            nonZeroTracesInverse[f] = numNonZeroTraces;
            numNonZeroTraces++;
        }
    }

    private void IncreaseMinTrace() // Try to make room for more traces by incrementing minimum_trace by 10%,
    // culling any traces that fall below the new minimum
    {
        minimumTrace += 0.1 * minimumTrace;
        for (int loc = numNonZeroTraces - 1; loc >= 0; loc--) // necessary to loop downwards
        {
            int f = nonZeroTraces[loc];
            if (traces[f] < minimumTrace) {
                ClearExistentTrace(f, loc);
            }
        }
    }

    private void DecayTraces(double decay_rate) // Decays all the (nonzero) traces by decay_rate, removing those below minimum_trace
    {
        for (int loc = numNonZeroTraces - 1; loc >= 0; loc--) // necessary to loop downwards
        {
            int f = nonZeroTraces[loc];
            traces[f] *= decay_rate;
            if (traces[f] < minimumTrace) {
                ClearExistentTrace(f, loc);
            }
        }
    }

    private void ClearExistentTrace(int f, int loc) // Clear the trace for feature f at location loc in the list of nonzero traces
    {
        traces[f] = 0.0f;
        numNonZeroTraces--;
        nonZeroTraces[loc] = nonZeroTraces[numNonZeroTraces];
        nonZeroTracesInverse[nonZeroTraces[loc]] = loc;
    }

    public void update(Observation theObservation, int theAction, double delta) {
        assert (theObsScaler != null);
        Observation scaledObservation = theObsScaler.scaleObservation(theObservation);
        theFAVector.get(theAction).update(scaledObservation, alpha * delta);
    }

    public void cleanup() {
        this.nonZeroTraces = null;
        this.nonZeroTracesInverse = null;
        this.tempFeatures = null;
        this.traces = null;
        lastObservation = null;
        if (theFAVector != null) {
            for (FunctionApproximatorInterface thisFA : theFAVector) {
                thisFA.cleanup();
            }
            theFAVector.clear();
            theFAVector = null;
        }
        theObsScaler = null;
    }
}


text:
var path = require('path');

var engine = require("./server/middleware/engine.js");
var router = require("express-router-middleware");
var middleware = require("./server/middleware/middleware");

// 启动express
var app = engine(__dirname);

//注册中间件
app.use(middleware(app));

//初始化路由
app.use(router(app));

//首页
app.get('/',function(req,res){
    res.redirect('/news/index');
});

//app.use(function (req, res, next) {
//    //console.log(' app normal next');
//    next();
//})

//var router = express.Router();
//
//router.all('*', function *(req, res, next) {
//    //res.body.generatorYieldPromise = yield new Promise(function (resolve) {
//    //    setTimeout(function () {
//    //        console.log(5, Date.now());
//    //        resolve(true);
//    //    }, 500);
//    //});
//    next();
//});
//

//app.use('/test', require('./server/controller/test/test.js'));
//app.use('/news', require('./server/controller/news/index.js'));

//app.use(function(err, req, res, next) {
//    res.status(err.status || 500);
//    res.render('widget/error/error', {
//        message: err.message,
//        error: err.status
//    });
//});

var args = process.argv.join('|');
var port = /\-\-port\|(\d+)(?:\||$)/.test(args) ? ~~RegExp.$1 : 9999;

var server = app.listen(port, function() {
    console.log('Express server listening on port ' + server.address().port);
});

module.exports = app;


text:
The sample source code below will teach you how to add images advanced with spreadsheet sdk in VB.NET. ByteScout Barcode Suite is the set that includes three different SDK products to generate barcodes, read barcodes and read and write spreadsheets: Barcode SDK, Barcode Reader SDK and Spreadsheet SDK. It can add images advanced with spreadsheet sdk in VB.NET.

The SDK samples given below describe how to quickly make your application do add images advanced with spreadsheet sdk in VB.NET with the help of ByteScout Barcode Suite. Just copy and paste the code into your VB.NET application's code and follow the instructions. Check VB.NET sample code samples to see if they respond to your needs and requirements for the project.

If you want to try other source code samples then the free trial version of ByteScout Barcode Suite is available for download from our website. Just try other source code samples for VB.NET.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Barcode%20Suite%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Barcode%20Suite%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### ****AddImagesAdvanced.VS2005.vbproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{9657B957-A895-438C-9D1E-80763CCEB185}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>AddImagesAdvanced</RootNamespace>
    <AssemblyName>AddImagesAdvanced</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG,TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Reference Include="Bytescout.Spreadsheet, Version=1.5.0.29, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
    <Compile Include="Program.vb" />
    <Compile Include="Properties\AssemblyInfo.vb" />
    <Content Include="image1.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="image2.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****AddImagesAdvanced.VS2008.vbproj:**

```
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{9657B957-A895-438C-9D1E-80763CCEB185}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>AddImagesAdvanced</RootNamespace>
    <AssemblyName>AddImagesAdvanced</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG,TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.Targets" />
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Reference Include="Bytescout.Spreadsheet, Version=1.5.0.29, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
    <Compile Include="Program.vb" />
    <Compile Include="Properties\AssemblyInfo.vb" />
    <Content Include="image1.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="image2.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****AddImagesAdvanced.VS2010.vbproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{9657B957-A895-438C-9D1E-80763CCEB185}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>AddImagesAdvanced</RootNamespace>
    <AssemblyName>AddImagesAdvanced</AssemblyName>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG,TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.Targets" />
  <ItemGroup>
    <Import Include="Microsoft.VisualBasic" />
    <Import Include="System" />
    <Reference Include="Bytescout.Spreadsheet, Version=1.5.0.29, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
    <Compile Include="Program.vb" />
    <Compile Include="Properties\AssemblyInfo.vb" />
    <Content Include="image1.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="image2.jpg">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.vb:**

```
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.IO
Imports System.Text
Imports Bytescout.Spreadsheet
Imports Bytescout.Spreadsheet.MSODrawing

Namespace AddImages
	Class Program
		Friend Shared Sub Main(args As String())
			' Create spreadsheet
			Dim doc As New Spreadsheet()
			' Add worksheet
			Dim worksheet As Worksheet = doc.Worksheets.Add()

			' Put an image to "C3" cell
			Dim shape As PictureShape = worksheet.Pictures.Add(2, 2, "image1.jpg")

			' Make the picture "floating". It will be not moved if you move or resize the "C3" cell
			shape.PlacementType = Placement.FreeFloating

			' Make the picture brighter
			shape.Brightness = 0.8F

			' Put second image to "K11" cell
			shape = worksheet.Pictures.Add(10, 10, "image2.jpg")

			' Make the picture bound to the cell. It will be moved alonf with the "K11" cell
			shape.PlacementType = Placement.Move

			' Crop 10% from left and right side of the image
			shape.CropFromLeft = 0.1F
			shape.CropFromRight = 0.1F

			' Delete output file if exists
			If File.Exists("output.xls") Then
				File.Delete("output.xls")
			End If

			' Save document
			doc.SaveAs("output.xls")

			' Close spreadsheet
			doc.Close()

			' Open generated XLS document in default application
			Process.Start("output.xls")

			doc.Dispose()
		End Sub
	End Class
End Namespace

```

<!-- code block end -->


text:
'''
Created on Nov 9, 2016

@author: Admin
'''
from ImageFacade import *

facade = ImageFacadeClass()
facade.zip_image('sunshine.png', 'sunshine.zip')


text:
"""
If "modified" date/time is not defined in article metadata, fall back to the "created" date.
"""

from pelican import signals
from pelican.contents import Content, Article

def add_modified(content):
    if not isinstance(content, Article):
        return

    if not content.settings.get('ALWAYS_MODIFIED', False):
        return

    if hasattr(content, 'date') and not hasattr(content, 'modified'):
        content.modified = content.date
        content.locale_modified = content.locale_date

def register():
    signals.content_object_init.connect(add_modified)


text:
<?php
switch($_SERVER ['SERVER_NAME']) {
    case 'eurotax':
        define('ConfigType', 'dev'); break;
//        define('ConfigType', 'test'); break;
//    case 'eurotax.local':
//    case 'eurotax.testenm.com.local':
    case 'eurotax.testenm.com':
        define('ConfigType', 'prod'); break;
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>7.3. struct — Interpret strings as packed binary data — Pythonista Documentation</title>
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Pythonista Documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Pythonista Documentation" href="../index.html" />
    <link rel="up" title="7. String Services" href="strings.html" />
    <link rel="next" title="7.4. difflib — Helpers for computing deltas" href="difflib.html" />
    <link rel="prev" title="7.2. re — Regular expression operations" href="re.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

          next |

          previous |

Pythonista Documentation »

The Python Standard Library »

7. String Services »

7.3. <tt class="xref py py-mod docutils literal">struct</tt> — Interpret strings as packed binary data¶

This module performs conversions between Python values and C structs represented
as Python strings.  This can be used in handling binary data stored in files or
from network connections, among other sources.  It uses
Format Strings as compact descriptions of the layout of the C
structs and the intended conversion to/from Python values.

Note

By default, the result of packing a given C struct includes pad bytes in
order to maintain proper alignment for the C types involved; similarly,
alignment is taken into account when unpacking.  This behavior is chosen so
that the bytes of a packed struct correspond exactly to the layout in memory
of the corresponding C struct.  To handle platform-independent data formats
or omit implicit pad bytes, use <tt class="docutils literal">standard</tt> size and alignment instead of
<tt class="docutils literal">native</tt> size and alignment: see Byte Order, Size, and Alignment for details.

7.3.1. Functions and Exceptions¶

The module defines the following exception and functions:

exception <tt class="descclassname">struct.</tt><tt class="descname">error</tt>¶

Exception raised on various occasions; argument is a string describing what
is wrong.

<tt class="descclassname">struct.</tt><tt class="descname">pack</tt><big>(</big>fmt, v1, v2, ...<big>)</big>¶

Return a string containing the values <tt class="docutils literal">v1, v2, ...</tt> packed according to the
given format.  The arguments must match the values required by the format
exactly.

<tt class="descclassname">struct.</tt><tt class="descname">pack_into</tt><big>(</big>fmt, buffer, offset, v1, v2, ...<big>)</big>¶

Pack the values <tt class="docutils literal">v1, v2, ...</tt> according to the given format, write the
packed bytes into the writable buffer starting at offset. Note that the
offset is a required argument.

New in version 2.5.

<tt class="descclassname">struct.</tt><tt class="descname">unpack</tt><big>(</big>fmt, string<big>)</big>¶

Unpack the string (presumably packed by <tt class="docutils literal">pack(fmt, ...)</tt>) according to the
given format.  The result is a tuple even if it contains exactly one item.
The string must contain exactly the amount of data required by the format
(<tt class="docutils literal">len(string)</tt> must equal <tt class="docutils literal">calcsize(fmt)</tt>).

<tt class="descclassname">struct.</tt><tt class="descname">unpack_from</tt><big>(</big>fmt, buffer[, offset=0]<big>)</big>¶

Unpack the buffer according to the given format. The result is a tuple even
if it contains exactly one item. The buffer must contain at least the
amount of data required by the format (<tt class="docutils literal">len(buffer[offset:])</tt> must be at
least <tt class="docutils literal">calcsize(fmt)</tt>).

New in version 2.5.

<tt class="descclassname">struct.</tt><tt class="descname">calcsize</tt><big>(</big>fmt<big>)</big>¶

Return the size of the struct (and hence of the string) corresponding to the
given format.

7.3.2. Format Strings¶

Format strings are the mechanism used to specify the expected layout when
packing and unpacking data.  They are built up from Format Characters,
which specify the type of data being packed/unpacked.  In addition, there are
special characters for controlling the Byte Order, Size, and Alignment.

7.3.2.1. Byte Order, Size, and Alignment¶

By default, C types are represented in the machine’s native format and byte
order, and properly aligned by skipping pad bytes if necessary (according to the
rules used by the C compiler).

Alternatively, the first character of the format string can be used to indicate
the byte order, size and alignment of the packed data, according to the
following table:

<colgroup>
<col width="20%" />
<col width="43%" />
<col width="18%" />
<col width="20%" />
</colgroup>

Character
Byte order
Size
Alignment

<tt class="docutils literal">@</tt>
native
native
native

<tt class="docutils literal">=</tt>
native
standard
none

<tt class="docutils literal"><</tt>
little-endian
standard
none

<tt class="docutils literal">></tt>
big-endian
standard
none

<tt class="docutils literal">!</tt>
network (= big-endian)
standard
none

If the first character is not one of these, <tt class="docutils literal">'@'</tt> is assumed.

Native byte order is big-endian or little-endian, depending on the host
system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
switchable endianness (bi-endian). Use <tt class="docutils literal">sys.byteorder</tt> to check the
endianness of your system.

Native size and alignment are determined using the C compiler’s
<tt class="docutils literal">sizeof</tt> expression.  This is always combined with native byte order.

Standard size depends only on the format character;  see the table in
the Format Characters section.

Note the difference between <tt class="docutils literal">'@'</tt> and <tt class="docutils literal">'='</tt>: both use native byte order, but
the size and alignment of the latter is standardized.

The form <tt class="docutils literal">'!'</tt> is available for those poor souls who claim they can’t remember
whether network byte order is big-endian or little-endian.

There is no way to indicate non-native byte order (force byte-swapping); use the
appropriate choice of <tt class="docutils literal">'<'</tt> or <tt class="docutils literal">'>'</tt>.

Notes:

Padding is only automatically added between successive structure members.
No padding is added at the beginning or the end of the encoded struct.

No padding is added when using non-native size and alignment, e.g.
with ‘<’, ‘>’, ‘=’, and ‘!’.

To align the end of a structure to the alignment requirement of a
particular type, end the format with the code for that type with a repeat
count of zero.  See Examples.

7.3.2.2. Format Characters¶

Format characters have the following meaning; the conversion between C and
Python values should be obvious given their types.  The ‘Standard size’ column
refers to the size of the packed value in bytes when using standard size; that
is, when the format string starts with one of <tt class="docutils literal">'<'</tt>, <tt class="docutils literal">'>'</tt>, <tt class="docutils literal">'!'</tt> or
<tt class="docutils literal">'='</tt>.  When using native size, the size of the packed value is
platform-dependent.

<colgroup>
<col width="10%" />
<col width="32%" />
<col width="24%" />
<col width="20%" />
<col width="15%" />
</colgroup>

Format
C Type
Python type
Standard size
Notes

<tt class="docutils literal">x</tt>
pad byte
no value

<tt class="docutils literal">c</tt>
<tt class="xref c c-type docutils literal">char</tt>
string of length 1
1

<tt class="docutils literal">b</tt>
<tt class="xref c c-type docutils literal">signed char</tt>
integer
1
(3)

<tt class="docutils literal">B</tt>
<tt class="xref c c-type docutils literal">unsigned char</tt>
integer
1
(3)

<tt class="docutils literal">?</tt>
<tt class="xref c c-type docutils literal">_Bool</tt>
bool
1
(1)

<tt class="docutils literal">h</tt>
<tt class="xref c c-type docutils literal">short</tt>
integer
2
(3)

<tt class="docutils literal">H</tt>
<tt class="xref c c-type docutils literal">unsigned short</tt>
integer
2
(3)

<tt class="docutils literal">i</tt>
<tt class="xref c c-type docutils literal">int</tt>
integer
4
(3)

<tt class="docutils literal">I</tt>
<tt class="xref c c-type docutils literal">unsigned int</tt>
integer
4
(3)

<tt class="docutils literal">l</tt>
<tt class="xref c c-type docutils literal">long</tt>
integer
4
(3)

<tt class="docutils literal">L</tt>
<tt class="xref c c-type docutils literal">unsigned long</tt>
integer
4
(3)

<tt class="docutils literal">q</tt>
<tt class="xref c c-type docutils literal">long long</tt>
integer
8
(2), (3)

<tt class="docutils literal">Q</tt>
<tt class="xref c c-type docutils literal">unsigned long
long</tt>
integer
8
(2), (3)

<tt class="docutils literal">f</tt>
<tt class="xref c c-type docutils literal">float</tt>
float
4
(4)

<tt class="docutils literal">d</tt>
<tt class="xref c c-type docutils literal">double</tt>
float
8
(4)

<tt class="docutils literal">s</tt>
<tt class="xref c c-type docutils literal">char[]</tt>
string

<tt class="docutils literal">p</tt>
<tt class="xref c c-type docutils literal">char[]</tt>
string

<tt class="docutils literal">P</tt>
<tt class="xref c c-type docutils literal">void *</tt>
integer

(5), (3)

Notes:

The <tt class="docutils literal">'?'</tt> conversion code corresponds to the <tt class="xref c c-type docutils literal">_Bool</tt> type defined by
C99. If this type is not available, it is simulated using a <tt class="xref c c-type docutils literal">char</tt>. In
standard mode, it is always represented by one byte.

New in version 2.6.

The <tt class="docutils literal">'q'</tt> and <tt class="docutils literal">'Q'</tt> conversion codes are available in native mode only if
the platform C compiler supports C <tt class="xref c c-type docutils literal">long long</tt>, or, on Windows,
<tt class="xref c c-type docutils literal">__int64</tt>.  They are always available in standard modes.

New in version 2.2.

When attempting to pack a non-integer using any of the integer conversion
codes, if the non-integer has a <tt class="xref py py-meth docutils literal">__index__()</tt> method then that method is
called to convert the argument to an integer before packing.  If no
<tt class="xref py py-meth docutils literal">__index__()</tt> method exists, or the call to <tt class="xref py py-meth docutils literal">__index__()</tt> raises
<tt class="xref py py-exc docutils literal">TypeError</tt>, then the <tt class="xref py py-meth docutils literal">__int__()</tt> method is tried.  However, the use
of <tt class="xref py py-meth docutils literal">__int__()</tt> is deprecated, and will raise <tt class="xref py py-exc docutils literal">DeprecationWarning</tt>.

Changed in version 2.7: Use of the <tt class="xref py py-meth docutils literal">__index__()</tt> method for non-integers is new in 2.7.

Changed in version 2.7: Prior to version 2.7, not all integer conversion codes would use the
<tt class="xref py py-meth docutils literal">__int__()</tt> method to convert, and <tt class="xref py py-exc docutils literal">DeprecationWarning</tt> was
raised only for float arguments.

For the <tt class="docutils literal">'f'</tt> and <tt class="docutils literal">'d'</tt> conversion codes, the packed representation uses
the IEEE 754 binary32 (for <tt class="docutils literal">'f'</tt>) or binary64 (for <tt class="docutils literal">'d'</tt>) format,
regardless of the floating-point format used by the platform.

The <tt class="docutils literal">'P'</tt> format character is only available for the native byte ordering
(selected as the default or with the <tt class="docutils literal">'@'</tt> byte order character). The byte
order character <tt class="docutils literal">'='</tt> chooses to use little- or big-endian ordering based
on the host system. The struct module does not interpret this as native
ordering, so the <tt class="docutils literal">'P'</tt> format is not available.

A format character may be preceded by an integral repeat count.  For example,
the format string <tt class="docutils literal">'4h'</tt> means exactly the same as <tt class="docutils literal">'hhhh'</tt>.

Whitespace characters between formats are ignored; a count and its format must
not contain whitespace though.

For the <tt class="docutils literal">'s'</tt> format character, the count is interpreted as the size of the
string, not a repeat count like for the other format characters; for example,
<tt class="docutils literal">'10s'</tt> means a single 10-byte string, while <tt class="docutils literal">'10c'</tt> means 10 characters.
If a count is not given, it defaults to 1.  For packing, the string is
truncated or padded with null bytes as appropriate to make it fit. For
unpacking, the resulting string always has exactly the specified number of
bytes.  As a special case, <tt class="docutils literal">'0s'</tt> means a single, empty string (while
<tt class="docutils literal">'0c'</tt> means 0 characters).

The <tt class="docutils literal">'p'</tt> format character encodes a “Pascal string”, meaning a short
variable-length string stored in a fixed number of bytes, given by the count.
The first byte stored is the length of the string, or 255, whichever is smaller.
The bytes of the string follow.  If the string passed in to <tt class="xref py py-func docutils literal">pack()</tt> is too
long (longer than the count minus 1), only the leading <tt class="docutils literal">count-1</tt> bytes of the
string are stored.  If the string is shorter than <tt class="docutils literal">count-1</tt>, it is padded with
null bytes so that exactly count bytes in all are used.  Note that for
<tt class="xref py py-func docutils literal">unpack()</tt>, the <tt class="docutils literal">'p'</tt> format character consumes count bytes, but that the
string returned can never contain more than 255 characters.

For the <tt class="docutils literal">'P'</tt> format character, the return value is a Python integer or long
integer, depending on the size needed to hold a pointer when it has been cast to
an integer type.  A NULL pointer will always be returned as the Python integer
<tt class="docutils literal">0</tt>. When packing pointer-sized values, Python integer or long integer objects
may be used.  For example, the Alpha and Merced processors use 64-bit pointer
values, meaning a Python long integer will be used to hold the pointer; other
platforms use 32-bit pointers and will use a Python integer.

For the <tt class="docutils literal">'?'</tt> format character, the return value is either <tt class="xref py py-const xref docutils literal">True</tt> or
<tt class="xref py py-const xref docutils literal">False</tt>. When packing, the truth value of the argument object is used.
Either 0 or 1 in the native or standard bool representation will be packed, and
any non-zero value will be True when unpacking.

7.3.2.3. Examples¶

Note

All examples assume a native byte order, size, and alignment with a
big-endian machine.

A basic example of packing/unpacking three integers:

>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8

Unpacked fields can be named by assigning them to variables or by wrapping
the result in a named tuple:

>>> record = 'raymond   \x32\x12\x08\x01\x08'
>>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

>>> from collections import namedtuple
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._make(unpack('<10sHHb', record))
Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)

The ordering of format characters may have an impact on size since the padding
needed to satisfy alignment requirements is different:

>>> pack('ci', '*', 0x12131415)
'*\x00\x00\x00\x12\x13\x14\x15'
>>> pack('ic', 0x12131415, '*')
'\x12\x13\x14\x15*'
>>> calcsize('ci')
8
>>> calcsize('ic')
5

The following format <tt class="docutils literal">'llh0l'</tt> specifies two pad bytes at the end, assuming
longs are aligned on 4-byte boundaries:

>>> pack('llh0l', 1, 2, 3)
'\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

This only works when native size and alignment are in effect; standard size and
alignment does not enforce any alignment.

See also

Module <tt class="xref py py-mod docutils literal">array</tt>

Packed binary storage of homogeneous data.

Module <tt class="xref py py-mod docutils literal">xdrlib</tt>

Packing and unpacking of XDR data.

7.3.3. Classes¶

The <tt class="xref py py-mod docutils literal">struct</tt> module also defines the following type:

class <tt class="descclassname">struct.</tt><tt class="descname">Struct</tt><big>(</big>format<big>)</big>¶

Return a new Struct object which writes and reads binary data according to
the format string format.  Creating a Struct object once and calling its
methods is more efficient than calling the <tt class="xref py py-mod docutils literal">struct</tt> functions with the
same format since the format string only needs to be compiled once.

New in version 2.5.

Compiled Struct objects support the following methods and attributes:

<tt class="descname">pack</tt><big>(</big>v1, v2, ...<big>)</big>¶

Identical to the <tt class="xref py py-func docutils literal">pack()</tt> function, using the compiled format.
(<tt class="docutils literal">len(result)</tt> will equal <tt class="xref py py-attr docutils literal">self.size</tt>.)

<tt class="descname">pack_into</tt><big>(</big>buffer, offset, v1, v2, ...<big>)</big>¶

Identical to the <tt class="xref py py-func docutils literal">pack_into()</tt> function, using the compiled format.

<tt class="descname">unpack</tt><big>(</big>string<big>)</big>¶

Identical to the <tt class="xref py py-func docutils literal">unpack()</tt> function, using the compiled format.
(<tt class="docutils literal">len(string)</tt> must equal <tt class="xref py py-attr docutils literal">self.size</tt>).

<tt class="descname">unpack_from</tt><big>(</big>buffer, offset=0<big>)</big>¶

Identical to the <tt class="xref py py-func docutils literal">unpack_from()</tt> function, using the compiled format.
(<tt class="docutils literal">len(buffer[offset:])</tt> must be at least <tt class="xref py py-attr docutils literal">self.size</tt>).

<tt class="descname">format</tt>¶

The format string used to construct this Struct object.

<tt class="descname">size</tt>¶

The calculated size of the struct (and hence of the string) corresponding
to <tt class="xref py py-attr docutils literal">format</tt>.

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
import { FC, memo } from 'react'

import { ICON_CMD } from '@/config'
import { cutRest } from '@/utils/helper'

import DotDivider from '@/widgets/DotDivider'

import {
  Wrapper,
  DatetimeWrapper,
  Date,
  Week,
  IntroWrapper,
  Title,
  TitleText,
  Tag,
  BodyWrapper,
  Icon,
  FinishedHole,
} from './styles/activity_card'

type TProps = {
  item: {
    id?: number
    date: string
    week: string
    title: string
    company: string
    finished?: boolean
    type?: string
  }
}

const ActivityCard: FC<TProps> = ({ item }) => {
  return (
    <Wrapper finished={item.finished}>
      <DatetimeWrapper>
        <Date>{item.date}</Date>
        <Week>{item.week}</Week>
      </DatetimeWrapper>
      <IntroWrapper>
        <Title>
          <Tag>{item.type || '前端'}</Tag>
          <TitleText finished={item.finished}>
            {cutRest(item.title, 40)}
          </TitleText>
        </Title>
        <BodyWrapper>
          {item.company} <DotDivider radius={3} />
          <Icon src={`${ICON_CMD}/navi/chair.svg`} /> 200
          <DotDivider radius={3} />
          <Icon src={`${ICON_CMD}/navi/money-yuan.svg`} /> 200-300
          <DotDivider radius={3} />
          <Icon src={`${ICON_CMD}/navi/location.svg`} />
          深圳(南山区)
        </BodyWrapper>
      </IntroWrapper>
      {item.finished && <FinishedHole />}
    </Wrapper>
  )
}

export default memo(ActivityCard)


text:
package com.freshplanet.googleplaygames.functions;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.adobe.fre.FREWrongThreadException;
import com.freshplanet.googleplaygames.Extension;
import com.google.android.gms.games.Games;
import com.google.android.gms.games.Player;

public class AirGooglePlayGamesGetActivePlayerId implements FREFunction {

	@Override
	public FREObject call(FREContext arg0, FREObject[] arg1) {

		Extension.context.createHelperIfNeeded(arg0.getActivity());
		Player player = Games.Players.getCurrentPlayer(Extension.context.getApiClient());

		FREObject playerID = null;
		if (player != null)
		{
			try {
				playerID = FREObject.newObject(player.getPlayerId());
			} catch (FREWrongThreadException e) {
				e.printStackTrace();
			}
		}

		return playerID;
	}

}


text:
package org.gradoop.flink.model.impl.operators.aggregation.functions.max;

import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.common.model.impl.properties.PropertyValueUtils;
import org.gradoop.flink.model.api.functions.AggregateFunction;

/**
 * Interface of aggregate functions that determine a maximal value.
 */
public interface Max extends AggregateFunction {

  @Override
  default PropertyValue aggregate(PropertyValue aggregate, PropertyValue increment) {
    return PropertyValueUtils.Numeric.max(aggregate, increment);
  }
}