text:
Ansible role - Nginx server
=====
[![Build Status](https://travis-ci.org/repleo/ansible-role-nginx.svg?branch=master)](https://travis-ci.org/repleo/ansible-role-nginx)
[![Ansible Galaxy](http://img.shields.io/badge/galaxy-repleo.nginx-660198.svg?style=flat)](https://galaxy.ansible.com/repleo/nginx)

This role installs and configures the nginx web server. The user can specify
any http configuration parameters they wish to apply their site. Any number of
sites can be added with configurations of your choice.

This role supports letsencrypt SSL for easy installation of https webservers

Requirements
------------

This role requires Ansible 1.4 or higher and platform requirements are listed
in the metadata file.

Role Variables
--------------

The variables that can be passed to this role and a brief description about
them are as follows.

    # Force creation of nginx.conf. Normally, nginx.conf is only written if it does not exist.
    # If this parameter is true, it will override the current nginx.conf
    create_nginx_conf: true

    # The max clients allowed
    nginx_max_clients: 512

    # A hash of the http paramters. Note that any
    # valid nginx http paramters can be added here.
    # (see the nginx documentation for details.)
    nginx_http_params:
      sendfile: "on"
      tcp_nopush: "on"
      tcp_nodelay: "on"
      keepalive_timeout: "65"
      access_log: "/var/log/nginx/access.log"
      error_log: "/var/log/nginx/error.log"

    # A list of hashs that define the servers for nginx,
    # as with http parameters. Any valid server parameters
    # can be defined here.
    nginx_sites:
    - file_name: foo
      listen: 8080
      server_name: localhost
      root: "/tmp/site1"
      ssl:
        supplier: "local"
        local_keystore_dir: "{{ playbook_dir }}/files/"
        key: "ssl.key"
        certificate: "ssl_chain.pem"
      locations:
        - name: /
          lines:
            - "try_files: $uri $uri/ /index.html"
        - name: /images/
          lines:
            - "try_files: $uri $uri/ /index.html"
      lines:
        - "return 301 https://$http_host$request_uri;"
    - file_name: bar
      listen: 9090
      server_name: ansible
      root: "/tmp/site2"
      locations:
        - name: /
          lines:
            - "try_files: $uri $uri/ /index.html"
        - name: /images/
          lines:
            - "try_files: $uri $uri/ /index.html"

Examples
========

1) Install nginx with HTTP directives of choices, but with no sites
configured:

    - hosts: all
      roles:
      - {role: nginx,
            create_nginx_conf: true,
            nginx_http_params: { sendfile: "on",
                                               access_log: "/var/log/nginx/access.log"},
            nginx_sites: []
          }

2) Install nginx with different HTTP directives than previous example, but no
sites configured.

    - hosts: all
      roles:
      - {role: nginx,
            create_nginx_conf: true,
            nginx_http_params: { tcp_nodelay: "on",
                                               error_log: "/var/log/nginx/error.log"},
            nginx_sites: []
          }

Note: Please make sure the HTTP directives passed are valid, as this role
won't check for the validity of the directives. See the nginx documentation
for details.

3) Install nginx and add a site to the configuration.

    - hosts: all

      roles:
      - { role: nginx,
          create_nginx_conf: true,
          nginx_http_params: { tcp_nodelay: "on",
                                           error_log: "/var/log/nginx/error.log"},
          nginx_sites: [
            - file_name: bar,
              server_name: localhost,
              listen: 8080,
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
		   ]
		 ] }

Note: Each site added is represented by list of hashes, and the configurations
generated are populated in `/etc/nginx/sites-available/` and have corresponding
symlinks from `/etc/nginx/sites-enabled/`

The file name for the specific site configuration is specified in the hash
with the key "file_name", any valid server directives can be added to hash.

4) Install Nginx and add 2 sites (different method)

    - hosts: all

      roles:
      - { role: nginx,
          create_nginx_conf: true,
          nginx_http_params: { tcp_nodelay: "on",
                                           error_log: "/var/log/nginx/error.log"},
          nginx_sites: [
            - file_name: bar,
              server_name: localhost,
              listen: 8080,
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
		 ] }
            - file_name: bar,
              server_name: ansible,
              listen: 9090,
              root: "/tmp/site2",
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
		 ] }

5) Add virtual hosts to existing Nginx install (and install optionally Nginx if not installed yet)

    - hosts: all

      roles:
      - { role: nginx,
          nginx_sites: [
            - file_name: bar,
              server_name: localhost,
              listen: 8080,
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
		 ] }
            - file_name: bar,
              server_name: ansible,
              listen: 9090,
              root: "/tmp/site2",
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
		  ]
		] }

Note: without the parameter create_nginx_conf: true the role will not overwrite nginx.conf. This option allows to install virtual hosts to an existing nginx installation based on this role, i.e. installation scripts for different services using this role.

6) Example of an HTTPS server including installation of keys

    - hosts: all

      roles:
      - { role: nginx,
          nginx_sites: [
            - file_name: bar,
              server_name: localhost,
              listen: 8080,
              ssl: {
                  supplier: "local"
                  local_keystore_dir: "{{ playbook_dir }}/files/",
                  key: localhost.key,
                  certificate: localhost_chain.pem
              },
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		     ]
		  ]
		] }

Note: the ssl key and cert should be available in the calling project in the directory files.

7) Example of an HTTPS server including installation of letsencrypt keys

    - hosts: all

      roles:
      - { role: nginx,
          nginx_separate_logs_per_site: true,
          nginx_sites: [
            - file_name: bar.ssl,
              server_name: "example.com www.example.com",
              listen: 443,
              ssl: {
                  supplier: "letsencrypt",
                  domains: [
                    "example.com",
                    "www.example.com"
                  ],
		  generate_redirect: true
              },
              locations: [
                - name: /,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		              ]
                - name: /images/,
                  lines: [
                    - "try_files: $uri $uri/ /index.html"
		              ]
		          ]
		      ]
        }

Handlers
--------
The NGINX role provides two handlers:
- reload nginx
- restart nginx

Reloading the nginx configuration offers you the ability to update your webserver without downtime. However, it might occur old processes are not updated. Restart will ensure that the webserver is killed and restarted again and will cause (a short) downtime.

Example:

	- name: template configuration file
	  template: src=template.j2 dest=/etc/foo.conf
	  notify:
	     - restart nginx

Dependencies
------------

None

License
-------

BSD

Author Information
------------------

Repleo, Amstelveen, Holland -- www.repleo.nl
Jeroen Arnoldus (jeroen@repleo.nl)

Original version by:

Benno Joy


text:
using System;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Adaptive.ReactiveTrader.Client.Concurrency;
using Adaptive.ReactiveTrader.Client.Domain;
using Adaptive.ReactiveTrader.Client.Domain.Instrumentation;
using Adaptive.ReactiveTrader.Client.Domain.Models;
using Adaptive.ReactiveTrader.Client.Domain.Models.Execution;
using Adaptive.ReactiveTrader.Client.Domain.Models.Pricing;
using Adaptive.ReactiveTrader.Client.Domain.Models.ReferenceData;
using Adaptive.ReactiveTrader.Shared.Extensions;
using Adaptive.ReactiveTrader.Shared.Logging;
using Adaptive.ReactiveTrader.Shared.UI;
using PropertyChanged;

namespace Adaptive.ReactiveTrader.Client.UI.SpotTiles
{
    [ImplementPropertyChanged]
    public class SpotTilePricingViewModel : ViewModelBase, ISpotTilePricingViewModel
    {
        public IOneWayPriceViewModel Bid { get; private set; }
        public IOneWayPriceViewModel Ask { get; private set; }
        public string Notional { get; set; }
        public string Spread { get; private set; }
        public string DealtCurrency { get; private set; }
        public PriceMovement Movement { get; private set; }
        public string SpotDate { get; private set; }
        public bool IsSubscribing { get; private set; }
        public bool IsStale { get; private set; }

        private readonly SerialDisposable _priceSubscription;
        private readonly ICurrencyPair _currencyPair;
        private readonly ISpotTileViewModel _parent;
        private readonly IPriceLatencyRecorder _priceLatencyRecorder;
        private readonly IConcurrencyService _concurrencyService;
        private readonly IConstantRatePump _constantRatePump;
        private bool _disposed;
        private decimal? _previousRate;
        private SpotTileSubscriptionMode _subscriptionMode;

        private volatile IPrice _latestPrice;
        private IPrice _currentPrice;
        private readonly ILog _log;

        public SpotTilePricingViewModel(ICurrencyPair currencyPair, SpotTileSubscriptionMode spotTileSubscriptionMode, ISpotTileViewModel parent,
            Func<Direction, ISpotTilePricingViewModel, IOneWayPriceViewModel> oneWayPriceFactory,
            IReactiveTrader reactiveTrader,
            IConcurrencyService concurrencyService,
            IConstantRatePump constantRatePump,
            ILoggerFactory loggerFactory)
        {
            _currencyPair = currencyPair;
            _subscriptionMode = spotTileSubscriptionMode;
            _parent = parent;
            _priceLatencyRecorder = reactiveTrader.PriceLatencyRecorder;
            _concurrencyService = concurrencyService;
            _constantRatePump = constantRatePump;
            _log = loggerFactory.Create(typeof (SpotTilePricingViewModel));

            _priceSubscription = new SerialDisposable();
            Bid = oneWayPriceFactory(Direction.SELL, this);
            Ask = oneWayPriceFactory(Direction.BUY, this);
            Notional = "1000000";
            DealtCurrency = currencyPair.BaseCurrency;
            SpotDate = "SP";
            IsSubscribing = true;

            SubscribeForPrices();
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                _priceSubscription.Dispose();
                _disposed = true;
            }
        }

        public string Symbol { get { return String.Format("{0} / {1}", _currencyPair.BaseCurrency, _currencyPair.CounterCurrency); } }

        public SpotTileSubscriptionMode SubscriptionMode
        {
            get { return _subscriptionMode; }
            set
            {
                if (_subscriptionMode != value)
                {
                    _subscriptionMode = value;
                    SubscribeForPrices();
                }
            }
        }

        public SpotTileExecutionMode ExecutionMode
        {
            get { return Bid.ExecutionMode; }
            set {
                Bid.ExecutionMode = value;
                Ask.ExecutionMode = value;
            }
        }

        private void SubscribeForPrices()
        {
            switch (SubscriptionMode)
            {
                case SpotTileSubscriptionMode.OnDispatcher:
                    SubscribeForPricesOnDispatcher();
                    break;
                case SpotTileSubscriptionMode.ObserveLatestOnDispatcher:
                    SubscribeForPricesLatestOnDispatch();
                    break;
                case SpotTileSubscriptionMode.Conflate:
                    SubscribeForPricesConflate();
                    break;
                case SpotTileSubscriptionMode.ConstantRate:
                    SubscribeForPricesConstantRate();
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        private void SubscribeForPricesOnDispatcher()
        {
            _priceSubscription.Disposable = _currencyPair.PriceStream
                                        .SubscribeOn(_concurrencyService.TaskPool)
                                        .ObserveOn(_concurrencyService.Dispatcher)
                                        .Subscribe(OnPrice, OnError);
        }

        private void SubscribeForPricesLatestOnDispatch()
        {
            _priceSubscription.Disposable = _currencyPair.PriceStream
                                        .SubscribeOn(_concurrencyService.TaskPool)
                                        .ObserveLatestOn(_concurrencyService.Dispatcher)
                                        .Subscribe(OnPrice, OnError);
        }

        private void SubscribeForPricesConflate()
        {
            _priceSubscription.Disposable = _currencyPair.PriceStream
                                        .SubscribeOn(_concurrencyService.TaskPool)
                                        .Conflate(TimeSpan.FromMilliseconds(125), _concurrencyService.Dispatcher)
                                        .Subscribe(OnPrice, OnError);
        }

        private void SubscribeForPricesConstantRate()
        {
            var ps = _currencyPair.PriceStream
                                  .SubscribeOn(_concurrencyService.TaskPool)
                                  .Subscribe(price =>
                                      {
                                          _latestPrice = price;
                                      }, OnError);

            var el = _constantRatePump.Tick.Subscribe(_ =>
                {
                    if (_currentPrice != _latestPrice && _latestPrice != null)
                    {
                        OnPrice(_latestPrice);
                    }
                });

            _priceSubscription.Disposable = new CompositeDisposable(ps, el);
        }

        private void OnPrice(IPrice price)
        {
            IsSubscribing = false;
            IsStale = price.IsStale;

            if (price.IsStale)
            {
                Bid.OnStalePrice();
                Ask.OnStalePrice();
                Spread = string.Empty;
                _previousRate = null;
                Movement = PriceMovement.None;
                SpotDate = "SP";
            }
            else
            {
                if (_previousRate.HasValue)
                {
                    if (price.Mid > _previousRate.Value)
                        Movement = PriceMovement.Up;
                    else if (price.Mid < _previousRate.Value)
                        Movement = PriceMovement.Down;
                    else
                        Movement = PriceMovement.None;
                }
                _previousRate = price.Mid;

                Bid.OnPrice(price.Bid);
                Ask.OnPrice(price.Ask);
                Spread = PriceFormatter.GetFormattedSpread(price.Spread, _currencyPair.RatePrecision, _currencyPair.PipsPosition);
                SpotDate = "SP. " + price.ValueDate.ToString("dd MMM");

                _priceLatencyRecorder.OnRendered(price);

            }
            _currentPrice = price;
        }

        private void OnError(Exception ex)
        {
            _log.Error("Failed to get prices for " + _currencyPair.Symbol, ex);
        }

        public void OnTrade(ITrade trade)
        {
            _parent.OnTrade(trade);
        }

        public void OnExecutionError(string message)
        {
            _parent.OnExecutionError(message);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const common = require('./components/common');
const logger = require('./components/logger');
// const redis = require('./components/redis');
// const redis = require('./components/rabbitmq');
const server = require('./components/server');

module.exports = Object.assign({}, common, logger, server);


text:
default['debnetwork']['ipv4_forward'] = false
default['debnetwork']['ipv4_preferred'] = false
default['debnetwork']['ipv6_forward'] = false
default['debnetwork']['ipv6_enabled'] = true

# Automatically turn off ipv6 if no global exists
inet6global = node['network']['interfaces'].select do |_, netdata|
  unless netdata.attribute? 'addresses'
    return false
  end

  inet6 = netdata['addresses'].select do |_, adata|
    adata['scope'] == 'Global' && adata['family'] == 'inet6'
  end

  inet6.count > 0
end

if inet6global.empty?
  Chef::Log.info 'Disabling ipv6 by default since no global interface is found'
  override['debnetwork']['ipv6_enabled'] = false
end

default['debnetwork']['accept_redirects'] = false
default['debnetwork']['send_redirects'] = true

default['debnetwork']['input_rules'] = [ ]
default['debnetwork']['output_rules'] = [ ]
default['debnetwork']['postrouting_rules'] = [ ]
default['debnetwork']['forward_rules'] = [ ]
default['debnetwork']['forward6_rules'] = [ ]

default['debnetwork']['after_rules']['template_source']      = 'ufw/after.rules.erb'
default['debnetwork']['after_rules']['template_cookbook']    = 'debnetwork'

default['debnetwork']['after6_rules']['template_source']     = 'ufw/after6.rules.erb'
default['debnetwork']['after6_rules']['template_cookbook']   = 'debnetwork'

default['debnetwork']['before_rules']['template_source']     = 'ufw/before.rules.erb'
default['debnetwork']['before_rules']['template_cookbook']   = 'debnetwork'

default['debnetwork']['before6_rules']['template_source']    = 'ufw/before6.rules.erb'
default['debnetwork']['before6_rules']['template_cookbook']  = 'debnetwork'

default['debnetwork']['default_ufw']['template_source']      = 'ufw/default.erb'
default['debnetwork']['default_ufw']['template_cookbook']    = 'debnetwork'

default['debnetwork']['sysctl_conf']['template_source']      = 'ufw/sysctl.conf.erb'
default['debnetwork']['sysctl_conf']['template_cookbook']    = 'debnetwork'


text:
<!DOCTYPE html>

<title>BluetoothHealthProfileHandler_connectToSource_missarg</title>


text:
class Greeter {
    greet(name : string) {
        return "A type-scripting greeting to you, " + name;
    }
}

export = Greeter;


text:
using System;
using System.Web.UI.WebControls;
using BLL;
using Model;

namespace News
{
    public partial class NewsSortList : System.Web.UI.Page
    {
        NewsSortMgr nsm = new NewsSortMgr();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                newsBind();
            }
        }

        public void newsBind()
        {
            var list = nsm.Select();
            gvNewSort.DataSource = list;
            gvNewSort.DataBind();
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var user = (UserInfo)Session["User"];
            if (user == null)
            {
                Response.Redirect("Login.aspx");
            }
            int id = Convert.ToInt32(gvNewSort.Rows[e.RowIndex].Cells[1].Text);
            NewsSort ns = new NewsSort()
            {
                ID = id
            };
            nsm.Delete(ns);
            newsBind();
            Response.Write("<script>alert('删除成功!')</script>");
            e.Cancel = true;
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            var user = (UserInfo)Session["User"];
            if (user == null)
            {
                Response.Redirect("Login.aspx");
            }
            int id = Convert.ToInt32(gvNewSort.Rows[e.NewEditIndex].Cells[1].Text);
            Response.Redirect("NewsSortEdit.aspx?id=" + id);
        }
    }
}


text:
<?php

use app\components\Migration;
use app\modules\content\models\beds\Bed;
use app\modules\content\models\beds\BedBlock;

class m150303_074024_added_bed_tables extends Migration
{
    private $bedTbl;
    private $blockTbl;
    private $blockIsActiveIndex;
    private $blockPositionIndex;
    private $bedIdProtoFk;
    private $blockIdBedFk;

    public function init()
    {
        parent::init();
        $this->bedTbl = Bed::tableName();
        $this->blockTbl = BedBlock::tableName();
        $this->blockIsActiveIndex = $this->createIndexData($this->blockTbl, 'is_active');
        $this->blockPositionIndex = $this->createIndexData($this->blockTbl, 'position');
        $this->bedIdProtoFk = $this->createFkData($this->bedTbl, 'id_proto', $this->bedTbl, 'id', 'restrict', 'cascade');
        $this->blockIdBedFk = $this->createFkData($this->blockTbl, 'id_bed', $this->bedTbl, 'id', 'cascade', 'cascade');
    }

    public function getType()
    {
        return self::TYPE_STRUCT;
    }

    public function safeUp()
    {
        $this->createTable($this->bedTbl, [
            'id' => 'serial primary key',
            'id_proto' => 'int',
            'is_default' => 'boolean not null default false',
        ]);

        $this->createTable($this->blockTbl, [
            'id' => 'serial primary key',
            'id_bed' => 'int not null',
            'is_active' => 'boolean not null default true',
            'position' => 'smallint not null',
            'source' => 'varchar(255) not null',
            'params' => 'jsonb',
        ]);

        $this->createIndex(...$this->blockIsActiveIndex);
        $this->createIndex(...$this->blockPositionIndex);

        $this->addForeignKey(...$this->bedIdProtoFk);
        $this->addForeignKey(...$this->blockIdBedFk);
    }

    public function safeDown()
    {
        $this->dropForeignKey(...$this->bedIdProtoFk);
        $this->dropForeignKey(...$this->blockIdBedFk);

        $this->dropIndex(...$this->blockIsActiveIndex);
        $this->dropIndex(...$this->blockPositionIndex);

        $this->dropTable($this->blockTbl);
        $this->dropTable($this->bedTbl);
    }
}


text:
package io.fintrospect

import java.io.File
import java.net.URL

trait ResourceLoader {
  def load(path: String): URL
}

object ResourceLoader {
  /**
    * Load static resources from the classpath path. Useful when you're just loading from a JAR. Note that due to security concerns
    * this should be with a package which does NOT contain class files.
    *
    * @param basePackagePath
    */
  def Classpath(basePackagePath: String = "/") = new ResourceLoader {
    private val withStarting = if (basePackagePath.startsWith("/")) basePackagePath else "/" + basePackagePath
    private val finalBasePath = if (withStarting.endsWith("/")) withStarting else withStarting + "/"

    override def load(path: String): URL = getClass.getResource(finalBasePath + path)
  }

  /**
    * Load static resources from a directory path. Using this version allows for hot-reload from the file system.
    *
    * @param baseDir
    */
  def Directory(baseDir: String) = new ResourceLoader {
    private val finalBaseDir = if (baseDir.endsWith("/")) baseDir else baseDir + "/"

    override def load(path: String): URL = {
      val f = new File(finalBaseDir, path)
      if (f.exists() && f.isFile) f.toURI.toURL else null
    }
  }
}


text:
require "navigatrix/version"
require "navigatrix/item"
require "navigatrix/item_collection"
require "navigatrix/renderer"
require "navigatrix/builder"
require 'navigatrix/integration/rails' if defined?(Rails)
require 'navigatrix/integration/sinatra' if defined?(Sinatra)

module Navigatrix
  extend self

  mattr_accessor :list_renderers

  self.list_renderers = {
    :unordered_list   => Rendering::Strategies::List,
    :bootstrap_navbar => Rendering::Strategies::Bootstrap::Navbar,
    :bootstrap_tabs   => Rendering::Strategies::Bootstrap::Tabs
  }

  mattr_accessor :item_renderers
  self.item_renderers = {
    :item => Rendering::Strategies::Item
  }

  def register_list_renderer(name, &block)
    list_renderers[name] = ListBuilder.build(&block)
  end

  def register_item_renderer(name, &block)
    item_renderers[name] = ItemBuilder.build(&block)
  end
end


text:
package com.dacer.androidcharts;

import java.util.ArrayList;
import java.util.Collections;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.NinePatchDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Dacer on 11/4/13.
 * Edited by Lee youngchan 21/1/14
 */
public class LineView extends View {
    private int mViewHeight;
    //drawBackground
    private boolean autoSetDataOfGird = true;
    private boolean autoSetGridWidth = true;
    private int dataOfAGird = 10;
    private int bottomTextHeight = 0;
    private ArrayList<String> bottomTextList;

    private ArrayList<ArrayList<Integer>> dataLists;
    private ArrayList<Integer> dataList;

    private ArrayList<Integer> xCoordinateList = new ArrayList<Integer>();
    private ArrayList<Integer> yCoordinateList = new ArrayList<Integer>();

    private ArrayList<ArrayList<Dot>> drawDotLists = new ArrayList<ArrayList<Dot>>();
    private ArrayList<Dot> drawDotList = new ArrayList<Dot>();

    private Paint bottomTextPaint = new Paint();
    private int bottomTextDescent;

    //popup
    private Paint popupTextPaint = new Paint();
    private final int bottomTriangleHeight = 12;
    public boolean showPopup = true;

	private Dot selectedDot;

    private int topLineLength = MyUtils.dip2px(getContext(), 12);; // | | ←this
                                                                   //-+-+-
    private int sideLineLength = MyUtils.dip2px(getContext(),45)/3*2;// --+--+--+--+--+--+--
                                                                     //  ↑this
    private int backgroundGridWidth = MyUtils.dip2px(getContext(),45);

    //Constants
    private final int popupTopPadding = MyUtils.dip2px(getContext(),2);
    private final int popupBottomMargin = MyUtils.dip2px(getContext(),5);
    private final int bottomTextTopMargin = MyUtils.sp2px(getContext(),5);
    private final int bottomLineLength = MyUtils.sp2px(getContext(), 22);
    private final int DOT_INNER_CIR_RADIUS = MyUtils.dip2px(getContext(), 2);
    private final int DOT_OUTER_CIR_RADIUS = MyUtils.dip2px(getContext(),5);
    private final int MIN_TOP_LINE_LENGTH = MyUtils.dip2px(getContext(),12);
    private final int MIN_VERTICAL_GRID_NUM = 4;
    private final int MIN_HORIZONTAL_GRID_NUM = 1;
    private final int BACKGROUND_LINE_COLOR = Color.parseColor("#EEEEEE");
    private final int BOTTOM_TEXT_COLOR = Color.parseColor("#9B9A9B");

    public static final int SHOW_POPUPS_All = 1;
    public static final int SHOW_POPUPS_MAXMIN_ONLY = 2;
    public static final int SHOW_POPUPS_NONE = 3;

    private int showPopupType = SHOW_POPUPS_NONE;
    public void setShowPopup(int popupType) {
		this.showPopupType = popupType;
	}

	//점선표시
    private Boolean drawDotLine = false;
    //라인컬러
    private String[] colorArray = {"#e74c3c","#2980b9","#1abc9c"};
    //popup 컬러
    private int[] popupColorArray = {R.drawable.popup_red,R.drawable.popup_blue,R.drawable.popup_green};

	public void setDrawDotLine(Boolean drawDotLine) {
		this.drawDotLine = drawDotLine;
	}

	private Runnable animator = new Runnable() {
        @Override
        public void run() {
            boolean needNewFrame = false;
            for(ArrayList<Dot> data : drawDotLists){
            	for(Dot dot : data){
                    dot.update();
                    if(!dot.isAtRest()){
                        needNewFrame = true;
                    }
                }
            }
            if (needNewFrame) {
                postDelayed(this, 25);
            }
            invalidate();
        }
    };

    public LineView(Context context){
        this(context,null);
    }
    public LineView(Context context, AttributeSet attrs){
        super(context, attrs);
        popupTextPaint.setAntiAlias(true);
        popupTextPaint.setColor(Color.WHITE);
        popupTextPaint.setTextSize(MyUtils.sp2px(getContext(), 13));
        popupTextPaint.setStrokeWidth(5);
        popupTextPaint.setTextAlign(Paint.Align.CENTER);

        bottomTextPaint.setAntiAlias(true);
        bottomTextPaint.setTextSize(MyUtils.sp2px(getContext(),12));
        bottomTextPaint.setTextAlign(Paint.Align.CENTER);
        bottomTextPaint.setStyle(Paint.Style.FILL);
        bottomTextPaint.setColor(BOTTOM_TEXT_COLOR);
    }

    /**
     * dataList will be reset when called is method.
     * @param bottomTextList The String ArrayList in the bottom.
     */
    public void setBottomTextList(ArrayList<String> bottomTextList){
        this.dataList = null;
        this.bottomTextList = bottomTextList;

        Rect r = new Rect();
        int longestWidth = 0;
        String longestStr = "";
        bottomTextDescent = 0;
        for(String s:bottomTextList){
            bottomTextPaint.getTextBounds(s,0,s.length(),r);
            if(bottomTextHeight<r.height()){
                bottomTextHeight = r.height();
            }
            if(autoSetGridWidth&&(longestWidth<r.width())){
                longestWidth = r.width();
                longestStr = s;
            }
            if(bottomTextDescent<(Math.abs(r.bottom))){
                bottomTextDescent = Math.abs(r.bottom);
            }
        }

        if(autoSetGridWidth){
            if(backgroundGridWidth<longestWidth){
                backgroundGridWidth = longestWidth+(int)bottomTextPaint.measureText(longestStr,0,1);
            }
            if(sideLineLength<longestWidth/2){
                sideLineLength = longestWidth/2;
            }
        }

        refreshXCoordinateList(getHorizontalGridNum());
    }

    /**
     *
     * @param dataLists The Integer ArrayLists for showing,
     *                 dataList.size() must < bottomTextList.size()
     */
    public void setDataList(ArrayList<ArrayList<Integer>> dataLists){
    	selectedDot = null;
        this.dataLists = dataLists;
        for(ArrayList<Integer> list : dataLists){
        	if(list.size() > bottomTextList.size()){
                throw new RuntimeException("dacer.LineView error:" +
                        " dataList.size() > bottomTextList.size() !!!");
            }
        }
        int biggestData = 0;
        for(ArrayList<Integer> list : dataLists){
        	if(autoSetDataOfGird){
                for(Integer i:list){
                    if(biggestData<i){
                        biggestData = i;
                    }
                }
        	}
        	dataOfAGird = 1;
        	while(biggestData/10 > dataOfAGird){
        		dataOfAGird *= 10;
        	}
        }

        refreshAfterDataChanged();
        showPopup = true;
        setMinimumWidth(0); // It can help the LineView reset the Width,
                                // I don't know the better way..
        postInvalidate();
    }

    private void refreshAfterDataChanged(){
        int verticalGridNum = getVerticalGridlNum();
        refreshTopLineLength(verticalGridNum);
        refreshYCoordinateList(verticalGridNum);
        refreshDrawDotList(verticalGridNum);
    }

    private int getVerticalGridlNum(){
        int verticalGridNum = MIN_VERTICAL_GRID_NUM;
        if(dataLists != null && !dataLists.isEmpty()){
        	for(ArrayList<Integer> list : dataLists){
	        	for(Integer integer:list){
	        		if(verticalGridNum<(integer+1)){
	        			verticalGridNum = integer+1;
	        		}
	        	}
        	}
        }
        return verticalGridNum;
    }

    private int getHorizontalGridNum(){
        int horizontalGridNum = bottomTextList.size()-1;
        if(horizontalGridNum<MIN_HORIZONTAL_GRID_NUM){
            horizontalGridNum = MIN_HORIZONTAL_GRID_NUM;
        }
        return horizontalGridNum;
    }

    private void refreshXCoordinateList(int horizontalGridNum){
        xCoordinateList.clear();
        for(int i=0;i<(horizontalGridNum+1);i++){
            xCoordinateList.add(sideLineLength + backgroundGridWidth*i);
        }

    }

    private void refreshYCoordinateList(int verticalGridNum){
        yCoordinateList.clear();
        for(int i=0;i<(verticalGridNum+1);i++){
            yCoordinateList.add(topLineLength +
                    ((mViewHeight-topLineLength-bottomTextHeight-bottomTextTopMargin-
                            bottomLineLength-bottomTextDescent)*i/(verticalGridNum)));
        }
    }

    private void refreshDrawDotList(int verticalGridNum){
        if(dataLists != null && !dataLists.isEmpty()){
    		if(drawDotLists.size() == 0){
    			for(int k = 0; k < dataLists.size(); k++){
    				drawDotLists.add(new ArrayList<LineView.Dot>());
    			}
    		}
        	for(int k = 0; k < dataLists.size(); k++){
        		int drawDotSize = drawDotLists.get(k).isEmpty()? 0:drawDotLists.get(k).size();

        		for(int i=0;i<dataLists.get(k).size();i++){
                    int x = xCoordinateList.get(i);
                    int y = yCoordinateList.get(verticalGridNum - dataLists.get(k).get(i));
                    if(i>drawDotSize-1){
                    	//도트리스트를 추가한다.
                        drawDotLists.get(k).add(new Dot(x, 0, x, y, dataLists.get(k).get(i),k));
                    }else{
                    	//도트리스트에 타겟을 설정한다.
                        drawDotLists.get(k).set(i, drawDotLists.get(k).get(i).setTargetData(x,y,dataLists.get(k).get(i),k));
                    }
                }

        		int temp = drawDotLists.get(k).size() - dataLists.get(k).size();
        		for(int i=0; i<temp; i++){
        			drawDotLists.get(k).remove(drawDotLists.get(k).size()-1);
        		}
        	}
        }
        removeCallbacks(animator);
        post(animator);
    }

    private void refreshTopLineLength(int verticalGridNum){
        // For prevent popup can't be completely showed when backgroundGridHeight is too small.
        // But this code not so good.
        if((mViewHeight-topLineLength-bottomTextHeight-bottomTextTopMargin)/
                (verticalGridNum+2)<getPopupHeight()){
            topLineLength = getPopupHeight()+DOT_OUTER_CIR_RADIUS+DOT_INNER_CIR_RADIUS+2;
        }else{
            topLineLength = MIN_TOP_LINE_LENGTH;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        drawBackgroundLines(canvas);
        drawLines(canvas);
        drawDots(canvas);

        for(int k=0; k < drawDotLists.size(); k++){
        	int MaxValue = Collections.max(dataLists.get(k));
        	int MinValue = Collections.min(dataLists.get(k));
        	for(Dot d: drawDotLists.get(k)){
        		if(showPopupType == SHOW_POPUPS_All)
        			drawPopup(canvas, String.valueOf(d.data), d.getPoint(),popupColorArray[k%3]);
        		else if(showPopupType == SHOW_POPUPS_MAXMIN_ONLY){
        			if(d.data == MaxValue)
        				drawPopup(canvas, String.valueOf(d.data), d.getPoint(),popupColorArray[k%3]);
        			if(d.data == MinValue)
        				drawPopup(canvas, String.valueOf(d.data), d.getPoint(),popupColorArray[k%3]);
        		}
        	}
        }
// 선택한 dot 만 popup 이 뜨게 한다.
        if(showPopup && selectedDot != null){
            drawPopup(canvas,
                    String.valueOf(selectedDot.data),
                    selectedDot.getPoint(),popupColorArray[selectedDot.linenumber%3]);
        }
    }

    /**
     *
     * @param canvas  The canvas you need to draw on.
     * @param point   The Point consists of the x y coordinates from left bottom to right top.
     *                Like is
     *
     *                3
     *                2
     *                1
     *                0 1 2 3 4 5
     */
    private void drawPopup(Canvas canvas,String num, Point point,int PopupColor){
        boolean singularNum = (num.length() == 1);
        int sidePadding = MyUtils.dip2px(getContext(),singularNum? 8:5);
        int x = point.x;
        int y = point.y-MyUtils.dip2px(getContext(),5);
        Rect popupTextRect = new Rect();
        popupTextPaint.getTextBounds(num,0,num.length(),popupTextRect);
        Rect r = new Rect(x-popupTextRect.width()/2-sidePadding,
                y - popupTextRect.height()-bottomTriangleHeight-popupTopPadding*2-popupBottomMargin,
                x + popupTextRect.width()/2+sidePadding,
                y+popupTopPadding-popupBottomMargin);

        NinePatchDrawable popup = (NinePatchDrawable)getResources().getDrawable(PopupColor);
        popup.setBounds(r);
        popup.draw(canvas);
        canvas.drawText(num, x, y-bottomTriangleHeight-popupBottomMargin, popupTextPaint);
    }

    private int getPopupHeight(){
        Rect popupTextRect = new Rect();
        popupTextPaint.getTextBounds("9",0,1,popupTextRect);
        Rect r = new Rect(-popupTextRect.width()/2,
                 - popupTextRect.height()-bottomTriangleHeight-popupTopPadding*2-popupBottomMargin,
                 + popupTextRect.width()/2,
                +popupTopPadding-popupBottomMargin);
        return r.height();
    }

    //도트그리기
    private void drawDots(Canvas canvas){
        Paint bigCirPaint = new Paint();
        bigCirPaint.setAntiAlias(true);
        Paint smallCirPaint = new Paint(bigCirPaint);
        smallCirPaint.setColor(Color.parseColor("#FFFFFF"));
        if(drawDotLists!=null && !drawDotLists.isEmpty()){
        	for(int k=0; k < drawDotLists.size(); k++){
        		bigCirPaint.setColor(Color.parseColor(colorArray[k%3]));
        		for(Dot dot : drawDotLists.get(k)){
                	canvas.drawCircle(dot.x,dot.y,DOT_OUTER_CIR_RADIUS,bigCirPaint);
                	canvas.drawCircle(dot.x,dot.y,DOT_INNER_CIR_RADIUS,smallCirPaint);
            	}
        	}
        }
    }

    //선그리기
    private void drawLines(Canvas canvas){
        Paint linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(MyUtils.dip2px(getContext(), 2));
        for(int k = 0; k<drawDotLists.size(); k ++){
        	linePaint.setColor(Color.parseColor(colorArray[k%3]));
	        for(int i=0; i<drawDotLists.get(k).size()-1; i++){
	            canvas.drawLine(drawDotLists.get(k).get(i).x,
	                    drawDotLists.get(k).get(i).y,
	                    drawDotLists.get(k).get(i+1).x,
	                    drawDotLists.get(k).get(i+1).y,
	                    linePaint);
	        }
        }
    }

     private void drawBackgroundLines(Canvas canvas){
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(MyUtils.dip2px(getContext(),1f));
        paint.setColor(BACKGROUND_LINE_COLOR);
        PathEffect effects = new DashPathEffect(
                new float[]{10,5,10,5}, 1);

        //draw vertical lines
        for(int i=0;i<xCoordinateList.size();i++){
            canvas.drawLine(xCoordinateList.get(i),
                    0,
                    xCoordinateList.get(i),
                    mViewHeight - bottomTextTopMargin - bottomTextHeight-bottomTextDescent,
                    paint);
        }

        //draw dotted lines
      paint.setPathEffect(effects);
      Path dottedPath = new Path();
      for(int i=0;i<yCoordinateList.size();i++){
          if((yCoordinateList.size()-1-i)%dataOfAGird == 0){
              dottedPath.moveTo(0, yCoordinateList.get(i));
              dottedPath.lineTo(getWidth(), yCoordinateList.get(i));
              canvas.drawPath(dottedPath, paint);
          }
      }
    	  //draw bottom text
      if(bottomTextList != null){
    	  for(int i=0;i<bottomTextList.size();i++){
    		  canvas.drawText(bottomTextList.get(i), sideLineLength+backgroundGridWidth*i, mViewHeight-bottomTextDescent, bottomTextPaint);
    	  }
      }

      if(!drawDotLine){
    	//draw solid lines
          for(int i=0;i<yCoordinateList.size();i++){
              if((yCoordinateList.size()-1-i)%dataOfAGird == 0){
                  canvas.drawLine(0,yCoordinateList.get(i),getWidth(),yCoordinateList.get(i),paint);
              }
          }
      }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int mViewWidth = measureWidth(widthMeasureSpec);
        mViewHeight = measureHeight(heightMeasureSpec);
        refreshAfterDataChanged();
        setMeasuredDimension(mViewWidth,mViewHeight);
    }

    private int measureWidth(int measureSpec){
        int horizontalGridNum = getHorizontalGridNum();
        int preferred = backgroundGridWidth*horizontalGridNum+sideLineLength*2;
        return getMeasurement(measureSpec, preferred);
    }

    private int measureHeight(int measureSpec){
        int preferred = 0;
        return getMeasurement(measureSpec, preferred);
    }

    private int getMeasurement(int measureSpec, int preferred){
        int specSize = MeasureSpec.getSize(measureSpec);
        int measurement;
        switch(MeasureSpec.getMode(measureSpec)){
            case MeasureSpec.EXACTLY:
                measurement = specSize;
                break;
            case MeasureSpec.AT_MOST:
                measurement = Math.min(preferred, specSize);
                break;
            default:
                measurement = preferred;
                break;
        }
        return measurement;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Point point = new Point();
        point.x = (int) event.getX();
        point.y = (int) event.getY();
        Region r = new Region();
        int width = backgroundGridWidth/2;
        if(drawDotLists != null || !drawDotLists.isEmpty()){
	        for(ArrayList<Dot> data : drawDotLists){
	        	for(Dot dot : data){
	        		r.set(dot.x-width,dot.y-width,dot.x+width,dot.y+width);
	                if (r.contains(point.x,point.y) && event.getAction() == MotionEvent.ACTION_DOWN){
	                    selectedDot = dot;
	                }else if (event.getAction() == MotionEvent.ACTION_UP){
	                    if (r.contains(point.x,point.y)){
	                        showPopup = true;
	                    }
	                }
	            }
	        }
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN ||
                event.getAction() == MotionEvent.ACTION_UP){
            postInvalidate();
        }
        return true;
    }

    class Dot{
        int x;
        int y;
        int data;
        int targetX;
        int targetY;
        int linenumber;
        int velocity = MyUtils.dip2px(getContext(),18);

        Dot(int x,int y,int targetX,int targetY,Integer data,int linenumber){
            this.x = x;
            this.y = y;
            this.linenumber = linenumber;
            setTargetData(targetX, targetY,data,linenumber);
        }

        Point getPoint(){
            return new Point(x,y);
        }

        Dot setTargetData(int targetX,int targetY,Integer data,int linenumber){
            this.targetX = targetX;
            this.targetY = targetY;
            this.data = data;
            this.linenumber = linenumber;
            return this;
        }

        boolean isAtRest(){
            return (x==targetX)&&(y==targetY);
        }

        void update(){
            x = updateSelf(x, targetX, velocity);
            y = updateSelf(y, targetY, velocity);
        }

        private int updateSelf(int origin, int target, int velocity){
            if (origin < target) {
                origin += velocity;
            } else if (origin > target){
                origin-= velocity;
            }
            if(Math.abs(target-origin)<velocity){
                origin = target;
            }
            return origin;
        }
    }
}


text:
using System.Reflection;
using System.Windows.Controls;

namespace MVVMTemplateSelection
{
    public abstract class BaseDataTemplateSelector : DataTemplateSelector
    {
        public Assembly[] Assembly { get; set; }
    }
}


text:
package com.navercorp.pinpoint.test.plugin.util;

import org.junit.Test;

public class TestPluginVersionTest {
    @Test
    public void test() {
        org.junit.Assert.assertNotNull(TestPluginVersion.getVersion());
    }

}


text:
using LCL.Domain.Entities;
using System;
using System.Collections.Generic;
namespace LCL.Domain.Services
{
    public interface ILocalizationService
    {
        void DeleteLocaleStringResource(LocaleStringResource localeStringResource);
        string GetResource(string resourceKey);
        List<LocaleStringResource> GetStringResourceAll();
        void InsertLocaleStringResource(LocaleStringResource localeStringResource);
        void UpdateLocaleStringResource(LocaleStringResource localeStringResource);
    }
}


text:
module Stackage.Database
    ( module X
    ) where
import Stackage.Database.Schema as X
import Stackage.Database.Query as X
import Stackage.Database.Types as X


text:
title: Greedy Algorithms
localeTitle: Жадные алгоритмы
---
## Что такое жадный алгоритм

Вы, должно быть, слышали о многих алгоритмических методах проектирования, просеивая некоторые из статей здесь. Некоторые из них :

*   Грубая сила
*   Разделить и покорить
*   Жадное программирование
*   Динамическое программирование назвать несколько. В этой статье вы узнаете, что такое жадный алгоритм и как вы можете использовать эту технику для решения многих проблем программирования, которые в противном случае не кажутся тривиальными.

Представьте, что вы собираетесь отправиться в поход, и ваша цель - достичь максимально возможного пика. У вас уже есть карта, прежде чем вы начнете, но есть тысячи возможных путей, отображаемых на карте. Вы слишком ленивы и просто не имеете времени оценить каждую из них. Вверните карту! Вы начали поход с простой стратегией - быть жадным и близоруким. Просто пройдите по дорожкам, которые больше склоняются вверх. Это похоже на хорошую стратегию для пеших прогулок. Но всегда ли это лучше?

После того, как поездка закончилась, и ваше тело болело и устало, вы впервые смотрите на карту походов. О мой Бог! Там мутная река, которую я должен был пересечь, вместо того, чтобы идти вверх. Это означает, что жадный алгоритм выбирает лучший немедленный выбор и никогда не пересматривает свой выбор. Что касается оптимизации решения, это просто означает, что жадное решение будет пытаться найти локальные оптимальные решения, которые могут быть многими, и могут пропустить глобальное оптимальное решение.

## Формальное определение

Предположим, что у вас есть целевая функция, которая должна быть оптимизирована (максимизирована или минимизирована) в данной точке. Алгоритм Greedy делает жадные варианты на каждом шаге, чтобы оптимизировать целевую функцию. Алгоритм Жадности имеет только один выстрел для вычисления оптимального решения, чтобы он никогда не возвращался и не менял решение.

### Жадные алгоритмы имеют некоторые преимущества и недостатки:

*   Легко придумать жадный алгоритм (или даже несколько жадных алгоритмов) для проблемы. Анализ времени выполнения жадных алгоритмов будет намного проще, чем для других методов (например, Divide and conquer). Для техники «Разделить и властвовать» неясно, является ли техника быстрой или медленной. Это связано с тем, что на каждом уровне рекурсии размер уменьшается и увеличивается количество подзадач.

*   Трудная часть заключается в том, что для жадных алгоритмов вам приходится много работать, чтобы понять проблемы правильности. Даже при правильном алгоритме трудно доказать, почему оно правильно. Доказательство правильности жадного алгоритма - это скорее искусство, чем наука. Это связано с большим количеством творчества. Обычно придумывание алгоритма может показаться тривиальным, но доказывая, что оно на самом деле правильно, представляет собой совершенно другую проблему.

## Проблема с интервальным расписанием

Давайте погрузиться в интересную проблему, с которой вы можете столкнуться практически в любой отрасли или в любом обществе. Некоторые примеры проблемы заключаются в следующем:

*   В течение одного дня в университете вам предоставляется набор N графиков лекций. График для конкретной лекции имеет вид ( _время,_ время), где _время представляет собой время начала этой лекции, и аналогично время f_ представляет время окончания. Учитывая список N расписаний лекций, нам нужно выбрать максимальный набор лекций, которые будут проводиться в течение дня, чтобы **ни одна из лекций не совпадала одна с другой, т.е. если лекция Li и Lj включены в наш выбор, тогда время начала j > = время окончания i или наоборот** .

*   Ваш друг работает в качестве советника лагеря, и он отвечает за организацию мероприятий для набора отдыхающих. Один из его планов состоит в следующем упражнении по мини-триатлону: каждый участник должен поплавать 20 кругов пула, затем проехать 10 миль, затем пробежать 3 мили.

*   План состоит в том, чтобы отправить участников в шахматном порядке по следующему правилу: участники должны использовать пул по одному за раз. Другими словами, первый участник соревнований плавает по 20 кругов, выходит и начинает кататься на велосипеде.

*   Как только этот первый человек выходит из бассейна, второй участник начинает плавать 20 кругов; как только он или она выходит и начинает кататься на велосипеде, третий участник начинает плавать и так далее.

*   Каждый участник имеет запланированное время плавания, прогнозируемое время езды на велосипеде и прогнозируемое время работы. Ваш друг хочет принять решение о расписании для триатлона: порядок, в котором можно начинать старты конкурсантов.

*   Предположим, что время завершения расписания - это самое раннее время, когда все участники будут закончены со всеми тремя ногами триатлона, предполагая, что прогнозы времени точны. Каков наилучший порядок отправки людей, если вы хотите, чтобы весь конкурс закончился как можно скорее? Точнее, дать эффективный алгоритм, который создает график, время завершения которого как можно меньше

### Проблема планирования лекций

Давайте рассмотрим различные подходы к решению этой проблемы.

1.  **Самое раннее время начала Сначала** выберите интервал, который имеет самое раннее время начала. Взгляните на следующий пример, который нарушает это решение. Это решение не получилось, потому что может быть интервал, который начинается очень рано, но очень длинный. Это означает, что следующая стратегия, которую мы могли бы попробовать, будет заключаться в том, чтобы сначала посмотреть на меньшие интервалы. ![Самое раннее время начала](https://algorithmsandme.files.wordpress.com/2015/03/f268b-jobs.png?w=840)

2.  **Наименьший интервал Первый,** т. Е. Вы в конечном итоге выбираете лекции в порядке их общего интервала, который является ничем иным, как их `finish time - start time` . Опять же, это решение неверно. Посмотрите на следующий случай. ![Кратчайший интервал](https://i.stack.imgur.com/4bz2N.png)

Вы можете отчетливо видеть, что кратчайшая лекция - это посередине, но здесь это не оптимальное решение. Давайте посмотрим на еще одно решение этой проблемы, получающее информацию из этого решения.

3.  **Наименее конфликтный интервал Сначала** вы должны смотреть на интервалы, которые вызывают наименьшее количество конфликтов. Еще раз у нас есть пример, когда этот подход не находит оптимального решения. ![Наименее конфликтный интервал](https://i.stack.imgur.com/5LZ9V.png)

Диаграмма показывает нам, что наименьший интервал согласования - это один посередине с двумя конфликтами. После этого мы можем выбрать только два интервала в самом конце с конфликтами 3 каждый. Но оптимальным решением является выбор 4 интервалов на самом верхнем уровне.

4.  **Самое раннее время окончания** . Это тот подход, который всегда дает нам наиболее оптимальное решение этой проблемы. Мы получили много идей из предыдущих подходов и, наконец, пришли к такому подходу. Мы сортируем интервалы в соответствии с возрастающим порядком их времени окончания, а затем начинаем выбирать интервалы с самого начала. Посмотрите на следующий псевдо-код для большей ясности.
```
function interval_scheduling_problem(requests)
    schedule \gets \{\}
    while requests is not yet empty
        choose a request i_r \in requests that has the lowest finishing time
        schedule \gets schedule \cup \{i_r\}
        delete all requests in requests that are not compatible with i_r
    end
    return schedule
 end
```

## Когда мы используем Жадные алгоритмы

Жадные алгоритмы могут помочь вам найти решения многих, казалось бы, сложных проблем. Единственная проблема с ними заключается в том, что вы можете найти правильное решение, но вы, возможно, не сможете проверить, соответствует ли он правильному. Все жадные проблемы разделяют общее свойство, что локальный оптимизатор может в конечном итоге привести к глобальным минимумам, не пересматривая уже принятый набор вариантов.

Жадные алгоритмы помогают нам решать множество различных проблем. Будьте в курсе предстоящих учебников по каждому из них.

1.  Кратчайший путь.
2.  Минимальная проблема связующего дерева на графике.
3.  Проблема кодирования Хаффмана.
4.  Проблема K-центров

#### Дополнительная информация:

 [![Жадные проблемы](http://img.youtube.com/vi/HzeK7g8cD0Y/0.jpg)](https://www.youtube.com/watch?v=HzeK7g8cD0Y)

 [![Жадные проблемы](http://img.youtube.com/vi/poWB2UCuozA/0.jpg)](https://www.youtube.com/watch?v=poWB2UCuozA)


text:
import os
import json
import time
import argparse
from twisted.python import log
from twisted.internet import reactor

import pgandj

logger = pgandj.get_logger()

def eb(f):
    logger.error(f.getBriefTraceback())

def stop(schema, args, start_time):
    logger.error("complete in %s seconds" % (time.time() - start_time,))
    reactor.stop()
    data = json.dumps(schema, indent=4, sort_keys=False, separators=(',', ': '))

    next_id = 0
    outfile = None
    try:
        if not args.outfile:
            outfile = os.path.realpath("./%s_%03d.json" % (args.database, next_id,))
            while  os.path.exists(outfile):
                next_id += 1
                outfile = os.path.realpath("./%s_%03d.json" % (args.database, next_id,))
        else:
            outfile = os.path.realpath(args.outfile)
    except Exception as e:
        print("Failed to write json data to '%s': %s" % (outfile, e,))
        sys.exit(1)

    if os.path.exists(outfile):
        overwrite = raw_input("File '%s' exists. Replace? \n(Y/N) " % (args.outfile,))
        if overwrite.lower() != 'y':
            return

    try:
        fh = open(outfile, "w")
        fh.write(data)
        fh.close()
        print("JSON file created at " + outfile)
    except Exception as e:
        print("Failed to write json data to '%s': %s" % (outfile, e,))
        sys.exit(1)

def begin(args):
    start_time = time.time()
    inspect = pgandj.Inspect(args.database,
                             port=args.port,
                             host=args.host,
                             password=args.password,
                             user=args.username)
    df = inspect.table(args.table)
    df.addErrback(eb)
    df.addBoth(stop, args, start_time)

def main():
    parser = argparse.ArgumentParser(
            description='Parse a PostgreSQL database schema into JSON.',
            prog='pgandj'
        )

    parser.add_argument('database', metavar="DATABASE", type=str,
                        help='The name of the database')
    parser.add_argument('table', metavar="TABLE", type=str,
                        help='The name of the table')
    parser.add_argument('-o', metavar="FILEPATH", type=str,
                        help='A path to write the JSON file', dest='outfile')
    parser.add_argument('-u', metavar="USERNAME", type=str,
                        help='postgres username', dest='username')
    parser.add_argument('-w', metavar="PASSWORD", type=str,
                        help='postgres password', dest='password')
    parser.add_argument('--host', metavar="HOST", type=str,
                        default='127.0.0.1', dest='host',
                        help='postgres server hostname')
    parser.add_argument('-p', metavar="PORT", type=int,
                        default=5432, dest='port',
                        help='postgres server port')

    args = parser.parse_args()

    reactor.callWhenRunning(begin, args)
    reactor.run()

if __name__ == '__main__':
    main()


text:
package com.intive.patronage.toz.storage.model.view;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class UrlView {

    @ApiModelProperty(example = "/storage/a9/2c/cd/a92ccd6a-f51c-4ff0-8645-02adff409051.jpg", position = 1)
    private String url;

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    @Override
    public String toString() {
        return url;
    }
}


text:
package com.hartveld.examples;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class PersonTest {

	@Test
	public void test() {
		Person p = new Person("David", null, "Hartveld");

		assertThat(p.getMiddleName(), is(nullValue()));
	}

}


text:
require('please-upgrade-node')(require('../../package.json'))
require('./')()


text:
module Admin::Resources::DataTypes::HasAndBelongsToManyHelper

  def display_has_and_belongs_to_many(item, attribute)
    item.send(attribute).map(&:to_label).join(', ')
  end

  def table_has_and_belongs_to_many_field(attribute, item)
    item.send(attribute).map(&:to_label).join(', ')
  end

  alias_method :table_has_many_field, :table_has_and_belongs_to_many_field

  def typus_has_and_belongs_to_many_field(attribute, form)
    klass = @resource.reflect_on_association(attribute.to_sym).class_name.constantize

    resource_ids = "#{attribute.singularize}_ids"
    html_options = {}
    model = @resource.name.underscore.gsub('/', '_')
    options = { attribute: "#{model}_#{attribute}" }

    label_text = @resource.human_attribute_name(attribute)
    if (text = build_label_text_for_has_and_belongs_to_many(klass, html_options, options))
      label_text += " <small>#{text}</small>"
    end

    locals = {
      attribute: attribute,
      attribute_id: "#{model}_#{attribute}",
      related_klass: klass,
      related_items: @item.send(attribute),
      related_ids: "#{model}[#{resource_ids}][]",
      values: klass,
      form: form,
      label_text: label_text.html_safe,
      html_options: html_options,
    }

    render get_template_for(@resource, attribute.singularize, "has_and_belongs_to_many"), locals
  end

  def build_label_text_for_has_and_belongs_to_many(klass, html_options, options = {})
    if html_options[:disabled] == true
      I18n.t('typus.labels.read_only')
    elsif admin_user.can?('create', klass) && !headless_mode?
      build_add_new_for_has_and_belongs_to_many(klass, options)
    end
  end

  def build_add_new_for_has_and_belongs_to_many(klass, options)
    html_options = set_modal_options_for(klass)
    html_options['url'] = url_for(controller: "/admin/#{klass.to_resource}", action: :new, _popup: true)
    html_options['data-controls-modal'] = "modal-from-dom-#{options[:attribute]}"

    options = { anchor: html_options['data-controls-modal'] }

    link_to I18n.t('typus.buttons.add'), options, html_options
  end

end


text:
<?php

namespace Enqueue\Consumption\Extension;

use Enqueue\Consumption\Context\PostMessageReceived;
use Enqueue\Consumption\PostMessageReceivedExtensionInterface;
use Enqueue\Consumption\Result;

class ReplyExtension implements PostMessageReceivedExtensionInterface
{
    public function onPostMessageReceived(PostMessageReceived $context): void
    {
        $replyTo = $context->getMessage()->getReplyTo();
        if (false == $replyTo) {
            return;
        }

        /** @var Result $result */
        $result = $context->getResult();
        if (false == $result instanceof Result) {
            return;
        }

        if (false == $result->getReply()) {
            return;
        }

        $correlationId = $context->getMessage()->getCorrelationId();
        $replyMessage = clone $result->getReply();
        $replyMessage->setCorrelationId($correlationId);

        $replyQueue = $context->getContext()->createQueue($replyTo);

        $context->getLogger()->debug(sprintf('[ReplyExtension] Send reply to "%s"', $replyTo));
        $context->getContext()->createProducer()->send($replyQueue, $replyMessage);
    }
}


text:
package com.ofallonminecraft.moarTP;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import com.ofallonminecraft.SpellChecker.SpellChecker;

public class Describe {

  public static boolean describe(CommandSender sender, String[] args, Connection c) {

    // check number of arguments
    if (args.length < 1) {
      sender.sendMessage("Must enter a location name and a description!");
      return false;
    } else if (args.length < 2) {
      sender.sendMessage("Must enter a description for the location!");
      return false;
    } else {
      if (!(args[1].startsWith("\"") && args[args.length-1].endsWith("\""))) {
        sender.sendMessage("Location name or description not formatted correctly!");
        return false;
      }
    }

    // check if user is the creator of the location
    boolean isCreator = false;
    try {
      PreparedStatement s = c.prepareStatement("select creator from moarTP where location=?;");
      s.setString(1, args[0].toLowerCase());
      ResultSet creatorName = s.executeQuery();
      if (creatorName.next() &&
          creatorName.getString(1)!=null &&
          !creatorName.getString(1).equals("null") &&
          Bukkit.getServer().getOfflinePlayer(UUID.fromString(
              creatorName.getString(1))).getName().equals(
                  sender.getName())) isCreator = true;
      creatorName.close();
    } catch (Exception e) {
      e.printStackTrace();
    }

    // check user permissions
    if (sender.isOp() || isCreator) {

      // ----- DESCRIBE ----- //
      try {
        PreparedStatement s = c.prepareStatement("select location from moarTP where location=?;");
        s.setString(1, args[0].toLowerCase());
        String description = "";
        for (int i=1; i<args.length; ++i) {
          description += args[i] + ' ';
        }
        description = description.substring(1,description.length()-2 );
        ResultSet rs = s.executeQuery();
        if (!rs.next()) {
          sender.sendMessage(args[0].toLowerCase()+" is not in the library!");
          HashSet<String> dict_subs = new HashSet<String>();
          dict_subs.add(SpellChecker.LOCATIONS);
          String sug = new SpellChecker(c, dict_subs).getSuggestion(args[0].toLowerCase());
          if (sug != null) {
            sender.sendMessage("Did you mean '/describe " + sug + "\"" + description + "\"'?");
          }
        } else {
          PreparedStatement ps = c.prepareStatement("update moarTP set info=? where location=?;");
          ps.setString(1, description);
          ps.setString(2, args[0].toLowerCase());
          ps.executeUpdate();
          sender.sendMessage(args[0].toLowerCase()+"'s description was successfully updated in the library.");
        }
        rs.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      return true;
      // ----- END DESCRIBE ----- //
    }
    // if the user doesn't have permission, present an error message
    sender.sendMessage("You don't have permission to do this!");
    return false;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.php.project</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/php-project/1">
            <name>PuntoSeguro</name>
        </data>
    </configuration>
</project>


text:
"""
This script can be used to get the p value for classifiers. It takes input files with column vectors corresponding to features and lables.
Then there are two different routes one can go down. When mode has a value of 1, then a grid search will be performed on
one set of input files. If it is 2, then the hyperparemeter search is performed by spearmint. When the mode is turned off (0),
then the p value is computed for multiple sets of input files and the p value distribution is plotted. One sets all the valiables
including the classifier in the "args" list. The classifier provided is ignored if keras_mode is on (1) in which case a keras neural
network is used.
"""

from __future__ import print_function
print(__doc__)
import os
import p_value_scoring_object
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

from sklearn import cross_validation
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.grid_search import GridSearchCV
from scipy import stats
import math

##############################################################################
# Utility function to move the midpoint of a colormap to be around
# the values of interest.

class MidpointNormalize(Normalize):

    def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
        self.midpoint = midpoint
        Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
        return np.ma.masked_array(np.interp(value, x, y))

class Counter(object):
    # Creating a counter object to be able to perform cross validation with only one split
    def __init__(self, list1,list2):
        self.current = 1
        self.list1 =list1
        self.list2 =list2

    def __iter__(self):
        'Returns itself as an iterator object'
        return self

    def __next__(self):
        'Returns the next value till current is lower than high'
        if self.current > 1:
            raise StopIteration
        else:
            self.current += 1
            return self.list1,self.list2
    next = __next__ #python2

def histo_plot_pvalue(U_0,abins,axlabel,aylabel,atitle,aname):
        bins_probability=np.histogram(U_0,bins=abins)[1]

        #Finding the p values corresponding to 1,2 and 3 sigma significance.
        no_one_std_dev=sum(i < (1-0.6827) for i in U_0)
        no_two_std_dev=sum(i < (1-0.9545) for i in U_0)
        no_three_std_dev=sum(i < (1-0.9973) for i in U_0)

        print(no_one_std_dev,no_two_std_dev,no_three_std_dev)

        #plt.rc('text', usetex=True)
        textstr = '$1\sigma=%i$\n$2\sigma=%i$\n$3\sigma=%i$'%(no_one_std_dev, no_two_std_dev, no_three_std_dev)

        # Making a histogram of the probability predictions of the algorithm.
        fig_pred_0= plt.figure()
        ax1_pred_0= fig_pred_0.add_subplot(1, 1, 1)
        n0, bins0, patches0 = ax1_pred_0.hist(U_0, bins=bins_probability, facecolor='red', alpha=0.5)
        ax1_pred_0.set_xlabel(axlabel)
        ax1_pred_0.set_ylabel(aylabel)
        ax1_pred_0.set_title(atitle)
        plt.xlim([0,1])

        # these are matplotlib.patch.Patch properties
        props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

        # place a text box in upper left in axes coords
        ax1_pred_0.text(0.85, 0.95, textstr, transform=ax1_pred_0.transAxes, fontsize=14,
        verticalalignment='top', bbox=props)

        fig_pred_0.savefig(aname+".png")
        #fig_pred_0.show()
        plt.close(fig_pred_0)

def classifier_eval(mode,keras_mode,args):
	##############################################################################
	# Setting parameters
	#

	name=args[0]
	sample1_name= args[1]
	sample2_name= args[2]

	shuffling_seed = args[3]

	#mode =0 if you want evaluation of a model =1 if grid hyperparameter search =2 if spearmint hyperparameter search
	comp_file_list=args[4]
	print(comp_file_list)
	cv_n_iter = args[5]
	clf = args[6]
	C_range = args[7]
	gamma_range = args[8]

        if mode==0:
                #For standard evaluation
                score_list=[]
		print("standard evaluation mode")
	elif mode==1:
		#For grid search
		print("grid hyperparameter search mode")
		param_grid = dict(gamma=gamma_range, C=C_range)

	elif mode==2:
		#For spearmint hyperparameter search
		print("spearmint hyperparameter search mode")
	else:
		print("No valid mode chosen")
		return 1

	##############################################################################
	# Load and prepare data set
	#
	# dataset for grid search

	for comp_file_0,comp_file_1 in comp_file_list:

		print("Operating of files :"+comp_file_0+"   "+comp_file_1)

		#extracts data from the files
		features_0=np.loadtxt(comp_file_0,dtype='d')
		features_1=np.loadtxt(comp_file_1,dtype='d')

		#determine how many data points are in each sample
		no_0=features_0.shape[0]
		no_1=features_1.shape[0]
		no_tot=no_0+no_1
		#Give all samples in file 0 the label 0 and in file 1 the feature 1
		label_0=np.zeros((no_0,1))
		label_1=np.ones((no_1,1))

		#Create an array containing samples and features.
		data_0=np.c_[features_0,label_0]
		data_1=np.c_[features_1,label_1]

		data=np.r_[data_0,data_1]

		np.random.shuffle(data)

		X=data[:,:-1]
		y=data[:,-1]
		print("X : ",X)
		print("y : ",y)
		atest_size=0.2
		if cv_n_iter==1:
			train_range = range(int(math.floor(no_tot*(1-atest_size))))
			test_range  = range(int(math.ceil(no_tot*(1-atest_size))),no_tot)
			#print("train_range : ", train_range)
			#print("test_range : ", test_range)
			acv = Counter(train_range,test_range)
			#print(acv)
		else:
			acv = StratifiedShuffleSplit(y, n_iter=cv_n_iter, test_size=atest_size, random_state=42)

		print("Finished with setting up samples")

		# It is usually a good idea to scale the data for SVM training.
		# We are cheating a bit in this example in scaling all of the data,
		# instead of fitting the transformation on the training set and
		# just applying it on the test set.

		scaler = StandardScaler()
		X = scaler.fit_transform(X)

		if mode==1:
			##############################################################################
			# Grid Search
			#
			# Train classifiers
			#
			# For an initial search, a logarithmic grid with basis
			# 10 is often helpful. Using a basis of 2, a finer
			# tuning can be achieved but at a much higher cost.

			grid = GridSearchCV(clf, scoring=p_value_scoring_object.p_value_scoring_object ,param_grid=param_grid, cv=acv)
			grid.fit(X, y)

			print("The best parameters are %s with a score of %0.2f"
					% (grid.best_params_, grid.best_score_))

			# Now we need to fit a classifier for all parameters in the 2d version
			# (we use a smaller set of parameters here because it takes a while to train)

			C_2d_range = [1e-2, 1, 1e2]
			gamma_2d_range = [1e-1, 1, 1e1]
			classifiers = []
			for C in C_2d_range:
				for gamma in gamma_2d_range:
					clf = SVC(C=C, gamma=gamma)
					clf.fit(X_2d, y_2d)
					classifiers.append((C, gamma, clf))

			##############################################################################
			# visualization
			#
			# draw visualization of parameter effects

			plt.figure(figsize=(8, 6))
			xx, yy = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200))
			for (k, (C, gamma, clf)) in enumerate(classifiers):
				# evaluate decision function in a grid
				Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
				Z = Z.reshape(xx.shape)

				# visualize decision function for these parameters
				plt.subplot(len(C_2d_range), len(gamma_2d_range), k + 1)
				plt.title("gamma=10^%d, C=10^%d" % (np.log10(gamma), np.log10(C)),size='medium')

				# visualize parameter's effect on decision function
				plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu)
				plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=plt.cm.RdBu_r)
				plt.xticks(())
				plt.yticks(())
				plt.axis('tight')

				plt.savefig('prediction_comparison.png')
				# plot the scores of the grid
				# grid_scores_ contains parameter settings and scores
				# We extract just the scores
				scores = [x[1] for x in grid.grid_scores_]
				scores = np.array(scores).reshape(len(C_range), len(gamma_range))

			# Draw heatmap of the validation accuracy as a function of gamma and C
			#
			# The score are encoded as colors with the hot colormap which varies from dark
			# red to bright yellow. As the most interesting scores are all located in the
			# 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so
			# as to make it easier to visualize the small variations of score values in the
			# interesting range while not brutally collapsing all the low score values to
			# the same color.

			plt.figure(figsize=(8, 6))
			plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95)
			plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot,
					norm=MidpointNormalize(vmin=-1.0, midpoint=-0.0001))
			plt.xlabel('gamma')
			plt.ylabel('C')
			plt.colorbar()
			plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45)
			plt.yticks(np.arange(len(C_range)), C_range)
			plt.title('Validation accuracy')
			plt.savefig('Heat_map.png')
		else:
			if keras_mode==1:
				from keras.models import Sequential
				from keras.layers.core import Dense, Activation
				from keras.layers import Dropout
				from keras.utils import np_utils, generic_utils

				dimof_input = X.shape[1]
				dimof_output =1

				print("dimof_input : ",dimof_input, "dimof_output : ", dimof_output)
				#y = np_utils.to_categorical(y, dimof_output)
				scores = []
				counter = 1
				for train_index, test_index in acv:
					print("Cross validation run ", counter)
					X_train, X_test = X[train_index], X[test_index]
					y_train, y_test = y[train_index], y[test_index]

					print("X_train : ",X_train)
					print("y_train : ",y_train)

					batch_size = 1
					dimof_middle = 100
					dropout = 0.5
					countof_epoch = 5
					n_hidden_layers =4

					model = Sequential()
					model.add(Dense(input_dim=dimof_input, output_dim=dimof_middle, init="glorot_uniform",activation='tanh'))
					model.add(Dropout(dropout))

					for n in range(n_hidden_layers):
						model.add(Dense(input_dim=dimof_middle, output_dim=dimof_middle, init="glorot_uniform",activation='tanh'))
						model.add(Dropout(dropout))

					model.add(Dense(input_dim=dimof_middle, output_dim=dimof_output, init="glorot_uniform",activation='sigmoid'))

					print("Does it make it here?")
					#Compiling (might take longer)
					model.compile(loss='categorical_crossentropy', optimizer='sgd')
					model.fit(X_train, y_train,show_accuracy=True,batch_size=batch_size, nb_epoch=countof_epoch, verbose=0)
					prob_pred = model.predict_proba(X_test)
					print("prob_pred : ", prob_pred)
					assert (not (np.isnan(np.sum(prob_pred))))

					#Just like in p_value_scoring_strategy.py
				        y_test         = np.reshape(y_test,(1,y_test.shape[0]))
					prob_pred = np.reshape(prob_pred,(1,prob_pred.shape[0]))
					prob_0    = prob_pred[np.logical_or.reduce([y_test==0])]
					prob_1    = prob_pred[np.logical_or.reduce([y_test==1])]
					if __debug__:
						print("Plot")
					p_KS=stats.ks_2samp(prob_0,prob_1)
					print(p_KS)
					scores.append(p_KS[1])
					counter +=1

			else:
				scores = cross_validation.cross_val_score(clf,X,y,cv=acv,scoring=p_value_scoring_object.p_value_scoring_object)
			print(scores)
			score_list.append(np.mean(scores))
			if mode==2:
				return (-1)* np.mean(scores)

	############################################################################################################################################################
	###############################################################  Evaluation of results  ####################################################################
	############################################################################################################################################################

	if mode==0:
		# The score list has been computed. Let's plot the distribution
		print(score_list)
		print("I havent implemented plotting of the distribution")
		histo_plot_pvalue(score_list,50,"p value","Frequency","p value distribution",name[i]+"_p_value")

if __name__ == "__main__":
	print("Executing classifier_eval_simplified as a stand-alone script")
	print()
        comp_file_list=[]
	for i in range(1,10):
		comp_file_list.append((os.environ['MLToolsDir']+"/Dalitz/dpmodel/data/data.{0}.0.txt".format(i), os.environ['MLToolsDir']+"/Dalitz/dpmodel/data/data.2{0}.1.txt".format(str(i).zfill(2))))

	clf = SVC(C=100,gamma=0.1,probability=True, cache_size=7000)
	args=["dalitz_svc","particle","antiparticle",100,comp_file_list,1,clf,np.logspace(-2, 10, 13),np.logspace(-9, 3, 13)]
	#classifier_eval_simplified(aC,agamma)
	classifier_eval(0,0,args)


text:
template "/etc/init.d/smtp" do
	source "smtp.erb"
	owner 'root'
    group 'root'
    mode '0700'
end

execute "update-rc.d sbc_a defaults 98 02" do
        command "update-rc.d smtp defaults 98 02"
        action :run
end

execute "/etc/init.d/smtp" do
        command "/etc/init.d/smtp"
        action :run
        ignore_failure true
end


text:
<?php /* Template Name: Help */
get_header();

if ( have_posts() ) :
    while ( have_posts() ) :
        the_post(); ?>

<?php the_title(); ?>

  <?php the_content(); ?>

Talk

      Ask our community, become a part of it and get in touch with us.

Community Forums

          ownClouds main help desk. Get in touch with our community and devs and work on solutions together.

        Go to ownCloud Central

GitHub

          ownClouds' development happens here. Participate or let us know if you found a bug.

        Take me there
        Bugtracker

Social Media

          Follow us, stay up-to-date and get in touch with us.

          <?php
          foreach(get_option( 'spacexchimp_p005_settings' )['media'] as $name=>$platform) {
            if($platform['content'] === '')
              continue;

            if ($name === 'rss-feed' || $name === 'google-play')
              continue;
            ?>
            <a href="<?php echo $platform['content']; ?>" class="button-oc icon-only" target="_blank"><i class="fa fa-<?php echo $name; ?>">
            <?php
          }
          ?>

Read

      Learn about ownCloud and become a ownCloud expert.

Documentation

          Install instructions, user guides and everything you need about ownCloud.

        Admin Manual
        User Manual
        Developer Manual

Frequently Asked Questions

          All recurring questions in one place.

        <a href="<?php echo get_page_link(13126); ?>" class="button-oc">Read FAQ

Security

          ownCloud is all about security. Read here everything about it.

        <a href="<?php echo get_page_link(13133); ?>" class="button-oc">Take me there

Knowledge Base

          Fact sheets, Whitepapers, Webinars, Analysis and more about ownCloud.

        Take me there

RSS Feed

          Stay up-to-date to our <a href="<?php echo get_page_link(2); ?>">blog by signing up on our RSS Feed.

        <a href="<?php echo get_page_link(2); ?>feed/" class="button-oc">Show RSS Feed

Newsletter

          Get all news directly to your inbox.

        <a href="<?php echo get_page_link(14934); ?>" class="button-oc">Sign up now

Extend

      ownCloud is easily extendible with apps. There are many community apps but also enterprise driven apps available.

Marktplace

          Have a look at the ownCloud marketplace and browse all apps.

        Go to Marketplace
        App install manual

App development guide

          You have an app idea and don't know where to start? See our app development guide.

        Read the guide

Buy

      Beyond the free plans of ownCloud there are paid ones, too.

      Get to know the experts behind the ownCloud technology helping you with your large scale environments with many users and even more files.

Enterprise Support

          Need professional support? Explore your options how we can help you.

        See Enterprise Support Plans

Enterprise Features

          Need to extend your ownCloud functionalites even more? Have a look at our ownCloud enterprise bundle.

        See product description
        Explore Enterprise Features

<?php
    endwhile;
endif;
get_footer();
?>


text:
import "./Tests";
import { SortDefinitionOrder, TriggerCallbackHandler, SortDefinition, RelativeSortDefinition, Parser, Widget, ParsedCell, TablesorterHeading, StorageConfiguration } from "tablesorter";
import { RelativeSorting } from "tablesorter/Sorting/RelativeSorting";
import { StorageType } from "tablesorter/Storage/StorageType";

/**
 * Provides tests for the methods.
 */
export class TestMethods<T extends HTMLElement> {
    /**
     * A jQuery-object for testing.
     */
    protected table = $<T>("");

    /**
     * A set of sort-definitions for testing.
     */
    protected sorting: ReadonlyArray<SortDefinition> = [[0, 1], [1, 0]];

    /**
     * A set of relative sort-definitions for testing.
     */
    protected relativeSorting: ReadonlyArray<RelativeSortDefinition> = [[0, "o"], [1, "s"]];

    /**
     * A set of mixed sort-definitions for testing.
     */
    protected mixedSorting: ReadonlyArray<SortDefinition | RelativeSortDefinition> = [
        [0, "d"],
        [1, "o"]];

    /**
     * A trigger-callback for testing.
     */
    protected triggerCallback: TriggerCallbackHandler<T> = (table) => {
        // $ExpectType T
        table;
    }

    /**
     * Tests for the methods.
     */
    Test() {
        const $: JQueryStatic<T> = {} as any;
        const tableElement = this.table[0];
        const config = this.table[0].config;
        const parser: Parser<T> = {} as any;
        const widget: Widget<T> = {} as any;
        const parsedCellCallback = (cell: ParsedCell): void => { };
        const ajaxSettings: JQuery.AjaxSettings = {} as any;
        const request: JQuery.jqXHR = {} as any;
        const storageConfig: StorageConfiguration = {
            group: "",
            id: "",
            page: "",
            storageType: "c",
            url: ""
        };

        /**
         * Methods
         * Invoking methods directly
         */
        $.tablesorter.addHeaderResizeEvent(this.table, true);
        $.tablesorter.addHeaderResizeEvent(this.table, true, { timer: 20 });
        $.tablesorter.addHeaderResizeEvent(tableElement, true);
        $.tablesorter.addHeaderResizeEvent(tableElement, true, { timer: 20 });

        $.tablesorter.addRows(config, $(), true);
        $.tablesorter.addRows(config, $(), true, this.triggerCallback);
        $.tablesorter.addRows(config, $(), this.sorting);
        $.tablesorter.addRows(config, $(), this.sorting, this.triggerCallback);
        $.tablesorter.addRows(config, "", true);
        $.tablesorter.addRows(config, "", true, this.triggerCallback);
        $.tablesorter.addRows(config, "", this.sorting);
        $.tablesorter.addRows(config, "", this.sorting, this.triggerCallback);

        $.tablesorter.addInstanceMethods({ hello: () => null });
        $.tablesorter.addInstanceMethods({ world() { } });

        $.tablesorter.addParser(parser);

        $.tablesorter.addWidget(widget);

        $.tablesorter.appendCache(config);

        $.tablesorter.applyWidget(this.table);
        $.tablesorter.applyWidget(this.table, true);
        $.tablesorter.applyWidget(this.table, true, this.triggerCallback);
        $.tablesorter.applyWidget(tableElement);
        $.tablesorter.applyWidget(tableElement, true);
        $.tablesorter.applyWidget(tableElement, true, this.triggerCallback);

        $.tablesorter.applyWidgetId(this.table, "zebra");
        $.tablesorter.applyWidgetId(tableElement, "zebra");

        $.tablesorter.bindEvents(this.table, $());
        $.tablesorter.bindEvents(tableElement, $());

        $.tablesorter.clearTableBody(this.table);
        $.tablesorter.clearTableBody(tableElement);

        $.tablesorter.computeColumnIndex($(), config);

        $.tablesorter.destroy(this.table);
        $.tablesorter.destroy(this.table, true);
        $.tablesorter.destroy(this.table, true, this.triggerCallback);
        $.tablesorter.destroy(tableElement);
        $.tablesorter.destroy(tableElement, true);
        $.tablesorter.destroy(tableElement, true, this.triggerCallback);

        $.tablesorter.fixColumnWidth(this.table);
        $.tablesorter.fixColumnWidth(tableElement);

        $.tablesorter.formatFloat("", this.table);
        $.tablesorter.formatFloat("", tableElement);

        // $ExpectType Widget<T>
        $.tablesorter.getColumnData(this.table, { 0: widget, "*": widget }, 0);
        // $ExpectType Widget<T>
        $.tablesorter.getColumnData(this.table, { 0: widget, "*": widget }, "*");
        // $ExpectType Widget<T>
        $.tablesorter.getColumnData(tableElement, { 0: widget, "*": widget }, 0);
        // $ExpectType Widget<T>
        $.tablesorter.getColumnData(tableElement, { 0: widget, "*": widget }, "*");

        $.tablesorter.getColumnText(this.table, 0);
        $.tablesorter.getColumnText(this.table, 0, parsedCellCallback);
        $.tablesorter.getColumnText(this.table, 0, parsedCellCallback, "*");
        $.tablesorter.getColumnText(this.table, 0, parsedCellCallback, $());
        $.tablesorter.getColumnText(this.table, 0, parsedCellCallback, $()[0]);
        $.tablesorter.getColumnText(
            this.table,
            0,
            parsedCellCallback,
            (index, element) => {
                // $ExpectType number
                index;
                // $ExpectType HTMLElement
                element;
                return true;
            });
        $.tablesorter.getColumnText(tableElement, 0);
        $.tablesorter.getColumnText(tableElement, 0, parsedCellCallback);
        $.tablesorter.getColumnText(tableElement, 0, parsedCellCallback, "*");
        $.tablesorter.getColumnText(tableElement, 0, parsedCellCallback, $());
        $.tablesorter.getColumnText(tableElement, 0, parsedCellCallback, $()[0]);
        $.tablesorter.getColumnText(
            tableElement,
            0,
            parsedCellCallback,
            (index, element) => {
                // $ExpectType number
                index;
                // $ExpectType HTMLElement
                element;
                return true;
            });

        // $ExpectType string | boolean | undefined
        $.tablesorter.getData($(), config.headers[0], "sorter");
        // $ExpectType string | boolean | undefined
        $.tablesorter.getData($()[0], config.headers[0], "sorter");
        // $ExpectType "top" | "bottom" | "zero" | "min" | "max" | undefined || "top" | "bottom" | "min" | "max" | "zero" | undefined || StringSorting | undefined
        $.tablesorter.getData($(), config.headers[0], "string");
        // $ExpectType "top" | "bottom" | "zero" | "min" | "max" | undefined || "top" | "bottom" | "min" | "max" | "zero" | undefined || StringSorting | undefined
        $.tablesorter.getData($()[0], config.headers[0], "string");

        // $ExpectType string[]
        $.tablesorter.getFilters(this.table);
        // $ExpectType string[]
        $.tablesorter.getFilters(this.table, true);
        // $ExpectType string[]
        $.tablesorter.getFilters(tableElement);
        // $ExpectType string[]
        $.tablesorter.getFilters(tableElement, true);

        // $ExpectType Widget<T>
        $.tablesorter.getWidgetById("");

        // $ExpectType boolean
        $.tablesorter.hasWidget(this.table, "");
        // $ExpectType boolean
        $.tablesorter.hasWidget(tableElement, "");

        // $ExpectType boolean
        $.tablesorter.isDigit("");

        $.tablesorter.isProcessing(this.table, true);
        $.tablesorter.isProcessing(this.table, true, $());
        $.tablesorter.isProcessing(tableElement, true);
        $.tablesorter.isProcessing(tableElement, true, $());

        // $ExpectType boolean
        $.tablesorter.isValueInArray(2, this.sorting);
        // $ExpectType boolean
        $.tablesorter.isValueInArray(2, [[0, "this.table"], [1, 2102311923084], [3, {}]]);

        // $ExpectType void
        $.tablesorter.processTbody(this.table, $());
        // $ExpectType void
        $.tablesorter.processTbody(this.table, $(), false);
        // $ExpectType JQuery<HTMLElement>
        $.tablesorter.processTbody(this.table, $(), true);
        // $ExpectType void
        $.tablesorter.processTbody(tableElement, $());
        // $ExpectType void
        $.tablesorter.processTbody(tableElement, $(), false);
        // $ExpectType JQuery<HTMLElement>
        $.tablesorter.processTbody(tableElement, $(), true);

        $.tablesorter.refreshWidgets(this.table);
        $.tablesorter.refreshWidgets(this.table, true);
        $.tablesorter.refreshWidgets(this.table, true, true);
        $.tablesorter.refreshWidgets(tableElement);
        $.tablesorter.refreshWidgets(tableElement, true);
        $.tablesorter.refreshWidgets(tableElement, true, true);

        $.tablesorter.removeWidget(this.table, true);
        $.tablesorter.removeWidget(this.table, true, true);
        $.tablesorter.removeWidget(this.table, "");
        $.tablesorter.removeWidget(this.table, "", true);
        $.tablesorter.removeWidget(this.table, ["", ""]);
        $.tablesorter.removeWidget(this.table, ["", ""], true);
        $.tablesorter.removeWidget(tableElement, true);
        $.tablesorter.removeWidget(tableElement, true, true);
        $.tablesorter.removeWidget(tableElement, "");
        $.tablesorter.removeWidget(tableElement, "", true);
        $.tablesorter.removeWidget(tableElement, ["", ""]);
        $.tablesorter.removeWidget(tableElement, ["", ""], true);

        // $ExpectType string
        $.tablesorter.replaceAccents("");

        $.tablesorter.resizableReset(this.table);
        $.tablesorter.resizableReset(this.table, true);
        $.tablesorter.resizableReset(tableElement);
        $.tablesorter.resizableReset(tableElement, true);

        $.tablesorter.restoreHeaders(this.table);
        $.tablesorter.restoreHeaders(tableElement);

        $.tablesorter.setFilters(this.table, [""]);
        $.tablesorter.setFilters(this.table, [""], true);
        $.tablesorter.setFilters(tableElement, [""]);
        $.tablesorter.setFilters(tableElement, [""], true);

        $.tablesorter.showError(this.table, "", ajaxSettings, "");
        $.tablesorter.showError(this.table, request, ajaxSettings, "");
        $.tablesorter.showError(tableElement, "", ajaxSettings, "");
        $.tablesorter.showError(tableElement, request, ajaxSettings, "");

        // $ExpectType number
        $.tablesorter.sortNatural("", "");

        // $ExpectType number
        $.tablesorter.sortText("", "");

        $.tablesorter.sortOn(config, this.sorting);
        $.tablesorter.sortOn(config, this.sorting, this.triggerCallback);
        $.tablesorter.sortOn(config, this.relativeSorting);
        $.tablesorter.sortOn(config, this.relativeSorting, this.triggerCallback);
        $.tablesorter.sortOn(config, this.mixedSorting);
        $.tablesorter.sortOn(config, this.mixedSorting, this.triggerCallback);

        $.tablesorter.sortReset(config);
        $.tablesorter.sortReset(config, this.triggerCallback);

        // $ExpectType any
        $.tablesorter.storage(this.table, "");
        // $ExpectType void
        $.tablesorter.storage(this.table, "", {});
        // $ExpectType void
        $.tablesorter.storage(this.table, "", {}, storageConfig);
        // $ExpectType any
        $.tablesorter.storage(tableElement, "");
        // $ExpectType void
        $.tablesorter.storage(tableElement, "", {});
        // $ExpectType void
        $.tablesorter.storage(tableElement, "", {}, storageConfig);

        $.tablesorter.update(config);
        $.tablesorter.update(config, true);
        $.tablesorter.update(config, true, this.triggerCallback);
        $.tablesorter.update(config, this.sorting);
        $.tablesorter.update(config, this.sorting, this.triggerCallback);
        $.tablesorter.updateRows(config);
        $.tablesorter.updateRows(config, true);
        $.tablesorter.updateRows(config, true, this.triggerCallback);
        $.tablesorter.updateRows(config, this.sorting);
        $.tablesorter.updateRows(config, this.sorting, this.triggerCallback);

        $.tablesorter.updateAll(config);
        $.tablesorter.updateAll(config, true);
        $.tablesorter.updateAll(config, true, this.triggerCallback);
        $.tablesorter.updateAll(config, this.sorting);
        $.tablesorter.updateAll(config, this.sorting, this.triggerCallback);

        $.tablesorter.updateCache(config);
        $.tablesorter.updateCache(config, this.triggerCallback);
        $.tablesorter.updateCache(config, this.triggerCallback, $());

        $.tablesorter.updateCell(config, $());
        $.tablesorter.updateCell(config, $(), true);
        $.tablesorter.updateCell(config, $(), true, this.triggerCallback);
        $.tablesorter.updateCell(config, $(), this.sorting);
        $.tablesorter.updateCell(config, $(), this.sorting, this.triggerCallback);

        $.tablesorter.updateHeaders(config);
        $.tablesorter.updateHeaders(config, this.triggerCallback);

        $.tablesorter.filter.bindSearch(this.table, $(), true);
        $.tablesorter.filter.bindSearch(tableElement, $(), true);

        $.tablesorter.filter.buildSelect(this.table, 0, [1, 2, 3, 4], true);
        $.tablesorter.filter.buildSelect(this.table, 0, [1, 2, 3, 4], true, true);
        $.tablesorter.filter.buildSelect(this.table, 0, "", true);
        $.tablesorter.filter.buildSelect(this.table, 0, "", true, true);
        $.tablesorter.filter.buildSelect(this.table, 0, $(), true);
        $.tablesorter.filter.buildSelect(this.table, 0, $(), true, true);
        $.tablesorter.filter.buildSelect(tableElement, 0, [1, 2, 3, 4], true);
        $.tablesorter.filter.buildSelect(tableElement, 0, [1, 2, 3, 4], true, true);
        $.tablesorter.filter.buildSelect(tableElement, 0, "", true);
        $.tablesorter.filter.buildSelect(tableElement, 0, "", true, true);
        $.tablesorter.filter.buildSelect(tableElement, 0, $(), true);
        $.tablesorter.filter.buildSelect(tableElement, 0, $(), true, true);

        // $ExpectType string[]
        $.tablesorter.filter.getOptions(this.table, 0);
        // $ExpectType string[]
        $.tablesorter.filter.getOptions(this.table, 0, true);
        // $ExpectType string[]
        $.tablesorter.filter.getOptions(tableElement, 0);
        // $ExpectType string[]
        $.tablesorter.filter.getOptions(tableElement, 0, true);

        // $ExpectType ParsedOption[]
        $.tablesorter.filter.getOptionSource(this.table, 0);
        // $ExpectType ParsedOption[]
        $.tablesorter.filter.getOptionSource(this.table, 0, true);
        // $ExpectType ParsedOption[]
        $.tablesorter.filter.getOptionSource(tableElement, 0);
        // $ExpectType ParsedOption[]
        $.tablesorter.filter.getOptionSource(tableElement, 0, true);

        // $ExpectType string[]
        $.tablesorter.filter.processOptions(this.table, 0, []);
        // $ExpectType string[]
        $.tablesorter.filter.processOptions(this.table, null, []);
    }
}


text:
package ch.christianmenz.machinelearning;

import java.util.List;

/**
 *
 * @author Christian
 */
public class Trainer {

    private final NeuralNetwork network;

    private final TrainingSet trainingSet;
    private final double learningRate;
    private double currentError = Double.MAX_VALUE;

    public Trainer(NeuralNetwork net, TrainingSet trainingSet, double learningRate) {
        this.network = net;
        this.trainingSet = trainingSet;
        this.learningRate = learningRate;
    }

    public void train() {
        double epochError = 0;
        List<TrainingRow> trainingRows = trainingSet.getTrainingRows();
        for (TrainingRow trainingRow : trainingRows) {
            double[] outputs = network.activate(trainingRow.getInput());

            for (int i = 0; i < outputs.length; i++) {
                double expectedOut = trainingRow.getOutput()[i];
                double actualOut = outputs[i];
                double error = actualOut - expectedOut;
                epochError += Math.pow(error, 2); // square error

                // backpropagate..
                for (int layer = network.getNeurons().length - 1; layer > 0; layer--) {
                    for (int n = 0; n < network.getNeurons()[layer].length; n++) {
                        Neuron neuron = network.getNeurons()[layer][n];
                        Neuron[] inputNeurons = network.getNeurons()[layer - 1];

                        for (int z = 0; z < inputNeurons.length; z++) {
                            double changeWeight = learningRate * error * inputNeurons[z].getOutput() * neuron.getOutput() * (1.d - neuron.getOutput());
                            neuron.getInputWeights()[z] = neuron.getInputWeights()[z] + changeWeight; // I know how this feels.. but maybe the perormance is good
                        }
                        // update bias
                        double changeWeight = learningRate * error * 1d * neuron.getOutput() * (1 - neuron.getOutput());
                        neuron.setBias(neuron.getBias() + changeWeight);
                    }
                }

            }

        }
        this.currentError = epochError;
    }

    public double getCurrentError() {
        return currentError;
    }

}