text:
using Anywhere.ArcGIS.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;

namespace Anywhere.ArcGIS.Operation
{
    /// <summary>
    /// This operation adds, updates and deletes features to the associated feature layer or table in a single call (POST only).
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [DataContract]
    public class ApplyEdits<T> : ArcGISServerOperation
        where T : IGeometry
    {
        public ApplyEdits(string relativeUrl, Action beforeRequest = null, Action<string> afterRequest = null)
            : this(relativeUrl.AsEndpoint(), beforeRequest, afterRequest)
        { }

        public ApplyEdits(ArcGISServerEndpoint endpoint, Action beforeRequest = null, Action<string> afterRequest = null)
            : base(endpoint.RelativeUrl.Trim('/') + "/" + Operations.ApplyEdits, beforeRequest, afterRequest)
        {
            Adds = new List<Feature<T>>();
            Updates = new List<Feature<T>>();
            Deletes = new List<long>();
            DeleteGlobalIds = new List<Guid>();
            RollbackOnFailure = true;
        }

        /// <summary>
        /// The array of features to be added.
        /// </summary>
        [DataMember(Name = "adds")]
        public List<Feature<T>> Adds { get; set; }

        /// <summary>
        /// The array of features to be updated.
        /// </summary>
        [DataMember(Name = "updates")]
        public List<Feature<T>> Updates { get; set; }

        /// <summary>
        ///  The object IDs of this layer / table to be deleted.
        /// </summary>
        [IgnoreDataMember]
        public List<long> Deletes { get; set; }

        /// <summary>
        ///  The Global IDs of this layer / table to be deleted. Use if useGlobalIds is true
        /// </summary>
        [IgnoreDataMember]
        public List<Guid> DeleteGlobalIds { get; set; }

        [DataMember(Name = "deletes")]
        public string DeleteIds
        {
            get
            {
                /* Return in form array of quoted, braced GUIDS - examples:
                []
                ['{509caea1-7a3f-444d-a0ef-81c942474624}']
                ['{509caea1-7a3f-444d-a0ef-81c942474624}','{701a68ab-86df-4244-a9cb-dda10028f528}']
                */
                if (UseGlobalIds)
                {
                    var deleteIds = new StringBuilder("[");
                    if (DeleteGlobalIds != null && DeleteGlobalIds.Any())
                    {
                        foreach (var deleteGlobalId in DeleteGlobalIds)
                        {
                            deleteIds.AppendFormat("'{0:B}',", deleteGlobalId);
                        }
                        deleteIds.Remove(deleteIds.Length - 1, 1);
                    }
                    deleteIds.Append("]");
                    return deleteIds.ToString();
                }
                else
                {
                    return Deletes == null ? string.Empty : string.Join(",", Deletes);
                }
            }
        }

        /// <summary>
        /// Geodatabase version to apply the edits. This parameter applies only if the isDataVersioned property of the layer is true.
        /// If the gdbVersion parameter is not specified, edits are made to the published map's version.
        /// This option was added at 10.1.
        /// </summary>
        [DataMember(Name = "gdbVersion")]
        public string GeodatabaseVersion { get; set; }

        /// <summary>
        /// Optional parameter specifying whether the response will report the time features were deleted.
        /// If returnEditMoment = true, the server will report the time in the response's editMoment key.
        /// The default value is false.
        /// This option was added at 10.5 and works with ArcGIS Server services only.
        /// </summary>
        [DataMember(Name = "returnEditMoment")]
        public bool ReturnEditMoment { get; set; }

        /// <summary>
        /// Optional parameter to specify if the edits should be applied only if all submitted edits succeed.
        /// If false, the server will apply the edits that succeed even if some of the submitted edits fail.
        /// If true, the server will apply the edits only if all edits succeed. The default value is true.
        /// Not all data supports setting this parameter.
        /// Query the supportsRollbackonFailureParameter property of the layer to determine whether or not a layer supports setting this parameter.
        /// If supportsRollbackOnFailureParameter = false for a layer, then when editing this layer, rollbackOnFailure will always be true, regardless of how the parameter is set.
        /// However, if supportsRollbackonFailureParameter = true, this means the rollbackOnFailure parameter value will be honored on edit operations.
        /// This option was added at 10.1.
        /// </summary>
        [DataMember(Name = "rollbackOnFailure")]
        public bool RollbackOnFailure { get; set; }

        /// <summary>
        /// When set to true, the features and attachments in the adds, updates, deletes, and attachments parameters are identified by their globalIds.
        /// When true, the service adds the new features and attachments while preserving the globalIds submitted in the payload.
        /// If the globalId of a feature (or an attachment) collides with a pre-existing feature (or an attachment), that feature and/or attachment add fails.
        /// Other adds, updates, or deletes are attempted if rollbackOnFailure is false.
        /// If rollbackOnFailure is true, the whole operation fails and rolls back on any failure including a globalId collision.
        /// When useGlobalIds is true, updates and deletes are identified by each feature or attachment globalId rather than their objectId or attachmentId.
        /// This option was added at 10.4.
        /// </summary>
        [DataMember(Name = "useGlobalIds")]
        public bool UseGlobalIds { get; set; }
    }

    /// <summary>
    ///  Results of the apply edits. The results are grouped by type of edit.
    /// </summary>
    [DataContract]
    public class ApplyEditsResponse : PortalResponse
    {
        [DataMember(Name = "addResults")]
        public List<ApplyEditResponse> Adds { get; set; }

        [DataMember(Name = "updateResults")]
        public List<ApplyEditResponse> Updates { get; set; }

        [DataMember(Name = "deleteResults")]
        public List<ApplyEditResponse> Deletes { get; set; }

        [IgnoreDataMember]
        public int ExpectedAdds { get; private set; }

        [IgnoreDataMember]
        public int ActualAdds { get { return Adds == null ? 0 : Adds.Count; } }

        [IgnoreDataMember]
        public int ActualAddsThatSucceeded { get { return AddsSuccessful.Count(); } }

        [IgnoreDataMember]
        public int ExpectedUpdates { get; private set; }

        [IgnoreDataMember]
        public int ActualUpdates { get { return Updates == null ? 0 : Updates.Count; } }

        [IgnoreDataMember]
        public int ActualUpdatesThatSucceeded { get { return UpdatesSuccessful.Count(); } }

        [IgnoreDataMember]
        public int ExpectedDeletes { get; private set; }

        [IgnoreDataMember]
        public int ActualDeletes { get { return Deletes == null ? 0 : Deletes.Count; } }

        [IgnoreDataMember]
        public int ActualDeletesThatSucceeded { get { return DeletesSuccessful.Count(); } }

        [IgnoreDataMember]
        public IEnumerable<ApplyEditResponse> AddsSuccessful { get { return CheckResults(Adds, true); } }

        [IgnoreDataMember]
        public IEnumerable<ApplyEditResponse> AddsFailed { get { return CheckResults(Adds, false); } }

        [IgnoreDataMember]
        public IEnumerable<ApplyEditResponse> UpdatesSuccessful { get { return CheckResults(Updates, true); } }

        [IgnoreDataMember]
        public IEnumerable<ApplyEditResponse> UpdatesFailed { get { return CheckResults(Updates, false); } }

        [IgnoreDataMember]
        public IEnumerable<ApplyEditResponse> DeletesSuccessful { get { return CheckResults(Deletes, true); } }

        [IgnoreDataMember]
        public IEnumerable<ApplyEditResponse> DeletesFailed { get { return CheckResults(Deletes, false); } }

        IEnumerable<ApplyEditResponse> CheckResults(List<ApplyEditResponse> results, bool success)
        {
            if (results == null || !results.Any()) return Enumerable.Empty<ApplyEditResponse>();

            return results.Where(r => r.Success == success);
        }

        public void SetExpected<T>(ApplyEdits<T> operation)
            where T : IGeometry
        {
            if (operation == null) return;

            ExpectedAdds = operation.Adds == null ? 0 : operation.Adds.Count;
            ExpectedUpdates = operation.Updates == null ? 0 : operation.Updates.Count;
            ExpectedDeletes = operation.Deletes == null ? 0 : operation.Deletes.Count;
        }
    }

    /// <summary>
    /// Identifies a single feature and indicates if the edit was successful or not.
    /// </summary>
    [DataContract]
    public class ApplyEditResponse : PortalResponse
    {
        [DataMember(Name = "objectId")]
        public long ObjectId { get; set; }

        [DataMember(Name = "globalId")]
        public string GlobalId { get; set; }

        [DataMember(Name = "success")]
        public bool Success { get; set; }

        [DataMember(Name = "editMoment")]
        public string EditMoment { get; set; }
    }
}


text:
'use strict';

/**
 * Test Prompt public APIs
 */

require('mocha');
var expect = require('chai').expect;
var _ = require('lodash');

var fixtures = require('../helpers/fixtures');
var ReadlineStub = require('../helpers/readline');
var inquirer = require('../../')();

// Define prompts and their public API
var prompts = [{
  name: 'input',
  apis: [
    'filter',
    'validate',
    'default',
    'message',
    'requiredValues'
  ]
}, {
  name: 'confirm',
  apis: [
    'message',
    'requiredValues'
  ]
}, {
  name: 'rawlist',
  apis: [
    'filter',
    'message',
    'choices',
    'requiredValues'
  ]
}, {
  name: 'list',
  apis: [
    'filter',
    'message',
    'choices',
    'requiredValues'
  ]
}, {
  name: 'expand',
  apis: [
    'requiredValues',
    'filter',
    'message'
  ]
}, {
  name: 'checkbox',
  apis: [
    'requiredValues',
    'message',
    'choices',
    'filter',
    'validate'
  ]
}, {
  name: 'password',
  apis: [
    'requiredValues',
    'message',
    'filter',
    'validate',
    'default'
  ]
}];

// Define tests
var tests = {

  'filter': function() {
    describe('filter API', function() {
      it('should filter the user input', function(done) {
        this.fixture.filter = function() {
          return 'pass';
        };

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          expect(answer).to.equal('pass');
          done();
        });

        this.rl.emit('line', '');
      });

      it('should allow filter function to be asynchronous', function(done) {
        this.fixture.filter = function() {
          var done = this.async();
          setTimeout(function() {
            done('pass');
          }, 0);
        };

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          expect(answer).to.equal('pass');
          done();
        });

        this.rl.emit('line', '');
      });
    });
  },

  'validate': function() {
    describe('validate API', function() {
      it('should reject input if boolean false is returned', function(done) {
        var called = 0;

        this.fixture.validate = function(value) {
          called++;
          // Make sure returning false won't continue
          if (called === 2) {
            done();
          } else {
            this.rl.emit('line');
          }
          return false;
        }.bind(this);

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          // This should NOT be called
          expect(false).to.be.true;
        });

        this.rl.emit('line');
      });

      it('should reject input if a string is returned', function(done) {
        var self = this;
        var called = 0;
        var errorMessage = 'uh oh, error!';

        this.fixture.validate = function(value) {
          called++;
          // Make sure returning false won't continue
          if (called === 2) {
            done();
          } else {
            self.rl.emit('line');
          }
          return errorMessage;
        };

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          // This should NOT be called
          expect(false).to.be.true;
        });

        this.rl.emit('line');
      });

      it('should accept input if boolean true is returned', function(done) {
        var called = 0;

        this.fixture.validate = function(value) {
          called++;
          return true;
        };

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          expect(called).to.equal(1);
          done();
        });

        this.rl.emit('line');
      });

      it('should allow validate function to be asynchronous', function(next) {
        var self = this;
        var called = 0;

        this.fixture.validate = function(value) {
          var done = this.async();
          setTimeout(function() {
            called++;
            // Make sure returning false won't continue
            if (called === 2) {
              done(true);
            } else {
              self.rl.emit('line');
            }
            done(false);
          }, 0);
        };

        var prompt = new this.Prompt(this.fixture, this.rl);

        prompt.run(function(answer) {
          next();
        });

        this.rl.emit('line');
      });

      it('should pass previous answers to the prompt validation function', function(done) {
        var prompt = inquirer.createPromptModule();
        var questions = [{
          type: 'confirm',
          name: 'q1',
          message: 'message'
        }, {
          type: 'confirm',
          name: 'q2',
          message: 'message',
          validate: function(input, answers) {
            expect(answers.q1).to.be.true;
            return true;
          },
          default: false
        }];

        var ui = prompt(questions, function(answers) {
          expect(answers.q1).to.be.true;
          expect(answers.q2).to.be.false;
          done();
        });

        ui.rl.emit('line');
        ui.rl.emit('line');
      });
    });
  },

  'default': function() {
    describe('default API', function() {
      it('should allow a default value', function(done) {
        this.fixture.default = 'pass';

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          expect(this.rl.output.__raw__).to.contain('(pass)');
          expect(answer).to.equal('pass');
          done();
        }.bind(this));

        this.rl.emit('line', '');
      });

      it('should allow a falsy default value', function(done) {
        this.fixture.default = 0;

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run(function(answer) {
          expect(this.rl.output.__raw__).to.contain('(0)');
          expect(answer).to.equal(0);
          done();
        }.bind(this));

        this.rl.emit('line', '');
      });
    });
  },

  'message': function() {
    describe('message API', function() {
      it('should print message on screen', function() {
        this.fixture.message = 'Foo bar bar foo bar';

        var prompt = new this.Prompt(this.fixture, this.rl);
        prompt.run();

        expect(this.rl.output.__raw__).to.contain(this.fixture.message);
      });
    });
  },

  'choices': function() {
    describe('choices API', function() {
      it('should print choices to screen', function() {
        var prompt = new this.Prompt(this.fixture, this.rl);
        var choices = prompt.opt.choices;

        prompt.run();

        _.each(choices.filter(inquirer.Separator.exclude), function(choice) {
          expect(this.rl.output.__raw__).to.contain(choice.name);
        }, this);
      });
    });
  },

  'requiredValues': function() {
    describe('Missing value', function() {
      it('`message` should throw', function() {
        var mkPrompt = function() {
          delete this.fixture.message;
          new this.Prompt(this.fixture, this.rl);
        }.bind(this);
        expect(mkPrompt).to.throw(/message/);
      });

      it('`name` should throw', function() {
        var mkPrompt = function() {
          delete this.fixture.name;
          new this.Prompt(this.fixture, this.rl);
        }.bind(this);
        expect(mkPrompt).to.throw(/name/);
      });
    });
  }
};

// Run tests
describe('Prompt public APIs', function() {
  _.each(prompts, function(detail) {
    describe('on ' + detail.name + ' prompt', function() {

      beforeEach(function() {
        this.fixture = _.clone(fixtures[detail.name]);
        this.Prompt = inquirer.prompt.prompts[detail.name];
        this.rl = new ReadlineStub();
      });

      _.each(detail.apis, function(apiName) {
        tests[apiName](detail.name);
      }, this);
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using FirstPopCoffee.Common.Domain.Model;
using FirstPopCoffee.RoastPlanning.Application;
using FirstPopCoffee.RoastPlanning.Domain.Model;
using FluentAssertions;

namespace FirstPopCoffee.RoastPlanning.Tests.Scenarios.Adding_a_new_roast_schedule {
    public class When_starting_to_create_a_new_roast_schedule : CommandSpecification<RoastSchedule, CreateNewRoastScheduleCommand> {

        private readonly Guid _roastScheduleId = Guid.NewGuid();

        protected override CreateNewRoastScheduleCommand When() {
            return new CreateNewRoastScheduleCommand(_roastScheduleId);
        }

        protected override ICommandHandler<CreateNewRoastScheduleCommand> CommandHandler() {
            return new RoastScheduleCommandHandlers(MockRepository.Object);
        }

        [Then]
        public void Then_a_roast_schedule_is_created() {
            PublishedEvents.Should().NotBeNullOrEmpty();
            PublishedEvents.Last().Should().BeOfType<RoastScheduleCreatedEvent>();
            PublishedEvents.Last().As<RoastScheduleCreatedEvent>().RoastScheduleId.Should().Be(_roastScheduleId);
        }
    }
}


text:
package com.wix.restaurants.jsonclient;

/** A raw file. */
public class BinaryFile {
	private final String contentType;
    private final byte[] content;

    public BinaryFile(String contentType, byte[] content) {
        this.contentType = contentType;
        this.content = content;
    }

    public String getContentType() {
        return contentType;
    }

    public byte[] getContent() {
        return content;
    }

    @Override
	public String toString() {
		return "BinaryFile [contentType=" + contentType + ", contentLength=" + content.length + "]";
	}
}


text:
using System;
using Silphid.DataTypes;

namespace Silphid.Tweenzup
{
    public class Easer : TypeSafeEnum<Easer>, IEaser
    {
        #region Statics

        public static readonly IEaser Instant = new Easer("Instant", _ => 1);
        public static readonly IEaser Linear = new Easer("Linear", t => t);
        public static readonly IEaser InQuadratic = new Easer("InQuadratic", EasingExtensions.EaseInQuadratic);
        public static readonly IEaser OutQuadratic = new Easer("OutQuadratic", EasingExtensions.EaseOutQuadratic);
        public static readonly IEaser InOutQuadratic = new Easer("InOutQuadratic", EasingExtensions.EaseInOutQuadratic);
        public static readonly IEaser InCubic = new Easer("InCubic", EasingExtensions.EaseInCubic);
        public static readonly IEaser OutCubic = new Easer("OutCubic", EasingExtensions.EaseOutCubic);
        public static readonly IEaser InOutCubic = new Easer("InOutCubic", EasingExtensions.EaseInOutCubic);
        public static readonly IEaser InQuartic = new Easer("InQuartic", EasingExtensions.EaseInQuartic);
        public static readonly IEaser OutQuartic = new Easer("OutQuartic", EasingExtensions.EaseOutQuartic);
        public static readonly IEaser InOutQuartic = new Easer("InOutQuartic", EasingExtensions.EaseInOutQuartic);
        public static readonly IEaser InQuintic = new Easer("InQuintic", EasingExtensions.EaseInQuintic);
        public static readonly IEaser OutQuintic = new Easer("OutQuintic", EasingExtensions.EaseOutQuintic);
        public static readonly IEaser InOutQuintic = new Easer("InOutQuintic", EasingExtensions.EaseInOutQuintic);
        public static readonly IEaser InSine = new Easer("InSine", EasingExtensions.EaseInSine);
        public static readonly IEaser OutSine = new Easer("OutSine", EasingExtensions.EaseOutSine);
        public static readonly IEaser InOutSine = new Easer("InOutSine", EasingExtensions.EaseInOutSine);
        public static readonly IEaser InCircular = new Easer("InCircular", EasingExtensions.EaseInCircular);
        public static readonly IEaser OutCircular = new Easer("OutCircular", EasingExtensions.EaseOutCircular);
        public static readonly IEaser InOutCircular = new Easer("InOutCircular", EasingExtensions.EaseInOutCircular);
        public static readonly IEaser InExponential = new Easer("InExponential", EasingExtensions.EaseInExponential);
        public static readonly IEaser OutExponential = new Easer("OutExponential", EasingExtensions.EaseOutExponential);

        public static readonly IEaser InOutExponential = new Easer(
            "InOutExponential",
            EasingExtensions.EaseInOutExponential);

        public static readonly IEaser InElastic = new Easer("InElastic", EasingExtensions.EaseInElastic);
        public static readonly IEaser OutElastic = new Easer("OutElastic", EasingExtensions.EaseOutElastic);
        public static readonly IEaser InOutElastic = new Easer("InOutElastic", EasingExtensions.EaseInOutElastic);
        public static readonly IEaser InBack = new Easer("InBack", EasingExtensions.EaseInBack);
        public static readonly IEaser OutBack = new Easer("OutBack", EasingExtensions.EaseOutBack);
        public static readonly IEaser InOutBack = new Easer("InOutBack", EasingExtensions.EaseInOutBack);
        public static readonly IEaser InBounce = new Easer("InBounce", EasingExtensions.EaseInBounce);
        public static readonly IEaser OutBounce = new Easer("OutBounce", EasingExtensions.EaseOutBounce);
        public static readonly IEaser InOutBounc = new Easer("InOutBounc", EasingExtensions.EaseInOutBounce);

        /// <summary>
        /// Converts an Ease enum value into an IEaser
        /// </summary>
        public static IEaser From(Ease ease) =>
            FromValue((int) ease);

        #endregion

        private readonly Func<float, float> _func;

        public Easer(string name, Func<float, float> func)
            : base(name)
        {
            _func = func;
        }

        public float Ease(float t) =>
            _func(t);
    }
}


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.implementation;

import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.Operations;
import rx.Observable;
import rx.functions.Func1;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.Page;
import com.microsoft.azure.arm.utils.PagedListConverter;
import com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10.OperationsDiscovery;

class OperationsImpl extends WrapperImpl<OperationsInner> implements Operations {
    private PagedListConverter<OperationsDiscoveryInner, OperationsDiscovery> converter;
    private final RecoveryServicesManager manager;

    OperationsImpl(RecoveryServicesManager manager) {
        super(manager.inner().operations());
        this.manager = manager;
        this.converter = new PagedListConverter<OperationsDiscoveryInner, OperationsDiscovery>() {
            @Override
            public Observable<OperationsDiscovery> typeConvertAsync(OperationsDiscoveryInner inner) {
                return Observable.just((OperationsDiscovery) wrapModel(inner));
            }
        };
    }

    public RecoveryServicesManager manager() {
        return this.manager;
    }

    private OperationsDiscoveryImpl wrapModel(OperationsDiscoveryInner inner) {
        return  new OperationsDiscoveryImpl(inner, manager());
    }

    @Override
    public PagedList<OperationsDiscovery> list() {
        OperationsInner client = this.inner();
        return converter.convert(client.listByResourceGroup());
    }

    @Override
    public Observable<OperationsDiscovery> listAsync() {
        OperationsInner client = this.inner();
        return client.listByResourceGroupAsync()
        .flatMapIterable(new Func1<Page<OperationsDiscoveryInner>, Iterable<OperationsDiscoveryInner>>() {
            @Override
            public Iterable<OperationsDiscoveryInner> call(Page<OperationsDiscoveryInner> page) {
                return page.items();
            }
        })
        .map(new Func1<OperationsDiscoveryInner, OperationsDiscovery>() {
            @Override
            public OperationsDiscovery call(OperationsDiscoveryInner inner) {
                return wrapModel(inner);
            }
        });
    }

}


text:
if [[ -z $GIT_PROMPT_ORDER ]]; then
	GIT_PROMPT_ORDER=(
		"prefix"
		"branch"
		"behind"
		"ahead"
		"separator"
		"staged"
		"changed"
		"conflicts"
		"untracked"
		"clean"
		"suffix"
	)
fi

if [[ -z $GIT_PROMPT_SYMBOLS ]]; then
	declare -A GIT_PROMPT_SYMBOLS
	GIT_PROMPT_SYMBOLS=(
		"prefix" "%F{250}[%f"
		"branch" "%F{120}"
		"behind" "%F{216}%{←%G%}"
		"ahead" "%F{216}%{→%G%}"
		"separator" "%F{250}|%f"
		"staged" "%F{117}%{♦%G%}"
		"changed" "%F{226}%{◊%G%}"
		"conflicts" "%F{9}%{≠%G%}"
		"untracked" "%F{214}%{…%G%}"
		"clean" "%F{10}%B%{✓%G%}%b"
		"suffix" "%F{250}]%f"
	)
fi

# Remove right margin from $RPROMPT. In theory, setting ZLE_RPROMPT_INDENT
# appropriately should be enough, but in practice results vary:
# https://superuser.com/q/655607
: ${GIT_PROMPT_INDENT_HACK:=1}

declare -A GIT_STATUS_MAP
GIT_STATUS_MAP=(
	' M' 'changed'    # not updated, work tree changed since index
	' D' 'changed'    # not updated, deleted in work tree
	' T' 'changed'    # type changed in work tree, not staged
	'M ' 'staged'     # updated in index, index and work tree matches
	'MM' 'changed'    # updated in index, work tree changed since index
	'MD' 'changed'    # updated in index, deleted in work tree
	'MT' 'changed'    # updated in index, type changed in work tree
	'A ' 'staged'     # added to index, index and work tree matches
	'AM' 'changed'    # added to index, work tree changed since index
	'AD' 'changed'    # added to index, deleted in work tree
	'AT' 'changed'    # added to index, type changed in work tree
	'D ' 'staged'     # deleted from index
	'DM' 'changed'    # deleted from index
	'R ' 'staged'     # renamed in index, index and work tree matches
	'RM' 'changed'    # renamed in index, work tree changed since index
	'RD' 'changed'    # renamed in index, deleted in work tree
	'C ' 'staged'     # copied in index, index and work tree matches
	'CM' 'changed'    # copied in index, work tree changed since index
	'CD' 'changed'    # copied in index, deleted in work tree
	'T ' 'staged'     # type changed in index, index and work tree matches
	'TM' 'changed'    # type changed in index and matches type in work tree, content differs
	'TD' 'changed'    # type changed in index, deleted in work tree
	'TT' 'changed'    # type changed in index and differs from type in work tree
	'DD' 'conflicts'  # unmerged, both deleted
	'AU' 'conflicts'  # unmerged, added by us
	'UD' 'conflicts'  # unmerged, deleted by them
	'UA' 'conflicts'  # unmerged, added by them
	'DU' 'conflicts'  # unmerged, deleted by us
	'AA' 'conflicts'  # unmerged, both added
	'UU' 'conflicts'  # unmerged, both modified
	'??' 'untracked'  # untracked
	'!!' 'ignored'    # ignored
)

GIT_PROMPT_FIFO_DIR="$HOME/.tmp/zsh-git-prompt"

if [[ $GIT_PROMPT_INDENT_HACK -eq 1 ]]; then
	if [[ $TMUX_PANE ]]; then
		export ZLE_RPROMPT_INDENT=0
	else
		export ZLE_RPROMPT_INDENT=1
	fi
fi

function git_get_status() {
	local status_string map_status chunk chunk_index mapped_status
	local -a status_chunks
	local -A git_flags git_strings git_numbers
	status_string="$(git status --branch -u --porcelain -z 2> /dev/null)"
	if [[ $? -ne 0 ]]; then
		git_flags=(
			"in_repo" 0
		)
		typeset -p git_flags git_strings git_numbers
		return
	fi
	for map_status in $GIT_STATUS_MAP; do
		git_numbers[$map_status]=0
	done
	status_chunks=(${(0)status_string})
	chunk_index=1
	while [[ chunk_index -le ${#status_chunks} ]]; do
		chunk="${status_chunks[$chunk_index]}"
		if [[ "${chunk:0:2}" == '##' ]]; then
			git_parse_status_header "${chunk:2}"
			git_strings[branch]="$RETURN_BRANCH"
			git_numbers[ahead]=$RETURN_AHEAD
			git_numbers[behind]=$RETURN_BEHIND
		else
			mapped_status=${GIT_STATUS_MAP[${chunk:0:2}]}
			git_numbers[$mapped_status]=$((git_numbers[$mapped_status] + 1))
		fi
		if [[ "${chunk:0:2}" == R* || "${chunk:0:2}" == C* ]]; then
			chunk_index=$((chunk_index + 2))
		else
			chunk_index=$((chunk_index + 1))
		fi
	done
	git_flags[in_repo]=1
	git_flags[clean]=0
	if [[ \
		${git_numbers[staged]} -eq 0
		&& ${git_numbers[changed]} -eq 0
		&& ${git_numbers[conflicts]} -eq 0
		&& ${git_numbers[untracked]} -eq 0
	]] then
		git_flags[clean]=1
	fi
	typeset -p git_flags git_strings git_numbers
}

function git_parse_status_header() {
	local branches divergence div
	typeset -g RETURN_AHEAD RETURN_BEHIND RETURN_BRANCH
	RETURN_AHEAD=0
	RETURN_BEHIND=0
	if [[ "$1" == *'Initial commit on '* ]]; then
		RETURN_BRANCH="${1/#*'Initial commit on '/}"
		return
	fi
	if [[ "$1" == *'No commits yet on '* ]]; then
		RETURN_BRANCH="${1/#*'No commits yet on '/}"
		return
	fi
	if [[ "$1" == *'no branch'* ]]; then
		git_get_tag_or_hash
		RETURN_BRANCH="$RETURN_TAG_OR_HASH"
		return
	fi
	if [[ "$1" == *'...'* ]]; then
		# local and remote branch info
		branches=(${(s:...:)1})
		RETURN_BRANCH="${branches[1]# }"
		if [[ $#branches -ne 1 ]]; then
			# ahead or behind
			divergence="${(M)branches[2]%\[*\]}"
			divergence="${divergence#\[}"
			divergence="${divergence%\]}"
			for div in ${(s:, :)divergence}; do
				if [[ "$div" == 'ahead '* ]]; then
					RETURN_AHEAD="${div#ahead }"
				elif [[ "$div" == 'behind '* ]]; then
					RETURN_BEHIND="${div#behind }"
				fi
			done
		fi
		return
	fi
	RETURN_BRANCH="${1# }"
}

function git_get_tag_or_hash() {
	local log_string
	local refs ref
	local ret_hash ret_tag
	typeset -g RETURN_TAG_OR_HASH
	log_string="$(git log -1 --decorate=full --format="%h%d" 2> /dev/null)"
	if [[ "$log_string" == *' ('*')' ]]; then
		ret_hash="${log_string%% (*)}"
		refs="${(M)log_string%% (*)}"
		refs="${refs# \(}"
		refs="${refs%\)}"
		for ref in ${(s:, :)refs}; do
			if [[ "$ref" == 'refs/tags/'* ]]; then # git 1.7.x
				ret_tag="${ref#refs/tags/}"
			elif [[ "$ref" == 'tag: refs/tags/'* ]]; then # git 2.1.x
				ret_tag="${ref#tag: refs/tags/}"
			fi
			if [[ "$ret_tag" != "" ]]; then
				RETURN_TAG_OR_HASH="tags/$ret_tag"
				return
			fi
		done
		RETURN_TAG_OR_HASH="$ret_hash"
	fi
}

function git_prompt_completed_callback() {
	local symbol line k buffer=""
	while read -t 0 -r -u $GIT_PROMPT_DESCRIPTOR line; do
		eval $line
	done
	if [[ ${git_flags[in_repo]} -eq 1 ]]; then
		for k in $GIT_PROMPT_ORDER; do
			symbol="${GIT_PROMPT_SYMBOLS[$k]}"
			if [[ $GIT_PROMPT_INDENT_HACK -eq 1 ]]; then
				if [[ -z $TMUX_PANE ]]; then
					if [[ $k == suffix ]]; then
						symbol="%{$symbol%}"
					fi
				fi
			fi
			if [[ ${git_strings[$k]} != "" ]] then
				buffer+="$symbol${git_strings[$k]}"
			elif [[ ${git_numbers[$k]} != "" ]] then
				if [[ ${git_numbers[$k]} != 0 ]] then
					buffer+="$symbol${git_numbers[$k]}"
				fi
			elif [[ ${git_flags[$k]} != "" ]]; then
				if [[ ${git_flags[$k]} -eq 1 ]] then
					buffer+="$symbol"
				fi
			else
				buffer+="$symbol"
			fi
		done
	fi
	RPROMPT=$buffer
	zle && zle reset-prompt
}

function git_prompt_bg() {
	git_get_status >&$GIT_PROMPT_DESCRIPTOR
	kill -s USR1 $$
}

function git_prompt_hook() {
	if [[ $GIT_PROMPT_BG_PID != 0 ]]; then
		kill -s HUP $GIT_PROMPT_BG_PID > /dev/null 2>&1
	fi
	git_prompt_bg &!
	GIT_PROMPT_BG_PID=$!
}

function git_prompt_init() {
	typeset -g GIT_PROMPT_BG_PID GIT_PROMPT_DESCRIPTOR
	GIT_PROMPT_BG_PID=0
	local fifo="$GIT_PROMPT_FIFO_DIR/$$.fifo"
	mkdir -m 700 -p "$GIT_PROMPT_FIFO_DIR"
	mkfifo -m 600 $fifo
	exec {GIT_PROMPT_DESCRIPTOR}<>$fifo
	rm -f $fifo
}

function TRAPUSR1() {
	git_prompt_completed_callback
	GIT_PROMPT_BG_PID=0
}

autoload -Uz add-zsh-hook
add-zsh-hook precmd git_prompt_hook
git_prompt_init


text:
"""
Data Visualization HS 17 - Exercise 4
Moritz Eck - 14-715-296
"""

import ex4_reader as data_reader
import numpy as np
import matplotlib.pyplot as plt

# z-value constants
MIN_HEIGHT = 0.035
MAX_HEIGHT = 19.835
STEP_SIZE = 0.2

# x & y position
X_POS = 200
Y_POS = 250

# load the temperature data for hours 1 - 5
raw_data = list()

for i in range(1, 6):
    raw_data.append(data_reader.read_geo_data('TC',i))

# y-values: list of temperature data for location (200, 250)
# temperatures[0] = hour1, etc.
temperatures = list()

for i in range(0, 5):
    temperatures.append(raw_data[i][X_POS - 1][Y_POS - 1])

stacked_data = list()
stacked_data.append(temperatures[0])

for i in range(1, 5):
    stacked_data.append(np.add(stacked_data[i-1], temperatures[i]))

# x-values: list containing the heights of the plot
heights = np.arange(MIN_HEIGHT, MAX_HEIGHT + STEP_SIZE, STEP_SIZE)

# create the plot and the two axis
figure, (axis1, axis2) = plt.subplots(nrows=2, ncols=1)

# set title of the window
figure.canvas.set_window_title("DataVis HS17 Ex04 - Task 3")

# plot the data
axis1.plot(heights, stacked_data[0], label='Hour 1')
axis1.plot(heights, stacked_data[1], label='Hour 2')
axis1.plot(heights, stacked_data[2], label='Hour 3')
axis1.plot(heights, stacked_data[3], label='Hour 4')
axis1.plot(heights, stacked_data[4], label='Hour 5')

# different stacked verison (filled with color)
# axis1.stackplot(heights, temperatures, baseline='zero')

# setup and layout axis1
axis1.set_title("Stacked Version 1: Temperatures at different altitude levels.\n" + "At Position: (" + str(X_POS) + ", " + str(Y_POS) + ")")
axis1.set_xlabel("Altitude Level [km]")
axis1.set_ylabel("Temperature [C°]")
axis1.minorticks_on()
axis1.legend()

##########################################
# subplot 2: different version of stacking
##########################################

# plot overlaying / stacked plots
axis2.plot(heights, temperatures[0], label='Hour 1')
axis2.plot(heights, temperatures[1], label='Hour 2')
axis2.plot(heights, temperatures[2], label='Hour 3')
axis2.plot(heights, temperatures[3], label='Hour 4')
axis2.plot(heights, temperatures[4], label='Hour 5')

# layout axis2
axis2.set_title("Stacked Version2: Temperatures at different altitude levels.\n" + "At Position: (" + str(X_POS) + ", " + str(Y_POS) + ")")
axis2.set_xlabel("Altitude Level [km]")
axis2.set_ylabel("Temperature [C°]")
axis2.minorticks_on()
axis2.legend()

# show the plot
plt.show()


text:
"""
Keys and certificates for tests (KEY1 is a private key of CERT1, etc.)

Generated with:

.. code-block:: bash

    $ openssl genrsa -des3 -passout pass:test -out key1.key 1024
    $ openssl req -new -key key1.key -out key1.csr -passin pass:test
    $ cp key1.key key1.key.org
    $ openssl rsa -in key1.key.org -out key1.key -passin pass:test
    $ openssl x509 -req -days 365 -in cert1.csr \
              -signkey key1.key -out cert1.crt
    $ rm key1.key.org cert1.csr

"""
from __future__ import absolute_import

from kombu.serialization import disable_insecure_serializers

from celery.exceptions import ImproperlyConfigured, SecurityError
from celery.five import builtins
from celery.security.utils import reraise_errors
from kombu.serialization import registry

from .case import SecurityCase

from celery.tests.case import Mock, mock_open, patch

class test_security(SecurityCase):

    def teardown(self):
        registry._disabled_content_types.clear()

    def test_disable_insecure_serializers(self):
        try:
            disabled = registry._disabled_content_types
            self.assertTrue(disabled)

            disable_insecure_serializers(
                ['application/json', 'application/x-python-serialize'],
            )
            self.assertIn('application/x-yaml', disabled)
            self.assertNotIn('application/json', disabled)
            self.assertNotIn('application/x-python-serialize', disabled)
            disabled.clear()

            disable_insecure_serializers(allowed=None)
            self.assertIn('application/x-yaml', disabled)
            self.assertIn('application/json', disabled)
            self.assertIn('application/x-python-serialize', disabled)
        finally:
            disable_insecure_serializers(allowed=['json'])

    def test_setup_security(self):
        disabled = registry._disabled_content_types
        self.assertEqual(0, len(disabled))

        self.app.conf.CELERY_TASK_SERIALIZER = 'json'
        self.app.setup_security()
        self.assertIn('application/x-python-serialize', disabled)
        disabled.clear()

    @patch('celery.security.register_auth')
    @patch('celery.security._disable_insecure_serializers')
    def test_setup_registry_complete(self, dis, reg, key='KEY', cert='CERT'):
        calls = [0]

        def effect(*args):
            try:
                m = Mock()
                m.read.return_value = 'B' if calls[0] else 'A'
                return m
            finally:
                calls[0] += 1

        self.app.conf.CELERY_TASK_SERIALIZER = 'auth'
        with mock_open(side_effect=effect):
            with patch('celery.security.registry') as registry:
                store = Mock()
                self.app.setup_security(['json'], key, cert, store)
                dis.assert_called_with(['json'])
                reg.assert_called_with('A', 'B', store, 'sha1', 'json')
                registry._set_default_serializer.assert_called_with('auth')

    def test_security_conf(self):
        self.app.conf.CELERY_TASK_SERIALIZER = 'auth'
        with self.assertRaises(ImproperlyConfigured):
            self.app.setup_security()

        _import = builtins.__import__

        def import_hook(name, *args, **kwargs):
            if name == 'OpenSSL':
                raise ImportError
            return _import(name, *args, **kwargs)

        builtins.__import__ = import_hook
        with self.assertRaises(ImproperlyConfigured):
            self.app.setup_security()
        builtins.__import__ = _import

    def test_reraise_errors(self):
        with self.assertRaises(SecurityError):
            with reraise_errors(errors=(KeyError, )):
                raise KeyError('foo')
        with self.assertRaises(KeyError):
            with reraise_errors(errors=(ValueError, )):
                raise KeyError('bar')


text:
mvn -Phsql exec:java

##Start messaging
mvn -Pzookeeper exec:java

mvn -Pkafka-boot exec:java

mvn -Pkafka-topics exec:java

List all kafka topics
kafka-topics --list --zookeeper localhost:2181

Console producer
kafka-console-producer --broker-list localhost:9092 --topic sample


text:
#ifndef ScriptH
#define ScriptH
#include <windows.h>

#define ONOFF int

#define FPHook(adr, func) (*(void**)adr = (void*)func) ;
#define R(adr) (*(long*)(adr)) // Watch out the size of long
#define P(adr, off) ( R( (R(adr) + off) ) )

#define SCRIPT_INCLUDE(SCRIPT) void __declspec(naked) SCRIPT () ;
#define SCRIPT_START(SCRIPT)   void __declspec(naked) SCRIPT () { __asm {
#define SCRIPT_END             }}
#define ACALL(ADDRESS)         mov  [esp-0x08], ADDRESS; call [esp-0x08]
#define AJUMP(ADDRESS)         push ADDRESS; ret
#define AMOVESP(ESP,ADDRESS)   mov [esp-0x8],eax;mov eax,ADDRESS;mov [esp+ESP],eax;mov eax,[esp-0x8]

//---------------------------------------------------------------------------

extern GodMode_OnOff;
extern SCRIPT_INCLUDE(GodMode_Entry)
extern SCRIPT_INCLUDE(GodMode_Main)

extern CSX_OnOff;
extern SCRIPT_INCLUDE(CSX_Entry)

extern SuperDiagua_OnOff;
extern SCRIPT_INCLUDE(SuperDiagua_Entry)

extern SuperMobStupid_OnOff;
extern SCRIPT_INCLUDE(SuperMobStupide_Entry)
extern SCRIPT_INCLUDE(SuperMobStupid_Main)

extern FullMap_OnOff;
extern SCRIPT_INCLUDE(FullMap_Entry)
extern SCRIPT_INCLUDE(FullMap_Main)
extern SCRIPT_INCLUDE(FullMap_Bypass)

extern ItemVac_OnOff;
extern SCRIPT_INCLUDE(ItemVac_Entry)
extern SCRIPT_INCLUDE(ItemVac_Main)

extern FaceLR_OnOff;
extern FaceLR_Value;
extern SCRIPT_INCLUDE(FaceLR_Entry)
extern SCRIPT_INCLUDE(FaceLR_Main)

extern UltimateJmp_OnOff;
extern SCRIPT_INCLUDE(UltimateJmp_Entry)

extern NoSkillAni_OnOff;
extern SCRIPT_INCLUDE(NoSkillAni_Entry)

extern WalkSpeedUp_OnOff;
extern SCRIPT_INCLUDE(WalkSpeedUp_Entry)

extern SCRIPT_INCLUDE(ItemFilter_Main)
extern SCRIPT_INCLUDE(ItemFilter_Entry)

extern AutoLR_Value;
extern AutoLR_Range;
extern AutoLR_Step;
extern AutoLR_Position;
extern AutoLR_OnOff;
extern SCRIPT_INCLUDE(AutoLR_Main)
extern SCRIPT_INCLUDE(AutoLR_Entry)

extern CSMobVac_OnOff;

extern NoBkImg_OnOff;

extern SCRIPT_INCLUDE(GetInfo_Entry)

extern void __stdcall InstallScript();

#endif


text:
package org.ohdsi.rabbitInAHat.dataModel;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JOptionPane;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.ohdsi.utilities.collections.Pair;

public class StemTableFactory {

	private static final String STEM_TABLE_NAME = "stem_table";

	public static void addStemTable(ETL etl) {
		Database sourceDatabase = etl.getSourceDatabase();
		Database targetDatabase = etl.getTargetDatabase();
		InputStream tableStream;
		InputStream mappingStream;
		if (targetDatabase.getDbName().equalsIgnoreCase("cdmv5.0")) {
			tableStream = StemTableFactory.class.getResourceAsStream("StemTableV5.0.csv");
			mappingStream = StemTableFactory.class.getResourceAsStream("StemTableDefaultMappingV5.0.csv");
		} else if (targetDatabase.getDbName().equalsIgnoreCase("cdmv5.1")) {
			tableStream = StemTableFactory.class.getResourceAsStream("StemTableV5.1.csv");
			mappingStream = StemTableFactory.class.getResourceAsStream("StemTableDefaultMappingV5.1.csv");
		} else if (targetDatabase.getDbName().equalsIgnoreCase("cdmv5.2")) {
			tableStream = StemTableFactory.class.getResourceAsStream("StemTableV5.2.csv");
			mappingStream = StemTableFactory.class.getResourceAsStream("StemTableDefaultMappingV5.2.csv");
		} else if (targetDatabase.getDbName().equalsIgnoreCase("cdmv5.3")) {
			tableStream = StemTableFactory.class.getResourceAsStream("StemTableV5.3.csv");
			mappingStream = StemTableFactory.class.getResourceAsStream("StemTableDefaultMappingV5.3.csv");
		} else if (targetDatabase.getDbName().equalsIgnoreCase("cdmv5.4")) {
			tableStream = StemTableFactory.class.getResourceAsStream("StemTableV5.4.csv");
			mappingStream = StemTableFactory.class.getResourceAsStream("StemTableDefaultMappingV5.4.csv");
		} else if (targetDatabase.getDbName().equalsIgnoreCase("cdmv6.0")) {
			tableStream = StemTableFactory.class.getResourceAsStream("StemTableV6.0.csv");
			mappingStream = StemTableFactory.class.getResourceAsStream("StemTableDefaultMappingV6.0.csv");
		} else {
			JOptionPane.showMessageDialog(null, "No stem table definition available for " + targetDatabase.getDbName(), "Error", JOptionPane.ERROR_MESSAGE);
			return;
		}

		try {
			Table sourceStemTable = new Table();
			sourceStemTable.setStem(true);
			sourceStemTable.setName(STEM_TABLE_NAME);
			CSVFormat csvFormat = CSVFormat.Builder.create(CSVFormat.RFC4180).setHeader().build();
			for (CSVRecord row : csvFormat.parse(new InputStreamReader(tableStream))) {
				Field field = new Field(row.get("COLUMN_NAME").toLowerCase(), sourceStemTable);
				field.setNullable(row.get("IS_NULLABLE").equals("YES"));
				field.setType(row.get("DATA_TYPE"));
				field.setDescription(row.get("DESCRIPTION"));
				field.setStem(true);
				sourceStemTable.getFields().add(field);
			}
			sourceDatabase.getTables().add(sourceStemTable);
			Table targetStemTable = new Table(sourceStemTable);
			targetStemTable.setDb(targetDatabase);
			targetDatabase.getTables().add(targetStemTable);

			Mapping<Table> mapping = etl.getTableToTableMapping();
			Map<String, Table> nameToTable = new HashMap<>();
			for (CSVRecord row : csvFormat.parse(new InputStreamReader(mappingStream))) {
				String targetTableName = row.get("TARGET_TABLE");
				Table targetTable = nameToTable.get(targetTableName);
				if (targetTable == null) {
					targetTable = targetDatabase.getTableByName(targetTableName);
					mapping.addSourceToTargetMap(sourceStemTable, targetTable);
					nameToTable.put(targetTableName, targetTable);
				}
				Mapping<Field> fieldToFieldMapping = etl.getFieldToFieldMapping(sourceStemTable, targetTable);
				Field sourceField = sourceStemTable.getFieldByName(row.get("SOURCE_FIELD"));
				Field targetField = targetTable.getFieldByName(row.get("TARGET_FIELD"));
				fieldToFieldMapping.addSourceToTargetMap(sourceField, targetField);
			}

		} catch (IOException e) {
			throw new RuntimeException(e.getMessage());
		}

	}

	public static void removeStemTable(ETL etl) {
		// Find stem source and target tables
		Mapping<Table> mapping = etl.getTableToTableMapping();
		List<Pair<Table, Table>> tablesMappingsToRemove = new ArrayList<>();
		for (ItemToItemMap sourceToTargetMap : mapping.getSourceToTargetMaps()) {
			Table sourceTable = (Table) sourceToTargetMap.getSourceItem();
			Table targetTable = (Table) sourceToTargetMap.getTargetItem();
			if (sourceTable.isStem() || targetTable.isStem()) {
				tablesMappingsToRemove.add(new Pair<>(sourceTable, targetTable));
			}
		}

		// Remove stem table to table and field to field mappings
		for (Pair<Table, Table> tableTablePair : tablesMappingsToRemove) {
			etl.getFieldToFieldMapping(tableTablePair.getItem1(), tableTablePair.getItem2()).removeAllSourceToTargetMaps();
			mapping.removeSourceToTargetMap(tableTablePair.getItem1(), tableTablePair.getItem2());
		}

		// Remove stem source table
		Database sourceDatabase = etl.getSourceDatabase();
		List<Table> newSourceTables = new ArrayList<>();
		for (Table table : sourceDatabase.getTables()) {
			if (!table.isStem()) {
				newSourceTables.add(table);
			}
		}
		sourceDatabase.setTables(newSourceTables);

		// Remove stem target table
		Database targetDatabase = etl.getTargetDatabase();
		List<Table> newTargetTables = new ArrayList<>();
		for (Table table : targetDatabase.getTables()) {
			if (!table.isStem()) {
				newTargetTables.add(table);
			}
		}
		targetDatabase.setTables(newTargetTables);
	}

}


text:
Music!

        <form ng-submit="searchSubmit()">
            <input type="text" legnth="20" id="searchText" ng-model="searchText" placeholder="Search" />
            <input type="submit" id="searchButton" value="Search" />
        </form>

No results found

        <input type="button" value="Stop" ng-click="stopPlaying()" />


text:
<link rel="stylesheet" href="https://bootswatch.com/cerulean/bootstrap.min.css" />

<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/create_character.css">

Character Creation

				<canvas class="avatar-ctx" id="ctx-avatar-prev"></canvas>

			<?php if(count($avatars) > 0) { ?>
				<?php foreach ($avatars as $a) { ?>
					<input type="radio" id="avtr_<?php echo $a['CHAR_NAME']; ?>" name="avatars" onclick="changeAvtImg(this);" value="<?php echo $a['CHAR_ID']; ?>">
					<label for="avtr_<?php echo $a['CHAR_NAME']; ?>"><?php echo $a['CHAR_NAME']; ?>
				<?php } ?>
			<?php } ?>


text:
//
// $
//

package edu.gemini.spModel.target.obsComp;

import edu.gemini.shared.util.immutable.MapOp;
import edu.gemini.shared.util.immutable.Some;
import edu.gemini.skycalc.Angle;
import edu.gemini.skycalc.Coordinates;
import edu.gemini.skycalc.Offset;
import edu.gemini.shared.skyobject.SkyObject;
import edu.gemini.shared.util.immutable.None;
import edu.gemini.shared.util.immutable.Option;
import edu.gemini.spModel.gemini.gmos.GmosCommonType;
import edu.gemini.spModel.gemini.gmos.InstGmosCommon;
import edu.gemini.spModel.guide.*;
import edu.gemini.spModel.obs.SchedulingBlock;
import edu.gemini.spModel.obs.context.ObsContext;
import edu.gemini.spModel.obscomp.SPInstObsComp;
import edu.gemini.spModel.target.SPTarget;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.util.Set;

/**
 * The Peripheral guide probes.
 */
public enum PwfsGuideProbe implements ValidatableGuideProbe, OffsetValidatingGuideProbe {

    pwfs1(1) {
        @Override public double getScale() {
           return getPwfs1Scale();
        }

        @Override public Angle getVignettingClearance(ObsContext ctx) {
            final SPInstObsComp oc = ctx.getInstrument();
            return (oc == null) ? Angle.ANGLE_0DEGREES : oc.pwfs1VignettingClearance();
        }
    },

    pwfs2(2) {
        @Override public double getScale() {
            return getPwfs2Scale();
        }

        @Override public Angle getVignettingClearance(ObsContext ctx) {
            final SPInstObsComp oc = ctx.getInstrument();
            return (oc == null) ? Angle.ANGLE_0DEGREES : oc.pwfs2VignettingClearance();
        }
    };

    // The radius of the outer limit for PWFS 417" or 6.95' (valid for all instruments).
    private static final int PWFS_RADIUS_ARCSEC = 417;
    public static final Angle PWFS_RADIUS = Angle.arcsecs(PWFS_RADIUS_ARCSEC);

    /* Geometry */
    // -- Define constants that define geometry of the two PWFS --

    // Used for conversion between mm and pixel
    private static final double MM_FACTOR = 1.611;

    // Distance from M2 to focal plane
    private static final double M2_FPLANE_SEP = 16539.326;

    // Radius of M2 (mm)
    private static final double M2_RADIUS = 511.0;

    // Pivot to mirror centre (mm)
    private static final double ARM_LENGTH = 400.0;

    // Distance of pwfs1 from focal plane
    private static final double PWFS1_FPLANE_SEP = 1995.0;

    // Distance of pwfs2 from focal plane
    private static final double PWFS2_FPLANE_SEP = 1610.0;

    // Width of pickoff mirror (mm)
    private static final double PWFS1_M_WIDTH = 157.0;

    // Length of pickoff mirror (mm)
    private static final double PWFS1_M_LENGTH = 157.0;

    // Width of pickoff mirror (mm)
    private static final double PWFS2_M_WIDTH = 127.0;

    // Length of pickoff mirror (mm)
    private static final double PWFS2_M_LENGTH = 127.0;

    // Width of probe arm (mm)
    private static final double PWFS1_A_WIDTH = 202.0;

    // Width of probe arm (mm)
    private static final double PWFS2_A_WIDTH = 202.0;

    // Scale to convert mm in focal plane to mm at height of pwfs1
    private static final double PWFS1_SCALE = (getM2FplaneSep() - getPwfs1FplaneSep()) / getM2FplaneSep();

    // Scale to convert mm in focal plane to mm at height of pwfs2
    private static final double PWFS2_SCALE = (getM2FplaneSep() - getPwfs2FplaneSep()) / getM2FplaneSep();

    private final int index;

    private final PatrolField patrolField;

    public abstract double getScale();
    public abstract Angle getVignettingClearance(ObsContext ctx);

    private final double planeSep;
    private final double mWidth;

    public double getMWidth() {
        return mWidth;
    }

    private final double mLength;

    public double getMLength() {
        return  mLength;
    }

    private final double aWidth;

    public double getAWidth() {
        return aWidth;
    }

    private final int radius;

    public int getRadius() {
       return radius;
    }

    public double getFPlaneSep() {
        return planeSep;
    }

    public static double getArmLength() {
        return ARM_LENGTH;
    }

    public static double getM2FplaneSep() {
        return M2_FPLANE_SEP;
    }

    public static double getM2Radius() {
        return M2_RADIUS;
    }

    /**
     * Creates a polygon The polygon has four corners in the correct orientation
     * and projection in the focal plane
     *
     * @param pwfsScale scale for PWFS1 or 2
     * @param xc        the X screen coordinate for the base position
     * @param yc        the Y screen coordinate for the base position
     * @param xp        X point of pivot
     * @param yp        Y point of pivot
     * @param dx        WFS X position relative to field centre with allowance for height of wfs above focal plane
     * @param dy        WFS Y position relative to field centre with allowance for height of wfs above focal plane
     * @param xyList    array of points in partially vignetted region
     * @param xySize    length of xyList array to use
     * @param tx        translate resulting figure by this amount of pixels in X (used when WFS is frozen)
     * @param ty        translate resulting figure by this amount of pixels in Y (used when WFS is frozen)
     */
    public static Shape buildFigure(double pwfsScale, double xc, double yc, double xp, double yp, double dx, double dy, double[] xyList, int xySize, double tx, double ty) {
        // Rotate each x,y pair to a frame aligned along the axis of the probe
        double dxp = dx + xc - xp;
        double dyp = dy + yc - yp;
        double rot = Math.atan2(-dyp, dxp);

        double cosrot = Math.cos(rot);
        double sinrot = Math.sin(rot);

        GeneralPath path = new GeneralPath();
        int numPoints = xySize / 2;
        double firstX = 0.0;
        double firstY = 0.0;
        for (int i = 0; i < numPoints; i++) {
            int xIndex = 2 * i;
            int yIndex = xIndex + 1;

            // Rotate these points to the correct orientation
            double xnp = (xyList[xIndex] * cosrot + xyList[yIndex] * sinrot) + xp;
            double ynp = (xyList[xIndex] * -sinrot + xyList[yIndex] * cosrot) + yp;

            // project points into focal plane
            final double x = (xnp - xc) / pwfsScale + xc + tx;
            final double y = (ynp - yc) / pwfsScale + yc + ty;

            if (i == 0) {
                path.moveTo(x, y);
                firstX = x;
                firstY = y;
            } else {
                path.lineTo(x, y);
            }
        }
        //Close the path
        path.lineTo(firstX, firstY);

        return path;
    }

   public static double getMmFactor() {
        return MM_FACTOR;
    }

    PwfsGuideProbe(int index) {
        this.index = index;

        radius = PWFS_RADIUS_ARCSEC;
        patrolField = new PatrolField(
                new Ellipse2D.Double(-radius, -radius, radius * 2.0, radius * 2.0),                           // fov
                new Ellipse2D.Double(-radius + 2.0, -radius + 2.0, radius * 2.0 - 4.0, radius * 2.0 - 4.0),   // fov in  (-2 arcsecs)
                new Ellipse2D.Double(-radius - 2.0, -radius - 2.0, radius * 2.0 + 4.0, radius * 2.0 + 4.0)    // fov out (+2 arcsecs)
        );

        if (index == 1) {
            planeSep = getPwfs1FplaneSep();
            mWidth   = PWFS1_M_WIDTH;
            mLength  = PWFS1_M_LENGTH;
            aWidth   = PWFS1_A_WIDTH;
        } else {
            planeSep = getPwfs2FplaneSep();
            mWidth   = PWFS2_M_WIDTH;
            mLength  = PWFS2_M_LENGTH;
            aWidth   = PWFS2_A_WIDTH;
        }
    }

    public static double getPwfs1Scale() {
        return PWFS1_SCALE;
    }

    public static double getPwfs1FplaneSep() {
        return PWFS1_FPLANE_SEP;
    }

    public static double getPwfs2Scale() {
        return PWFS2_SCALE;
    }

    public static double getPwfs2FplaneSep() {
        return PWFS2_FPLANE_SEP;
    }

    public String getKey() {
        return "PWFS" + index;
    }

    public String toString() {
        return getKey();
    }

    public Type getType() {
        return Type.PWFS;
    }

    public String getDisplayName() {
        return "Peripheral WFS " + index;
    }

    public String getSequenceProp() {
        return "guideWithPWFS" + index;
    }

    public GuideOptions getGuideOptions() {
        return StandardGuideOptions.instance;
    }

    public Option<GuideProbeGroup> getGroup() {
        return None.instance();
    }

    /* ValidatableGuideProbe */

    public GuideStarValidation validate(SPTarget guideStar, ObsContext ctx) {
        final Option<Long> when = ctx.getSchedulingBlock().map(SchedulingBlock::start);
        return guideStar.getTarget().getSkycalcCoordinates(when).map(coords ->
            validate(coords, ctx)
        ).getOrElse(GuideStarValidation.UNDEFINED);
    }

    public GuideStarValidation validate(SkyObject guideStar, ObsContext ctx) {
        return GuideProbeUtil.instance.validate(guideStar, this, ctx);
    }

    public GuideStarValidation validate(Coordinates coords, ObsContext ctx) {
        return GuideProbeUtil.instance.validate(coords, this, ctx);
    }

    public Option<BoundaryPosition> checkBoundaries(SPTarget guideStar, ObsContext ctx){
        return checkBoundaries(guideStar.getTarget().getSkycalcCoordinates(), ctx);
    }

    /**
     * Returns BoundaryPosition.outside, if the coordinates are outside the outer limit,
     * inside, if inside the inner limit and innerBoundary if between the inner and outer limits
     * (which is where the PWFS should normally be).
     *
     * @param coords the coordinates
     * @param ctx the context
     * @return
     */
    public Option<BoundaryPosition> checkBoundaries(final Coordinates coords, final ObsContext ctx) {
        return ctx.getBaseCoordinates().map(baseCoordinates -> {
            final Angle positionAngle = ctx.getPositionAngle();
            final Set<Offset> sciencePositions = ctx.getSciencePositions();

            // check positions against corrected outer patrol field bounds
            return getCorrectedPatrolField(ctx).map(new MapOp<PatrolField, BoundaryPosition>() {
                @Override
                public BoundaryPosition apply(PatrolField patrolField) {
                    final BoundaryPosition bp = patrolField.checkBoundaries(coords, baseCoordinates, positionAngle, sciencePositions);
                    if (bp != BoundaryPosition.inside) {
                        return BoundaryPosition.outside;
                    }

                    // Check if any of the guide stars are inside the inner bounds (opposite logic needed, union instead of intersection)
                    final double minLimit = getVignettingClearance(ctx).toArcsecs().getMagnitude();
                    final Ellipse2D e = new Ellipse2D.Double(-minLimit, -minLimit, minLimit * 2.0, minLimit * 2.0);
                    final PatrolField p = getCorrectedPatrolField(new PatrolField(e, e, e), ctx);
                    if (p.anyInside(coords, baseCoordinates, positionAngle, sciencePositions)) {
                        return BoundaryPosition.inside;
                    }
                    return BoundaryPosition.innerBoundary;
                }
            }).getOrElse(BoundaryPosition.outside);
        });
    }

    /* OffsetValidatingGuideProbe */

    public boolean inRange(ObsContext ctx, Offset offset) {
        return GuideProbeUtil.instance.inRange(this, ctx, offset);
    }

    @Override
    public Option<PatrolField> getCorrectedPatrolField(ObsContext ctx) {
        return GuideProbeUtil.instance.isAvailable(ctx, this) ? new Some<>(getCorrectedPatrolField(getPatrolField(), ctx)) : None.<PatrolField>instance();
    }

    public PatrolField getCorrectedPatrolField(PatrolField patrolField, ObsContext ctx) {
        // special case for GMOS: take IFU offest into account for patrol field
        final SPInstObsComp instrument = ctx.getInstrument();
        if (InstGmosCommon.class.isAssignableFrom(instrument.getClass())) {
            final double wfsOffset = ((GmosCommonType.FPUnit) ((InstGmosCommon) instrument).getFPUnit()).getWFSOffset();
            AffineTransform correction = AffineTransform.getTranslateInstance(wfsOffset, 0.0);
            return patrolField.getTransformed(correction);

        // TODO: if needed add special corrections (translation) for nod and chop mode for Michelle and TReCS
        // see: TReCS_SciAreaFeature and Michelle_SciAreaFeature : getNodChopOffset()

        } else {
            return patrolField;
        }
    }

    @Override
    public PatrolField getPatrolField() {
        return patrolField;
    }
}


text:
{{ site.description }}

      Home
      Video Overview

      GitHub
      {% for article in site.data.lessons %}
          {{ article.title }}
      {% endfor %}
      v{{ site.version }}

© {{ site.time | date: '%Y' }} Bixelcog LLC. All rights reserved.