text:
/*
 * UltraCart Rest API V2
 *
 * UltraCart REST API Version 2
 *
 * OpenAPI spec version: 2.0.0
 * Contact: support@ultracart.com
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 */

using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;

namespace com.ultracart.admin.v2.Model
{
    /// <summary>
    /// EmailList
    /// </summary>
    [DataContract]
    public partial class EmailList :  IEquatable<EmailList>, IValidatableObject
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="EmailList" /> class.
        /// </summary>
        /// <param name="allowCsvDownload">True if the current user has the rights to download this list..</param>
        /// <param name="createdDts">Created date.</param>
        /// <param name="deleted">True if this campaign was deleted.</param>
        /// <param name="emailListUuid">Email list UUID.</param>
        /// <param name="espListSegmentFolderUuid">List/Segment folder UUID.</param>
        /// <param name="memberCount">Count of members in this list.</param>
        /// <param name="merchantId">Merchant ID.</param>
        /// <param name="name">Name of email list.</param>
        /// <param name="publicDescription">Description of list shown to customer..</param>
        /// <param name="publicList">True if this list is public.</param>
        /// <param name="storefrontOid">Storefront oid.</param>
        /// <param name="usedBy">Details on the flows or campaigns that use this list..</param>
        public EmailList(bool? allowCsvDownload = default(bool?), string createdDts = default(string), bool? deleted = default(bool?), string emailListUuid = default(string), string espListSegmentFolderUuid = default(string), int? memberCount = default(int?), string merchantId = default(string), string name = default(string), string publicDescription = default(string), bool? publicList = default(bool?), int? storefrontOid = default(int?), List<EmailListSegmentUsedBy> usedBy = default(List<EmailListSegmentUsedBy>))
        {
            this.AllowCsvDownload = allowCsvDownload;
            this.CreatedDts = createdDts;
            this.Deleted = deleted;
            this.EmailListUuid = emailListUuid;
            this.EspListSegmentFolderUuid = espListSegmentFolderUuid;
            this.MemberCount = memberCount;
            this.MerchantId = merchantId;
            this.Name = name;
            this.PublicDescription = publicDescription;
            this.PublicList = publicList;
            this.StorefrontOid = storefrontOid;
            this.UsedBy = usedBy;
        }

        /// <summary>
        /// True if the current user has the rights to download this list.
        /// </summary>
        /// <value>True if the current user has the rights to download this list.</value>
        [DataMember(Name="allow_csv_download", EmitDefaultValue=false)]
        public bool? AllowCsvDownload { get; set; }

        /// <summary>
        /// Created date
        /// </summary>
        /// <value>Created date</value>
        [DataMember(Name="created_dts", EmitDefaultValue=false)]
        public string CreatedDts { get; set; }

        /// <summary>
        /// True if this campaign was deleted
        /// </summary>
        /// <value>True if this campaign was deleted</value>
        [DataMember(Name="deleted", EmitDefaultValue=false)]
        public bool? Deleted { get; set; }

        /// <summary>
        /// Email list UUID
        /// </summary>
        /// <value>Email list UUID</value>
        [DataMember(Name="email_list_uuid", EmitDefaultValue=false)]
        public string EmailListUuid { get; set; }

        /// <summary>
        /// List/Segment folder UUID
        /// </summary>
        /// <value>List/Segment folder UUID</value>
        [DataMember(Name="esp_list_segment_folder_uuid", EmitDefaultValue=false)]
        public string EspListSegmentFolderUuid { get; set; }

        /// <summary>
        /// Count of members in this list
        /// </summary>
        /// <value>Count of members in this list</value>
        [DataMember(Name="member_count", EmitDefaultValue=false)]
        public int? MemberCount { get; set; }

        /// <summary>
        /// Merchant ID
        /// </summary>
        /// <value>Merchant ID</value>
        [DataMember(Name="merchant_id", EmitDefaultValue=false)]
        public string MerchantId { get; set; }

        /// <summary>
        /// Name of email list
        /// </summary>
        /// <value>Name of email list</value>
        [DataMember(Name="name", EmitDefaultValue=false)]
        public string Name { get; set; }

        /// <summary>
        /// Description of list shown to customer.
        /// </summary>
        /// <value>Description of list shown to customer.</value>
        [DataMember(Name="public_description", EmitDefaultValue=false)]
        public string PublicDescription { get; set; }

        /// <summary>
        /// True if this list is public
        /// </summary>
        /// <value>True if this list is public</value>
        [DataMember(Name="public_list", EmitDefaultValue=false)]
        public bool? PublicList { get; set; }

        /// <summary>
        /// Storefront oid
        /// </summary>
        /// <value>Storefront oid</value>
        [DataMember(Name="storefront_oid", EmitDefaultValue=false)]
        public int? StorefrontOid { get; set; }

        /// <summary>
        /// Details on the flows or campaigns that use this list.
        /// </summary>
        /// <value>Details on the flows or campaigns that use this list.</value>
        [DataMember(Name="used_by", EmitDefaultValue=false)]
        public List<EmailListSegmentUsedBy> UsedBy { get; set; }

        /// <summary>
        /// Returns the string presentation of the object
        /// </summary>
        /// <returns>String presentation of the object</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append("class EmailList {\n");
            sb.Append("  AllowCsvDownload: ").Append(AllowCsvDownload).Append("\n");
            sb.Append("  CreatedDts: ").Append(CreatedDts).Append("\n");
            sb.Append("  Deleted: ").Append(Deleted).Append("\n");
            sb.Append("  EmailListUuid: ").Append(EmailListUuid).Append("\n");
            sb.Append("  EspListSegmentFolderUuid: ").Append(EspListSegmentFolderUuid).Append("\n");
            sb.Append("  MemberCount: ").Append(MemberCount).Append("\n");
            sb.Append("  MerchantId: ").Append(MerchantId).Append("\n");
            sb.Append("  Name: ").Append(Name).Append("\n");
            sb.Append("  PublicDescription: ").Append(PublicDescription).Append("\n");
            sb.Append("  PublicList: ").Append(PublicList).Append("\n");
            sb.Append("  StorefrontOid: ").Append(StorefrontOid).Append("\n");
            sb.Append("  UsedBy: ").Append(UsedBy).Append("\n");
            sb.Append("}\n");
            return sb.ToString();
        }

        /// <summary>
        /// Returns the JSON string presentation of the object
        /// </summary>
        /// <returns>JSON string presentation of the object</returns>
        public virtual string ToJson()
        {
            return JsonConvert.SerializeObject(this, Formatting.Indented);
        }

        /// <summary>
        /// Returns true if objects are equal
        /// </summary>
        /// <param name="input">Object to be compared</param>
        /// <returns>Boolean</returns>
        public override bool Equals(object input)
        {
            return this.Equals(input as EmailList);
        }

        /// <summary>
        /// Returns true if EmailList instances are equal
        /// </summary>
        /// <param name="input">Instance of EmailList to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(EmailList input)
        {
            if (input == null)
                return false;

            return
                (
                    this.AllowCsvDownload == input.AllowCsvDownload ||
                    (this.AllowCsvDownload != null &&
                    this.AllowCsvDownload.Equals(input.AllowCsvDownload))
                ) &&
                (
                    this.CreatedDts == input.CreatedDts ||
                    (this.CreatedDts != null &&
                    this.CreatedDts.Equals(input.CreatedDts))
                ) &&
                (
                    this.Deleted == input.Deleted ||
                    (this.Deleted != null &&
                    this.Deleted.Equals(input.Deleted))
                ) &&
                (
                    this.EmailListUuid == input.EmailListUuid ||
                    (this.EmailListUuid != null &&
                    this.EmailListUuid.Equals(input.EmailListUuid))
                ) &&
                (
                    this.EspListSegmentFolderUuid == input.EspListSegmentFolderUuid ||
                    (this.EspListSegmentFolderUuid != null &&
                    this.EspListSegmentFolderUuid.Equals(input.EspListSegmentFolderUuid))
                ) &&
                (
                    this.MemberCount == input.MemberCount ||
                    (this.MemberCount != null &&
                    this.MemberCount.Equals(input.MemberCount))
                ) &&
                (
                    this.MerchantId == input.MerchantId ||
                    (this.MerchantId != null &&
                    this.MerchantId.Equals(input.MerchantId))
                ) &&
                (
                    this.Name == input.Name ||
                    (this.Name != null &&
                    this.Name.Equals(input.Name))
                ) &&
                (
                    this.PublicDescription == input.PublicDescription ||
                    (this.PublicDescription != null &&
                    this.PublicDescription.Equals(input.PublicDescription))
                ) &&
                (
                    this.PublicList == input.PublicList ||
                    (this.PublicList != null &&
                    this.PublicList.Equals(input.PublicList))
                ) &&
                (
                    this.StorefrontOid == input.StorefrontOid ||
                    (this.StorefrontOid != null &&
                    this.StorefrontOid.Equals(input.StorefrontOid))
                ) &&
                (
                    this.UsedBy == input.UsedBy ||
                    this.UsedBy != null &&
                    this.UsedBy.SequenceEqual(input.UsedBy)
                );
        }

        /// <summary>
        /// Gets the hash code
        /// </summary>
        /// <returns>Hash code</returns>
        public override int GetHashCode()
        {
            unchecked // Overflow is fine, just wrap
            {
                int hashCode = 41;
                if (this.AllowCsvDownload != null)
                    hashCode = hashCode * 59 + this.AllowCsvDownload.GetHashCode();
                if (this.CreatedDts != null)
                    hashCode = hashCode * 59 + this.CreatedDts.GetHashCode();
                if (this.Deleted != null)
                    hashCode = hashCode * 59 + this.Deleted.GetHashCode();
                if (this.EmailListUuid != null)
                    hashCode = hashCode * 59 + this.EmailListUuid.GetHashCode();
                if (this.EspListSegmentFolderUuid != null)
                    hashCode = hashCode * 59 + this.EspListSegmentFolderUuid.GetHashCode();
                if (this.MemberCount != null)
                    hashCode = hashCode * 59 + this.MemberCount.GetHashCode();
                if (this.MerchantId != null)
                    hashCode = hashCode * 59 + this.MerchantId.GetHashCode();
                if (this.Name != null)
                    hashCode = hashCode * 59 + this.Name.GetHashCode();
                if (this.PublicDescription != null)
                    hashCode = hashCode * 59 + this.PublicDescription.GetHashCode();
                if (this.PublicList != null)
                    hashCode = hashCode * 59 + this.PublicList.GetHashCode();
                if (this.StorefrontOid != null)
                    hashCode = hashCode * 59 + this.StorefrontOid.GetHashCode();
                if (this.UsedBy != null)
                    hashCode = hashCode * 59 + this.UsedBy.GetHashCode();
                return hashCode;
            }
        }

        /// <summary>
        /// To validate all properties of the instance
        /// </summary>
        /// <param name="validationContext">Validation context</param>
        /// <returns>Validation Result</returns>
        IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
        {
            // Name (string) maxLength
            if(this.Name != null && this.Name.Length > 250)
            {
                yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be less than 250.", new [] { "Name" });
            }

            yield break;
        }
    }

}


text:
package azkaban.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class SplitterOutputStream extends OutputStream {
	List<OutputStream> outputs;

	public SplitterOutputStream(OutputStream... outputs) {
		this.outputs = new ArrayList<OutputStream>(outputs.length);
		for (OutputStream output : outputs) {
			this.outputs.add(output);
		}
	}

	@Override
	public void write(int b) throws IOException {
		for (OutputStream output : outputs) {
			output.write(b);
		}
	}

	@Override
	public void write(byte[] b) throws IOException {
		for (OutputStream output : outputs) {
			output.write(b);
		}
	}

	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		for (OutputStream output : outputs) {
			output.write(b, off, len);
		}
	}

	@Override
	public void flush() throws IOException {
		IOException exception = null;
		for (OutputStream output : outputs) {
			try {
				output.flush();
			} catch (IOException e) {
				exception = e;
			}
		}
		if (exception != null) {
			throw exception;
		}
	}

	@Override
	public void close() throws IOException {
		IOException exception = null;
		for (OutputStream output : outputs) {
			try {
				output.close();
			} catch (IOException e) {
				exception = e;
			}
		}
		if (exception != null) {
			throw exception;
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
C. r. Congr. natn. Socs. sav. Paris, sect. sci. , fasc. 1. (Paleobotanique) 105: 188 + pl. II, fig. 19 (1980)

#### Original name
Psidimobipiospora clarkii Sal.-Cheb. & Locq.

### Remarks
null


text:
class PyKernelPCA : public KernelPCA
{

private:

bool CheckNpArray(PyObject* arr);

// Copy a c-contiguous strided numpy array to a fortran-contiguous float or double array
float* c_cont_npy_to_f_cont_float_ptr(int M, int N, PyObject* R_);
double* c_cont_npy_to_f_cont_double_ptr(int M, int N, PyObject* R_);

public:

PyKernelPCA(int n_components);

// overload KernelPCA::fit_transform
PyObject* fit_transform(PyObject* R, bool verbose);

};

boost::shared_ptr<PyKernelPCA> initWrapper(int n_components);


text:
import { Component, OnInit, ViewChild, ElementRef, Renderer } from '@angular/core';
import { LeafletMapService } from '../leaflet-map.service';
import * as L from 'leaflet';
import 'leaflet-measure/dist/leaflet-measure';

@Component({
  selector: 'app-leaflet-measure',
  templateUrl: './leaflet-measure.component.html',
  styleUrls: ['./leaflet-measure.component.sass']
})
export class LeafletMeasureComponent implements OnInit {
  public control: L.Control;

  @ViewChild('controlwrapper') controlWrapper: ElementRef;

  constructor(
    private _mapService: LeafletMapService,
    private _renderer: Renderer
  ) {}

  ngOnInit() {
    this.control = new (L as any).Control.Measure({
        primaryLengthUnit: 'kilometers',
        secondaryLengthUnit: 'meters',
        primaryAreaUnit: 'hectares',
        activeColor: '#ffffff',
        completedColor: '#ffffff'
    });

    this._mapService
      .getMap()
      .then((map: L.Map) => {
        const container = this.control.onAdd(map);

        // append the element container to the controlWrapper
        this._renderer.invokeElementMethod(this.controlWrapper.nativeElement, 'appendChild', [
          container
        ]);
      })
      ;
  }

}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace Twinder.Model
{
	public sealed class LikeSentModel
	{
		[JsonProperty("match")]
		[JsonConverter(typeof(MatchedConverter))]
		public MatchModel Match { get; set; }

		[JsonProperty("status")]
		public int Status { get; set; }

		/// <summary>
		/// Simple like was sent
		/// </summary>
		[JsonProperty("likes_remaining")]
		public int LikesRemainig { get; set; }

		/// <summary>
		/// Super like was sent
		/// </summary>
		[JsonProperty("super_likes")]
		public SuperLikesModel SuperLikes { get; set; }
	}

	public sealed class SuperLikesModel
	{
		[JsonProperty("remaining")]
		public int Remaining { get; set; }

		[JsonProperty("alc_remaining")]
		public int AlcRemaining { get; set; }

		[JsonProperty("new_alc_remaining")]
		public int NewAlcRemaining { get; set; }

		[JsonProperty("allotment")]
		public int Allotment { get; set; }

		[JsonProperty("superlike_refresh_amount")]
		public int SuperLikeRefreshAmount { get; set; }

		[JsonProperty("superlike_refresh_interval")]
		public int SuperLikeRefreshInteval { get; set; }

		[JsonProperty("superlike_refresh_interval_unit")]
		public string SuperLikeRefreshIntervalUnit { get; set; }

		[JsonProperty("resets_at")]
		public DateTime ResetsAt { get; set; }
	}

	/// <summary>
	/// Bool is returned when there's no match, <see cref="MatchModel"/> is returned when there is
	/// </summary>
	/// <typeparam name="T"></typeparam>
	internal class MatchedConverter : JsonConverter
	{
		public override bool CanConvert(Type objectType)
		{
			return (objectType == typeof(bool) || objectType == typeof(MatchModel));
		}

		public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			JToken token = JToken.Load(reader);
			// If it's not a match, it gives 'false', so basically it's a null
			if (token.Type == JTokenType.Boolean)
			{
				return null;
			}
			if (token.Type == JTokenType.Object)
			{
				return token.ToObject<MatchModel>();
			}
			return null;
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			serializer.Serialize(writer, value);
		}
	}
}


text:
package net.zephyrizing.http_server.middleware;

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

import net.zephyrizing.http_server.handlers.Handler;

public class Middlewares {
    public static Handler wrapWithAll(Handler handler, Middleware... wares) {
        Handler temp = handler;

        List<Middleware> middlewares = Arrays.asList(wares);
        Collections.reverse(middlewares);

        for(Middleware m : middlewares) {
            temp = m.wrap(temp);
        }

        return temp;
    }
}


text:
while true
do
while [ $(date +%H:%M) != "$1" ]; do
date +%H:%M
    sleep 1
done
echo "Testing build"
make check
echo "Bravo test results are attached." | mutt -a *.log -s "Bravo Test Results" -- mark1@helixport.com

sleep 61
done


text:
So you really want that One Last Cigarette, just the last one and it's over!?

This is just a momentary craving and you know you are stronger than this.

improve


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.github.nhirakawa</groupId>
    <artifactId>beanfs</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>beanfs-core</artifactId>

  <dependencies>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
  </dependencies>
</project>


text:
package world.action;

import world.Player;
import world.PlayerState;
import world.Point;
import world.Snowball;
import world.Team;
import world.World;

/**
 *
 * KNOW BUG: a snowball can explode on a player that is behind a very slim wall. this is because at each frame, I check the collisions with the players before...
 *
 * @author Mathieu Plourde - mat.plourde@gmail.com
 *
 */
public class ThrowAction extends Action {

	private Point _destination;
	private Player _player;

	private int _chargingFrames;

	private int _currentFrame = 0;

	private Snowball _snowball;

	private double _mX;
	private double _mY;
	private double _bX;
	private double _bY;

	private double _startX;
	private double _startY;

	private World _world;

	private double _distance;

	public Point getDestination()
	{
		return _destination;
	}

	public ThrowAction(int teamId, int playerId, Point destination)
	{
		super(teamId, playerId);
		this._destination = destination;

		this._toString = "t " + teamId + " " + playerId + " " + destination.getX() + " " + destination.getY();
	}

	public boolean initialize(World world)
	{
		if(!super.initialize(world))
		{
			return false;
		}
		append = "";
		if(_world == null)
		{
			_world = world;
			_player = world.getTeams()[_teamId].getPlayerById(_playerId);
			if(_player == null || _player.getPlayerState().getStateType() == PlayerState.StateType.Dead)
			{
				return false;
			}
			_startX = _player.getX();
			_startY = _player.getY();

			_distance = Math.sqrt(Math.pow(_destination.getX() - _startX, 2) + Math.pow(_destination.getY() - _startY, 2));

			if(_player.getHealth() <= 0 || _distance == 0 /* < OFFSET || _distance > MAXIMUM_DISTANCE*/)
			{
				// this is not permitted, it will hit the player
				return false;
			}

			double destX = -1;
			double destY = -1;
			if(_distance < MINIMUM_DISTANCE)
			{
				destX = (_destination.getX() - _startX) * (MINIMUM_DISTANCE / _distance) + _startX;
				destY = (_destination.getY() - _startY) * (MINIMUM_DISTANCE / _distance) + _startY;
			}
			else if(_distance > MAXIMUM_DISTANCE)
			{
				destX = (_destination.getX() - _startX) * (MAXIMUM_DISTANCE / _distance) + _startX;
				destY = (_destination.getY() - _startY) * (MAXIMUM_DISTANCE / _distance) + _startY;
			}

			// we need to offset the snowball, or else it will hit the player
			_startX = (_destination.getX() - _startX) * (OFFSET / _distance) + _startX;
			_startY = (_destination.getY() - _startY) * (OFFSET / _distance) + _startY;

			if(destX != -1)
			{
				_destination.setX(destX);
				_destination.setY(destY);
			}

			_mX = _destination.getX() - _startX;
			_mY = _destination.getY() - _startY;
			_bX = _startX;
			_bY = _startY;

			_distance = Math.sqrt(Math.pow(_destination.getX() - _startX, 2) + Math.pow(_destination.getY() - _startY, 2));

			if(_distance < MINIMUM_SPEED_DISTANCE)
			{
				_steps = _distance / (MINIMUM_SPEED_DISTANCE/STEPS_COUNT);
			}
			else if(_distance > MAXIMUM_SPEED_DISTANCE)
			{
				_steps = _distance / (MAXIMUM_SPEED_DISTANCE/STEPS_COUNT);
			}
			else
			{
				_steps = STEPS_COUNT;
			}

			// we compute the number of frames to "charge" depending of the distance
			// let's say it's 10 per frame
			_chargingFrames = (int) Math.round(_distance / CHARGING_FRAMES_DIVIDER);

			double dist = utilities.maths.Math.getEuclidianDistance(_player.getX(), _player.getY(), _destination.getX(), _destination.getY());
			_player.getOrientation().setX((_destination.getX() - _player.getX())/dist);
			_player.getOrientation().setY((_destination.getY() - _player.getY())/dist);
		}
		else
		{
			if(_snowball != null && !_snowball.isActive()/* || _player.getHealth() <= 0*/)
			{
				if(_snowball != null)
				{
					_snowball.setActive(false);
					//world.getSnowballs().remove(_snowball);
				}
				return false;
			}
		}

		return true;
	}

	private double _steps;

	private static double MAXIMUM_DISTANCE = 600;
	private static double MINIMUM_DISTANCE = 50;

	private static double MINIMUM_SPEED_DISTANCE = 100;
	private static double MAXIMUM_SPEED_DISTANCE = 400;
	private static double STEPS_COUNT = 20;

	private static double CHARGING_FRAMES_DIVIDER = 15;
	public static double MINIMUM_HIT_DISTANCE = 15;
	private static double OFFSET = 20;
	public static double DAMAGE_DIVIDER = 10;

	public boolean execute(World world)
	{
		super.execute(world);

		if(_currentFrame >= _chargingFrames)
		{
			//if the snowball doesn't exist, create it. if it does, make it move forward
			if(_snowball == null)
			{
				if(_playerId != -1 || _teamId != -1)
				{
					_player.getPlayerState().setCurrentAction(null);
					_player.getPlayerState().setStateType(PlayerState.StateType.Idle);
					append += " i " + _teamId + " " + _playerId;

					_playerId = -1;
					_teamId = -1;
				}

				int snowballId;
				if(_world.getSnowballs().size() > 0)
				{
					snowballId = _world.getSnowballs().get(_world.getSnowballs().size()-1).getId() + 1;
				}
				else
				{
					snowballId = 0;
				}
				_snowball = new Snowball(snowballId, _startX, _startY);
				_snowball.setDestination(_destination);
				_snowball.setDistancePerFrame(_distance / _steps);
				_snowball.setDamage(_distance / DAMAGE_DIVIDER);

				// add it to the world!!
				_world.getSnowballs().add(_snowball);
			}
			else
			{
				//move the snowball
				// x(t) = mx*t + bx
				double t = Math.min((_currentFrame - _chargingFrames)/_steps, 1.0);

				if(t <= 1)
				{
					double x0 = _snowball.getPoint().getX();
					double y0 = _snowball.getPoint().getY();
					_snowball.setX(t*_mX + _bX);
					_snowball.setY(t*_mY + _bY);

					Team[] teams = _world.getTeams();

					boolean hit = false;
					for(int i = 0; i < teams.length; i++)
					{
						Player[] players = teams[i].getPlayers();

						for(int j = 0; j < players.length; j++)
						{
							if(players[j].getPlayerState().getStateType() != PlayerState.StateType.Dead && utilities.maths.Math.getDistance(players[j].getX(), players[j].getY(), x0, y0, _snowball.getX(), _snowball.getY()) <= MINIMUM_HIT_DISTANCE)
							{
								players[j].setHealth(Math.max(0, players[j].getHealth() - _snowball.getDamage()));
								if(players[j].getHealth() == 0)
								{
									if(players[j].isFlagHolder())
									{
										players[j].setFlagHolder(false);
										world.getFlag().setHolder(null);
									}
									players[j].getPlayerState().setCurrentAction(null);
									players[j].getPlayerState().setStateType(PlayerState.StateType.Dead);
									append += " d " + players[j].getTeam().getId() + " " + players[j].getId();
								}

								hit = true;
							}
						}
					}

					if(hit || _world.getMap().isCrossingWall(x0,  y0, _snowball.getX(), _snowball.getY()))
					{
						_snowball.setActive(false);
						_world.getSnowballs().remove(_snowball);
						return true;
					}
				}

				if(t >= 1)
				{
					_snowball.setActive(false);
					_world.getSnowballs().remove(_snowball);
					return true;
				}
			}
		}
		else
		{
			_player.getPlayerState().setCurrentAction(this);
			_player.getPlayerState().setStateType(PlayerState.StateType.Throwing);
		}
		_currentFrame++;
		return false;
	}

	public int getRemainingFrames()
	{
		return _chargingFrames - _currentFrame;
	}

	//TODO: this. Or not??
	public Object clone() throws CloneNotSupportedException
	{
		return null;
	}

	private String append;

	public String toString()
	{
		if(_snowball == null)
		{
			// charging
			return "c " + _teamId + " " + _player.getId() + " " + _destination.getX() + " " + _destination.getY() + append;
		}
		else if(_snowball.isActive())
		{
			return "t " + _snowball.getId() + " " + _snowball.getX() + " " + _snowball.getY() + append;
		}
		else
		{
			return "r " + _snowball.getId() + append;
		}
	}
}


text:
using namespace std;

int main( const int argc, const char* const argv[])
{
    cout << "Welcome to UW Engineering, " << argv[1] << endl;

    // add a line of code to output the second command-line argument (argv[2])

    // add a line of code to output the content of argc

    // add a line of code to explain what is stored in argc

    return 0;
}


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
# require 'rspec/autorun'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
# Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
Dir[Rails.root.join('spec/helpers/*.rb')].each {|f| require f}

RSpec.configure do |config|

  config.include FactoryGirl::Syntax::Methods
  config.include Mongoid::Matchers, type: :model

  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  # config.use_transactional_fixtures = true

  # If true, the base class of anonymous controllers will be inferred
  # automatically. This will be the default behavior in future versions of
  # rspec-rails.
  config.infer_base_class_for_anonymous_controllers = false

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = "random"

  # Rspec 3 no longer automatically infers an example group's spec type from the file location.
  #  This turns the behavior back on.
  # Otherwise you will need to manually label spec types
  config.infer_spec_type_from_file_location!

  config.before(:each) do
    Mongoid::Sessions.default.collections.select {|c| c.name !~ /system/ }.each(&:drop)
    FactoryGirl.lint
  end
end


text:
package conexao;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Conexao {
	public static void main(String[] args) throws SQLException {
		// Criando conexão com a base de dados
		Connection con = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/testes", "root", "root");

		// O "ResultSet" recebe um resultado e o organiza, permitindo
		// reaver os dados linha por linha um a um
		ResultSet rs = con.getMetaData().getTables(null, null, null,
				new String[] { "TABLE" });
		while (rs.next()) { // enquanto houver linhas de resultado, pegue a
							// próxima.
			// Recebe os resultados da coluna TABLE_NAME
			System.out.println(rs.getString("TABLE_NAME"));
		}

		// Finaliza a conexão com a base de dados
		con.close();
	}
}


text:
package com.intellij.util.indexing.impl;

import com.intellij.util.indexing.ValueContainer;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;

@ApiStatus.Experimental
public interface InvertedIndexValueIterator<Value> extends ValueContainer.ValueIterator<Value> {
  @Override
  @NotNull
  ValueContainer.IntPredicate getValueAssociationPredicate();

  Object getFileSetObject();
}


text:
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>

<link href="doc-style.css" type="text/css" rel="StyleSheet">

		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods

Data Object - PhysicalNicLinkInfo

Property of

PhysicalNic, PhysicalNicSpec

Parameter to

UpdatePhysicalNicLinkSpeed

Extends

DynamicData

Data Object
                  Description

         The PhysicalNicLinkInfo data object describes
  the link speed and the type of duplex communication.  The link speed indicates
  the bit rate in megabits per second.  The duplex boolean indicates if the link
  is capable of full-duplex or half-duplex communication.

Properties

	          Name

	          Type

	          Description

duplex	xsd:boolean

         Flag to indicate whether or not the link is capable of
  full-duplex ("true") or only half-duplex ("false").

speedMb	xsd:int

         Bit rate on the link.

						Properties inherited from DynamicData

dynamicProperty, dynamicType

Show WSDL type definition

<textarea cols="20" rows="10" name="wsdl-textarea" wrap="off" readonly="1" id="wsdl-textarea">         <complexType xmlns="http://www.w3.org/2001/XMLSchema" xmlns:vim25="urn:vim25" name="PhysicalNicLinkInfo">
            <complexContent>
               <extension base="vim25:DynamicData">
                  <sequence>
                     <element name="speedMb" type="xsd:int"/>
                     <element name="duplex" type="xsd:boolean"/>
                  </sequence>
               </extension>
            </complexContent>
         </complexType></textarea>

Top of page		Local Properties

Managed Object Types	Data Object Types	All Properties	All Methods


text:
package com.sega.vimarket.Transformers;

import android.view.View;

import com.nineoldandroids.view.ViewHelper;

public class DepthPageTransformer extends BaseTransformer {

	private static final float MIN_SCALE = 0.75f;

	@Override
	protected void onTransform(View view, float position) {
		if (position <= 0f) {
            ViewHelper.setTranslationX(view,0f);
            ViewHelper.setScaleX(view,1f);
            ViewHelper.setScaleY(view,1f);
		} else if (position <= 1f) {
			final float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position));
            ViewHelper.setAlpha(view,1-position);
            ViewHelper.setPivotY(view,0.5f * view.getHeight());
            ViewHelper.setTranslationX(view,view.getWidth() * - position);
            ViewHelper.setScaleX(view,scaleFactor);
            ViewHelper.setScaleY(view,scaleFactor);
		}
	}

	@Override
	protected boolean isPagingEnabled() {
		return true;
	}

}


text:
if Rails.env.production?
  Raven.configure do |config|
    config.dsn = ENV.fetch('SENTRY_DSN')
    config.sanitize_fields = Rails.application.config.filter_parameters.map(&:to_s)
  end

  # Notify Sentry of a new release.
  Net::HTTP.post(
    URI.parse(ENV.fetch('SENTRY_RELEASE_WEBHOOK')),
    { 'version' => File.read('REVISION').strip }.to_json,
    'Content-Type' => 'application/json'
  )
end


text:
"""
Series-related oxml objects.
"""

from __future__ import absolute_import, print_function, unicode_literals

from .datalabel import CT_DLbls
from ..simpletypes import XsdUnsignedInt
from ..xmlchemy import (
    BaseOxmlElement,
    OneAndOnlyOne,
    OxmlElement,
    RequiredAttribute,
    ZeroOrMore,
    ZeroOrOne,
)

class CT_AxDataSource(BaseOxmlElement):
    """
    ``<c:cat>`` custom element class used in category charts to specify
    category labels and hierarchy.
    """

    multiLvlStrRef = ZeroOrOne("c:multiLvlStrRef", successors=())

    @property
    def lvls(self):
        """
        Return a list containing the `c:lvl` descendent elements in document
        order. These will only be present when the required single child
        is a `c:multiLvlStrRef` element. Returns an empty list when no
        `c:lvl` descendent elements are present.
        """
        return self.xpath(".//c:lvl")

class CT_DPt(BaseOxmlElement):
    """
    ``<c:dPt>`` custom element class, containing visual properties for a data
    point.
    """

    _tag_seq = (
        "c:idx",
        "c:invertIfNegative",
        "c:marker",
        "c:bubble3D",
        "c:explosion",
        "c:spPr",
        "c:pictureOptions",
        "c:extLst",
    )
    idx = OneAndOnlyOne("c:idx")
    marker = ZeroOrOne("c:marker", successors=_tag_seq[3:])
    spPr = ZeroOrOne("c:spPr", successors=_tag_seq[6:])
    del _tag_seq

    @classmethod
    def new_dPt(cls):
        """
        Return a newly created "loose" `c:dPt` element containing its default
        subtree.
        """
        dPt = OxmlElement("c:dPt")
        dPt.append(OxmlElement("c:idx"))
        return dPt

class CT_Lvl(BaseOxmlElement):
    """
    ``<c:lvl>`` custom element class used in multi-level categories to
    specify a level of hierarchy.
    """

    pt = ZeroOrMore("c:pt", successors=())

class CT_NumDataSource(BaseOxmlElement):
    """
    ``<c:yVal>`` custom element class used in XY and bubble charts, and
    perhaps others.
    """

    numRef = OneAndOnlyOne("c:numRef")

    @property
    def ptCount_val(self):
        """
        Return the value of `./c:numRef/c:numCache/c:ptCount/@val`,
        specifying how many `c:pt` elements are in this numeric data cache.
        Returns 0 if no `c:ptCount` element is present, as this is the least
        disruptive way to degrade when no cached point data is available.
        This situation is not expected, but is valid according to the schema.
        """
        results = self.xpath(".//c:ptCount/@val")
        return int(results[0]) if results else 0

    def pt_v(self, idx):
        """
        Return the Y value for data point *idx* in this cache, or None if no
        value is present for that data point.
        """
        results = self.xpath(".//c:pt[@idx=%d]" % idx)
        return results[0].value if results else None

class CT_SeriesComposite(BaseOxmlElement):
    """
    ``<c:ser>`` custom element class. Note there are several different series
    element types in the schema, such as ``CT_LineSer`` and ``CT_BarSer``,
    but they all share the same tag name. This class acts as a composite and
    depends on the caller not to do anything invalid for a series belonging
    to a particular plot type.
    """

    _tag_seq = (
        "c:idx",
        "c:order",
        "c:tx",
        "c:spPr",
        "c:invertIfNegative",
        "c:pictureOptions",
        "c:marker",
        "c:explosion",
        "c:dPt",
        "c:dLbls",
        "c:trendline",
        "c:errBars",
        "c:cat",
        "c:val",
        "c:xVal",
        "c:yVal",
        "c:shape",
        "c:smooth",
        "c:bubbleSize",
        "c:bubble3D",
        "c:extLst",
    )
    idx = OneAndOnlyOne("c:idx")
    order = OneAndOnlyOne("c:order")
    tx = ZeroOrOne("c:tx", successors=_tag_seq[3:])
    spPr = ZeroOrOne("c:spPr", successors=_tag_seq[4:])
    invertIfNegative = ZeroOrOne("c:invertIfNegative", successors=_tag_seq[5:])
    marker = ZeroOrOne("c:marker", successors=_tag_seq[7:])
    dPt = ZeroOrMore("c:dPt", successors=_tag_seq[9:])
    dLbls = ZeroOrOne("c:dLbls", successors=_tag_seq[10:])
    cat = ZeroOrOne("c:cat", successors=_tag_seq[13:])
    val = ZeroOrOne("c:val", successors=_tag_seq[14:])
    xVal = ZeroOrOne("c:xVal", successors=_tag_seq[15:])
    yVal = ZeroOrOne("c:yVal", successors=_tag_seq[16:])
    smooth = ZeroOrOne("c:smooth", successors=_tag_seq[18:])
    bubbleSize = ZeroOrOne("c:bubbleSize", successors=_tag_seq[19:])
    del _tag_seq

    @property
    def bubbleSize_ptCount_val(self):
        """
        Return the number of bubble size values as reflected in the `val`
        attribute of `./c:bubbleSize//c:ptCount`, or 0 if not present.
        """
        vals = self.xpath("./c:bubbleSize//c:ptCount/@val")
        if not vals:
            return 0
        return int(vals[0])

    @property
    def cat_ptCount_val(self):
        """
        Return the number of categories as reflected in the `val` attribute
        of `./c:cat//c:ptCount`, or 0 if not present.
        """
        vals = self.xpath("./c:cat//c:ptCount/@val")
        if not vals:
            return 0
        return int(vals[0])

    def get_dLbl(self, idx):
        """
        Return the `c:dLbl` element representing the label for the data point
        at offset *idx* in this series, or |None| if not present.
        """
        dLbls = self.dLbls
        if dLbls is None:
            return None
        return dLbls.get_dLbl_for_point(idx)

    def get_or_add_dLbl(self, idx):
        """
        Return the `c:dLbl` element representing the label of the point at
        offset *idx* in this series, newly created if not yet present.
        """
        dLbls = self.get_or_add_dLbls()
        return dLbls.get_or_add_dLbl_for_point(idx)

    def get_or_add_dPt_for_point(self, idx):
        """
        Return the `c:dPt` child representing the visual properties of the
        data point at index *idx*.
        """
        matches = self.xpath('c:dPt[c:idx[@val="%d"]]' % idx)
        if matches:
            return matches[0]
        dPt = self._add_dPt()
        dPt.idx.val = idx
        return dPt

    @property
    def xVal_ptCount_val(self):
        """
        Return the number of X values as reflected in the `val` attribute of
        `./c:xVal//c:ptCount`, or 0 if not present.
        """
        vals = self.xpath("./c:xVal//c:ptCount/@val")
        if not vals:
            return 0
        return int(vals[0])

    @property
    def yVal_ptCount_val(self):
        """
        Return the number of Y values as reflected in the `val` attribute of
        `./c:yVal//c:ptCount`, or 0 if not present.
        """
        vals = self.xpath("./c:yVal//c:ptCount/@val")
        if not vals:
            return 0
        return int(vals[0])

    def _new_dLbls(self):
        """Override metaclass method that creates `c:dLbls` element."""
        return CT_DLbls.new_dLbls()

    def _new_dPt(self):
        """
        Overrides the metaclass generated method to get `c:dPt` with minimal
        subtree.
        """
        return CT_DPt.new_dPt()

class CT_StrVal_NumVal_Composite(BaseOxmlElement):
    """
    ``<c:pt>`` element, can be either CT_StrVal or CT_NumVal complex type.
    Using this class for both, differentiating as needed.
    """

    v = OneAndOnlyOne("c:v")
    idx = RequiredAttribute("idx", XsdUnsignedInt)

    @property
    def value(self):
        """
        The float value of the text in the required ``<c:v>`` child.
        """
        return float(self.v.text)


text:
@interface VCETabBarViewController : UITabBarController

@end


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.feature.vt.gui.task;

import ghidra.feature.vt.api.db.VTSessionDB;
import ghidra.feature.vt.api.main.*;
import ghidra.util.Msg;
import ghidra.util.exception.CancelledException;
import ghidra.util.task.Task;
import ghidra.util.task.TaskMonitor;

import java.util.List;

public class SetMarkupItemConsideredTask extends Task {

	protected final List<VTMarkupItem> markupItems;
	private final VTSessionDB session;
	protected final VTMarkupItemConsideredStatus status;

	public SetMarkupItemConsideredTask(VTSession session, List<VTMarkupItem> markupItems,
			VTMarkupItemConsideredStatus status) {
		this(status.name() + " Markup Items", session, markupItems, status);
	}

	protected SetMarkupItemConsideredTask(String title, VTSession session,
			List<VTMarkupItem> markupItems, VTMarkupItemConsideredStatus status) {
		super(title, true, true, true, true);
		this.markupItems = markupItems;

		if (!(session instanceof VTSessionDB)) {
			throw new IllegalArgumentException(
				"Unexpected condition - VTSession is not a DB object!");
		}

		this.session = (VTSessionDB) session;
		this.status = status;
	}

	@Override
	public void run(TaskMonitor monitor) {

		boolean commit = true;

		int matchSetTransactionID = session.startTransaction(getTaskTitle());
		try {
			doWork(monitor);
		}
		catch (CancelledException e) {
			commit = false;
		}
		catch (Exception e) {
			commit = false;
			Msg.showError(this, null, "Unable to Apply Markup Item(s)",
				"An unexpected error occurred attempting to apply markup item(s).", e);
		}
		finally {
			session.endTransaction(matchSetTransactionID, commit);
		}
	}

	protected void doWork(TaskMonitor monitor) throws Exception, CancelledException {
		monitor.initialize(markupItems.size());
		for (VTMarkupItem markupItem : markupItems) {
			monitor.checkCanceled();
			markupItem.setConsidered(status);
			monitor.incrementProgress(1);
		}
	}
}


text:
brontide
==========

[![Build Status](http://img.shields.io/travis/lightningnetwork/lnd.svg)](https://travis-ci.org/lightningnetwork/lnd)
[![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/lightningnetwork/lnd/blob/master/LICENSE)
[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)](http://godoc.org/github.com/lightningnetwork/lnd/brontide)

The brontide package implements a secure crypto messaging protocol based off of
the [Noise Protocol Framework](http://noiseprotocol.org/noise.html). The
package exposes the raw state machine that handles the handshake and subsequent
message encryption/decryption scheme. Additionally, the package exposes a
[net.Conn](https://golang.org/pkg/net/#Conn) and a
[net.Listener](https://golang.org/pkg/net/#Listener) interface implementation
which allows the encrypted transport to be seamlessly integrated into a
codebase.

The secure messaging scheme implemented within this package is described in
detail in [BOLT #8 of the Lightning Network specifications](https://github.com/lightningnetwork/lightning-rfc/blob/master/08-transport.md).

This package has intentionally been designed so it can be used as a standalone
package for any projects needing secure encrypted+authenticated communications
between network enabled programs.

## Installation and Updating

```bash
$ go get -u github.com/lightningnetwork/lnd/brontide
```


text:
<?php

/*
 * Place any startup code that your application needs here.
 */


text: saxon func.xml ../style/module.xsl


text:
DIST=/vagrant/shared/${ALLUXIO_DIST}
tar xzf ${DIST} -C /alluxio --strip-components 1


text:
VOCABLENGTH = 6000

import csv, sys
import numpy as np
import pandas as pd
import math
# from random import shuffle
# from random import random as randomprob
from sklearn.linear_model import LinearRegression
from collections import Counter

csv.field_size_limit(sys.maxsize)

# Let's load some metadata about the publication dates of these works,
# and the inferred genders of their authors.

personalnames = set()
with open("/Users/tunder/Dropbox/booknlpscripts/PersonalNames.txt", encoding="utf-8") as f:
    names = f.readlines()

for line in names:
    name = line.rstrip()
    personalnames.add(name)
    personalnames.add('said-' + name)

vocab = Counter()

def add2vocab(vocab, filepath):
    with open(filepath, encoding = 'utf-8') as f:
        reader = csv.DictReader(f, delimiter = '\t')
        for row in reader:
            words = row['words'].split()
            for w in words:
                if not w.startswith('said-') and w not in personalnames:
                    vocab[w] += 1

add2vocab(vocab, '../data/chartable18c19c.tsv')
add2vocab(vocab, '../data/chartablepost1900.tsv')

vocabcount = len(vocab)
print("The data includes " + str(vocabcount) + " words")

wordsinorder = [x[0] for x in vocab.most_common(VOCABLENGTH)]

vocabulary = dict()
vocabset = set()

for idx, word in enumerate(wordsinorder):
    vocabulary[word] = idx
    vocabset.add(word)
print("Vocabulary sorted, top " + str(VOCABLENGTH) + " kept.")

vecbyyear = dict()
vecbyyear['m'] = dict()
vecbyyear['f'] = dict()
datevector = list(range(1780, 2008))

for g in ['f', 'm']:
    for i in range(1780, 2008):
        vecbyyear[g][i] = np.zeros((VOCABLENGTH))

def add2counts(vecbyyear, path):
    with open(path, encoding = 'utf-8') as f:
        reader = csv.DictReader(f, delimiter = '\t')
        for row in reader:
            gender = row['gender']

            if gender.startswith('u'):
                continue

            date = int(row['pubdate'])
            if date < 1780 or date > 2008:
                continue

            words = row['words'].split()
            for w in words:
                if w in vocabset:
                    idx = vocabulary[w]
                    np.add.at(vecbyyear[gender][date], idx, 1)

add2counts(vecbyyear, '../data/chartable18c19c.tsv')
add2counts(vecbyyear, '../data/chartablepost1900.tsv')

def dunnings(vectora, vectorb):
    assert len(vectora) == len(vectorb)
    veclen = len(vectora)
    totala = np.sum(vectora)
    totalb = np.sum(vectorb)
    totalboth = totala + totalb

    dunningvector = np.zeros(veclen)

    for i in range(veclen):
        if vectora[i] == 0 or vectorb[i] == 0:
            continue
            # Cause you know you're going to get div0 errors.

        try:
            probI = (vectora[i] + vectorb[i]) / totalboth
            probnotI = 1 - probI
            expectedIA = totala * probI
            expectedIB = totalb * probI
            expectedNotIA = totala * probnotI
            expectedNotIB = totalb * probnotI
            expected_table = np.array([[expectedIA, expectedNotIA],
                [expectedIB, expectedNotIB]])
            actual_table = np.array([[vectora[i], (totala - vectora[i])],
                [vectorb[i], (totalb - vectorb[i])]])
            G = np.sum(actual_table * np.log(actual_table / expected_table))

            # We're going to use a signed version of Dunnings, so features where
            # B is higher than expected will be negative.

            if expectedIB > vectorb[i]:
                G = -G

            dunningvector[i] = G

        except:
            pass
            # There are a million ways to get a div-by-zero or log-zero error
            # in that calculation. I could check them all, or just do this.
            # The vector was initialized with zeroes, which are the default
            # value I want for failed calculations anyhow.

    return dunningvector

def pure_rank_matrix(femalevectorsbyyear, malevectorsbyyear, datevector):
    rankmatrix = []
    magnitudematrix = []

    for i in datevector:
        d = dunnings(femalevectorsbyyear[i], malevectorsbyyear[i])

        # transform this into a nonparametric ranking
        decorated = [x for x in zip(d, [x for x in range(len(d))])]
        decorated.sort()

        negativeidx = -sum(d < 0)
        positiveidx = 1

        numzeros = sum(d == 0)

        ranking = np.zeros(len(d))
        for dvalue, index in decorated:
            # to understand what follows, it's crucial to remember that
            # we're iterating through decorated in dvalue order

            if dvalue < 0:
                ranking[index] = negativeidx
                negativeidx += 1
            elif dvalue > 0:
                ranking[index] = positiveidx
                positiveidx += 1
            else:
                # dvalue is zero
                pass

        checkzeros = sum(ranking == 0)
        if numzeros != checkzeros:
            print('error in number of zeros')

        rawmagnitude = femalevectorsbyyear[i] + malevectorsbyyear[i]
        normalizedmagnitude = rawmagnitude / np.sum(rawmagnitude)
        assert len(ranking) == len(normalizedmagnitude)
        rank_adjusted_by_magnitude = ranking * normalizedmagnitude

        rankmatrix.append(ranking)
        magnitudematrix.append(rank_adjusted_by_magnitude)

    return np.array(magnitudematrix), np.array(rankmatrix)

def diff_proportion(vecbyyear, datevector):
    diffmatrix = []

    for yr in datevector:
        mvec = (vecbyyear['m'][yr] * 5000) / np.sum(vecbyyear['m'][yr])
        fvec = (vecbyyear['f'][yr] * 5000) / np.sum(vecbyyear['f'][yr])
        dvec = fvec - mvec
        diffmatrix.append(dvec)

    return np.array(diffmatrix)

def normalized_dunning_matrix(femalevectorsbyyear, malevectorsbyyear, datevector):
    dmatrix = []

    for yr in datevector:
        mvec = (malevectorsbyyear[yr] * 10000) / np.sum(malevectorsbyyear[yr])
        fvec = (femalevectorsbyyear[yr] * 10000) / np.sum(femalevectorsbyyear[yr])
        dvec = dunnings(mvec, fvec)
        dmatrix.append(dvec)

    return np.array(dmatrix)

def ratio_matrix(femalevectorsbyyear, malevectorsbyyear, datevector):
    global wordsinorder
    rmatrix = []
    vlen = len(femalevectorsbyyear[1850])

    for yr in datevector:
        mvec = (malevectorsbyyear[yr] * 1000) / np.sum(malevectorsbyyear[yr])
        fvec = (femalevectorsbyyear[yr] * 1000) / np.sum(femalevectorsbyyear[yr])
        rvec = np.zeros(vlen)
        for i in range(vlen):
            if mvec[i] == 0 or fvec[i] == 0:
                continue
                # let it stay zero
            else:
                try:
                    rvec[i] = math.log((fvec[i] + 0.0001) / (mvec[i] + 0.001))
                except:
                    print(yr, fvec[i], mvec[i], wordsinorder[i])
        rmatrix.append(rvec)

    return np.array(rmatrix)

diffmatrix = diff_proportion(vecbyyear, datevector)

def writematrix(amatrix, outpath):
    global wordsinorder, datevector

    with open(outpath, mode = 'w', encoding = 'utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['thedate'] + wordsinorder)
        for i, date in enumerate(datevector):
            writer.writerow(np.insert(amatrix[i, : ], 0, date))

# writematrix(relative_freq_matrix, '../results/relativewordfreqs.csv')
writematrix(diffmatrix, '../dataforR/speechlessdiffmatrix.csv')
# writematrix(ratiomatrix, '../results/ratiomatrix.csv')
# writematrix(normaldunnings, '../results/dunningmatrix.csv')

# def magnitude_times_rank(femalevectorsbyyear, malevectorsbyyear, datevector):
#     dmatrix = []

#     for yr in datevector:
#         d = dunnings(femalevectorsbyyear[yr], malevectorsbyyear[yr])
#         rawmagnitude = femalevectorsbyyear[yr] + malevectorsbyyear[yr]
#         normalizedmagnitude = rawmagnitude / np.sum(rawmagnitude)

#         d = dunnings(femalevectorsbyyear[yr], malevectorsbyyear[yr])
#         normalized_d = d / np.sum(abs(d))

#         assert len(d) == len(rawmagnitude)
#         mtr = d * rawmagnitude
#         dmatrix.append(mtr)

#     return np.array(dmatrix)

# dunningmatrix, rankmatrix = pure_rank_matrix(femalevectorsbyyear, malevectorsbyyear, datevector)

print('Linear regression to infer slopes.')
datevector = np.array(datevector)
outrows = []
for i in range(VOCABLENGTH):
    thiscolumn = diffmatrix[ : , [i]]
    # note: the brackets around i extract it as a *column* rather than row

    notmissing = thiscolumn != 0
    # still a column

    y = thiscolumn[notmissing].transpose()

    # that's a cheap hack to create an array w/ more than one column,
    # which the linear regression seems to want

    x = datevector[notmissing.transpose()[0]]
    # We have to transpose the column "notmissing" to index a row.

    x = x[ : , np.newaxis]
    # Then we have to make x a row of an array with two
    # dimensions (even though it only has one row).

    vectorlen = len(x)

    word = wordsinorder[i]

    model = LinearRegression()

    model.fit(x, y)
    slope = model.coef_[0]
    intercept = model.intercept_
    standard_deviation = np.std(y)

    nineteenth = np.mean(thiscolumn[0:120])
    twentieth =np.mean(thiscolumn[120:])
    change = twentieth - nineteenth

    approachmid = abs(np.nanmean(thiscolumn[0:60])) - abs(np.nanmean(thiscolumn[150:210]))
    approachstd = approachmid / standard_deviation

    # note that it's important we use thiscolumn rather than y here, because y has been reduced
    # in length

    out = dict()
    out['word'] = word
    out['slope'] = slope
    out['mean'] = np.mean(thiscolumn)
    out['intercept'] = intercept
    out['change'] = change
    out['approachmid'] = approachmid
    out['approachstd'] = approachstd
    outrows.append(out)

with open('../dataforR/speechlessdiffslopes.csv', mode = 'w', encoding = 'utf-8') as f:
    writer = csv.DictWriter(f, fieldnames = ['word', 'slope', 'mean', 'intercept', 'change', 'approachmid', 'approachstd'])
    writer.writeheader()
    for row in outrows:
        writer.writerow(row)

# print('Writing results ...')
# with open('../results/magdunnings.csv', mode = 'w', encoding = 'utf-8') as f:
#     writer = csv.writer(f)
#     writer.writerow(wordsinorder)
#     for i in range(datecount):
#         thisrow = ['NA'] * VOCABLENGTH
#         for j in range(VOCABLENGTH):
#             thisval = dunningmatrix[i, j]
#             if thisval < - 0.00001 or thisval > 0.00001:
#                 thisrow[j] = thisval
#         writer.writerow(thisrow)

# print('Writing results ...')
# with open('../results/rawdunnings.csv', mode = 'w', encoding = 'utf-8') as f:
#     writer = csv.writer(f)
#     writer.writerow(wordsinorder)

#     rowsums = np.sum(abs(rankmatrix), axis = 1) / 3123750
#     # rescaled so that max should be ±2500

#     for i in range(datecount):
#         thisrow = ['NA'] * VOCABLENGTH
#         for j in range(VOCABLENGTH):
#             thisval = rankmatrix[i, j] / rowsums[i]
#             if thisval < -0.0001 or thisval > 0.0001:
#                 thisrow[j] = thisval
#         writer.writerow(thisrow)