text:
<file_sep># spanish-rap
El mayor vocabulario del rap español
<file_sep>var margin = { top: 30, right: 20, bottom: 30, left: 40 },
    width = parseInt(d3.select('.grafico').style('width'), 10),
    width = width - margin.left - margin.right,
    height = 420 - margin.top - margin.bottom,
    radio = 7;

var xScaleScaler = d3.scale.linear()
    .range([0, width]);

var yScaleScaler = d3.scale.linear()
    .range([height, 0]);

var xScaleBar = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var yScaleBar = d3.scale.linear()
    .range([height, 0]);

///////////////////////////////////////////////

var xAxisScaler = d3.svg.axis()
    .scale(xScaleScaler)
    .orient("bottom");

var yAxisScaler = d3.svg.axis()
    .scale(yScaleScaler)
    .orient("left");

/* var xAxisBar = d3.svg.axis()
    .scale(xScaleBar)
    .orient("bottom"); */

var yAxisBar = d3.svg.axis()
    .scale(yScaleBar)
    .orient("left")
    .tickFormat(d3.format(".0%"))
    .ticks(10);

///////////////////////////////////////////////

var svgscaler = d3.select("#scalerplot").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var svgbar = d3.select("#barplot").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var patterns = svgscaler.append('svg:defs');

d3.csv("/static/projects/hiphop/data/ArtistasH_all.csv", function(error, data) {
    data.forEach(function(d) {
        d.PUnica = +d.PUnica;
        d.PUnica20 = +d.PUnica20;
        d.PTotal = +d.PTotal;
    });

    function linearRegression(y, x) {
        var lr = {};
        var n = y.length;
        var sum_x = 0;
        var sum_y = 0;
        var sum_xy = 0;
        var sum_xx = 0;
        var sum_yy = 0;

        for (var i = 0; i < y.length; i++) {
            sum_x += x[i];
            sum_y += y[i];
            sum_xy += (x[i] * y[i]);
            sum_xx += (x[i] * x[i]);
            sum_yy += (y[i] * y[i]);
        }

        lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
        lr['intercept'] = (sum_y - lr.slope * sum_x) / n;
        lr['r2'] = Math.pow((n * sum_xy - sum_x * sum_y) / Math.sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y)), 2);

        return lr;
    }

    function mediaRegression(y, x) {
        var media = {};
        var sum_x = 0;
        var sum_y = 0;
        var n = y.length;

        for (var i = 0; i < y.length; i++) {
            sum_x += x[i];
            sum_y += y[i];
        }

        media['x'] = sum_x / n;
        media['y'] = sum_y / n;
        return media;
    }

    var known_y = data.map(function(d) {
        return parseFloat(d.PUnica);
    });
    var known_x = data.map(function(d) {
        return parseFloat(d.PTotal);
    });
    var known_y20 = data.map(function(d) {
        return parseFloat(d.PUnica / d.PTotal);
    });
    var lr = linearRegression(known_y, known_x);
    var max = d3.max(data, function(d) {
        return d.PTotal;
    });
    var media = mediaRegression(known_y, known_x)
    var media20 = mediaRegression(known_y20, known_x)

    xScaleScaler.domain([0, d3.max(data, function(d) {
        return d.PTotal;
    })]);
    yScaleScaler.domain([0, d3.max(data, function(d) {
        return d.PUnica;
    })]);
    //xScaleBar.domain(data.map(function(d) { return d.ID; }));
    yScaleBar.domain([0, d3.max(data, function(d) {
        return d.PUnica / d.PTotal;
    })]);

    var x0 = xScaleBar.domain(data.sort(function(a, b) {
                return (b.PUnica / b.PTotal) - (a.PUnica / a.PTotal);
            })
            .map(function(d) {
                return d.PUnica / d.PTotal;
            }))
        .copy();

    svgscaler.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxisScaler)
        .append("text")
        .attr("class", "label")
        .attr("x", width)
        .attr("y", -6)
        .attr("text-anchor", "end")
        .text("Palabras totales");

    svgscaler.append("g")
        .attr("class", "y axis")
        .call(yAxisScaler)
        .append("text")
        .attr("class", "label")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Palabras Ãºnicas")

    // BAR RECTANGULOS
    svgbar.append("g").selectAll(".bar")
        .data(data)
        .enter()
        .append("rect")
        .attr('class', function(d) {
            return 'bar' + d.Region + ' barrect';
        })
        .attr("height", function(d) {
            return height - yScaleBar(d.PUnica / d.PTotal);
        })
        .attr("width", xScaleBar.rangeBand())
        .attr("y", function(d) {
            return yScaleBar(d.PUnica / d.PTotal);
        })
        .attr("x", function(d) {
            return x0(d.PUnica / d.PTotal);
        });

    // BAR NOMBRE GRUPOS
    svgbar.selectAll(".text")
        .data(data)
        .enter()
        .append("text")
        .attr("class", "bartext")
        .attr("transform", function(d, i) {
            return "translate(" + (((xScaleBar.rangeBand() / 2) + 3) + x0(d.PUnica / d.PTotal)) + ", " + (height - 4) + ")" + "rotate(-90)";
        })
        .text(function(d) {
            return d.Cantante;
        })

    // BAR LINEA MEDIA
    svgbar.append('line')
        .attr("x1", 0)
        .attr("y1", yScaleBar(media20['y']))
        .attr("x2", width)
        .attr("y2", yScaleBar(media20['y']))
        .attr("class", "regressionline");

    // BAR LINEA MEDIA TEXTO
    var mediatextbar = svgbar.append("text")
        .attr("class", "textaxis")
        .attr("y", yScaleBar(media20['y']) - 12)
        .attr("x", width)
        .attr("dy", ".71em")
        .style("text-anchor", "end");

    mediatextbar.append('tspan').text('MEDIA:');
    mediatextbar.append('tspan').attr('dx', 10).attr("class", "quijoaxis").text(d3.round(media20['y'] * 100, 2));
    mediatextbar.append('tspan').attr("class", "quijoaxis").text('%');
    mediatextbar.append('tspan').text(' PALABRAS ÃšNICAS');

    // BAR Y AXIS
    svgbar.append("g")
        .attr("class", "y axis")
        .call(yAxisBar)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("% Ãºnicas/totales");

    patterns.append('defs').selectAll("pattern")
        .data(data)
        .enter()
        .append("pattern")
        .attr("id", function(d) {
            return d.ID + "pqn";
        })
        .attr("width", radio * 2)
        .attr("height", radio * 2)
        .attr("patternUnits", "objectBoundingBox")
        .append("image")
        .attr("xlink:href", function(d) {
            return '/static/projects/hiphop/img/' + d.ID + '.jpg';
        })
        .attr("width", radio * 2).attr("height", radio * 2).attr("x", 0).attr("y", 0);

    svgscaler.append("g").append("line")
        .attr("x1", xScaleScaler(0))
        .attr("y1", yScaleScaler(lr.intercept))
        .attr("x2", xScaleScaler(max))
        .attr("y2", yScaleScaler((max * lr.slope) + lr.intercept))
        .attr("class", "regressionline");

    var mediatext = svgscaler.append("g").append("text")
        .attr("class", "textaxis")
        .attr("y", height - 28)
        .attr("x", width)
        .attr("dy", ".71em")
        .style("text-anchor", "end");

    mediatext.append('tspan').text('MEDIA:');
    mediatext.append('tspan').attr('dx', 10).attr("class", "quijoaxis").text(d3.round(media['x']));
    mediatext.append('tspan').text(' P. TOTALES');
    mediatext.append('tspan').attr('dx', 10).attr("class", "quijoaxis").text(d3.round(media['y']));
    mediatext.append('tspan').text(' P. ÃšNICAS');
    mediatext.append('tspan').attr('dx', 10).attr("class", "quijoaxis").text(d3.round(media['y'] / media['x'], 3));
    mediatext.append('tspan').text(' P. ÃšNICAS/TOTALES');

    svgscaler.selectAll(".dot")
        .data(data)
        .enter().append("circle")
        .attr("class", function(d) {
            return d.Region + ' rapper-circle';
        })
        .attr("r", radio)
        .attr("cx", function(d) {
            return xScaleScaler(d.PTotal);
        })
        .attr("cy", function(d) {
            return yScaleScaler(d.PUnica);
        })
        .style("fill", function(d) {
            return "url(#" + d.ID + "pqn)";
        })
        .on("mouseover", function(d) {
            var coordinates = [0, 0];
            coordinates = d3.mouse(this);
            var x = coordinates[0];
            var y = coordinates[1];
            d3.select(".tooltipscaler")
                .style("left", x + "px")
                .style("top", y + "px")
                .style("margin-top", "160px")
                .select("#value")
                .text(d.PUnica);
            d3.select(".tooltipscaler")
                .select("#rapper")
                .text(d.Cantante);
            d3.select(".tooltipscaler")
                .select("#value2")
                .text(d.PTotal);
            d3.select(".tooltipscaler").classed("hidden", false);
        })

    .on("mouseout", function() {
        d3.select(".tooltipscaler").classed("hidden", true);
    })

    var legend = svgscaler.selectAll(".legend")
        .data(color.domain())
        .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function(d, i) {
            return "translate(0," + i * 20 + ")";
        });

    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);

    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) {
            return d;
        });

});

d3.csv("/static/projects/hiphop/data/ArtistasH_all.csv", function(error, datac) {
    var svg = d3.select("#rapper-circles svg");
    var margin = 50;
    var radius = 15;
    var padding = 3;
    var biggestFirst = true;
    var escala = 10000;

    var baselineHeight = height / 2;

    datac.forEach(function(d) {
        d.x = +d.PUnicaLim / escala;
    });

    var xScale = d3.scale.linear()
        .range([0, width])
        .domain([d3.min(datac, function(d) {
            return d.x - 0.02;
        }), d3.max(datac, function(d) {
            return d.x + 0.01;
        })]);

    var threads = svg.append("g")
        .attr("class", "threads");

    var bubbleLine = svg.append("g")
        .attr("class", "bubbles")
        .attr("transform",
            "translate(0," + baselineHeight + ")");

    bubbleLine.append("line")
        .attr("x1", xScale.range()[0])
        .attr("x2", xScale.range()[1])
        .attr("class", "midaxis");

    bubbleLine.append("line").attr("x1", xScale(0.14)).attr("x2", xScale(0.14)).attr("y1", -baselineHeight + 30).attr("y2", baselineHeight).attr("class", "countaxis");
    bubbleLine.append("line").attr("x1", xScale(0.17)).attr("x2", xScale(0.17)).attr("y1", -baselineHeight + 30).attr("y2", baselineHeight).attr("class", "countaxis");
    bubbleLine.append("line").attr("x1", xScale(0.20)).attr("x2", xScale(0.20)).attr("y1", -baselineHeight + 30).attr("y2", baselineHeight).attr("class", "countaxis");
    bubbleLine.append("line").attr("x1", xScale(0.23)).attr("x2", xScale(0.23)).attr("y1", -baselineHeight + 30).attr("y2", baselineHeight).attr("class", "countaxis");

    bubbleLine.append("text").attr("class", "textaxis").attr("y", -baselineHeight + 10).attr("x", xScale(0.14)).attr("dy", ".71em").style("text-anchor", "middle").text("1.400 PALABRAS");
    bubbleLine.append("text").attr("class", "textaxis").attr("y", -baselineHeight + 10).attr("x", xScale(0.17)).attr("dy", ".71em").style("text-anchor", "middle").text("1.700");
    bubbleLine.append("text").attr("class", "textaxis").attr("y", -baselineHeight + 10).attr("x", xScale(0.20)).attr("dy", ".71em").style("text-anchor", "middle").text("2.000");
    bubbleLine.append("text").attr("class", "textaxis").attr("y", -baselineHeight + 10).attr("x", xScale(0.23)).attr("dy", ".71em").style("text-anchor", "middle").text("2.300");

    bubbleLine.append("line").attr("x1", xScale(0.1488)).attr("x2", xScale(0.1488)).attr("y1", -baselineHeight + 60).attr("y2", baselineHeight - 60).attr("class", "countaxis countquijo");
    bubbleLine.append("text").attr("class", "textaxis quijoaxis").attr("y", -baselineHeight + 44).attr("x", xScale(0.1488)).attr("dy", ".71em").style("text-anchor", "middle").text("EL QUIJOTE");

    bubbleLine.append("line").attr("x1", xScale(0.1653)).attr("x2", xScale(0.1653)).attr("y1", -baselineHeight + 60).attr("y2", baselineHeight - 60).attr("class", "countaxis countquijo");
    bubbleLine.append("text").attr("class", "textaxis quijoaxis").attr("y", -baselineHeight + 32).attr("x", xScale(0.1653)).attr("dy", ".71em").style("text-anchor", "middle").text("ZALACAÃN");
    bubbleLine.append("text").attr("class", "textaxis quijoaxis").attr("y", -baselineHeight + 44).attr("x", xScale(0.1653)).attr("dy", ".71em").style("text-anchor", "middle").text("EL AVENTURERO");

    var quadtree = d3.geom.quadtree()
        .x(function(d) {
            return xScale(d.x);
        })
        .y(0)
        .extent([
            [xScale(-1), 0],
            [xScale(2), 0]
        ]);

    var quadroot = quadtree([]);

    function findNeighbours(root, scaledX, scaledR, maxR) {
        var neighbours = [];
        root.visit(function(node, x1, y1, x2, y2) {
            var p = node.point;
            if (p) {
                var overlap, x2 = xScale(p.x),
                    r2 = radius;
                if (x2 < scaledX) {
                    overlap = (x2 + r2 + padding >= scaledX - scaledR);
                } else {
                    overlap = (scaledX + scaledR + padding >= x2 - r2);
                }
                if (overlap) neighbours.push(p);
            }
            return (x1 - maxR > scaledX + scaledR + padding) && (x2 + maxR < scaledX - scaledR - padding);
        });
        return neighbours;
    }

    function calculateOffset(maxR) {
        return function(d) {
            neighbours = findNeighbours(quadroot, xScale(d.x), radius, maxR);
            var n = neighbours.length;
            var upperEnd = 0,
                lowerEnd = 0;
            if (n) {
                var j = n,
                    occupied = new Array(n);
                while (j--) {
                    var p = neighbours[j];
                    var hypoteneuse = 2 * radius + padding;
                    var base = xScale(d.x) - xScale(p.x);
                    var vertical = Math.sqrt(Math.pow(hypoteneuse, 2) - Math.pow(base, 2));
                    occupied[j] = [p.offset + vertical, p.offset - vertical];
                }
                occupied = occupied.sort(function(a, b) {
                    return a[0] - b[0];
                });
                lowerEnd = upperEnd = 1 / 0;
                j = n;
                while (j--) {
                    if (lowerEnd > occupied[j][0]) {
                        upperEnd = Math.min(lowerEnd, occupied[j][0]);
                        lowerEnd = occupied[j][1];
                    } else {
                        lowerEnd = Math.min(lowerEnd, occupied[j][1]);
                    }
                }
            }
            return d.offset = (Math.abs(upperEnd) < Math.abs(lowerEnd)) ? upperEnd : lowerEnd;
        };
    }

    bubbleLine.selectAll("circle")
        .data(datac.sort(biggestFirst ? function(a, b) {
            return b.r - a.r;
        } : function(a, b) {
            return a.r - b.r;
        }))
        .enter()
        .append("circle")
        .attr("r", radius)
        .each(function(d, i) {
            d3.select(this)
                .attr("cx", xScale(d.x))
                .attr("cy", -baselineHeight)
                .attr("cy", calculateOffset(0))
                .attr("class", function(d) {
                    return d.Region + ' rapper-circle';
                })
                .style("fill", function() {
                    return "url(#" + d.ID + ")";
                });
            quadroot.add(d);
        })
        .on("mouseover", function(d) {
            var coordinates = [0, 0];
            coordinates = d3.mouse(this);
            var x = coordinates[0];
            var y = coordinates[1];
            d3.select(".tooltipcircle")
                .style("left", x + "px")
                .style("top", y + "px")
                .style("margin-top", "150px")
                .select("#value")
                .text(function() {
                    return d3.round(d.x * escala);
                });
            d3.select(".tooltipcircle")
                .select("#rapper")
                .text(d.Cantante);
            d3.select(".tooltipcircle").classed("hidden", false);
        })
        .on("mouseout", function() {
            d3.select(".tooltipcircle").classed("hidden", true);
        });

    var backgrounds = bubbleLine.append('svg:defs');

    backgrounds.selectAll("pattern")
        .data(datac)
        .enter()
        .append("pattern")
        .attr("id", function(d) {
            return d.ID;
        })
        .attr("width", radius * 2)
        .attr("height", radius * 2)
        .attr("patternUnits", "objectBoundingBox")
        .append("image")
        .attr("xlink:href", function(d) {
            return '/static/projects/hiphop/img/' + d.ID + '.jpg';
        })
        .attr("width", radius * 2).attr("height", radius * 2).attr("x", 0).attr("y", 0);

});

d3.selectAll(".regionselect")
    .on("click", function(d) {
        d3.selectAll(".andalucia").classed("andaluz", true).classed("rapper-circle", false);
        d3.selectAll(".aragon").classed("aragones", true).classed("rapper-circle", false);
        d3.selectAll(".catalunya").classed("catalan", true).classed("rapper-circle", false);
        d3.selectAll(".madrid").classed("madrileno", true).classed("rapper-circle", false);
        d3.selectAll(".valencia").classed("valenciano", true).classed("rapper-circle", false);
        d3.selectAll(".leyenda").style("display", "initial");
    });
d3.selectAll(".allselect")
    .on("click", function(d) {
        d3.selectAll(".andalucia").classed("andaluz", false).classed("rapper-circle", true);
        d3.selectAll(".aragon").classed("aragones", false).classed("rapper-circle", true);
        d3.selectAll(".catalunya").classed("catalan", false).classed("rapper-circle", true);
        d3.selectAll(".madrid").classed("madrileno", false).classed("rapper-circle", true);
        d3.selectAll(".valencia").classed("valenciano", false).classed("rapper-circle", true);
        d3.selectAll(".leyenda").style("display", "none");
    });

repo_name: Saigesp/spanish-rap


text:
<file_sep>#error_explanation{
  position:relative;
  margin: 10px auto;
  width: 500px;
  ul li {
    color: #DF4A32;
  }
}<file_sep>class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :omniauthable,
         :rememberable, :trackable, :omniauth_providers => [:facebook, :google_oauth2, :twitter, :github]

  class << self
    def from_omniauth(auth)
      puts "-" * 50
      puts auth.to_json
      puts "-" * 50
      provider = auth.provider
      uid = auth.uid
      info = auth.info.symbolize_keys!
      email = "real_#{Time.now.to_i}#{rand(99)}<EMAIL>"
      if !info.email.nil?
        email = info.email
      end
      user = User.find_or_initialize_by(uid: uid, provider: provider, email: email)
      user.name = info.name
      user.save!
      user
    end
  end
end
<file_sep>require 'test_helper'

class RottenTomatoHelperTest < ActionController::TestCase
  test "the truth" do
    opening_movies
  end
end<file_sep>class UsersController < ApplicationController
  protect_from_forgery except: :create_guest

  def create_guest
    user = User.new { |user| user.guest = true }
    user.email = "guest_#{Time.now.to_i}#{rand(99)}<EMAIL>"
    user.save(:validate => false)
    user
    session[:guest_user_id] = user.id

    redirect_to '/chess'
  end
end
<file_sep>class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  layout :layout_by_resource
  helper_method :current_user

  def current_user
    super || guest_user
  end

  def after_sign_in_path_for(resource)
    flash[:notice] = "Congratulations, you're signed up!"
    '/chess'
  end

  def guest_user
    if guest_user?
      User.find(session[:guest_user_id])
    else
      false
    end
  end

  def guest_user?
    !session[:guest_user_id].nil?
  end

  def user_signed_in?
    super || guest_user?
  end

  private
  def layout_by_resource
    if devise_controller?
      'blank'
    else
      'application'
    end
  end
end<file_sep>require 'net/http'
namespace :rotten_tomato do
  desc "TODO"
  task seed_movies: :environment do
    uri = URI('http://localhost:3000/admin/upcomming_movies')
    Net::HTTP.get(uri)
  end

end
<file_sep>

Welcome to Bughouse Chess!

	  <button onclick="window.location.href='/users/sign_in'">Sign In</button>

        What is Bughouse Chess?

Bughouse is a chess variant played on two chessboards by four players in teams of two. Each team member faces one opponent of the other team. Partners sit next to each other and one player has black, while the other has white. Each player plays the opponent as in a standard chess game, with the exception of the rules specified below.

        What are the rules?

A player capturing a piece immediately passes that piece to the capturing player's partner. The partner keeps these pieces in reserve and may, instead of playing a regular move, place one of these pieces on the board (as in shogi and crazyhouse). Pieces in reserve or on deck may be placed on any vacant square, including squares where the piece delivers check or checkmate. However, pawns may not be dropped on the first or last rank. Dropped pawns may promote, but all promoted pawns convert back to pawns when captured. In play over the board, a promoted pawn can be put on its side to indicate promotion.[3] A pawn placed on the second rank may move two squares on its first move. Each player must keep the reserve or stock pieces on the table in front of the board, always visible to all players of the game.

        How do I start playing?

Simply sign in via 'Google' Twitter' or 'Github'. Once you log on you can click start game (non-competitive) to be paired with a random player.

Currently Online

Bobby(2112) and Neddy(2332)

VS

Bobby(2112) and Neddy(2332)

CHESS BOARD

<file_sep># Bughouse
This is a templant to get a up and running rails project already intergrated in with Devise and omniauth plugins for 'Facebook', 'Github', 'Twitter', and 'Google', as well as the ability to sign in as a 'Guest'. The content in it is for a bughouse chess application but can easily be removed and edited to your own liking as well as the CSS styles.

To get a up and running rails application you would need to:

1. pull down this application
2. run bundle install
3. run rake db:migrate
4. create the following ENV variables with their appropriate values:
	* FACEBOOK_APP_ID
	* FACEBOOK_APP_SECRET
	* GOOGLE_APP_ID
	* GOOGLE_APP_SECRET
	* TWITTER_APP_ID
	* TWITTER_APP_SECRET
	* GITHUB_APP_ID
	* GITHUB_APP_SECRET

which are being referenced in the config>initializers>devise.rb file
<file_sep>Rails.application.routes.draw do
  devise_for :users, controllers: {omniauth_callbacks: "omniauth_callbacks"}

  post '/users/auth/guest', to: 'users#create_guest'
  get '/chess', to: 'chess_home#index'

  root to: "home#index"
end

branch_name: refs/heads/master

languages: Markdown HTML+ERB SCSS Ruby

repo_language: Markdown

repo_name: benjaminPurdy/bughouse


text:
<file_sep>// see src/renderer/window-setup for the explanation

import { parse } from 'url';

const { webContents } = require('electron');
const ipcMain = require('@electron/internal/browser/ipc-main-internal');

const allowedWebContentsTypes = ['window', 'browserView', 'webview'];
const allowedProtocols = ['http:', 'https:'];

ipcMain.on(
  'ECX_POLYFILL_WINDOW_OPENER_POST_MESSAGE',
  (
    _event: Electron.Event,
    origin: string,
    message: any,
    targetOrigin?: string,
  ) => {
    const targetOriginMatchSender = origin === targetOrigin;

    if (targetOriginMatchSender) {
      for (const wc of webContents.getAllWebContents()) {
        const wcType = wc.getType();
        const wcURLProtocol = parse(wc.getURL()).protocol!;

        if (
          allowedWebContentsTypes.includes(wcType) &&
          allowedProtocols.includes(wcURLProtocol)
        ) {
          const js = `
            const messageObj = ${JSON.stringify(message)};
            const event = new MessageEvent('message', { data: messageObj, origin: '*' });
            window.dispatchEvent(event);
          `;

          wc.executeJavaScript(js);
        }
      }
    }
  }
);

repo_language: TypeScript

repo_name: dothq/electron-chrome-extension


text:
<file_sep># ASP.NET Core, React.js and Office UI Fabric React sample task pane web projects for Visual Studio 2019

This sample shows how to add Office UI Fabric React to an Excel Web Add-in project in Visual Studio 2019. You can build great cross-platform UI using the style and controls of Office UI Fabric React. This sample uses [React.js](https://reactjs.org/), [Office UI Fabric React](https://github.com/OfficeDev/office-ui-fabric-react), and the [React project template with ASP.NET Core](https://docs.microsoft.com/aspnet/core/client-side/spa/react). The template is equivalent to creating both an ASP.NET Core project and a standard create-react-app (CRA) React project to act as a UI, but with the convenience of hosting both in a single app project that you can build and publish as a single unit. To develop an add-in from the template, you can either add a Web API to the ASP.NET Core project or you can develop the project as a single-page React add-in. Since the project uses React as the UI, you should not attempt to use UI features of ASP.NET Core.

We'd like to hear about your experience with this sample and using ASP.NET Core with Office UI Fabric React and Office Add-ins. Just submit a new issue in this repo to let us know if you have any questions or suggestions.

## Sample Web Projects

- excel-ts: contains sample TypeScript web project that can be used with Office web add-in in Visual Studio.
- excel-js: contains sample JavaScript web project that can be used with Office web add-in in Visual Studio.

## Applies to

- Microsoft 365
- Visual Studio 2019

## Prerequisites

- Visual Studio 2019 (16.3 Preview 3 or newer) and the following Workloads and Optional Components installed:

  - ASP.NET and web development
  - Node.js development
  - Office/SharePoint development
  - Net Core 3.1 Runtime (individual component)

- Node.js, install from https://nodejs.org

> **Note:** Visual Studio 2019 can be downloaded from https://visualstudio.microsoft.com/downloads/

## Solution

| Solution                                                           | Author(s) |
| ------------------------------------------------------------------ | --------- |
| Add ASP.NET Core with Office UI Fabric React to your Office Add-in | Microsoft |

## Instructions

### Create a new Office Web add-in project

1. Start Visual Studio 2019.
2. Choose **Create a new project**.
3. Type "Excel" into the search box at the top of the dialog.
4. Choose the Excel Web Add-in template, then choose **Next**.
5. Give the new project a name on the **Configure your new project** page and use the default values for the remaining fields and then choose **Create**.
6. On the choose the add-in type page, select **Add new functionalities to Excel**. Then choose Finish.

### Add the ASP.NET Core React.js web project to the solution

1. Download or clone this repo. This will create a **PnP-OfficeAddins** folder.
2. In Visual Studio, right-click the solution in **Solution Explorer** and choose **Add > Existing Project**.
3. In the **Add Existing Project** dialog, go to the **PnP-OfficeAddins/Samples/Office.ASP.NETCoreReactAddins** folder. There are two project folders there: **excel-js** (JavaScript) and **excel-ts** (TypeScript). Choose the folder for the language you want to use, and then choose the .csproj file in the folder.
4. Build the project you just added, right-click the project in **Solution Explorer** and choose **Build**.
5. Select the add-in project in Solution Explorer. It will have the name you gave the project when you created it and a Manifest entry under it (i.e. ExcelWebAddin1).
6. Press F4 to view the **Properties** window for the project (if it is not already visible).
7. Change the **Web Project** property to the name of ASP .NET Core web project you just added to the solution.
   **Note:**: The ASP.NET Core web project must be on the same local drive as the Excel Web Add-in project.
8. In the **Solution Explorer** open the manifest.xml file under the Office Add-in project (the project only contains a manifest file). Copy and save the <Id> that has the GUID for your project.
9. Copy the contents of the manifest.xml file in the ASP.NET Core project and replace all of the contents in the manifest file in the Web Add-in project (i.e. ExcelWebAddin1Manifest.xml) with it.
10. Press F5 to debug the Office Web Add-in project.

> **Note:** npm install should run and install the packages prior to building the ASP.NET Core web project but you may need to watch the output window for errors. If errors occur, please try running npm install from the ./ClientApp folder.

## Known Issues

1. If you are using Visual Studio 2019 Update 3 on Windows 10 version 1903 or later and Office version 16.0.11424.10000 or later, there is a known issue that effects your ability to hit breakpoints in JavaScript files. For more information and instructions on how to work around this please see https://developercommunity.visualstudio.com/content/problem/740413/office-development-inconsistent-script-debugging-b.html

2. The ASP.NET Core web project must be on the same local drive as the Office Manifest project. If it is not you will see the error "Property value is not valid" when trying to switch the Web Project property.

## Feedback

Fill out this form to let us know your experience with this sample: [Developing with the ASP.NET Core + Fabric React Office Add-in sample](https://forms.microsoft.com/Pages/ResponsePage.aspx?id=v4j5cvGGr0GRqy180BHbR9Kwcf15u95EqS7NUgPuo5xUN0dYSFdQNVhFRDBaMjI1SDNXNFlKSkFNMC4u)

## Version history

| Version | Date               | Comments                           |
| ------- | ------------------ | ---------------------------------- |
| 1.0     | September 23, 2019 | Initial Release                    |
| 2.0     | May 14, 2020       | Upgraded from .NET Core 2.2 to 3.1 |

### Disclaimer

**THIS CODE IS PROVIDED _AS IS_ WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
<file_sep>import * as React from 'react';
import { Button } from 'office-ui-fabric-react';
const onClickFromDialogue = () => {
        const res = 'From Dialogue';
        Office.context.ui.messageParent(JSON.stringify({res}));
}
const ConnectButton = () =>

                    <Button onClick={onClickFromDialogue}>Insert from dialogue</Button>

;
export default ConnectButton;

languages: Markdown TSX

repo_name: TheSorbex/PnP-OfficeAddins


text:
<repo_name>juliagerlach/sweepstakes<file_sep>/Sweepstakes/Userinterface.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sweepstakes
{
    public static class Userinterface
    {
        public static string GetFirstName()
        {
            Console.WriteLine("Please enter contestant's first name.");
            return Console.ReadLine();

  }

        public static string GetLastName()
        {
            Console.WriteLine("Please enter contestant's last name.");
            return Console.ReadLine();
        }

        public static string GetEmailAddress()
        {
            Console.WriteLine("Please enter contestant's email address.");
            return Console.ReadLine();
        }

        public static int GetRegistrationNumber()
        {
            Console.WriteLine("Please enter contestant's registration number.");
            return int.Parse(Console.ReadLine());
        }
    }
}
<file_sep>/Sweepstakes/Sweepstakes.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sweepstakes
{
    public class Sweepstakes
    {
        Dictionary<int, Contestant> contestants = new Dictionary<int, Contestant>();
        Random random;
        public string sweepstakesName;
        int contestantCount;

        public Sweepstakes(string sweepstakesName)
        {
            this.sweepstakesName = sweepstakesName;
            this.random = new Random();
            contestantCount = 0;
        }

        public Contestant CreateContestant()
        {
            string firstName = Userinterface.GetFirstName();
            string lastName = Userinterface.GetLastName();
            string emailAddress = Userinterface.GetEmailAddress();
            contestantCount++;

            Contestant contestant = new Contestant(firstName, lastName, emailAddress, contestantCount);
            return contestant;
        }
        public void RegisterContestant(Contestant contestant)
        {
            contestants.Add(contestant.registrationNumber, contestant);
        }
        public string PickWinner()
        {
            int winningContestant = random.Next(1, contestantCount);
            Contestant contestant;
            contestants.TryGetValue(winningContestant, out contestant);
            return $"{contestant.firstName} {contestant.lastName}";
        }

        public void PrintContestantInfo(Contestant contestant)
        {
            foreach (KeyValuePair<int, Contestant> pair in contestants)
            {
                Console.WriteLine(pair.Key + "" + pair.Value);
            }
        }
    }
}
<file_sep>/Sweepstakes/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sweepstakes
{
    public class Program
    {
        static void Main(string[] args)
        {
            SweepstakesStackManager stackManager = new SweepstakesStackManager();
            SweepstakesQueueManager queueManager = new SweepstakesQueueManager();

            Sweepstakes sweepstakes = new Sweepstakes("Packers Ticket Giveaway");
            queueManager.InsertSweepstakes(sweepstakes);
            stackManager.InsertSweepstakes(sweepstakes);
            Console.WriteLine("Please enter at least two contestants for the " + sweepstakes.sweepstakesName + ".");
            Console.ReadLine();
            Contestant contestant = sweepstakes.CreateContestant();
            sweepstakes.RegisterContestant(contestant);
            sweepstakes.CreateContestant();
            sweepstakes.RegisterContestant(contestant);

            sweepstakes = new Sweepstakes("Brewers Ticket Giveaway");
            queueManager.InsertSweepstakes(sweepstakes);
            stackManager.InsertSweepstakes(sweepstakes);
            Console.WriteLine("Please enter at least two contestants for the " + sweepstakes.sweepstakesName + ".");
            Console.ReadLine();
            sweepstakes.CreateContestant();
            sweepstakes.RegisterContestant(contestant);
            sweepstakes.CreateContestant();
            sweepstakes.RegisterContestant(contestant);

            sweepstakes = new Sweepstakes("Bucks Ticket Giveaway");
            queueManager.InsertSweepstakes(sweepstakes);
            stackManager.InsertSweepstakes(sweepstakes);
            Console.WriteLine("Please enter at least two contestants for the " + sweepstakes.sweepstakesName + ".");
            Console.ReadLine();
            sweepstakes.CreateContestant();
            sweepstakes.RegisterContestant(contestant);
            sweepstakes.CreateContestant();
            sweepstakes.RegisterContestant(contestant);

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(sweepstakes.sweepstakesName);
                Console.WriteLine("Queue Manager:");
                RunSweepstakes(queueManager);
                Console.WriteLine("Stack Manager:");
                RunSweepstakes(stackManager);
                Console.WriteLine();
            }
            Console.ReadLine();
        }

            private static void RunSweepstakes(ISweepstakesManager sweepstakesManager)
            {
                Sweepstakes sweepstakes = sweepstakesManager.GetSweepstakes();
                Console.WriteLine($"The winner of {sweepstakes.sweepstakesName} is...");

                string winner = sweepstakes.PickWinner();
                Console.WriteLine(winner);
                Console.ReadLine();
            }

    }
}

repo_language: C#

repo_name: juliagerlach/sweepstakes


text:
<file_sep>import java.util.ArrayList;
import java.util.List;

public class Product implements Subject{

	  private List<Observer> obs = new ArrayList<Observer>();
	    private String nameProduct;
	    public Product(String nameProduct) {
	        super();
	        this.nameProduct = nameProduct;
	    }

	    @Override
	    public void attachObserver(Observer observer) {
	        obs.add(observer);
	    }

	    @Override
	    public void detachObserver(Observer observer) {
	        obs.remove(observer);
	    }

	    @Override
	    public void notifyObserver() {
	        for (Observer ob : obs) {
	            ob.update(nameProduct);
	        }
	}

}
<file_sep>
public class Test {

	public static void main(String[] args) {
		SinhVien sv=new SinhVien();
		sv.setHoTen("<NAME>");
		sv.setMSSV("2001167152");;
		System.out.print(sv.getHoTen());
	}

}
<file_sep>
public class Test {
	public static void main(String[] args) {
		ClassA c=new ClassB();
		c.show();
	}

}

repo_language: Java


text:
<repo_name>insamrand/Note-App<file_sep>/App.js
import React from "react";
import { StyleSheet, Platform } from "react-native";
import * as Font from "expo-font";
import { Ionicons } from "@expo/vector-icons";
import { AppLoading } from "expo";
import HomePage from "./pages/home-page/HomePage";
import NewNotePage from "./pages/new-note-page/NewNotePage";
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";

// import Provider Component มาใช้กับ
// store object ที่เราสร้างขึ้นมาเอง
import { Provider } from "react-redux";
import configureStore from "./redux/store";

const store = configureStore();

const AppNavigator = createStackNavigator({
  Home: {
    screen: HomePage
  },
  CreateNote: {
    screen: NewNotePage
  }
});
const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
  // Constructor method, ทำงานเป็นตัวแรกตอน class App ถูกสร้างขึ้นมาใช้งานในระบบ
  constructor(props) {
    super(props);
    this.state = {
      isReady: false
    };
  }

  // Life cycle method `componentDidMount()`
  // ทำงานหลังจาก App component ถูกสร้างขึ้นแสดงบนหน้าแอพแล้ว
  async componentDidMount() {
    // สั่งให้ Load font เพื่อใช้งานใน UI Component ที่สร้างด้วย Native base
    await Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      ...Ionicons.font
    });

    // ตั้งค่า State ใหม่ เพื่อให้ App component ทำการ render ตัวเองอีกครั้ง
    this.setState({ isReady: true });
  }

  render() {
    if (this.state.isReady == false) {
      return <AppLoading />;
    }
    const { container } = styles;
    return (
      <Provider store={store}>
        <AppContainer />
      </Provider>
    );
    // <NewNotePage />;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  },

  androidContainer: {
    height: 70,
    paddingTop: Platform.OS === "android" ? 27 : 0
  }
});
<file_sep>/pages/home-page/HomePage.js
import React from "react";
import { StyleSheet, Platform, Image } from "react-native";
import {
  Container,
  Text,
  Content,
  List,
  ListItem,
  Button,
  Icon,
  Left,
  Thumbnail,
  Body,
  Right
} from "native-base";
import { connect } from "react-redux";
import actions from "../../redux/reducers/actions";
const hogwartsImg =
  "http://www.penguinteen.com/content/uploads/Hogwarts-castle-harry-potter-166431-1.jpg";
class HomePage extends React.Component {
  // GO TO mapStateToProps
  // static defaultProps = {
  //   notes: [{ title: "a" }, { title: "b" }, { title: "c" }]
  // };
  static navigationOptions = ({ navigation }) => {
    return {
      title: "Hogwarts School",
      headerRight: (
        <Button
          transparent
          onPress={() => {
            console.log("GO GO GO");
            navigation.navigate("CreateNote");
          }}
        >
          <Icon name="add" />
        </Button>
      )
    };
  };
  // static navigationOptions = {
  //   title: "Home"
  // };
  componentDidMount() {
    this.props.ready();
  }

  render() {
    if (this.props.notes === undefined) {
      return <Text>No Data</Text>;
    }

    return (
      <Container>
        <Image
          style={styles.hogwarts}
          source={{
            uri: hogwartsImg
          }}
        />
        <Content>
          <List style={styles.listStyle}>
            {this.props.notes.map((item, index) => {
              return (
                <ListItem thumbnail key={index}>
                  <Left>
                    <Thumbnail square source={{ uri: item.url }} />
                  </Left>

                    <Text>{item.title}</Text>
                    <Text note numberOfLines={2}>
                      {item.text}
                    </Text>

                  <Right>
                    <Button transparent>
                      <Text>View</Text>
                    </Button>
                  </Right>
                </ListItem>
              );
            })}
          </List>
        </Content>
      </Container>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  },
  hogwarts: {
    backgroundColor: "#ccc",
    flex: 1,
    position: "absolute",
    width: "100%",
    height: "100%",
    justifyContent: "center"
  },
  listStyle: {
    backgroundColor: "rgba(255, 255, 255, 0.7)"
  }
});
// Pro Version
// const mapStateToProps = state => ({
//   notes: state.note.notes
// });

// Beginer Version
const mapStateToProps = state => {
  console.log("State form Reducer goto Home Page");
  console.log(state);

  return {
    notes: state.note.notes
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ready: () => dispatch(actions.appReady())
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(HomePage);
<file_sep>/pages/new-note-page/NewNotePage.js
import React from "react";
import { StyleSheet, Platform } from "react-native";
import { Container, Content, Text } from "native-base";
import NewNoteForm from "./NewNoteForm";
import { connect } from "react-redux";
import actions from "../../redux/reducers/actions";

class NewNotePage extends React.Component {
  static navigationOptions = {
    title: "Register Magician Member"
  };

  message = "Hello";
  onFormSave = values => {
    console.log("Form values: ", values);
    this.props.saveMessage(values);
    // this.props.saveMessage(values.text);
    // this.props.saveMessage(values.url);
    this.props.navigation.goBack();
  };
  render() {
    return (
      <Container>
        <Content padder>
          <Text>
            {this.message + " "}
            {this.props.username}
          </Text>
          <NewNoteForm onSubmit={this.onFormSave} />
        </Content>
      </Container>
    );
  }
}
const mapStateToProps = state => ({
  username: state.note.username
});

const mapDispatchToProps = dispatch => {
  return {
    saveMessage: values => dispatch(actions.saveNote(values)),
    // saveMessage: text => dispatch(actions.saveNote(text)),
    // saveMessage: url => dispatch(actions.saveNote(url))
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(NewNotePage);
<file_sep>/redux/reducers/note.reducer.js
import actions from "./actions";

const initialState = {
  username: "Mack",
  notes: [
    {
      title: "<NAME>",
      text:
        "<NAME> (b. 31 July 1980 ) was an English half-blood wizard, one of the most famous wizards of modern times. He was the only child and son of James and <NAME>",
      url: "https://timedotcom.files.wordpress.com/2014/07/301386_full1.jpg"
    },
    {
      title: "<NAME>",
      text:
        "Minister <NAME> (b. 19 September, 1979 ) was an English Muggle-born witch born to Mr and Mrs Granger. At the age of eleven, she learned about her magical nature and had been accepted",
      url: "https://timedotcom.files.wordpress.com/2015/04/emma-watson-23.jpg"
    },
    {
      title: "<NAME>",
      text:
        "<NAME> (b. 1 March, 1980) was an English pure-blood wizard, the sixth and youngest son of Arthur and <NAME>. He was also the younger brother of Bill, Charlie, Percy, <NAME>, and the elder brother of Ginny. Ron and his brothers and sister lived at the Burrow, on the outskirts of Ottery St Catchpole.",
      url:
        "https://images.pottermore.com/bxd3o8b291gf/4kRGmTOvVYmIwsOikwcuUw/8b8f2e4ffcc1a5218bafe615f976abb0/Ron_Weasley_WB_F1_Ron_with_Scabbers_on_shoulder_00393692.jpg?w=1200"
    }
  ]
};
export default (state = initialState, { type, payload }) => {
  switch (type) {
    case actions.Types.APP_READY: {
      console.log("Application Ready");
      return { ...state };
    }

    case actions.Types.SAVE_NOTE: {
      console.log("Have a saving noted: ", payload);

      let newNotes = [...state.notes, {...payload}];
      // newNotes.push({
      //   title: payload.tile,
      //   text: payload.text,
      //   url: payload.url
      // });

      return {
        ...state,
        notes: newNotes
      };
    }

    case "typeName":
      return { ...state, ...payload };

    default:
      return state;
  }
};
<file_sep>/redux/reducers/actions.js
const Types = {
  SAVE_NOTE: "SAVE_NOTE",
  APP_READY: "APP_READY"
};

// const saveNote2 = function(message){
//   return {
//     type: Types.SAVE_NOTE,
//     payload: message
//   }
// }

// const appReady = function() {
//   return {
//     type: Types.APP_READY,
//     payload: {}
//   };
// };

// arrowFN
const saveNote = values => {
  return {
    type: Types.SAVE_NOTE,
    payload: values
  };
};

const appReady = () => {
  return {
    type: Types.APP_READY,
    payload: {}
  };
};

export default {
  Types,
  saveNote,
  appReady
};
<file_sep>/redux/store.js
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import NoteReducer from "./reducers/note.reducer";
import { reducer as formReducer } from "redux-form";

export default function configureStore() {
  const store = createStore(
    combineReducers({
      note: NoteReducer,
      form: formReducer
    })
  );
  return store;
}
<file_sep>/pages/new-note-page/NewNoteForm.js
import React, { Component } from "react";
import { View, Alert } from "react-native";
import { Item, Label, Button, Text, Input } from "native-base";
import { reduxForm, Field } from "redux-form";
import { connect } from "react-redux";

class NewNoteForm extends Component {
  renderInput = ({ input }) => {
    return <Input {...input} />;
  };
  // renderInput({ input, label, type, meta: { touched, error, warning } }) {
  //   var hasError = false;

  //   // ถ้า function ได้รับ error ก็จะแสดง pop up ขึ้นมา
  //   if (error !== undefined && touched) {
  //     hasError = true;
  //     Alert.alert("Opps", error);
  //   }
  //   return (
  //     <Item error={hasError}>
  //       <Input {...input} />
  //     </Item>
  //   );
  // }

  render() {
    // const validate = values => {
    //   const error = {};
    //   error.message = "";

    //   var newMessage = values.message;

    //   if (values.message === undefined) {
    //     newMessage = "";
    //   }

    //   if (newMessage === "") {
    //     error.message = "fill something";
    //   }

    //   return error;
    // };
    const { handleSubmit } = this.props;
    // const handleSubmit = this.props.handleSubmit;
    return (
      <View>
        <Item stackedLabel>
          Name :
          <Field name="title" component={this.renderInput} />
        </Item>
        <Item stackedLabel>
          Description :
          <Field name="text" component={this.renderInput} />
        </Item>
        <Item stackedLabel>
          Image Url :
          <Field name="url" component={this.renderInput} />
        </Item>
        <Button primary block onPress={handleSubmit}>
          <Text>Save</Text>
        </Button>
        {/* <Text>{this.props.description}</Text> */}
      </View>
    );
  }
}
NewNoteForm = reduxForm({ form: "newNote" })(NewNoteForm);
// NewNoteForm = reduxForm({ form: "newNote", validate })(NewNoteForm);

const mapStateToProps = state => {
  return {
    description: state.form.newNote
  };
};

const mapDispatchToProps = {};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(NewNoteForm);

repo_language: JavaScript

repo_name: insamrand/Note-App


text:
<repo_name>rushil83/cricket_match_prediction<file_sep>/README.md
# cricket_match_prediction

###  cricker match prediction algorithm, but for....
![](http://st3.cricketcountry.com/wp-content/uploads/2015/02/Tanmay-Mukherjee-article2.jpg)


text:
<repo_name>MorozovGl/OOP<file_sep>/prog4/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(prog4)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES src/main.cpp src/PrimeFactoring.cpp src/PrimeFactoring.h)
add_executable(prog4 ${SOURCE_FILES})<file_sep>/prog2/src/StatisticMultiset.h
//
// Created by <NAME> on 22.11.17.
//

#pragma once

#include <vector>
#include <set>
#include <list>
#include <fstream>
#include <map>

template<class T>
class StatisticMultiset {

private:
    std::multiset<T> multset;
    T min;
    T max;
    float avg;
    mutable T countUnder;
    mutable T countAbove;
    mutable std::vector<float> countAboveCache;
    mutable std::vector<float> countUnderCache;
    mutable std::map<float, int> countAboveAns;
    mutable std::map<float, int> countUnderAns;

public:
    StatisticMultiset() = default;
    ~StatisticMultiset() = default;
    void AddNum( const T& numbers);
    void AddNum( const std::multiset<T>& numbers );
    void AddNum( const std::vector<T>& numbers );
    void AddNum( const std::list<T>& numbers );
    void AddNums( const StatisticMultiset& a_stat_set );
    void AddNumsFromFile( const char* filename );
    T GetMax() const;
    T GetMin() const;
    float GetAvg() const;
    int GetCountUnder( float threshold ) const;
    int GetCountAbove( float threshold ) const;
};

template<class T>
void StatisticMultiset<T>::AddNum( const T& numbers){
    if(numbers < min) min = numbers;
    if(numbers > max) max = numbers;
    multset.insert(numbers);
    if (multset.size() == 1) { max = numbers; min = numbers; avg = numbers; }
    else avg = (avg*(multset.size() - 1) + numbers) / multset.size();
}

template<class T>
void StatisticMultiset<T>::AddNum( const std::multiset<T>& numbers ){
    for(auto &it : numbers)
        AddNum(it);
}

template<class T>
void StatisticMultiset<T>::AddNum( const std::vector<T>& numbers ){
    for(auto &it : numbers)
        AddNum(it);
}

template<class T>
void StatisticMultiset<T>::AddNum( const std::list<T>& numbers ){
    for(auto &it : numbers)
        AddNum(it);
}

template<class T>
void StatisticMultiset<T>::AddNums( const StatisticMultiset& a_stat_set ){
    if(this != &a_stat_set)
        AddNum(a_stat_set.multset);
}

template<class T>
void StatisticMultiset<T>::AddNumsFromFile( const char* filename ){
    std::ifstream cin(filename);
    T x;
    while (!cin.eof()) {
        cin >> x;
        AddNum(x);
    }
}
template<class T>
float StatisticMultiset<T>::GetAvg() const {
    return avg;
}

template<class T>
T StatisticMultiset<T>::GetMin() const {
    return min;
}

template<class T>
T StatisticMultiset<T>::GetMax() const {
    return max;
}

template<class T>
int StatisticMultiset<T>::GetCountUnder( float threshold ) const{
    auto request = std::find(countUnderCache.begin(), countUnderCache.end(), threshold);
    if(request == countUnderCache.end()) {
        int ans = 0;
        countUnderCache.push_back(threshold);
        int count = 0;
        for (auto &it : multset)
            if (it < threshold) count++;
        countUnder = count;
        countUnderAns.insert(std::make_pair(threshold, countUnder));
        return countUnder;
    }
    else return countUnderAns[*request];

}

template<class T>
int StatisticMultiset<T>::GetCountAbove( float threshold ) const{
    auto request = std::find(countAboveCache.begin(), countAboveCache.end(), threshold);
    if(request == countAboveCache.end()) {
        countAboveCache.push_back(threshold);
        int count = 0;
        for (auto &it : multset)
            if (it < threshold) count++;
        countAbove = count;
        countAboveAns.insert(std::make_pair(threshold, countAbove));
        return countAbove;
    }
    else return countAboveAns[*request];

}
<file_sep>/prog4/src/PrimeFactoring.cpp
#include "PrimeFactoring.h"

PrimeFactors::PrimeFactors(uint64_t number) : number(number) {
    Factorize();
}
void PrimeFactors::Factorize() {
    uint64_t curr_number = number;
    int probe;
    unsigned power;
    for (probe = 2; probe <= curr_number; ++probe) {
        power = 0;
        while (curr_number % probe == 0) {
            ++power;
            curr_number /= probe;
        }
        if (power != 0) {
            factors.push_back(std::make_pair(probe, power));
        }
    }
}

std::string PrimeFactors::ToString() const {
    uint64_t temp = 1;
    std::string result(std::to_string(number) + " = 1");
    unsigned l = factors.size();
    for (unsigned i = 0; i != l; ++i) {
        if (factors[i].second == 1) {
            result += " * " + std::to_string(factors[i].first);
        }
        else {
            result += " * " + std::to_string(factors[i].first) + '^' + std::to_string(factors[i].second);
        }
    }
    return result;
}<file_sep>/prog1/src/IniParserException/IniParserException.cpp
#include "IniParserException.h"

const char* IniParserException::what() const noexcept {
	return message.c_str();
}<file_sep>/prog1/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(prog1)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES
        src/main.cpp
        src/IniParser/IniParser.cpp
        src/IniParser/IniParser.h
        src/IniParserException/IniParserException.cpp
        src/IniParserException/IniParserException.h)

add_executable(prog1 ${SOURCE_FILES})<file_sep>/prog2/src/main.cpp
#include "StatisticMultiset.h"

#include <iostream>

int main() {
    StatisticMultiset<int> mset, mset2;
    mset.AddNum(5);
    mset.AddNum(25);
    std::cout << mset.GetAvg() << '\n';
    mset2.AddNum(3);
    mset2.AddNum(7);
    mset.AddNums(mset2);
    std::cout << mset.GetAvg() << '\n';
    std::cout << mset.GetCountAbove(5) << '\n';
    std::cout << mset.GetCountAbove(5) << '\n';
    std::cout << mset.GetMin();

    return 0;
}<file_sep>/prog3/src/wav.cpp
#include "wav.h"

Wav::Wav(const string &filename) {
    f = fopen(filename.c_str(), "rb");
    if (f == NULL) {
        throw IO_Exception("No such file");
    }
    ReadHeader();
    ExtractDataInt16();
}
Wav::~Wav() {
    fclose(f);
}

void Wav::ReadHeader()
{
    //printf(">>>> read_header( %s )\n", filename);
    //null_header(header_ptr); // Fill header with zeroes.

    size_t blocks_read = fread(&head, sizeof(head), 1, f);
    if (blocks_read != 1) {
        // can't read header, because the file is too small.
        throw Format_Exception("Head hasn't been read.\n");
    }

    fseek(f, 0, SEEK_END); // seek to the end of the file
    //size_t file_size = ftell(f); // current position is a file size!
    data_size = ftell(f);
    //fclose(f);
    fseek(f, 0, SEEK_SET);

    CheckHeader();
}
void Wav::CheckHeader() {
    if (head.chunkId[0] != 0x52 ||
        head.chunkId[1] != 0x49 ||
        head.chunkId[2] != 0x46 ||
        head.chunkId[3] != 0x46)
    {
        throw Header_Exception("HEADER_RIFF_ERROR\n");
    }

    if (head.chunkSize != data_size - 8) {
        throw Header_Exception("HEADER_FILE_SIZE_ERROR\n");
    }

    if (head.format[0] != 0x57 ||
        head.format[1] != 0x41 ||
        head.format[2] != 0x56 ||
        head.format[3] != 0x45)
    {
        throw Header_Exception("HEADER_WAVE_ERROR\n");
    }

    if (head.subchunk1Id[0] != 0x66 ||
        head.subchunk1Id[1] != 0x6d ||
        head.subchunk1Id[2] != 0x74 ||
        head.subchunk1Id[3] != 0x20)
    {
        throw Header_Exception("HEADER_FMT_ERROR\n");
    }

    if (head.audioFormat != 1) {
        throw Header_Exception("HEADER_NOT_PCM\n");
    }

    if (head.subchunk1Size != 16) {
        throw Header_Exception("HEADER_SUBCHUNK1_ERROR\n");
    }

    if (head.byteRate != head.sampleRate * head.numChannels * head.bitsPerSample / 8) {
        throw Header_Exception("HEADER_BYTES_RATE_ERROR\n");
    }

    if (head.blockAlign != head.numChannels * head.bitsPerSample / 8) {
        throw Header_Exception("HEADER_BLOCK_ALIGN_ERROR\n");
    }
    if (head.bitsPerSample != 16) {
        throw Header_Exception("Bits per sample must be 16\n");
    }
    if (head.subchunk2Id[0] != 0x64 ||
        head.subchunk2Id[1] != 0x61 ||
        head.subchunk2Id[2] != 0x74 ||
        head.subchunk2Id[3] != 0x61)
    {
        throw Header_Exception("HEADER_FMT_ERROR\n");
    }

    if (head.subchunk2Size != data_size - 44)
    {
        throw Header_Exception("HEADER_SUBCHUNK2_SIZE_ERROR\n");
    }
}
void Wav::PrintInfo() {
    printf("-------------------------\n");
    printf(" audioFormat   %u\n", head.audioFormat);
    printf(" numChannels   %u\n", head.numChannels);
    printf(" sampleRate    %u\n", head.sampleRate);
    printf(" bitsPerSample %u\n", head.bitsPerSample);
    printf(" byteRate      %u\n", head.byteRate);
    printf(" blockAlign    %u\n", head.blockAlign);
    printf(" chunkSize     %u\n", head.chunkSize);
    printf(" subchunk1Size %u\n", head.subchunk1Size);
    printf(" subchunk2Size %u\n", head.subchunk2Size);
    printf("-------------------------\n");
}

void Wav::HeadRefactor(int chan_count, int sample_rate, int samples_count_per_chan) {

    int file_size_bytes = 44 + chan_count * (head.bitsPerSample / 8) * samples_count_per_chan;

    head.sampleRate = sample_rate;
    head.numChannels = chan_count;
    head.bitsPerSample = 16;

    head.chunkSize = file_size_bytes - 8;
    head.subchunk2Size = file_size_bytes - 44;

    head.byteRate = head.sampleRate * head.numChannels * head.bitsPerSample / 8;
    head.blockAlign = head.numChannels * head.bitsPerSample / 8;
}
void Wav::ExtractDataInt16()
{

    fseek(f, 44, SEEK_SET); // Seek to the begining of PCM data.

    int chan_count = head.numChannels;
    int samples_per_chan = (head.subchunk2Size / sizeof(short)) / chan_count;

    // 1. Reading all PCM data from file to a single vector.
    std::vector<short> all_channels;
    all_channels.resize(chan_count * samples_per_chan);
    size_t read_bytes = fread(all_channels.data(), 1, head.subchunk2Size, f);
    if (read_bytes != head.subchunk2Size) {
        printf("extract_data_int16() read only %zu of %u\n", read_bytes, head.subchunk2Size);
        throw Format_Exception("PCM data is bigger than it is declared in subchunk2Size.\n");
    }
    //fclose(f);

    // 2. Put all channels to its own vector.
    channels_data.resize(chan_count);
    for (size_t ch = 0; ch < channels_data.size(); ch++) {
        channels_data[ch].resize(samples_per_chan);
    }

    for (int ch = 0; ch < chan_count; ch++) {
        std::vector<short>& chdata = channels_data[ch];
        for (size_t i = 0; i < samples_per_chan; i++) {
            chdata[i] = all_channels[chan_count * i + ch];
        }
    }
    fseek(f, 0, SEEK_SET);
}

void Wav::MakeWavFile(const std::string filename) {
    //printf(">>>> make_wav_file( %s )\n", filename);

    int chan_count = head.numChannels;

    int samples_count_per_chan = (int)channels_data[0].size();

    // Verify that all channels have the same number of samples.
    for (size_t ch = 0; ch < chan_count; ch++) {
        if (channels_data[ch].size() != (size_t)samples_count_per_chan) {
            throw Format_Exception("Samples per channel differ from channel to channel\n");
        }
    }

    std::vector<short> all_channels;
    all_channels.resize(chan_count * samples_count_per_chan);

    for (int ch = 0; ch < chan_count; ch++) {
        const std::vector<short>& chdata = channels_data[ch];
        for (size_t i = 0; i < samples_count_per_chan; i++) {
            all_channels[chan_count * i + ch] = chdata[i];
        }
    }

    FILE* nf = fopen(filename.c_str(), "wb");
    if (nf == NULL) {
        throw ("Can't create/write to file.\n");
    }
    fwrite(&head, sizeof(wav_header_s), 1, nf);
    fwrite(all_channels.data(), sizeof(short), all_channels.size(), nf);
    fclose(nf);
}

void Wav::MakeMono()
{
    int chan_count = (int)channels_data.size();

    if (chan_count != 2 || chan_count == 1) {
        throw Parameters_Exception("Can't make mono out of " + std::to_string(chan_count) + " channel.\n");
    }

    int samples_count_per_chan = (int)channels_data[0].size();

    // Verify that all channels have the same number of samples.
    for (size_t ch = 0; ch < chan_count; ch++) {
        if (channels_data[ch].size() != (size_t)samples_count_per_chan) {
            throw Format_Exception("Samples per channel differ from channel to channel\n");
        }
    }

    std::vector< std::vector<short> > dest_mono;
    dest_mono.resize(1);
    std::vector<short>& mono = dest_mono[0];
    mono.resize(samples_count_per_chan);
    // Mono channel is an arithmetic mean of all (two) channels.
    for (size_t i = 0; i < samples_count_per_chan; i++) {
        mono[i] = (channels_data[0][i] + channels_data[1][i]) / 2;
    }
    channels_data = dest_mono;
    HeadRefactor(1, head.sampleRate, samples_count_per_chan);
}
void Wav::MakeReverb(double delay_seconds, float decay)
{
    int chan_count = (int)channels_data.size();
    int sample_rate = head.sampleRate;

    if (chan_count < 1) {
        throw Format_Exception("Channel count can't be fewer than 1");
    }

    int samples_count_per_chan = (int)channels_data[0].size();

    // Verify that all channels have the same number of samples.
    for (size_t ch = 0; ch < chan_count; ch++) {
        if (channels_data[ch].size() != (size_t)samples_count_per_chan) {
            throw Format_Exception("Samples per channel differ from channel to channel\n");
        }
    }

    int delay_samples = (int)(delay_seconds * sample_rate);

    for (size_t ch = 0; ch < chan_count; ch++) {
        std::vector<float> tmp;
        tmp.resize(channels_data[ch].size());

        // Convert signal from short to float
        for (size_t i = 0; i < samples_count_per_chan; i++) {
            tmp[i] = channels_data[ch][i];
        }

        // Add a reverb
        for (size_t i = 0; i < samples_count_per_chan - delay_samples; i++) {
            tmp[i + delay_samples] += decay * tmp[i];
        }

        // Find maximum signal's magnitude
        float max_magnitude = 0.0f;
        for (size_t i = 0; i < samples_count_per_chan - delay_samples; i++) {
            if (abs(tmp[i]) > max_magnitude) {
                max_magnitude = abs(tmp[i]);
            }
        }

        // Signed short can keep values from -32768 to +32767,
        // After reverb, usually there are values large 32000.
        // So we must scale all values back to [ -32768 ... 32768 ]
        float norm_coef = 30000.0f / max_magnitude;
        printf("max_magnitude = %.1f, coef = %.3f\n", max_magnitude, norm_coef);

        // Scale back and transform floats to shorts.
        for (size_t i = 0; i < samples_count_per_chan; i++) {
            channels_data[ch][i] = (short)(norm_coef * tmp[i]);
        }
    }
}<file_sep>/prog3/src/wav.h
#pragma once
#include <string>
#include <vector>
#include <iostream>
#include <cmath>
#include "WavExceptions.h"
#include "wav_header.h"

using namespace std;
class Wav {
public:
    Wav(const std::string &filename);
    void ReadHeader();
    void PrintInfo();
    void ExtractDataInt16();
    void MakeWavFile(const std::string filename);
    void MakeMono();
    void MakeReverb(double delay_seconds, float decay);
    ~Wav();
private:
    FILE *f;
    wav_header_s head;
    size_t data_size;
    vector<vector<short>> channels_data;

    void HeadRefactor(int chan_count, int sample_rate, int samples_count_per_chan);
    void CheckHeader();
};<file_sep>/prog1/src/main.cpp
#include "IniParser/IniParser.h"

int main() {
	try {
    IniParser p("../input_files/lab01_input_correct_01.ini");
		p.PrintAll();
		std::cout << p.GetValue<std::string>("SECTION", "MaxWaitTimeMs");
		std::cout << p.GetValue<int>("SECTION", "RawCacheMaxGapMs") << std::endl;
	}
	catch (std::exception& e) {
		std::cerr << e.what();
	}
    return 0;
}

<file_sep>/prog3/src/main.cpp
#include <iostream>
#include "wav.h"

using namespace std;

int main(int argc, char *argv[]) {
    try {
        Wav w("../0.wav");
        w.PrintInfo();
        w.MakeReverb(0.500, 0.6f);
        w.MakeWavFile("rev.wav");
    }
    catch (WavException &e) {
        std::cout << e.what();
    }
    return 0;
}<file_sep>/prog1/src/IniParserException/IniParserException.h
#pragma once
#include <exception>
#include <string>

class IniParserException : public std::exception {
public:
    IniParserException(const std::string &excMessage) : message(excMessage) {}
	virtual const char* what() const noexcept;
    ~IniParserException() noexcept {}
private:
    std::string message;
};
class IO_Exception : public IniParserException {
public:
	IO_Exception(const std::string &filename) : IniParserException("File " + filename + " can't be read.\n") {};
};
class Format_Exception : public IniParserException {
public:
	Format_Exception(const std::string &line) : IniParserException("Format incorrect in line: " + line + '\n') {};
};
class Data_Exception : public IniParserException {
public:
	Data_Exception(const char *data_key_level, const std::string &key_name) : IniParserException(std::string(data_key_level) + '"'+ key_name + '"' + " can`t be found.\n") {};
};
<file_sep>/prog4/src/PrimeFactoring.h
#pragma once
#include <cstdint>
#include <vector>
#include <cmath>
#include <string>

class PrimeFactors {
public:
    PrimeFactors(uint64_t);
    void Factorize();
    std::string ToString() const;
    ~PrimeFactors() = default;
private:
    const uint64_t number;
    std::vector<std::pair<int, unsigned> > factors;
};<file_sep>/prog3/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(prog3)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES src/main.cpp src/wav.cpp src/wav_core.cpp src/wav.h src/wav_core.h src/wav_header.h src/WavExceptions.h)
add_executable(prog3 ${SOURCE_FILES})<file_sep>/prog1/input_files/lab01_input_correct_01.ini
[SECTION]
MaxWaitTimeMs = time
RawCacheMaxGapMs = 123
<file_sep>/prog2/CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(prog2)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES src/main.cpp src/StatisticMultiset.h)
add_executable(prog2 ${SOURCE_FILES})<file_sep>/prog1/src/IniParser/IniParser.cpp
#include "IniParser.h"
#include "../IniParserException/IniParserException.h"

IniParser::IniParser(const std::string& filename) {
    Initialize(filename);
    Parse();
}
IniParser::~IniParser() {
	data.clear();
	file.close();
}
void IniParser::Initialize(const std::string& filename) {
    file.open(filename);
    if (!file.is_open()) {
        throw IO_Exception(filename);
    }
}
void IniParser::Parse() {
    std::string s;
    std::string section_name, param_key, param_value;
    size_t len, foundSemiColon, foundDelim;
    while (std::getline(file, s)) {
        foundSemiColon = s.find(';');
        if (foundSemiColon != std::string::npos) {
            s = s.substr(0, foundSemiColon);
        }
        s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
        if (!s.empty()) {
            len = s.length();
            if (s[0]=='[' && s[s.length()-1]==']') {
                section_name = s.substr(1, len-2);
            }
            else {
                foundDelim = s.find('=');
                if (foundDelim == std::string::npos) {
					throw Format_Exception(s);
                }
				param_key = s.substr(0, foundDelim);
				param_value = s.substr(foundDelim + 1, len - foundDelim);
                data[section_name].insert(make_pair(param_key, param_value));
            }
        }
    }
}
void IniParser::PrintAll() const noexcept {
	std::map<std::string, std::map<std::string, std::string> >::const_iterator it;
	std::map<std::string, std::string>::const_iterator init;
	for (it = data.begin(); it != data.end(); it++) {
		std::cout << it->first << std::endl;
		for (init = (it->second).begin(); init != (it->second).end(); init++) {
			std::cout << init->first << '=' << init->second << std::endl;
		}
	}
};
bool IniParser::IsHaveSection(const std::string& section_name) const {
	if (data.find(section_name) == data.end()) {
		throw Data_Exception("Section ", section_name);
	}
	return true;
};
bool IniParser::IsHaveParam(const std::string& section_name, const std::string& param_name) const {
	IsHaveSection(section_name);
	if (data.at(section_name).find(param_name) == data.at(section_name).end()) {
		throw Data_Exception("Parameter ", param_name);
	}
	return true;
};
template<>
int IniParser::GetValue<int>(const std::string &section_name, const std::string &param_name) const {
	IsHaveParam(section_name, param_name);
	std::string x = data.find(section_name)->second.find(param_name)->second;
	try {
		return std::stoi(x);
	}
	catch (const std::invalid_argument&) {
		std::cerr << "Argument is invalid\n";
		throw;
	}
	catch (const std::out_of_range&) {
		std::cerr << "Argument is out of range for a integer\n";
		throw;
	}
}
template<>
double IniParser::GetValue<double>(const std::string &section_name, const std::string &param_name) const {
	IsHaveParam(section_name, param_name);
	std::string x = data.find(section_name)->second.find(param_name)->second;
	try {
		return std::stod(x);
	}
	catch (const std::invalid_argument&) {
		std::cerr << "Argument is invalid\n";
		throw;
	}
	catch (const std::out_of_range&) {
		std::cerr << "Argument is out of range for a integer\n";
		throw;
	}
}
template<>
std::string IniParser::GetValue<std::string>(const std::string &section_name, const std::string &param_name) const {
	IsHaveParam(section_name, param_name);
	return data.find(section_name)->second.find(param_name)->second + '\n';
}<file_sep>/prog3/src/WavExceptions.h
#pragma once
#include <exception>
#include <string>

class WavException : public std::exception {
public:
    WavException(const std::string &excMessage) : message(excMessage) {}
    std::string what() {
        return message;
    }
    ~WavException() throw() {}
private:
    std::string message;
};

class IO_Exception : public WavException {
public:
    IO_Exception(const std::string& filename) : WavException("File " + filename + " can't be read.\n") {};
};
class Format_Exception : public WavException {
public:
    Format_Exception(const std::string& msg) : WavException(msg) {};
};
class Header_Exception : public WavException {
public:
    Header_Exception(const std::string& msg) : WavException(msg) {};
};
class Parameters_Exception : public WavException {
public:
    Parameters_Exception(const std::string& msg) : WavException(msg) {};
};<file_sep>/prog1/src/IniParser/IniParser.h
#pragma once
#include <iostream>
#include <fstream>
#include <map>
#include <algorithm>
#include "../IniParserException/IniParserException.h"

class IniParser {
public:
	IniParser(const std::string& filename);
	// Processing and saving data
	void Parse();
	// Print
	void PrintAll() const noexcept;
	// Checks if a section exists.
	bool IsHaveSection(const std::string& section_name) const;
	// Checks if a pair param-section exists.
	bool IsHaveParam(const std::string& section_name, const std::string& param_name) const;
	// Return value from data by section and parameter
	template<typename T>
	T GetValue(const std::string &section_name, const std::string &param_name) const;
	~IniParser();
private:
	// Opens Ini file
	void Initialize(const std::string& filename);
	std::ifstream file;
	std::map <std::string, std::map <std::string, std::string> > data;
};<file_sep>/prog4/src/main.cpp
#include <iostream>
#include <fstream>
#include "PrimeFactoring.h"

int main(int argc, char* argv[]) {

    if (argc != 3) {
        std::cerr << "Arguments error" << std::endl;
        return 0;
    }

    std::ifstream fin(argv[1]);
    std::ofstream fout(argv[2]);

    if (!(fin.is_open() && fout.is_open())) {
        std::cerr << "Can't open files." << std::endl;
        return 0;
    }

    uint64_t cur_value;
    while (fin >> cur_value) {
        if (cur_value <= UINT64_MAX && cur_value > 0) {
            PrimeFactors pf(cur_value);
            fout << cur_value << " = " << pf.ToString() << std::endl;
        }
    }

    fout << std::endl;

    fin.close();
    fout.close();
    return 0;
}

languages: C++ INI CMake

repo_name: MorozovGl/OOP


text:
<repo_name>BenV1121/UExcercices<file_sep>/Assets/Scripts/Teleporter.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Teleporter : MonoBehaviour
{

    public GameObject otherTeleporter;
    public Transform teleportDestination;

    public float teleportationTimeout = 2.0f;
    public float teleportationTimer;

    public void Update()
    {
        teleportationTimer -= Time.deltaTime;
    }

    private void OnCollisionEnter (Collision collision)
    {
        if (teleportationTimer > 0.0f) { return; }

        teleportationTimer = teleportationTimeout;
        otherTeleporter.GetComponent<Teleporter>().teleportationTimer = teleportationTimeout;

        collision.transform.position = otherTeleporter.transform.position;
    }

    public void RecieveObject(GameObject package, float timeout)
    {
        package.transform.position = teleportDestination.position;

        teleportationTimer = timeout;

        otherTeleporter.GetComponent<Teleporter>().teleportationTimer = teleportationTimeout;
    }
}
<file_sep>/Assets/Scripts/Explosives.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Explosives : MonoBehaviour
{
    public float explosionForce = 15;
    public float explosionUpward = 1;
    public float explosionRadius = 5;

	// Use this for initialization
	void OnCollisionEnter (Collision collision)
    {
        Collider[] nearbyColliders = Physics.OverlapSphere(transform.position, explosionRadius);

        for(int i = 0; i < nearbyColliders.Length; ++i)
        {
            Rigidbody targetRbody = nearbyColliders[i].GetComponent<Rigidbody>();
            if(targetRbody != null)
            {
                //targetRbody.AddExplosionForce;
            }
        }
        Destroy(gameObject);
	}
}
<file_sep>/Assets/Scripts/PlayerHealth.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// Describes a type that can take damage.
interface IDamageable
{
    // Estimates the amount of health lost if damage is dealt.
    float EstimatedDamageTaken(float damageDealt);

    // Applies damage to this object.
    void TakeDamage(float damageDealt);
}

public class PlayerHealth : MonoBehaviour, IDamageable
{
    public float healthValue = 100;
    public float armorValue = 20;

    public float EstimatedDamageTaken(float damageDealt)
    {
        return damageDealt - armorValue;
    }

    public void TakeDamage(float damageDealth)
    {
        healthValue -= damageDealth;
    }
}

<file_sep>/Assets/Scripts/PlayerController2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController2 : MonoBehaviour
{
    public new GameObject camera;

    public float Force;

    public float xForce;
    public float yForce;

    public bool canMove;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (!canMove)
        {
            return;
        }

        transform.rotation = Quaternion.Euler(0, camera.GetComponent<MouseLook>().currentYRotation, 0);

        xForce = Input.GetAxis("Horizontal") * Force;
        yForce = Input.GetAxis("Vertical") * Force;

        transform.Translate(new Vector3(xForce, 0, yForce));
    }
}
<file_sep>/Assets/Scripts/Selector.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Selector : MonoBehaviour
{

    public GameObject[] targets;
    private int activeIdx;

	// Use this for initialization
	private void Select (int selectedIdx)
    {
        for(int i = 0; i < targets.Length; ++i)
        {
            targets[i].SetActive(false);
        }

        targets[selectedIdx].SetActive(true);
	}

	// Update is called once per frame
	private void Start ()
    {
        activeIdx = Random.Range(0, targets.Length - 1);
	}

    private void Update()
    {
        if(Input.GetKey(KeyCode.D))
        {
            activeIdx = (activeIdx + 1) % targets.Length;
            Select(activeIdx);
        }
    }
}
<file_sep>/Assets/Scripts/SpawnTracker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnTracker : MonoBehaviour
{
    public Spawner origin;

	// Use this for initialization
	void OnDestroy ()
    {
        origin.objNum--;
	}
}
<file_sep>/Assets/Scripts/Turret.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Turret : MonoBehaviour
{
    public GameObject player;
    public GameObject bulletPrefab;

    public float launchForce = 10.0f;

    public Transform firePoint;

    public float firingInterval = 1.0f;
    private float firingTimer;

    public float firingRadius = 15.0f;

    bool IsPlayerInRange()
    {
        return (player.transform.position - transform.position).magnitude < firingRadius;
    }

    void start()
    {
        firingTimer = firingInterval;
    }

	void Update ()
    {
        bool inRange = IsPlayerInRange();

        if(inRange)
        {
            Vector3 newForward = (player.transform.position - transform.position).normalized;
            transform.forward = newForward;
        }

        firingTimer -= Time.deltaTime;

        if (firingTimer <= 0.0f && inRange)
        {
            GameObject babyBullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
            babyBullet.GetComponent<Rigidbody>().AddForce(firePoint.forward * launchForce);

            firingTimer = firingInterval;
        }
	}

    void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, firingRadius);
    }
}