text:
import argparse
from collections import defaultdict
import datetime
from pprint import pprint

from google.cloud import datastore
import google.cloud.exceptions

def incomplete_key(client):
    # [START incomplete_key]
    key = client.key('Task')
    # [END incomplete_key]

    return key

def named_key(client):
    # [START named_key]
    key = client.key('Task', 'sample_task')
    # [END named_key]

    return key

def key_with_parent(client):
    # [START key_with_parent]
    key = client.key('TaskList', 'default', 'Task', 'sample_task')
    # Alternatively
    parent_key = client.key('TaskList', 'default')
    key = client.key('Task', 'sample_task', parent=parent_key)
    # [END key_with_parent]

    return key

def key_with_multilevel_parent(client):
    # [START key_with_multilevel_parent]
    key = client.key(
        'User', 'alice',
        'TaskList', 'default',
        'Task', 'sample_task')
    # [END key_with_multilevel_parent]

    return key

def basic_entity(client):
    # [START basic_entity]
    task = datastore.Entity(client.key('Task'))
    task.update({
        'category': 'Personal',
        'done': False,
        'priority': 4,
        'description': 'Learn Cloud Datastore'
    })
    # [END basic_entity]

    return task

def entity_with_parent(client):
    # [START entity_with_parent]
    key_with_parent = client.key(
        'TaskList', 'default', 'Task', 'sample_task')

    task = datastore.Entity(key=key_with_parent)

    task.update({
        'category': 'Personal',
        'done': False,
        'priority': 4,
        'description': 'Learn Cloud Datastore'
    })
    # [END entity_with_parent]

    return task

def properties(client):
    key = client.key('Task')
    # [START properties]
    task = datastore.Entity(
        key,
        exclude_from_indexes=['description'])
    task.update({
        'category': 'Personal',
        'description': 'Learn Cloud Datastore',
        'created': datetime.datetime.utcnow(),
        'done': False,
        'priority': 4,
        'percent_complete': 10.5,
    })
    # [END properties]

    return task

def array_value(client):
    key = client.key('Task')
    # [START array_value]
    task = datastore.Entity(key)
    task.update({
        'tags': [
            'fun',
            'programming'
        ],
        'collaborators': [
            'alice',
            'bob'
        ]
    })
    # [END array_value]

    return task

def upsert(client):
    # [START upsert]
    complete_key = client.key('Task', 'sample_task')

    task = datastore.Entity(key=complete_key)

    task.update({
        'category': 'Personal',
        'done': False,
        'priority': 4,
        'description': 'Learn Cloud Datastore'
    })

    client.put(task)
    # [END upsert]

    return task

def insert(client):
    # [START insert]
    with client.transaction():
        incomplete_key = client.key('Task')

        task = datastore.Entity(key=incomplete_key)

        task.update({
            'category': 'Personal',
            'done': False,
            'priority': 4,
            'description': 'Learn Cloud Datastore'
        })

        client.put(task)
    # [END insert]

    return task

def update(client):
    # Create the entity we're going to update.
    upsert(client)

    # [START update]
    with client.transaction():
        key = client.key('Task', 'sample_task')
        task = client.get(key)

        task['done'] = True

        client.put(task)
    # [END update]

    return task

def lookup(client):
    # Create the entity that we're going to look up.
    upsert(client)

    # [START lookup]
    key = client.key('Task', 'sample_task')
    task = client.get(key)
    # [END lookup]

    return task

def delete(client):
    # Create the entity we're going to delete.
    upsert(client)

    # [START delete]
    key = client.key('Task', 'sample_task')
    client.delete(key)
    # [END delete]

    return key

def batch_upsert(client):
    task1 = datastore.Entity(client.key('Task', 1))

    task1.update({
        'category': 'Personal',
        'done': False,
        'priority': 4,
        'description': 'Learn Cloud Datastore'
    })

    task2 = datastore.Entity(client.key('Task', 2))

    task2.update({
        'category': 'Work',
        'done': False,
        'priority': 8,
        'description': 'Integrate Cloud Datastore'
    })

    # [START batch_upsert]
    client.put_multi([task1, task2])
    # [END batch_upsert]

    return task1, task2

def batch_lookup(client):
    # Create the entities we will lookup.
    batch_upsert(client)

    keys = [
        client.key('Task', 1),
        client.key('Task', 2)
    ]

    # [START batch_lookup]
    tasks = client.get_multi(keys)
    # [END batch_lookup]

    return tasks

def batch_delete(client):
    # Create the entities we will delete.
    batch_upsert(client)

    keys = [
        client.key('Task', 1),
        client.key('Task', 2)
    ]

    # [START batch_delete]
    client.delete_multi(keys)
    # [END batch_delete]

    return keys

def unindexed_property_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START unindexed_property_query]
    query = client.query(kind='Task')
    query.add_filter('description', '=', 'Learn Cloud Datastore')
    # [END unindexed_property_query]

    return list(query.fetch())

def basic_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START basic_query]
    query = client.query(kind='Task')
    query.add_filter('done', '=', False)
    query.add_filter('priority', '>=', 4)
    query.order = ['-priority']
    # [END basic_query]

    return list(query.fetch())

def projection_query(client):
    # Create the entity that we're going to query.
    task = datastore.Entity(client.key('Task'))
    task.update({
        'category': 'Personal',
        'done': False,
        'priority': 4,
        'description': 'Learn Cloud Datastore',
        'percent_complete': 0.5
    })
    client.put(task)

    # [START projection_query]
    query = client.query(kind='Task')
    query.projection = ['priority', 'percent_complete']
    # [END projection_query]

    # [START run_query_projection]
    priorities = []
    percent_completes = []

    for task in query.fetch():
        priorities.append(task['priority'])
        percent_completes.append(task['percent_complete'])
    # [END run_query_projection]

    return priorities, percent_completes

def ancestor_query(client):
    task = datastore.Entity(
        client.key('TaskList', 'default', 'Task'))
    task.update({
        'category': 'Personal',
        'description': 'Learn Cloud Datastore',
    })
    client.put(task)

    # [START ancestor_query]
    ancestor = client.key('TaskList', 'default')
    query = client.query(kind='Task', ancestor=ancestor)
    # [END ancestor_query]

    return list(query.fetch())

def run_query(client):
    # [START run_query]
    query = client.query()
    results = list(query.fetch())
    # [END run_query]

    return results

def limit(client):
    # [START limit]
    query = client.query()
    tasks = list(query.fetch(limit=5))
    # [END limit]

    return tasks

def cursor_paging(client):
    # [START cursor_paging]

    def get_one_page_of_tasks(cursor=None):
        query = client.query(kind='Task')
        query_iter = query.fetch(start_cursor=cursor, limit=5)
        page = next(query_iter.pages)

        tasks = list(page)
        next_cursor = query_iter.next_page_token

        return tasks, next_cursor
    # [END cursor_paging]

    page_one, cursor_one = get_one_page_of_tasks()
    page_two, cursor_two = get_one_page_of_tasks(cursor=cursor_one)
    return page_one, cursor_one, page_two, cursor_two

def property_filter(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START property_filter]
    query = client.query(kind='Task')
    query.add_filter('done', '=', False)
    # [END property_filter]

    return list(query.fetch())

def composite_filter(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START composite_filter]
    query = client.query(kind='Task')
    query.add_filter('done', '=', False)
    query.add_filter('priority', '=', 4)
    # [END composite_filter]

    return list(query.fetch())

def key_filter(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START key_filter]
    query = client.query(kind='Task')
    first_key = client.key('Task', 'first_task')
    query.key_filter(first_key, '>')
    # [END key_filter]

    return list(query.fetch())

def ascending_sort(client):
    # Create the entity that we're going to query.
    task = upsert(client)
    task['created'] = datetime.datetime.utcnow()
    client.put(task)

    # [START ascending_sort]
    query = client.query(kind='Task')
    query.order = ['created']
    # [END ascending_sort]

    return list(query.fetch())

def descending_sort(client):
    # Create the entity that we're going to query.
    task = upsert(client)
    task['created'] = datetime.datetime.utcnow()
    client.put(task)

    # [START descending_sort]
    query = client.query(kind='Task')
    query.order = ['-created']
    # [END descending_sort]

    return list(query.fetch())

def multi_sort(client):
    # Create the entity that we're going to query.
    task = upsert(client)
    task['created'] = datetime.datetime.utcnow()
    client.put(task)

    # [START multi_sort]
    query = client.query(kind='Task')
    query.order = [
        '-priority',
        'created'
    ]
    # [END multi_sort]

    return list(query.fetch())

def keys_only_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START keys_only_query]
    query = client.query()
    query.keys_only()
    # [END keys_only_query]

    # [START run_keys_only_query]
    keys = list([entity.key for entity in query.fetch(limit=10)])
    # [END run_keys_only_query]

    return keys

def distinct_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START distinct_query]
    query = client.query(kind='Task')
    query.distinct_on = ['category', 'priority']
    query.order = ['category', 'priority']
    query.projection = ['category', 'priority']
    # [END distinct_query]

    return list(query.fetch())

def distinct_on_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START distinct_on_query]
    query = client.query(kind='Task')
    query.distinct_on = ['category']
    query.order = ['category', 'priority']
    # [END distinct_on_query]

    return list(query.fetch())

def kindless_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    last_seen_key = client.key('Task', 'a')

    # [START kindless_query]
    query = client.query()
    query.key_filter(last_seen_key, '>')
    # [END kindless_query]

    return list(query.fetch())

def inequality_range(client):
    # [START inequality_range]
    start_date = datetime.datetime(1990, 1, 1)
    end_date = datetime.datetime(2000, 1, 1)
    query = client.query(kind='Task')
    query.add_filter(
        'created', '>', start_date)
    query.add_filter(
        'created', '<', end_date)
    # [END inequality_range]

    return list(query.fetch())

def inequality_invalid(client):
    try:
        # [START inequality_invalid]
        start_date = datetime.datetime(1990, 1, 1)
        query = client.query(kind='Task')
        query.add_filter(
            'created', '>', start_date)
        query.add_filter(
            'priority', '>', 3)
        # [END inequality_invalid]

        return list(query.fetch())

    except (google.cloud.exceptions.BadRequest,
            google.cloud.exceptions.GrpcRendezvous):
        pass

def equal_and_inequality_range(client):
    # [START equal_and_inequality_range]
    start_date = datetime.datetime(1990, 1, 1)
    end_date = datetime.datetime(2000, 12, 31, 23, 59, 59)
    query = client.query(kind='Task')
    query.add_filter('priority', '=', 4)
    query.add_filter('done', '=', False)
    query.add_filter(
        'created', '>', start_date)
    query.add_filter(
        'created', '<', end_date)
    # [END equal_and_inequality_range]

    return list(query.fetch())

def inequality_sort(client):
    # [START inequality_sort]
    query = client.query(kind='Task')
    query.add_filter('priority', '>', 3)
    query.order = ['priority', 'created']
    # [END inequality_sort]

    return list(query.fetch())

def inequality_sort_invalid_not_same(client):
    try:
        # [START inequality_sort_invalid_not_same]
        query = client.query(kind='Task')
        query.add_filter('priority', '>', 3)
        query.order = ['created']
        # [END inequality_sort_invalid_not_same]

        return list(query.fetch())

    except (google.cloud.exceptions.BadRequest,
            google.cloud.exceptions.GrpcRendezvous):
        pass

def inequality_sort_invalid_not_first(client):
    try:
        # [START inequality_sort_invalid_not_first]
        query = client.query(kind='Task')
        query.add_filter('priority', '>', 3)
        query.order = ['created', 'priority']
        # [END inequality_sort_invalid_not_first]

        return list(query.fetch())

    except (google.cloud.exceptions.BadRequest,
            google.cloud.exceptions.GrpcRendezvous):
        pass

def array_value_inequality_range(client):
    # [START array_value_inequality_range]
    query = client.query(kind='Task')
    query.add_filter('tag', '>', 'learn')
    query.add_filter('tag', '<', 'math')
    # [END array_value_inequality_range]

    return list(query.fetch())

def array_value_equality(client):
    # [START array_value_equality]
    query = client.query(kind='Task')
    query.add_filter('tag', '=', 'fun')
    query.add_filter('tag', '=', 'programming')
    # [END array_value_equality]

    return list(query.fetch())

def exploding_properties(client):
    # [START exploding_properties]
    task = datastore.Entity(client.key('Task'))
    task.update({
        'tags': [
            'fun',
            'programming',
            'learn'
        ],
        'collaborators': [
            'alice',
            'bob',
            'charlie'
        ],
        'created': datetime.datetime.utcnow()
    })
    # [END exploding_properties]

    return task

def transactional_update(client):
    # Create the entities we're going to manipulate
    account1 = datastore.Entity(client.key('Account'))
    account1['balance'] = 100
    account2 = datastore.Entity(client.key('Account'))
    account2['balance'] = 100
    client.put_multi([account1, account2])

    # [START transactional_update]
    def transfer_funds(client, from_key, to_key, amount):
        with client.transaction():
            from_account = client.get(from_key)
            to_account = client.get(to_key)

            from_account['balance'] -= amount
            to_account['balance'] += amount

            client.put_multi([from_account, to_account])
    # [END transactional_update]

    # [START transactional_retry]
    for _ in range(5):
        try:
            transfer_funds(client, account1.key, account2.key, 50)
            break
        except google.cloud.exceptions.Conflict:
            continue
    else:
        print('Transaction failed.')
    # [END transactional_retry]

    return account1.key, account2.key

def transactional_get_or_create(client):
    # [START transactional_get_or_create]
    with client.transaction():
        key = client.key('Task', datetime.datetime.utcnow().isoformat())

        task = client.get(key)

        if not task:
            task = datastore.Entity(key)
            task.update({
                'description': 'Example task'
            })
            client.put(task)

        return task
    # [END transactional_get_or_create]

def transactional_single_entity_group_read_only(client):
    client.put_multi([
        datastore.Entity(key=client.key('TaskList', 'default')),
        datastore.Entity(key=client.key('TaskList', 'default', 'Task', 1))
    ])

    # [START transactional_single_entity_group_read_only]
    with client.transaction():
        task_list_key = client.key('TaskList', 'default')

        task_list = client.get(task_list_key)

        query = client.query(kind='Task', ancestor=task_list_key)
        tasks_in_list = list(query.fetch())

        return task_list, tasks_in_list
    # [END transactional_single_entity_group_read_only]

def namespace_run_query(client):
    # Create an entity in another namespace.
    task = datastore.Entity(
        client.key('Task', 'sample-task', namespace='google'))
    client.put(task)

    # [START namespace_run_query]
    # All namespaces
    query = client.query(kind='__namespace__')
    query.keys_only()

    all_namespaces = [entity.key.id_or_name for entity in query.fetch()]

    # Filtered namespaces
    start_namespace = client.key('__namespace__', 'g')
    end_namespace = client.key('__namespace__', 'h')
    query = client.query(kind='__namespace__')
    query.key_filter(start_namespace, '>=')
    query.key_filter(end_namespace, '<')

    filtered_namespaces = [entity.key.id_or_name for entity in query.fetch()]
    # [END namespace_run_query]

    return all_namespaces, filtered_namespaces

def kind_run_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START kind_run_query]
    query = client.query(kind='__kind__')
    query.keys_only()

    kinds = [entity.key.id_or_name for entity in query.fetch()]
    # [END kind_run_query]

    return kinds

def property_run_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START property_run_query]
    query = client.query(kind='__property__')
    query.keys_only()

    properties_by_kind = defaultdict(list)

    for entity in query.fetch():
        kind = entity.key.parent.name
        property_ = entity.key.name

        properties_by_kind[kind].append(property_)
    # [END property_run_query]

    return properties_by_kind

def property_by_kind_run_query(client):
    # Create the entity that we're going to query.
    upsert(client)

    # [START property_by_kind_run_query]
    ancestor = client.key('__kind__', 'Task')
    query = client.query(kind='__property__', ancestor=ancestor)

    representations_by_property = {}

    for entity in query.fetch():
        property_name = entity.key.name
        property_types = entity['property_representation']

        representations_by_property[property_name] = property_types
    # [END property_by_kind_run_query]

    return representations_by_property

def eventual_consistent_query(client):
    # [START eventual_consistent_query]
    # Read consistency cannot be specified in google-cloud-python.
    # [END eventual_consistent_query]
    pass

def main(project_id):
    client = datastore.Client(project_id)

    for name, function in globals().iteritems():
        if name in ('main', 'defaultdict') or not callable(function):
            continue

        print(name)
        pprint(function(client))
        print('\n-----------------\n')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Demonstrates datastore API operations.')
    parser.add_argument('project_id', help='Your cloud project ID.')

    args = parser.parse_args()

    main(args.project_id)


text:
require 'date'
require 'markdo/commands/command'

module Markdo
  class TodayCommand < Command
    def run
      task_collection.due_today.each do |task|
        @stdout.puts(task.line)
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
def run(location,option=None):
    """run function, needs definition"""
    print()
    print('He is following you, about 30 feet back.')
    print()
    return location


text:
require 'rspec'
require 'dest'
require'./spec/class_example.rb'

describe Dest::Evaluator do

  it "should return true for a parsed doctest that is correct" do
    doctest = [7, "Greeter.new(\"Aaron\").say_hello", "\"Hello Aaron\""]

    Dest::Evaluator.new(doctest).evaluate.first.should == true
  end

  it "should return false for a parsed doctest that is incorrect" do
    doctest = [7, "Greeter.new(\"Aaron\").say_hello", "\"Hello DifferName\""]

    Dest::Evaluator.new(doctest).evaluate.first.should == false
  end

  it "should raise an error if a non contextd class is referenced" do
    doctest = [7, "SomeClass.new(\"Aaron\").say_hello", "\"Hello DifferName\""]

    expect { Dest::Evaluator.new(doctest).evaluate }.to raise_error
  end
end


text:
package org.lwjgl.opengl;

import org.lwjgl.util.generator.*;
import org.lwjgl.util.generator.opengl.GLenum;
import org.lwjgl.util.generator.opengl.GLintptr;
import org.lwjgl.util.generator.opengl.GLsizei;
import org.lwjgl.util.generator.opengl.GLvoid;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

import com.sun.mirror.type.PrimitiveType;

public interface ARB_indirect_parameters {

	/**
	 * Accepted by the <target> parameters of BindBuffer, BufferData,
	 * BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData,
	 * GetBufferPointerv, MapBufferRange, FlushMappedBufferRange,
	 * GetBufferParameteriv, and CopyBufferSubData:
	 */
	int GL_PARAMETER_BUFFER_ARB = 0x80EE;

	/**
	 * Accepted by the <value> parameter of GetIntegerv, GetBooleanv, GetFloatv,
	 * and GetDoublev:
	 */
	int GL_PARAMETER_BUFFER_BINDING_ARB = 0x80EF;

	void glMultiDrawArraysIndirectCountARB(@GLenum int mode,
	                                       @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 * 4 : stride) * maxdrawcount") @Const @GLvoid ByteBuffer indirect,
	                                       @GLintptr long drawcount,
	                                       @GLsizei int maxdrawcount,
	                                       @GLsizei int stride);

	@Alternate("glMultiDrawArraysIndirectCountARB")
	void glMultiDrawArraysIndirectCountARB(@GLenum int mode,
	                                       @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 4 : stride >> 2) * maxdrawcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect,
	                                       @GLintptr long drawcount,
	                                       @GLsizei int maxdrawcount,
	                                       @GLsizei int stride);

	void glMultiDrawElementsIndirectCountARB(@GLenum int mode,
	                                         @GLenum int type,
	                                         @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 * 4 : stride) * maxdrawcount") @Const @GLvoid ByteBuffer indirect,
	                                         @GLintptr long drawcount,
	                                         @GLsizei int maxdrawcount,
	                                         @GLsizei int stride);

	@Alternate("glMultiDrawElementsIndirectCountARB")
	void glMultiDrawElementsIndirectCountARB(@GLenum int mode,
	                                         @GLenum int type,
	                                         @BufferObject(BufferKind.IndirectBO) @Check("(stride == 0 ? 5 : stride >> 2) * maxdrawcount") @Const @GLvoid(PrimitiveType.Kind.INT) IntBuffer indirect,
	                                         @GLintptr long drawcount,
	                                         @GLsizei int maxdrawcount,
	                                         @GLsizei int stride);

}


text:
<?php

namespace Dvsa\Mot\Frontend\PersonModule\Routes;

use Dvsa\Mot\Frontend\PersonModule\View\ContextProvider;
use DvsaCommon\Factory\AutoWire\AutoWireableInterface;

class PersonProfileRoutes implements AutoWireableInterface
{
    const TEST_LOGS = '/tester-mot-test-log';
    const TEST_QUALITY = '/test-quality-information';
    const TEST_QUALITY_INFORMATION = '/test-quality-information';
    private $contextProvider;

    public function __construct(ContextProvider $contextProvider)
    {
        $this->contextProvider = $contextProvider;
    }

    public function getRoute()
    {
        $context = $this->contextProvider->getContext();
        switch ($context) {
            case ContextProvider::YOUR_PROFILE_CONTEXT:
                return ContextProvider::YOUR_PROFILE_PARENT_ROUTE;
            case ContextProvider::USER_SEARCH_CONTEXT:
                return ContextProvider::USER_SEARCH_PARENT_ROUTE;
            case ContextProvider::AE_CONTEXT:
                return ContextProvider::AE_PARENT_ROUTE;
            case ContextProvider::VTS_CONTEXT:
                return ContextProvider::VTS_PARENT_ROUTE;
            case ContextProvider::PERFORMANCE_DASHBOARD_CONTEXT:
                return ContextProvider::PERFORMANCE_DASHBOARD_ROUTE;
            default:
                throw new \Exception();
        }
    }

    public function getTestLogsRoute()
    {
        return $this->getRoute().self::TEST_LOGS;
    }

    public function getTestQualityRoute()
    {
        return $this->getRoute().self::TEST_QUALITY;
    }
}


text:
package com.fernandocejas.mycv;

import android.app.Application;

/**
 * The android10 coder: http://www.android10.org/
 * @author Fernando Cejas <http://fernandocejas.com/>
 */
public class MyCVApplication extends Application {

	private static MyCVApplication singleton;

	public static MyCVApplication getInstance() {
		return singleton;
	}

	@Override
	public final void onCreate() {
		super.onCreate();
		singleton = this;
	}
}


text:
package io.truthencode.ddo.subscription.config

case class CamelConfig (autostart:Boolean = true)


text:
{% extends "base.html" %}

{% block title %}
	Monengagement.fr
{% endblock %}

{% block css %}{% endblock %}

{% block content %}

MonEngagement.FR

			monengagement

{% endblock %}


text:
package io.atomix.copycat.client.response;

import io.atomix.catalyst.serializer.SerializeWith;

/**
 * Protocol query response.
 *
 * @author Jordan Halterman
 */
@SerializeWith(id=198)
public class QueryResponse extends OperationResponse<QueryResponse> {

  /**
   * Returns a new query response builder.
   *
   * @return A new query response builder.
   */
  public static Builder builder() {
    return new Builder(new QueryResponse());
  }

  /**
   * Returns a query response builder for an existing request.
   *
   * @param response The response to build.
   * @return The query response builder.
   * @throws NullPointerException if {@code request} is null
   */
  public static Builder builder(QueryResponse response) {
    return new Builder(response);
  }

  /**
   * Query response builder.
   */
  public static class Builder extends OperationResponse.Builder<Builder, QueryResponse> {
    protected Builder(QueryResponse response) {
      super(response);
    }
  }

}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Gaming.Game;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.GuiAutomation;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.DataStorage;
using MatterHackers.MatterControl.PluginSystem;
using MatterHackers.MatterControl.PrinterCommunication;
using MatterHackers.MatterControl.PrintQueue;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.SlicerConfiguration;
using MatterHackers.PolygonMesh.Processors;
using MatterHackers.RenderOpenGl.OpenGl;
using MatterHackers.VectorMath;
using Mindscape.Raygun4Net;

namespace MatterHackers.MatterControl
{
	public class MatterControlApplication : SystemWindow
	{
#if DEBUG
		//public static string MCWSBaseUri { get; } = "http://192.168.2.129:9206";
		public static string MCWSBaseUri { get; } = "https://mattercontrol-test.appspot.com";
#else
		public static string MCWSBaseUri { get; } = "https://mattercontrol.appspot.com";
#endif

		public static bool CameraInUseByExternalProcess { get; set; } = false;
		public bool RestartOnClose = false;
		private static readonly Vector2 minSize = new Vector2(600, 600);
		private static MatterControlApplication instance;
		private string[] commandLineArgs = null;
		private string confirmExit = "Confirm Exit".Localize();
		private bool DoCGCollectEveryDraw = false;
		private int drawCount = 0;
		private AverageMillisecondTimer millisecondTimer = new AverageMillisecondTimer();
		private DataViewGraph msGraph;
		private string savePartsSheetExitAnywayMessage = "You are currently saving a parts sheet, are you sure you want to exit?".Localize();
		private bool ShowMemoryUsed = false;

		public void ConfigureWifi()
		{
		}

		private Stopwatch totalDrawTime = new Stopwatch();

#if true//!DEBUG
		static RaygunClient _raygunClient = GetCorrectClient();
#endif

		static RaygunClient GetCorrectClient()
		{
			if (OsInformation.OperatingSystem == OSType.Mac)
			{
				return new RaygunClient("qmMBpKy3OSTJj83+tkO7BQ=="); // this is the Mac key
			}
			else
			{
				return new RaygunClient("hQIlyUUZRGPyXVXbI6l1dA=="); // this is the PC key
			}
		}

		public static bool IsLoading { get; private set; } = true;

		static MatterControlApplication()
		{
			if (OsInformation.OperatingSystem == OSType.Mac && StaticData.Instance == null)
			{
				// Set working directory - this duplicates functionality in Main but is necessary on OSX as Main fires much later (after the constructor in this case)
				// resulting in invalid paths due to path tests running before the working directory has been overridden. Setting the value before initializing StaticData
				// works around this architectural difference.
				Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
			}

			// Because fields on this class call localization methods and because those methods depend on the StaticData provider and because the field
			// initializers run before the class constructor, we need to init the platform specific provider in the static constructor (or write a custom initializer method)
			//
			// Initialize a standard file system backed StaticData provider
			if (StaticData.Instance == null) // it may already be initialized by tests
			{
				StaticData.Instance = new MatterHackers.Agg.FileSystemStaticData();
			}
		}

		private MatterControlApplication(double width, double height)
			: base(width, height)
		{
			ApplicationSettings.Instance.set("HardwareHasCamera", "false");

			Name = "MatterControl";

			// set this at startup so that we can tell next time if it got set to true in close
			UserSettings.Instance.Fields.StartCount = UserSettings.Instance.Fields.StartCount + 1;

			this.commandLineArgs = Environment.GetCommandLineArgs();
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

			for (int currentCommandIndex = 0; currentCommandIndex < commandLineArgs.Length; currentCommandIndex++)
			{
				string command = commandLineArgs[currentCommandIndex];
				string commandUpper = command.ToUpper();
				switch (commandUpper)
				{
					case "FORCE_SOFTWARE_RENDERING":
						GL.HardwareAvailable = false;
						break;

					case "CLEAR_CACHE":
						AboutWidget.DeleteCacheData(0);
						break;

					case "SHOW_MEMORY":
						ShowMemoryUsed = true;
						break;

					case "DO_GC_COLLECT_EVERY_DRAW":
						ShowMemoryUsed = true;
						DoCGCollectEveryDraw = true;
						break;

					//case "CREATE_AND_SELECT_PRINTER":
					//	if (currentCommandIndex + 1 <= commandLineArgs.Length)
					//	{
					//		currentCommandIndex++;
					//		string argument = commandLineArgs[currentCommandIndex];
					//		string[] printerData = argument.Split(',');
					//		if (printerData.Length >= 2)
					//		{
					//			Printer ActivePrinter = new Printer();

					//			ActivePrinter.Name = "Auto: {0} {1}".FormatWith(printerData[0], printerData[1]);
					//			ActivePrinter.Make = printerData[0];
					//			ActivePrinter.Model = printerData[1];

					//			if (printerData.Length == 3)
					//			{
					//				ActivePrinter.ComPort = printerData[2];
					//			}

					//			PrinterSetupStatus test = new PrinterSetupStatus(ActivePrinter);
					//			test.LoadSettingsFromConfigFile(ActivePrinter.Make, ActivePrinter.Model);
					//			ActiveSliceSettings.Instance = ActivePrinter;
					//		}
					//	}

					//	break;

					case "CONNECT_TO_PRINTER":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							PrinterConnectionAndCommunication.Instance.ConnectToActivePrinter();
						}
						break;

					case "START_PRINT":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							bool hasBeenRun = false;
							currentCommandIndex++;
							string fullPath = commandLineArgs[currentCommandIndex];
							QueueData.Instance.RemoveAll();
							if (!string.IsNullOrEmpty(fullPath))
							{
								string fileName = Path.GetFileNameWithoutExtension(fullPath);
								QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(fileName, fullPath)));
								PrinterConnectionAndCommunication.Instance.CommunicationStateChanged.RegisterEvent((sender, e) =>
								{
									if (!hasBeenRun && PrinterConnectionAndCommunication.Instance.CommunicationState == PrinterConnectionAndCommunication.CommunicationStates.Connected)
									{
										hasBeenRun = true;
										PrinterConnectionAndCommunication.Instance.PrintActivePartIfPossible();
									}
								}, ref unregisterEvent);
							}
						}
						break;

					case "SLICE_AND_EXPORT_GCODE":
						if (currentCommandIndex + 1 <= commandLineArgs.Length)
						{
							currentCommandIndex++;
							string fullPath = commandLineArgs[currentCommandIndex];
							QueueData.Instance.RemoveAll();
							if (!string.IsNullOrEmpty(fullPath))
							{
								string fileName = Path.GetFileNameWithoutExtension(fullPath);
								PrintItemWrapper printItemWrapper = new PrintItemWrapper(new PrintItem(fileName, fullPath));
								QueueData.Instance.AddItem(printItemWrapper);

								SlicingQueue.Instance.QueuePartForSlicing(printItemWrapper);
								ExportPrintItemWindow exportForTest = new ExportPrintItemWindow(printItemWrapper);
								exportForTest.ExportGcodeCommandLineUtility(fileName);
							}
						}
						break;
				}

				if (MeshFileIo.ValidFileExtensions().Contains(Path.GetExtension(command).ToUpper()))
				{
					// If we are the only instance running then do nothing.
					// Else send these to the running instance so it can load them.
				}
			}

			//WriteTestGCodeFile();
#if !DEBUG
			if (File.Exists("RunUnitTests.txt"))
#endif
			{
#if IS_WINDOWS_FORMS
				if (!Clipboard.IsInitialized)
				{
					Clipboard.SetSystemClipboard(new WindowsFormsClipboard());
				}
#endif

				// you can turn this on to debug some bounds issues
				//GuiWidget.DebugBoundsUnderMouse = true;
			}

			GuiWidget.DefaultEnforceIntegerBounds = true;

			if (UserSettings.Instance.DisplayMode == ApplicationDisplayType.Touchscreen)
			{
				GuiWidget.DeviceScale = 1.3;
			}
			//GuiWidget.DeviceScale = 2;

			using (new PerformanceTimer("Startup", "MainView"))
			{
				this.AddChild(ApplicationController.Instance.MainView);
			}
			this.MinimumSize = minSize;
			this.Padding = new BorderDouble(0); //To be re-enabled once native borders are turned off

#if false // this is to test freeing gcodefile memory
			Button test = new Button("test");
			test.Click += (sender, e) =>
			{
				//MatterHackers.GCodeVisualizer.GCodeFile gcode = new GCodeVisualizer.GCodeFile();
				//gcode.Load(@"C:\Users\lbrubaker\Downloads\drive assy.gcode");
				SystemWindow window = new SystemWindow(100, 100);
				window.ShowAsSystemWindow();
			};
			allControls.AddChild(test);
#endif
			this.AnchorAll();

			if (GL.HardwareAvailable)
			{
				UseOpenGL = true;
			}
			string version = "1.6";

			Title = "MatterHackers: MatterControl {0}".FormatWith(version);
			if (OemSettings.Instance.WindowTitleExtra != null && OemSettings.Instance.WindowTitleExtra.Trim().Length > 0)
			{
				Title = Title + " - {1}".FormatWith(version, OemSettings.Instance.WindowTitleExtra);
			}

			UiThread.RunOnIdle(CheckOnPrinter);

			string desktopPosition = ApplicationSettings.Instance.get(ApplicationSettingsKey.DesktopPosition);
			if (desktopPosition != null && desktopPosition != "")
			{
				string[] sizes = desktopPosition.Split(',');

				//If the desktop position is less than -10,-10, override
				int xpos = Math.Max(int.Parse(sizes[0]), -10);
				int ypos = Math.Max(int.Parse(sizes[1]), -10);

				DesktopPosition = new Point2D(xpos, ypos);
			}
		}

		public void TakePhoto(string imageFileName)
		{
			ImageBuffer noCameraImage = new ImageBuffer(640, 480);
			Graphics2D graphics = noCameraImage.NewGraphics2D();
			graphics.Clear(RGBA_Bytes.White);
			graphics.DrawString("No Camera Detected", 320, 240, pointSize: 24, justification: Agg.Font.Justification.Center);
			graphics.DrawString(DateTime.Now.ToString(), 320, 200, pointSize: 12, justification: Agg.Font.Justification.Center);
			ImageIO.SaveImageData(imageFileName, noCameraImage);

			PictureTaken?.Invoke(null, null);
		}

		bool dropWasOnChild = true;
		public override void OnDragEnter(FileDropEventArgs fileDropEventArgs)
		{
			base.OnDragEnter(fileDropEventArgs);

			if (!fileDropEventArgs.AcceptDrop)
			{
				// no child has accepted the drop
				foreach (string file in fileDropEventArgs.DroppedFiles)
				{
					string extension = Path.GetExtension(file).ToUpper();
					if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension))
						|| extension == ".GCODE"
						|| extension == ".ZIP")
					{
						fileDropEventArgs.AcceptDrop = true;
					}
				}
				dropWasOnChild = false;
			}
			else
			{
				dropWasOnChild = true;
			}
		}

		public override void OnDragOver(FileDropEventArgs fileDropEventArgs)
		{
			base.OnDragOver(fileDropEventArgs);

			if (!fileDropEventArgs.AcceptDrop)
			{
				// no child has accepted the drop
				foreach (string file in fileDropEventArgs.DroppedFiles)
				{
					string extension = Path.GetExtension(file).ToUpper();
					if ((extension != "" && MeshFileIo.ValidFileExtensions().Contains(extension))
						|| extension == ".GCODE"
						|| extension == ".ZIP")
					{
						fileDropEventArgs.AcceptDrop = true;
					}
				}
				dropWasOnChild = false;
			}
			else
			{
				dropWasOnChild = true;
			}
		}

		public override void OnDragDrop(FileDropEventArgs fileDropEventArgs)
		{
			base.OnDragDrop(fileDropEventArgs);

			if (!dropWasOnChild)
			{
				QueueDataWidget.DoAddFiles(fileDropEventArgs.DroppedFiles);
			}
		}

		public enum ReportSeverity2 { Warning, Error }

		public void ReportException(Exception e, string key = "", string value = "", ReportSeverity2 warningLevel = ReportSeverity2.Warning)
		{
			// Conditionally spin up error reporting if not on the Stable channel
			string channel = UserSettings.Instance.get(UserSettingsKey.UpdateFeedType);
			if (string.IsNullOrEmpty(channel) || channel != "release" || OemSettings.Instance.WindowTitleExtra == "Experimental")
			{
#if !DEBUG
				_raygunClient.Send(e);
#endif
			}
		}

		private EventHandler unregisterEvent;

		public static MatterControlApplication Instance
		{
			get
			{
				if (instance == null)
				{
					instance = CreateInstance();
					instance.ShowAsSystemWindow();
				}

				return instance;
			}
		}

		public event EventHandler PictureTaken;

		public static MatterControlApplication CreateInstance(int overrideWidth = -1, int overrideHeight = -1)
		{
			int width = 0;
			int height = 0;

			// check if the app has a size alread set
			string windowSize = ApplicationSettings.Instance.get(ApplicationSettingsKey.WindowSize);
			if (windowSize != null && windowSize != "")
			{
				// try and open our window matching the last size that we had for it.
				string[] sizes = windowSize.Split(',');
				width = Math.Max(int.Parse(sizes[0]), (int)minSize.x + 1);
				height = Math.Max(int.Parse(sizes[1]), (int)minSize.y + 1);
			}
			else // try to set it to a big size or the min size
			{
				Point2D desktopSize = OsInformation.DesktopSize;

				if (overrideWidth != -1)
				{
					width = overrideWidth;
				}
				else // try to set it to a good size
				{
					if (width < desktopSize.x)
					{
						width = 1280;
					}
				}

				if (overrideHeight != -1)
				{
					height = overrideHeight;
				}
				else
				{
					if (height < desktopSize.y)
					{
						height = 720;
					}
				}
			}

			using (new PerformanceTimer("Startup", "Total"))
			{
				instance = new MatterControlApplication(width, height);

				if (instance.DesktopPosition == new Point2D())
				{
					Point2D desktopSize = OsInformation.DesktopSize;

					// Now try and center the window. If this is saved it will got overridden
					instance.DesktopPosition = new Point2D((desktopSize.x - instance.Width) / 2, (desktopSize.y - instance.Height) / 2);
				}
			}

			return instance;
		}

		[STAThread]
		public static void Main()
		{
			PerformanceTimer.GetParentWindowFunction = () => { return MatterControlApplication.instance; };

			CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
			Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

			// Make sure we have the right working directory as we assume everything relative to the executable.
			Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));

			Datastore.Instance.Initialize();

#if !DEBUG
			// Conditionally spin up error reporting if not on the Stable channel
			string channel = UserSettings.Instance.get(UserSettingsKey.UpdateFeedType);
			if (string.IsNullOrEmpty(channel) || channel != "release" || OemSettings.Instance.WindowTitleExtra == "Experimental")
#endif
			{
				System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
				AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
			}

			MatterControlApplication app = MatterControlApplication.Instance;
		}

		private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
		{
#if !DEBUG
			_raygunClient.Send(e.Exception);
#endif
		}

		private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
#if !DEBUG
			_raygunClient.Send(e.ExceptionObject as Exception);
#endif
		}

		public static void WriteTestGCodeFile()
		{
			using (StreamWriter file = new StreamWriter("PerformanceTest.gcode"))
			{
				//int loops = 150000;
				int loops = 150;
				int steps = 200;
				double radius = 50;
				Vector2 center = new Vector2(150, 100);

				file.WriteLine("G28 ; home all axes");
				file.WriteLine("G90 ; use absolute coordinates");
				file.WriteLine("G21 ; set units to millimeters");
				file.WriteLine("G92 E0");
				file.WriteLine("G1 F7800");
				file.WriteLine("G1 Z" + (5).ToString());
				WriteMove(file, center);

				for (int loop = 0; loop < loops; loop++)
				{
					for (int step = 0; step < steps; step++)
					{
						Vector2 nextPosition = new Vector2(radius, 0);
						nextPosition.Rotate(MathHelper.Tau / steps * step);
						WriteMove(file, center + nextPosition);
					}
				}

				file.WriteLine("M84     ; disable motors");
			}
		}

		public void LaunchBrowser(string targetUri)
		{
			UiThread.RunOnIdle(() =>
			{
				System.Diagnostics.Process.Start(targetUri);
			});
		}

		public override void OnClosed(EventArgs e)
		{
			UserSettings.Instance.Fields.StartCountDurringExit = UserSettings.Instance.Fields.StartCount;

			TerminalWindow.CloseIfOpen();
			if (PrinterConnectionAndCommunication.Instance.CommunicationState != PrinterConnectionAndCommunication.CommunicationStates.PrintingFromSd)
			{
				PrinterConnectionAndCommunication.Instance.Disable();
			}
			//Close connection to the local datastore
			PrinterConnectionAndCommunication.Instance.HaltConnectionThread();
			SlicingQueue.Instance.ShutDownSlicingThread();
			ApplicationController.Instance.OnApplicationClosed();

			Datastore.Instance.Exit();

			if (RestartOnClose)
			{
				string appPathAndFile = System.Reflection.Assembly.GetExecutingAssembly().Location;
				string pathToAppFolder = Path.GetDirectoryName(appPathAndFile);

				ProcessStartInfo runAppLauncherStartInfo = new ProcessStartInfo();
				runAppLauncherStartInfo.Arguments = "\"{0}\" \"{1}\"".FormatWith(appPathAndFile, 1000);
				runAppLauncherStartInfo.FileName = Path.Combine(pathToAppFolder, "Launcher.exe");
				runAppLauncherStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
				runAppLauncherStartInfo.CreateNoWindow = true;

				Process.Start(runAppLauncherStartInfo);
			}
			base.OnClosed(e);
		}

		public override void OnClosing(out bool CancelClose)
		{
			// save the last size of the window so we can restore it next time.
			ApplicationSettings.Instance.set(ApplicationSettingsKey.WindowSize, string.Format("{0},{1}", Width, Height));
			ApplicationSettings.Instance.set(ApplicationSettingsKey.DesktopPosition, string.Format("{0},{1}", DesktopPosition.x, DesktopPosition.y));

			//Save a snapshot of the prints in queue
			QueueData.Instance.SaveDefaultQueue();

			if (PrinterConnectionAndCommunication.Instance.PrinterIsPrinting)
			{
				if (PrinterConnectionAndCommunication.Instance.CommunicationState != PrinterConnectionAndCommunication.CommunicationStates.PrintingFromSd)
				{
					// Needed as we can't assign to CancelClose inside of the lambda below
					bool continueWithShutdown = false;

					StyledMessageBox.ShowMessageBox(
						(shutdownConfirmed) => continueWithShutdown = shutdownConfirmed,
						"Are you sure you want to abort the current print and close MatterControl?".Localize(),
						"Abort Print".Localize(),
						StyledMessageBox.MessageType.YES_NO);

					if (continueWithShutdown)
					{
						PrinterConnectionAndCommunication.Instance.Disable();
						this.Close();
						CancelClose = false;
					}
					else
					{
						// It's safe to cancel an active print because PrinterConnectionAndCommunication.Disable will be called
						// when MatterControlApplication.OnClosed is invoked
						CancelClose = true;
					}
				}
				else
				{
					bool continueWithShutdown = false;

					StyledMessageBox.ShowMessageBox(
						(shutdownConfirmed) => continueWithShutdown = shutdownConfirmed,
						"Are you sure you want exit while a print is running from SD Card?\n\nNote: If you exit, it is recommended you wait until the print is completed before running MatterControl again.".Localize(),
						"Exit while printing".Localize(),
						StyledMessageBox.MessageType.YES_NO);

					if (continueWithShutdown)
					{
						PrinterConnectionAndCommunication.Instance.Disable();
						this.Close();
						CancelClose = false;
					}
					else
					{
						// It's safe to cancel an active print because PrinterConnectionAndCommunication.Disable will be called
						// when MatterControlApplication.OnClosed is invoked
						CancelClose = true;
					}
				}
			}
			else if (PartsSheet.IsSaving())
			{
				StyledMessageBox.ShowMessageBox(onConfirmExit, savePartsSheetExitAnywayMessage, confirmExit, StyledMessageBox.MessageType.YES_NO);
				CancelClose = true;
			}
			else
			{
				base.OnClosing(out CancelClose);
			}
		}

		public override void OnDraw(Graphics2D graphics2D)
		{
			totalDrawTime.Restart();
			GuiWidget.DrawCount = 0;
			using (new PerformanceTimer("Draw Timer", "MC Draw"))
			{
				base.OnDraw(graphics2D);
			}
			totalDrawTime.Stop();

			millisecondTimer.Update((int)totalDrawTime.ElapsedMilliseconds);

			if (ShowMemoryUsed)
			{
				long memory = GC.GetTotalMemory(false);
				this.Title = "Allocated = {0:n0} : {1:000}ms, d{2} Size = {3}x{4}, onIdle = {5:00}:{6:00}, widgetsDrawn = {7}".FormatWith(memory, millisecondTimer.GetAverage(), drawCount++, this.Width, this.Height, UiThread.CountExpired, UiThread.Count, GuiWidget.DrawCount);
				if (DoCGCollectEveryDraw)
				{
					GC.Collect();
				}
			}

			//msGraph.AddData("ms", totalDrawTime.ElapsedMilliseconds);
			//msGraph.Draw(MatterHackers.Agg.Transform.Affine.NewIdentity(), graphics2D);
		}

		public override void OnLoad(EventArgs args)
		{
			foreach (string arg in commandLineArgs)
			{
				string argExtension = Path.GetExtension(arg).ToUpper();
				if (argExtension.Length > 1
					&& MeshFileIo.ValidFileExtensions().Contains(argExtension))
				{
					QueueData.Instance.AddItem(new PrintItemWrapper(new PrintItem(Path.GetFileName(arg), Path.GetFullPath(arg))));
				}
			}

			TerminalWindow.ShowIfLeftOpen();

			ApplicationController.Instance.OnLoadActions();

			//HtmlWindowTest();

			IsLoading = false;
		}

		private static void HtmlWindowTest()
		{
			try
			{
				SystemWindow htmlTestWindow = new SystemWindow(640, 480);
				string htmlContent = "";
				if (true)
				{
					string releaseNotesFile = Path.Combine("C:\\Users\\lbrubaker\\Downloads", "test1.html");
					htmlContent = File.ReadAllText(releaseNotesFile);
				}
				else
				{
					WebClient webClient = new WebClient();
					htmlContent = webClient.DownloadString("http://www.matterhackers.com/s/store?q=pla");
				}

				HtmlWidget content = new HtmlWidget(htmlContent, RGBA_Bytes.Black);
				content.AddChild(new GuiWidget(HAnchor.AbsolutePosition, VAnchor.ParentBottomTop));
				content.VAnchor |= VAnchor.ParentTop;
				content.BackgroundColor = RGBA_Bytes.White;
				htmlTestWindow.AddChild(content);
				htmlTestWindow.BackgroundColor = RGBA_Bytes.Cyan;
				UiThread.RunOnIdle((state) =>
				{
					htmlTestWindow.ShowAsSystemWindow();
				}, 1);
			}
			catch
			{
				int stop = 1;
			}
		}

		public override void OnMouseMove(MouseEventArgs mouseEvent)
		{
			if (GuiWidget.DebugBoundsUnderMouse)
			{
				Invalidate();
			}
			base.OnMouseMove(mouseEvent);
		}

		public override void OnParentChanged(EventArgs e)
		{
			if (File.Exists("RunUnitTests.txt"))
			{
				//DiagnosticWidget diagnosticView = new DiagnosticWidget(this);
			}

			base.OnParentChanged(e);

			// now that we are all set up lets load our plugins and allow them their chance to set things up
			FindAndInstantiatePlugins();

			if (ApplicationController.Instance.PluginsLoaded != null)
			{
				ApplicationController.Instance.PluginsLoaded.CallEvents(null, null);
			}
		}

		public void OpenCameraPreview()
		{
			//Camera launcher placeholder (KP)
			if (ApplicationSettings.Instance.get(ApplicationSettingsKey.HardwareHasCamera) == "true")
			{
				//Do something
			}
			else
			{
				//Do something else (like show warning message)
			}
		}

		public void PlaySound(string fileName)
		{
			if (OsInformation.OperatingSystem == OSType.Windows)
			{
				using (var mediaStream = StaticData.Instance.OpenSteam(Path.Combine("Sounds", fileName)))
				{
					(new System.Media.SoundPlayer(mediaStream)).Play();
				}
			}
		}

		private static void WriteMove(StreamWriter file, Vector2 center)
		{
			file.WriteLine("G1 X" + center.x.ToString() + " Y" + center.y.ToString());
		}

		private void CheckOnPrinter()
		{
			try
			{
				PrinterConnectionAndCommunication.Instance.OnIdle();
			}
			catch (Exception e)
			{
				Debug.Print(e.Message);
				GuiWidget.BreakInDebugger();
#if DEBUG
				throw e;
#endif
			}
			UiThread.RunOnIdle(CheckOnPrinter);
		}

		private void FindAndInstantiatePlugins()
		{
#if false
			string pluginDirectory = Path.Combine("..", "..", "..", "MatterControlPlugins", "bin");
#if DEBUG
			pluginDirectory = Path.Combine(pluginDirectory, "Debug");
#else
			pluginDirectory = Path.Combine(pluginDirectory, "Release");
#endif
			if (!Directory.Exists(pluginDirectory))
			{
				string dataPath = ApplicationDataStorage.Instance.ApplicationUserDataPath;
				pluginDirectory = Path.Combine(dataPath, "Plugins");
			}
			// TODO: this should look in a plugin folder rather than just the application directory (we probably want it in the user folder).
			PluginFinder<MatterControlPlugin> pluginFinder = new PluginFinder<MatterControlPlugin>(pluginDirectory);
#else
			PluginFinder<MatterControlPlugin> pluginFinder = new PluginFinder<MatterControlPlugin>();
#endif

			string oemName = ApplicationSettings.Instance.GetOEMName();
			foreach (MatterControlPlugin plugin in pluginFinder.Plugins)
			{
				string pluginInfo = plugin.GetPluginInfoJSon();
				Dictionary<string, string> nameValuePairs = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(pluginInfo);

				if (nameValuePairs != null && nameValuePairs.ContainsKey("OEM"))
				{
					if (nameValuePairs["OEM"] == oemName)
					{
						plugin.Initialize(this);
					}
				}
				else
				{
					plugin.Initialize(this);
				}
			}
		}

		private void onConfirmExit(bool messageBoxResponse)
		{
			bool CancelClose;
			if (messageBoxResponse)
			{
				base.OnClosing(out CancelClose);
			}
		}

		private static void AssertDebugNotDefined()
		{
#if DEBUG
			throw new Exception("DEBUG is defined and should not be!");
#endif
		}

		bool showNamesUnderMouse = false;
		public override void OnKeyDown(KeyEventArgs keyEvent)
		{
			if (keyEvent.KeyCode == Keys.F1)
			{
				showNamesUnderMouse = !showNamesUnderMouse;
			}
			base.OnKeyDown(keyEvent);
		}

		public static void CheckKnownAssemblyConditionalCompSymbols()
		{
			MatterControlApplication.AssertDebugNotDefined();
			MatterHackers.GCodeVisualizer.GCodeFile.AssertDebugNotDefined();
			MatterHackers.Agg.Graphics2D.AssertDebugNotDefined();
			MatterHackers.Agg.UI.SystemWindow.AssertDebugNotDefined();
			MatterHackers.Agg.ImageProcessing.InvertLightness.AssertDebugNotDefined();
			MatterHackers.Localizations.TranslationMap.AssertDebugNotDefined();
			MatterHackers.MarchingSquares.MarchingSquaresByte.AssertDebugNotDefined();
			MatterHackers.MatterControl.PluginSystem.MatterControlPlugin.AssertDebugNotDefined();
			MatterHackers.MatterSlice.MatterSlice.AssertDebugNotDefined();
			MatterHackers.MeshVisualizer.MeshViewerWidget.AssertDebugNotDefined();
			MatterHackers.RenderOpenGl.GLMeshTrianglePlugin.AssertDebugNotDefined();
		}

		public bool IsNetworkConnected()
		{
			return true;
		}
	}
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: zuhair
 * Date: 11/06/2016
 * Time: 02:01 م
 */
?>

<link rel="stylesheet" href="<?= base_url() ?>assets/bootstrap-3.3.6/bootstrap-tagsinput/bootstrap-tagsinput.min.css">

<form class="hide" action="<?= base_url() ?>upload/uploadMultiImgs" id="imgsUpForm" enctype="multipart/form-data"
      method="post" accept-charset="utf-8">
    <input type="file" name="file[]" multiple="multiple" id="file" accept="image/*"/>

</form>

    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#add_post_modal">

        إضافة مقال
    </button>

<form role="form" id="add_post_form" action="<?= base_url() ?>welcome/insert_post" method="post">

<input type="text" class="form-control" id="post_title"
                                     name="post_title" placeholder="عنوان المقال"/>

            <select name="post_part" id="post_part" class="form-control">
                <option disabled="disabled" selected="selected" value="0">اختر القسم</option>
                <? foreach ($parts as $part): ?>
                    <option value="<?= $part->part_id ?>"><?= $part->part_title ?></option>
                <? endforeach; ?>
            </select>

         رفع الصور (0%)

    <link rel="stylesheet" href="<?= base_url() ?>assets/summernote/summernote.css"/>

                    <textarea form="add_post_form" title="ضع المقال هنا" name="post_content" id="post_content"
                              class="summernote hide"></textarea>

         الكلمات المفتاحية:  (ضع فاصلة بين الكلمات)
        <input data-role="tagsinput" type="text" class="form-control" id="post_tags" name="post_tags">

    <input type="hidden" name="author_id" value="<?= $this->session->user_id ?>"/>

    <button type="submit" class="btn btn-primary btn-block"> حفظ
    </button>
</form>


text:
set -e

function osd_volume_activate {
  check_device

  # Verify the device is a valid ceph-volume device
  # If not the following command will return 1 with "No valid Ceph devices found"
  if ! ceph-volume lvm list "${OSD_DEVICE}"; then
    cat /var/log/ceph
    exit 1
  fi

  # Find the OSD ID
  OSD_ID="$(ceph-volume lvm list "$OSD_DEVICE" --format json | python -c 'import sys, json; print(json.load(sys.stdin).keys()[0])')"

  # Find the OSD FSID
  OSD_FSID="$(ceph-volume lvm list "$OSD_DEVICE" --format json | python -c "import sys, json; print(json.load(sys.stdin)[\"$OSD_ID\"][0][\"tags\"][\"ceph.osd_fsid\"])")"

  # Activate the OSD
  ceph-volume lvm activate --no-systemd "${OSD_ID}" "${OSD_FSID}"

  log "SUCCESS"
  # This ensures all resources have been unmounted after the OSD has exited
  # We define `sigterm_cleanup_post` here because:
  # - we want to 'protect' the following `exec` in particular.
  # - having the cleaning code just next to the concerned function in the same file is nice.
  function sigterm_cleanup_post {
    local ceph_mnt
    ceph_mnt=$(findmnt --nofsroot --noheadings --output SOURCE --submounts --target /var/lib/ceph/osd/ | tail -n +2)
    for mnt in $ceph_mnt; do
      log "Unmounting $mnt"
      umount "$mnt" || log "Failed to umount $mnt"
    done
  }
  exec /usr/bin/ceph-osd "${CLI_OPTS[@]}" -f -i "${OSD_ID}"
}


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Closure Unit Tests - goog.format</title>


text:
import { connect } from 'react-redux';

import ObservationsContainer from './ObservationsContainer';
import mapActionCreatorsToProps from '../../utils/mapActionCreatorsToProps';

import { loadObservations } from '../../actions';

import { getObservations } from '../../selectors';

const mapStateToProps = (state) => ({
  observations: getObservations(state),
});

const actionCreators = mapActionCreatorsToProps({
  loadObservations,
});

export default connect(
  mapStateToProps,
  actionCreators,
)(ObservationsContainer);


text:
require 'test_helper'
require 'garen'

class Garen::SpectatorTest < Minitest::Test
  def setup
    @garen = Garen::Client.new(api_key: 'RGAPI-87738e80-70a6-4e82-abee-3eda0b1644bf')
  end

  def test_status
    VCR.use_cassette 'spectator/by_summoner_id' do
      assert_raises(Faraday::Error::ClientError) { @garen.spectator.by_summoner_id 22_332_661 }
    end
  end

  def test_featured_games
    VCR.use_cassette 'spectator/featured_games' do
      s = @garen.spectator.featured_games
      assert_equal 5, s.game_list.count
      s.game_list.first.keys.each do |key|
        assert_includes(%w[game_id map_id game_mode game_type game_queue_config_id participants observers platform_id banned_champions game_start_time game_length], key)
      end
    end
  end
end


text:
@implementation ParallaxBackground

-(id) init
{
	if ((self = [super init]))
	{
		// The screensize never changes during gameplay, so we can cache it in a member variable.
		screenSize = [[CCDirector sharedDirector] winSize];

		// Get the game's texture atlas texture by adding it. Since it's added already it will simply return
		// the CCTexture2D associated with the texture atlas.
		CCTexture2D* gameArtTexture = [[CCTextureCache sharedTextureCache] addImage:@"game-art.png"];

		// Create the background spritebatch
		spriteBatch = [CCSpriteBatchNode batchNodeWithTexture:gameArtTexture];
		[self addChild:spriteBatch];

		numStripes = 7;

		// Add the 7 different stripes and position them on the screen
		for (int i = 0; i < numStripes; i++)
		{
			NSString* frameName = [NSString stringWithFormat:@"bg%i.png", i];
			CCSprite* sprite = [CCSprite spriteWithSpriteFrameName:frameName];
			sprite.anchorPoint = CGPointMake(0, 0.5f);
			sprite.position = CGPointMake(0, screenSize.height / 2);
			[spriteBatch addChild:sprite z:i tag:i];
		}

		// Add 7 more stripes, flip them and position them next to their neighbor stripe
		for (int i = 0; i < numStripes; i++)
		{
			NSString* frameName = [NSString stringWithFormat:@"bg%i.png", i];
			CCSprite* sprite = [CCSprite spriteWithSpriteFrameName:frameName];

			// Position the new sprite one screen width to the right
			sprite.anchorPoint = CGPointMake(0, 0.5f);
			sprite.position = CGPointMake(screenSize.width - 1, screenSize.height / 2);

			// Flip the sprite so that it aligns perfectly with its neighbor
			sprite.flipX = YES;

			// Add the sprite using the same tag offset by numStripes
			[spriteBatch addChild:sprite z:i tag:i + numStripes];
		}

		// Initialize the array that contains the scroll factors for individual stripes.
		speedFactors = [[CCArray alloc] initWithCapacity:numStripes];
		[speedFactors addObject:[NSNumber numberWithFloat:0.3f]];
		[speedFactors addObject:[NSNumber numberWithFloat:0.5f]];
		[speedFactors addObject:[NSNumber numberWithFloat:0.5f]];
		[speedFactors addObject:[NSNumber numberWithFloat:0.8f]];
		[speedFactors addObject:[NSNumber numberWithFloat:0.8f]];
		[speedFactors addObject:[NSNumber numberWithFloat:1.2f]];
		[speedFactors addObject:[NSNumber numberWithFloat:1.2f]];
		NSAssert([speedFactors count] == numStripes, @"speedFactors count does not match numStripes!");

		scrollSpeed = 1.0f;
		[self scheduleUpdate];
	}

	return self;
}

-(void) dealloc
{
	[speedFactors release];
	[super dealloc];
}

-(void) update:(ccTime)delta
{
	CCSprite* sprite;
	CCARRAY_FOREACH([spriteBatch children], sprite)
	{
		//CCLOG(@"tag: %i", sprite.tag);
		NSNumber* factor = [speedFactors objectAtIndex:sprite.zOrder];

		CGPoint pos = sprite.position;
		pos.x -= scrollSpeed * [factor floatValue];

		// Reposition stripes when they're out of bounds
		if (pos.x < -screenSize.width)
		{
			pos.x += (screenSize.width * 2) - 2;
		}

		sprite.position = pos;
	}
}

@end


text:
/**
 * Created at 3:13:48 AM Jul 17, 2010
 */
package org.jbox2d.testbed.framework;

import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import org.jbox2d.callbacks.DebugDraw;

/**
 * A TestbedPanel encapsulates the graphical panel displayed to the user. Also it is responsible for
 * populating panel-specific data in the model (like panel width).
 *
 * @author Daniel Murphy
 */
public interface TestbedPanel {

  /**
   * Adds a key listener
   *
   * @param argListener
   */
  public void addKeyListener(KeyListener argListener);

  /**
   * Adds a mouse listener
   *
   * @param argListener
   */
  public void addMouseListener(MouseListener argListener);

  /**
   * Adds a mouse motion listener
   *
   * @param argListener
   */
  public void addMouseMotionListener(MouseMotionListener argListener);

  public void grabFocus();

  /**
   * Gets the display-specific debug draw
   * @return
   */
  public DebugDraw getDebugDraw();

  /**
   * Renders the world
   */
  public void render();

  /**
   * Paints the rendered world to the screen
   */
  public void paintScreen();
}


text:
<?php

/**
 * The "drafts" collection of methods.
 * Typical usage is:
 *  <code>
 *   $gmailService = new Google_Service_Gmail(...);
 *   $drafts = $gmailService->drafts;
 *  </code>
 */
class Google_Service_Gmail_Resource_UsersDrafts extends Google_Service_Resource
{
  /**
   * Creates a new draft with the DRAFT label. (drafts.create)
   *
   * @param string $userId The user's email address. The special value me can be
   * used to indicate the authenticated user.
   * @param Google_Service_Gmail_Draft $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Gmail_Draft
   */
  public function create($userId, Google_Service_Gmail_Draft $postBody, $optParams = array())
  {
    $params = array('userId' => $userId, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('create', array($params), "Google_Service_Gmail_Draft");
  }
  /**
   * Immediately and permanently deletes the specified draft. Does not simply
   * trash it. (drafts.delete)
   *
   * @param string $userId The user's email address. The special value me can be
   * used to indicate the authenticated user.
   * @param string $id The ID of the draft to delete.
   * @param array $optParams Optional parameters.
   */
  public function delete($userId, $id, $optParams = array())
  {
    $params = array('userId' => $userId, 'id' => $id);
    $params = array_merge($params, $optParams);
    return $this->call('delete', array($params));
  }
  /**
   * Gets the specified draft. (drafts.get)
   *
   * @param string $userId The user's email address. The special value me can be
   * used to indicate the authenticated user.
   * @param string $id The ID of the draft to retrieve.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string format The format to return the draft in.
   * @return Google_Service_Gmail_Draft
   */
  public function get($userId, $id, $optParams = array())
  {
    $params = array('userId' => $userId, 'id' => $id);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Gmail_Draft");
  }
  /**
   * Lists the drafts in the user's mailbox. (drafts.listUsersDrafts)
   *
   * @param string $userId The user's email address. The special value me can be
   * used to indicate the authenticated user.
   * @param array $optParams Optional parameters.
   *
   * @opt_param bool includeSpamTrash Include drafts from SPAM and TRASH in the
   * results.
   * @opt_param string maxResults Maximum number of drafts to return.
   * @opt_param string pageToken Page token to retrieve a specific page of results
   * in the list.
   * @return Google_Service_Gmail_ListDraftsResponse
   */
  public function listUsersDrafts($userId, $optParams = array())
  {
    $params = array('userId' => $userId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Gmail_ListDraftsResponse");
  }
  /**
   * Sends the specified, existing draft to the recipients in the To, Cc, and Bcc
   * headers. (drafts.send)
   *
   * @param string $userId The user's email address. The special value me can be
   * used to indicate the authenticated user.
   * @param Google_Service_Gmail_Draft $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Gmail_Message
   */
  public function send($userId, Google_Service_Gmail_Draft $postBody, $optParams = array())
  {
    $params = array('userId' => $userId, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('send', array($params), "Google_Service_Gmail_Message");
  }
  /**
   * Replaces a draft's content. (drafts.update)
   *
   * @param string $userId The user's email address. The special value me can be
   * used to indicate the authenticated user.
   * @param string $id The ID of the draft to update.
   * @param Google_Service_Gmail_Draft $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_Gmail_Draft
   */
  public function update($userId, $id, Google_Service_Gmail_Draft $postBody, $optParams = array())
  {
    $params = array('userId' => $userId, 'id' => $id, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('update', array($params), "Google_Service_Gmail_Draft");
  }
}


text:
import json

from sqlalchemy import BigInteger, Column, Index, Integer, String, Text

from airflow.configuration import conf
from airflow.exceptions import AirflowException
from airflow.models.base import ID_LEN, Base
from airflow.utils import timezone
from airflow.utils.session import provide_session
from airflow.utils.sqlalchemy import UtcDateTime
from airflow.utils.state import State

class SensorInstance(Base):
    """
    SensorInstance support the smart sensor service. It stores the sensor task states
    and context that required for poking include poke context and execution context.
    In sensor_instance table we also save the sensor operator classpath so that inside
    smart sensor there is no need to import the dagbag and create task object for each
    sensor task.

    SensorInstance include another set of columns to support the smart sensor shard on
    large number of sensor instance. The key idea is to generate the hash code from the
    poke context and use it to map to a shorter shard code which can be used as an index.
    Every smart sensor process takes care of tasks whose `shardcode` are in a certain range.

    """

    __tablename__ = "sensor_instance"

    id = Column(Integer, primary_key=True)
    task_id = Column(String(ID_LEN), nullable=False)
    dag_id = Column(String(ID_LEN), nullable=False)
    execution_date = Column(UtcDateTime, nullable=False)
    state = Column(String(20))
    _try_number = Column('try_number', Integer, default=0)
    start_date = Column(UtcDateTime)
    operator = Column(String(1000), nullable=False)
    op_classpath = Column(String(1000), nullable=False)
    hashcode = Column(BigInteger, nullable=False)
    shardcode = Column(Integer, nullable=False)
    poke_context = Column(Text, nullable=False)
    execution_context = Column(Text)
    created_at = Column(UtcDateTime, default=timezone.utcnow(), nullable=False)
    updated_at = Column(UtcDateTime, default=timezone.utcnow(), onupdate=timezone.utcnow(), nullable=False)

    __table_args__ = (
        Index('ti_primary_key', dag_id, task_id, execution_date, unique=True),
        Index('si_hashcode', hashcode),
        Index('si_shardcode', shardcode),
        Index('si_state_shard', state, shardcode),
        Index('si_updated_at', updated_at),
    )

    def __init__(self, ti):
        self.dag_id = ti.dag_id
        self.task_id = ti.task_id
        self.execution_date = ti.execution_date

    @staticmethod
    def get_classpath(obj):
        """
        Get the object dotted class path. Used for getting operator classpath.

        :param obj:
        :type obj:
        :return: The class path of input object
        :rtype: str
        """
        module_name, class_name = obj.__module__, obj.__class__.__name__

        return module_name + "." + class_name

    @classmethod
    @provide_session
    def register(cls, ti, poke_context, execution_context, session=None):
        """
        Register task instance ti for a sensor in sensor_instance table. Persist the
        context used for a sensor and set the sensor_instance table state to sensing.

        :param ti: The task instance for the sensor to be registered.
        :type: ti:
        :param poke_context: Context used for sensor poke function.
        :type poke_context: dict
        :param execution_context: Context used for execute sensor such as timeout
            setting and email configuration.
        :type execution_context: dict
        :param session: SQLAlchemy ORM Session
        :type session: Session
        :return: True if the ti was registered successfully.
        :rtype: Boolean
        """
        if poke_context is None:
            raise AirflowException('poke_context should not be None')

        encoded_poke = json.dumps(poke_context)
        encoded_execution_context = json.dumps(execution_context)

        sensor = (
            session.query(SensorInstance)
            .filter(
                SensorInstance.dag_id == ti.dag_id,
                SensorInstance.task_id == ti.task_id,
                SensorInstance.execution_date == ti.execution_date,
            )
            .with_for_update()
            .first()
        )

        if sensor is None:
            sensor = SensorInstance(ti=ti)

        sensor.operator = ti.operator
        sensor.op_classpath = SensorInstance.get_classpath(ti.task)
        sensor.poke_context = encoded_poke
        sensor.execution_context = encoded_execution_context

        sensor.hashcode = hash(encoded_poke)
        sensor.shardcode = sensor.hashcode % conf.getint('smart_sensor', 'shard_code_upper_limit')
        sensor.try_number = ti.try_number

        sensor.state = State.SENSING
        sensor.start_date = timezone.utcnow()
        session.add(sensor)
        session.commit()

        return True

    @property
    def try_number(self):
        """
        Return the try number that this task number will be when it is actually
        run.
        If the TI is currently running, this will match the column in the
        database, in all other cases this will be incremented.
        """
        # This is designed so that task logs end up in the right file.
        if self.state in State.running:
            return self._try_number
        return self._try_number + 1

    @try_number.setter
    def try_number(self, value):
        self._try_number = value

    def __repr__(self):
        return (
            "<{self.__class__.__name__}: id: {self.id} poke_context: {self.poke_context} "
            "execution_context: {self.execution_context} state: {self.state}>".format(self=self)
        )


text:
'use strict';

const {
  GENESIS_HASH,
  BLOCK_ONE,
  BLOCK_ONE_COINBASE,
  BLOCK_ONE_PRIVKEY,
  BLOCK_ONE_PRIVKEY_BASE58,
  REMOTE_FUNDING_PUBKEY,
  FUNDING_WITNESS_SCRIPT,
  FUNDING_INPUT_TXID,
  FUNDING_INPUT_INDEX,
  FUNDING_INPUT_SATOSHIS,
  FUNDING_INPUT_FUNDING_SATOSHIS,
  FUNDING_INPUT_WITNESS_SCRIPT,
  FUNDING_FEERATE_PER_KW,
  FUNDING_CHANGE_SATOSHIS,
  FUNDING_OUTPUT_INDEX,
  FUNDING_TX,
  FUNDING_TXID,
  LOCAL_FUNDING_PRIVKEY,
  LOCAL_FUNDING_PUBKEY,
  LOCAL_PRIVKEY,
  LOCALPUBKEY,
  LIGHTNING_TEST_HEADER,
  LIGHTNING_BMM_HEADER,
  LIGHTNING_SIDECHAIN_NUM,
  LIGHTNING_SIDEBLOCK_HASH,
  LIGHTNING_PARENT_SIDEBLOCK_HASH,
  REMOTEPUBKEY,
  LOCAL_DELAYEDPUBKEY,
  LOCAL_REVOCATION_PUBKEY
} = require('./fixtures/lightning');

// Testing
const assert = require('assert');
const crypto = require('crypto');

const Fabric = require('../');
const Message = require('../types/message');

const config = require('../settings/test');
const handler = require('../functions/handleException');
const Lightning = {} || require('../services/lightning');
const LightningMessage = require('../types/lightning/message');

describe('@fabric/core/services/lightning', function () {
  describe('Lightning', function () {
    xit('can create an instance', async function provenance () {
      let lightning = new Lightning({
        name: 'Test'
      });

      assert.ok(lightning);
    });

    xit('can create a message', async function provenance () {
      let lightning = new Lightning({
        name: 'Test'
      });

      let entropy = await lightning.machine.sip();
      let message = Message.fromVector(['Cycle', entropy.toString(8)]);
      let next = await lightning.machine.sip();
      let prediction = Message.fromVector(['Cycle', next.toString(8)]);

      assert.ok(lightning);
      assert.ok(message);
      assert.ok(prediction);
    });
  });
});


text:
import {
	getReducerPropertyName,
	injectModuleReducer,
	injectReducer
} from './reducerUtils.js';

import {
	injectModuleSaga,
	injectSaga
} from './sagasUtils.js';

import {
	injectModuleComponent,
	injectNamespaceComponent
} from './componentsUtils.js';

import {
	combineAllModuleComponents,
	getModelComponentList,
	prepareModelWithImports,
  prepareModelWithObjects,
	combineAllModulesComponents
} from './modelUtils.js';

import {
	getModulesImports
} from './sourceCodeUtils.js';

export default {
	getReducerPropertyName,
	injectModuleReducer,
	injectReducer,
	injectModuleSaga,
	injectSaga,
	injectModuleComponent,
	injectNamespaceComponent,
	combineAllModuleComponents,
	getModelComponentList,
	prepareModelWithImports,
  prepareModelWithObjects,
	combineAllModulesComponents,
	getModulesImports,
};


text:
ALTER TABLE bundle_link
  ADD COLUMN slug VARCHAR(128) NULL DEFAULT NULL AFTER id,
  ADD COLUMN is_default BOOLEAN NOT NULL DEFAULT false AFTER slug,
  ADD UNIQUE INDEX slug_index (slug),
  ADD INDEX is_default_index (is_default);

-- +migrate Down

ALTER TABLE bundle_link
  DROP INDEX is_default_index,
  DROP INDEX slug_index,
  DROP COLUMN is_default,
  DROP COLUMN slug;


text:
require "spec_helper"

describe Tr3llo::Command do
  describe ".generate_suggestions" do
    it "generates suggestions" do
      assert_suggestions("", "", %w[board list card label help exit])

      assert_suggestions("b", "b", ["board"])
      assert_suggestions("", "board ", %w[add list select])
      assert_suggestions("se", "board se", ["select"])
      assert_suggestions("l", "board l", ["list"])

      assert_suggestions("l", "l", ["list", "label"])
      assert_suggestions("", "list ", %w[list add cards archive-cards])
      assert_suggestions("a", "list a", ["add", "archive-cards"])
      assert_suggestions("ca", "list ca", ["cards"])
      assert_suggestions("l", "list l", ["list"])

      assert_suggestions("c", "c", ["card"])
      assert_suggestions(
        "",
        "card ",
        %w[
          list show add edit archive list-mine move
          comment comments self-assign assign
          add-checklist edit-checklist remove-checklist
          add-item edit-item remote-item check-item uncheck-item add-label
        ]
      )
      assert_suggestions("l", "card l", ["list", "list-mine"])
      assert_suggestions("a", "card a", %w[add archive assign add-checklist add-item add-label])
      assert_suggestions("e", "card e", %w[edit edit-checklist edit-item])
      assert_suggestions("l", "label l", ["list"])
      assert_suggestions("a", "label a", ["add"])
      assert_suggestions("e", "label e", ["edit"])
      assert_suggestions("r", "label r", ["remove"])
    end

    def assert_suggestions(buffer, line_buffer, expected_suggestions)
      actual_suggestions = described_class.generate_suggestions(buffer, line_buffer)

      expect(actual_suggestions).to eq(expected_suggestions)
    end
  end
end


text:
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<metadata namespace="http://purl.org/dc/elements/1.1/">
  <element name="title" multiple="false" editable="true" searchable="true"/>
  <element name="creator" multiple="false" editable="true"/>
  <element name="subject" multiple="false" editable="true" searchable="true"/>
  <element name="description" multiple="false" editable="true" searchable="true"/>
  <element name="publisher" multiple="false" editable="true"/>
  <element name="contributor" multiple="false" editable="true"/>
  <element name="date" multiple="false" editable="true"/>
  <element name="type" multiple="false" editable="true"/>
  <element name="format" multiple="false" editable="true"/>
  <element name="identifier" multiple="false" editable="true"/>
  <element name="source" multiple="false" editable="true"/>
  <element name="language" multiple="false" editable="true"/>
  <element name="relation" multiple="false" editable="true"/>
  <element name="coverage" multiple="false" editable="true"/>
  <element name="rights" multiple="false" editable="true"/>
</metadata>


text:
'use strict';

angular.module('palaso.ui.archiveProject', ['bellows.services'])
  .directive('puiArchiveProject', [function () {
    return {
      restrict: 'E',
      templateUrl: '/angular-app/bellows/directive/' + bootstrapVersion + '/pui-archive-project.html',
      scope: {
        puiActionInProgress: '='
      },
      controller: ['$scope', 'projectService', 'sessionService',
        'silNoticeService', 'modalService', '$window',
        function ($scope, projectService, ss, notice, modalService, $window) {

          // Archive the project
          $scope.archiveProject = function () {
            var message = 'Are you sure you want to archive this project?';
            var modalOptions = {
              closeButtonText: 'Cancel',
              actionButtonText: 'Archive',
              headerText: 'Archive Project?',
              bodyText: message
            };
            modalService.showModal({}, modalOptions).then(function () {
              $scope.puiActionInProgress = true;
              projectService.archiveProject(function (result) {
                if (result.ok) {
                  notice.push(notice.SUCCESS, 'The project was archived successfully');
                  $window.location.href = '/app/projects';
                } else {
                  $scope.puiActionInProgress = false;
                }
              });
            });
          };
        }]
    };
  }])

;


text:
import logging
from obj_sys.obj_tools import is_web_url, is_ufs_url

log = logging.getLogger(__name__)

class TastypieItem(object):
    def __init__(self, tastypie_item_dict):
        super(TastypieItem, self).__init__()
        self.item = tastypie_item_dict

    def is_valid_url(self):
        url = self.get_url()
        log.debug(url)
        if url == "":
            return False
        if is_web_url(url):
            return True
        if is_ufs_url(url):
            return True
        return False

    def get_description(self):
        descriptions = self.item["descriptions"]
        if len(descriptions) > 0:
            description = descriptions[0]
        else:
            description = ""
        return description

    def get_description_content(self):
        description = self.get_description()
        result = ""
        if "content" in description:
            result = description["content"]
        return result

    def get_url(self):
        url = self.item["ufs_url"]
        return url

    def get_tag_str(self):
        tags = self.item["tags"]

        if len(tags) > 0:
            tags_str = u",".join(tags)
        else:
            tags_str = ""
        return tags_str