text:
package io.druid.server;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.metamx.emitter.service.ServiceEmitter;
import io.druid.client.CachingClusteredClient;
import io.druid.query.FluentQueryRunnerBuilder;
import io.druid.query.PostProcessingOperator;
import io.druid.query.Query;
import io.druid.query.QueryRunner;
import io.druid.query.QuerySegmentWalker;
import io.druid.query.QueryToolChest;
import io.druid.query.QueryToolChestWarehouse;
import io.druid.query.RetryQueryRunner;
import io.druid.query.RetryQueryRunnerConfig;
import io.druid.query.SegmentDescriptor;
import org.joda.time.Interval;

/**
 */
public class ClientQuerySegmentWalker implements QuerySegmentWalker
{
  private final ServiceEmitter emitter;
  private final CachingClusteredClient baseClient;
  private final QueryToolChestWarehouse warehouse;
  private final RetryQueryRunnerConfig retryConfig;
  private final ObjectMapper objectMapper;

  @Inject
  public ClientQuerySegmentWalker(
      ServiceEmitter emitter,
      CachingClusteredClient baseClient,
      QueryToolChestWarehouse warehouse,
      RetryQueryRunnerConfig retryConfig,
      ObjectMapper objectMapper
  )
  {
    this.emitter = emitter;
    this.baseClient = baseClient;
    this.warehouse = warehouse;
    this.retryConfig = retryConfig;
    this.objectMapper = objectMapper;
  }

  @Override
  public <T> QueryRunner<T> getQueryRunnerForIntervals(Query<T> query, Iterable<Interval> intervals)
  {
    return makeRunner(query);
  }

  @Override
  public <T> QueryRunner<T> getQueryRunnerForSegments(Query<T> query, Iterable<SegmentDescriptor> specs)
  {
    return makeRunner(query);
  }

  private <T> QueryRunner<T> makeRunner(Query<T> query)
  {
    QueryToolChest<T, Query<T>> toolChest = warehouse.getToolChest(query);
    PostProcessingOperator<T> postProcessing = objectMapper.convertValue(
        query.<String>getContextValue("postProcessing"),
        new TypeReference<PostProcessingOperator<T>>()
        {
        }
    );

    return new FluentQueryRunnerBuilder<>(toolChest)
        .create(
            new RetryQueryRunner<>(
                baseClient,
                toolChest,
                retryConfig,
                objectMapper
            )
        )
        .applyPreMergeDecoration()
        .mergeResults()
        .applyPostMergeDecoration()
        .emitCPUTimeMetric(emitter)
        .postProcess(postProcessing);
  }

}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

//
// Scenario8.xaml.cpp
// Implementation of the Scenario8 class
//

#include "pch.h"
#include "Scenario8_Receipt.xaml.h"

using namespace SDKTemplate;

using namespace Concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Store;
using namespace Windows::UI::Xaml::Navigation;

Scenario8_Receipt::Scenario8_Receipt()
{
    InitializeComponent();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.  The Parameter
/// property is typically used to configure the page.</param>
void Scenario8_Receipt::OnNavigatedTo(NavigationEventArgs^ e)
{
    ConfigureSimulatorAsync("receipt.xml");
}

void Scenario8_Receipt::ShowReceipt()
{
    create_task(CurrentAppSimulator::GetAppReceiptAsync()).then([this](task<String^> currentTask)
    {
        try
        {
            String^ receipt = currentTask.get();
            Output->Text = receipt;
        }
        catch (Exception^ exception)
        {
            rootPage->NotifyUser("Get Receipt failed.", NotifyType::ErrorMessage);
        }
    });
}

redpajama_set_name: RedPajamaGithub


text:
Lightweight implementation of producer consumer paradigm in C#.

This library relies heavily on threads. TPL should be avoided when using this library, even at the cost of synchronously waiting tasks when no synchronous API is available.

Further details [here][justification], but the general idea is that the purpose of this library is avoiding to use the Managed Thread Pool. This is epescially useful in the context of Web API.

Every worker instance uses it's own thread, therefore use with caution at your own risk.

## Installing

To install, you can use the related nuget package.
```powershell
Install-Package BreadWinner
```

## Wiki
For further details, please refer to the [Wiki][home]. Some usages can be found in the projects in the samples folder of the repo.

[home]: https://github.com/gugu91/bread-winner/wiki
[justification]: https://github.com/gugu91/bread-winner/wiki#justification


text:
That's mostly written in {{project.data.language}}.*

    {{{languageBreakdown languages}}}

* = exactly {{ getLanguagePercent languages project.data.language }}%


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace Aardvark.Base
{
    public static class HardwareThread
    {
        private static Dictionary<int, ProcessThread> s_pts = new Dictionary<int, ProcessThread>();
        private static SpinLock s_ptsLock = new SpinLock();

        public static ProcessThread GetProcessThread(int tid)
        {
            ProcessThread result = null;

            bool lockTaken = false;
            try
            {
                s_ptsLock.Enter(ref lockTaken);
                if (s_pts.TryGetValue(tid, out result)) return result;
            }
            finally
            {
                if (lockTaken) s_ptsLock.Exit();
            }

            foreach (ProcessThread t in Process.GetCurrentProcess().Threads)
            {
                if (t.Id == tid)
                {
                    lockTaken = false;
                    try
                    {
                        s_ptsLock.Enter(ref lockTaken);
                        s_pts[tid] = t;
                    }
                    finally
                    {
                        if (lockTaken) s_ptsLock.Exit();
                    }
                    return t;
                }
            }

            return null;
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Lit - Popagandhi</title>
<meta name="description" content="Between long form cycling and tech">
<link rel="stylesheet" href="Cormorant:400,400i,600,600i|Poppins:400,500,600,700&subset=latin-ext">
<link rel="stylesheet" href="/css/main.css">
<link rel="canonical" href="http://localhost:4000/category/Lit/">
<link rel="alternate" type="application/rss+xml" title="Popagandhi" href="http://localhost:4000/feed.xml" />

Home

About

Lit

Videos Games & Political Consciousness

I wrote this piece some time ago about video games for Memory Insufficient, a games history ezine. This is it.

                            Adrianna tan in Lit

The Geography of Hope

At 18 I certainly believed I knew everything. I did not know just how much it'd hurt this boy's heart if I told him the inevitable: that I was in love with...

                            Adrianna tan in India

Before & After The Fire

                            A "poem" about my family during the Great Fire of 1961.

                            Adrianna tan in Lit

                Adrianna Tan

Hi, I am a startup founder in Southeast Asia. I specialise in emerging markets and mobile technologies. I co-founded Wobe, a fintech startup in Indonesia, and Gyanada Foundation, a non-profit that works to impact lives through education and code.

                    Indonesia / Singapore / India

                        Email

                        Twitter

                        Facebook

                        Instagram

                        Github

                        LinkedIn

Made with love by folks at 69signals.

							About

							Contact

    	<form method="get" action="https://www.google.com/search">
			<input type="search" name="q" size="25" maxlength="255" placeholder="Search.." value="" />
		</form>

Begin typing your search above and press return to search. Press Esc to cancel.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
using System.Threading.Tasks;
using RfxCom.Events;
using RfxCom.Messages;
using RfxCom.Messages.Handlers;

namespace RfxCom
{

    public class Transceiver : ITransceiver
    {
        private Transceiver()
        {
            ByteCounter = new ByteCounter(0);
        }

        public Transceiver(ICommunicationInterface communicationInterface, ILogger logger) : this(communicationInterface, logger, new ReceiveHandlerFactory())
        {
            CommunicationInterface = communicationInterface;
            Logger = logger;
        }

        public Transceiver(ICommunicationInterface communicationInterface, ILogger logger, IReceiveHandlerFactory handlerFactory) : this()
        {
            CommunicationInterface = communicationInterface;
            Logger = logger;
            HandlerFactory = handlerFactory;
        }

        protected ByteCounter ByteCounter { get; set; }
        protected IReceiveHandlerFactory HandlerFactory { get; set; }
        protected ILogger Logger { get; private set; }
        protected ICommunicationInterface CommunicationInterface { get; private set; }

        public IConnectableObservable<Event> Receive()
        {
            return Observable.Create<Event>(async (subject, cancellationToken) =>
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        var bytes = await CommunicationInterface.ReadAsync(cancellationToken);
                        var handler = HandlerFactory.Create();
                        var context = new ReceiveContext(subject, bytes);
                        handler.Handle(context);
                    }
                    catch (Exception exception)
                    {
                        subject.OnNext(new ErrorEvent(exception));
                    }
                }
            })
            .Publish();
        }

        public async Task Send(Message message)
        {
            const int sequenceNumberIndex = 3;

            var buffer = message.ToBytes().ToArray();
            buffer[sequenceNumberIndex] = ByteCounter.Next();

            await CommunicationInterface.WriteAsync(buffer);

            Logger.Info("Message Sent ({0}) - {1}", message.GetType().Name, message);
        }

        public async Task Reset()
        {
            ByteCounter.Reset();
            var message = new InterfaceControlMessage(InterfaceControlCommand.Reset);
            await Send(message);
            await Task.Delay(TimeSpan.FromSeconds(2));
        }

        public Task Flush()
        {
            return CommunicationInterface.FlushAsync();
        }

        public async Task Initialize()
        {
            await Reset();
            await Flush();
            await this.GetStatus();
        }

    }
}


text:
from __future__ import unicode_literals
from wikiciteparser.parser import parse_citation_template
from urllib import urlencode
try:
    import urlparse
except ImportError:
    from urllib.parse import urlparse
import mwparserfromhell
import requests
import json
import codecs
import sys
import urllib
from unidecode import unidecode
import re
from datetime import datetime
from copy import deepcopy
import os
from arguments import template_arg_mappings, get_value
from ranking import sort_links, is_blacklisted
from settings import *
from ondiskcache import OnDiskCache
from classifier import AcademicPaperFilter
import md5
from time import sleep
from Levenshtein import ratio

urls_cache = OnDiskCache('urls_cache.pkl')
paper_filter = AcademicPaperFilter()

class TemplateEdit(object):
    """
    This represents a proposed change (possibly empty)
    on a citation template
    """
    def __init__(self, tpl, page):
        """
        :param tpl: a mwparserfromhell template: the original template
                that we want to change
        """
        self.template = tpl
        self.orig_string = unicode(self.template)
        r = md5.md5()
        r.update(self.orig_string.encode('utf-8'))
        self.orig_hash = r.hexdigest()
        self.classification = None
        self.conflicting_value = ''
        self.proposed_change = ''
        self.proposed_link = None
        self.index = None
        self.page = page
        self.proposed_link_policy = None
        self.issn = None

    def json(self):
        return {
            'orig_string': self.orig_string,
            'orig_hash': self.orig_hash,
            'classification': self.classification,
            'conflicting_value': self.conflicting_value,
            'proposed_change': self.proposed_change,
            'proposed_link': self.proposed_link,
            'index': self.index,
            'policy': self.proposed_link_policy,
            'issn': self.issn,
        }

    def propose_change(self, only_doi=False):
        """
        Fetches open urls for that template and proposes a change
        """
        reference = parse_citation_template(self.template)
        tpl_name = unicode(self.template.name).lower().strip()
        if not reference or tpl_name in excluded_templates:
            self.classification = 'ignored'
            return

        sys.stdout.write('.')
        sys.stdout.flush()

        # First check if there is already a link to a full text
        # in the citation.
        already_oa_param = None
        already_oa_value = None
        for argmap in template_arg_mappings:
            if argmap.present_and_free(self.template):
                already_oa_param = argmap.name
                already_oa_value = argmap.get(self.template)

        change = {}

        # If so, we just skip it - no need for more free links
        if already_oa_param:
            self.classification = 'already_open'
            self.conflicting_value = already_oa_value
            return

        # --- Disabled for now ----
        # If the template is marked with |registration= or
        # |subscription= , let's assume that the editor tried to find
        # a better version themselves so it's not worth trying.
        if ((get_value(self.template, 'subscription')
            or get_value(self.template, 'registration')) in
            ['yes','y','true']):
            self.classification = 'registration_subscription'
            # return

        if only_doi:
            dissemin_paper_object = {}
        else:
            dissemin_paper_object = get_dissemin_paper(reference)

        # Otherwise, try to get a free link
        doi = reference.get('ID_list', {}).get('DOI')
        link = get_oa_link(paper=dissemin_paper_object, doi=doi, only_unpaywall=only_doi)
        if link is False:
            self.classification = 'already_open'
            if doi:
                self.proposed_change = "doi-access=free"
                self.proposed_link = "https://doi.org/{}".format(doi)
                return
            # TODO add the DOI suggested by Dissemin if missing. Needs some checks.
            # elif dissemin_paper_object.get('pdf_url') and 'doi.org' in dissemin_paper_object.get('pdf_url'):
            #    self.proposed_change = dissemin_paper_object.get('pdf_url')
            #    return
            else:
                return
        if not link:
            self.classification = 'not_found'
            return

        # We found an OA link!
        self.proposed_link = link
        # If the parameter is not present yet, add it
        self.classification = 'link_added'

        if dissemin_paper_object:
            self.proposed_link_policy = get_paper_values(dissemin_paper_object, 'policy')
            # TODO: fetch from Unpaywall?
            self.issn = get_paper_values(dissemin_paper_object, 'issn')

        # Try to match it with an argument
        argument_found = False
        for argmap in template_arg_mappings:
            # Did the link we have got match that argument place?
            match = argmap.extract(link)
            if not match:
                continue

            argument_found = True

            # If this parameter is already present in the template:
            current_value = argmap.get(self.template)
            if current_value:
                change['new_'+argmap.name] = (match,link)

                #if argmap.custom_access:
                #    stats['changed'] += 1
                #    template.add(argmap.custom_access, 'free')
                #else:

                self.classification = 'already_present'
                if argmap.name == 'hdl':
                    self.proposed_change = "hdl-access=free"
                # don't change anything else
                return

            if argmap.is_id:
                self.proposed_change = 'id={{%s|%s}}' % (argmap.name,match)
            else:
                self.proposed_change = '%s=%s' % (argmap.name,match)
                if argmap.name == 'hdl':
                    self.proposed_change += "|hdl-access=free"
            break

        # If we are going to add an URL, check it's not probably redundant
        if self.proposed_change.startswith('url='):
            hdl = get_value(self.template, 'hdl')
            if hdl and hdl in self.proposed_change:
                # Don't actually add the URL but mark the hdl as seemingly OA
                # and hope that the templates will later linkify it
                self.proposed_change = "hdl-access=free"

    def update_template(self, change):
        """
        Given a change of the form "param=value", add it to the template
        """
        bits = re.split('=', change, maxsplit=1)
        if len(bits) != 2:
            raise ValueError('invalid change')
        param = bits[0].lower().strip()
        value = bits[1].strip()

        # Escape various characters in Wikicode
        value = value.replace(' ', '%20')
        value = value.replace('|', '{{!}}')
        self.template.add(param, value)

def remove_diacritics(s):
    return unidecode(s) if type(s) == unicode else s

def get_dissemin_paper(reference):
    """
    Given a citation template (as parsed by wikiciteparser and a proposed link)
    get dissemin API information for that link
    """
    doi = reference.get('ID_list', {}).get('DOI')
    title = reference.get('Title', '')
    authors = reference.get('Authors', [])
    date = reference.get('Date', '')

    # CS1 represents unparsed authors as {'last':'First Last'}
    for i in range(len(authors)):
        if 'first' not in authors[i]:
            authors[i] = {'plain':authors[i].get('last','')}

    args = {
        'title':title,
        'authors':authors,
        'date':date,
        'doi':doi,
        }

    for retry in range(5):
        try:
            req = requests.post('https://dissem.in/api/query/',
                                json=args,
                                headers={'User-Agent':OABOT_USER_AGENT},
                                timeout=10)

            resp = req.json()
            paper_object = resp.get('paper', {})
            if not paper_object:
                return {}

            paper_year = paper_object.get("date", "")[:4]
            paper_authorlast = paper_object.get("authors")[0].get("name", {}).get("last", "")
            if date[:4] == paper_year and ratio(authors[0].get("last", ""), paper_authorlast) > 0.75:
                return paper_object
            else:
                # Fails a basic author/date check, ignore Dissemin record
                return {}
        except (ValueError, requests.exceptions.RequestException) as e:
            sleep(5)
            continue
        except IndexError:
            # The author names are not what expected, give up on a record match
            # TODO: could probably try harder
            return {}
    return {}

def get_paper_values(paper, attribute):

    for record in paper.get('records',[]):
        if record.get(attribute):
            return record.get(attribute)

    return None

def get_oa_link(paper, doi=None, only_unpaywall=True):

    if paper and not doi:
        doi = paper.get('doi')
        if doi is not None:
            doi = "/".join(doi.split("/")[-2:])

    dissemin_dois = set([ record.get('doi') for record in
                         paper.get('records',[]) if record.get('doi')  ])
    if len(dissemin_dois) > 2:
        # Do not use Dissemin suggestions: many DOIs suggest a risk of overmerged
        # records. https://github.com/dissemin/dissemin/issues/512
        candidate_urls = []
    else:
        # Get all the URLs which Dissemin considers to be full-text links
        candidate_urls = ([
            record.get('pdf_url') for record in
            paper.get('records',[])  if record.get('pdf_url')
        ])

    # Then, try OAdoi/Unpaywall
    # (It finds full texts that Dissemin does not, so it's always good to have!)
    if doi:
        resp = None
        attempts = 0
        while resp is None:
            email = '{}@{}.in'.format('contact', 'dissem')
            try:
                req = requests.get('http://api.unpaywall.org/v2/:{}'.format(doi), params={'email':email}, timeout=10)
                resp = req.json()
                sleep(0.15)
            except ValueError:
                sleep(10)
                attempts += 1
                if attempts >= 3:
                    break
                else:
                    continue

        boa = resp.get('best_oa_location', None)
        if only_unpaywall:
            # Just give up when Unpaywall doesn't know an OA location.
            if not resp['is_oa']:
                return None
        # If we have Unpaywall data, use it and prefer identifiers.
        if boa:
            if boa['host_type'] == 'publisher':
                # If we're coming from the DOI rather add doi-access=free
                # Avoid getting publisher URLs from Unpaywall or Dissemin
                return False
            if 'citeseerx.ist.psu.edu' in resp['best_oa_location']['url_for_landing_page']:
                # Use the CiteSeerX URL which gets converted to the parameter
                return resp['best_oa_location']['url_for_landing_page']
            else:
                if 'hdl.handle.net' in boa['url_for_landing_page']:
                    url = boa['url_for_landing_page']
                else:
                    url = boa['url']
                if not is_blacklisted(url):
                    return url

        for oa_location in resp.get('oa_locations') or []:
            if oa_location.get('url') and oa_location.get('host_type') != 'publisher':
                candidate_urls.append(oa_location['url'])

    # TODO If Dissemin considers this gold OA, it only needs a doi-access=free
    #if paper.get('classification', 'UNK') == 'OA':
    #    return False

    # Full text detection is not always accurate, so we try to pick
    # the URL which is most useful for citation templates and we
    # doule check that it's still up.
    for url in sort_links(candidate_urls):
        if url:
            try:
                head = requests.head(url, timeout=10)
                head.raise_for_status()
                if head.status_code < 400 and 'Location' in head.headers and urlparse.urlparse(head.headers['Location']).path == '/':
                    # Redirects to main page: fake status code, should be not found
                    continue
                if not is_blacklisted(url):
                    return url
            except requests.exceptions.RequestException:
                continue

def add_oa_links_in_references(text, page, only_doi=False):
    """
    Main function of the bot.

    :param text: the wikicode of the page to edit
    :returns: a tuple: the new wikicode, the list of changed templates,
            and edit statistics
    """
    wikicode = mwparserfromhell.parse(text)

    for index, template in enumerate(wikicode.filter_templates()):
        edit = TemplateEdit(template, page)
        edit.index = index
        edit.propose_change(only_doi)
        yield edit

def get_page_over_api(page_name):
    r = requests.get('https://en.wikipedia.org/w/api.php', params={
        'action':'query',
        'titles':page_name,
        'prop':'revisions',
        'rvprop':'content',
        'format':'json',},
        headers={'User-Agent':OABOT_USER_AGENT},
        timeout=10)
    r.raise_for_status()
    js = r.json()
    page = js.get('query',{}).get('pages',{}).values()[0]
    pagid = page.get('pageid', -1)
    if pagid == -1:
        raise ValueError("Invalid page.")
    text = page.get('revisions',[{}])[0]['*']
    return text

def bot_is_allowed(text, user):
    """
    Taken from https://en.wikipedia.org/wiki/Template:Bots
    For bot exclusion compliance.
    """
    user = user.lower().strip()
    text = mwparserfromhell.parse(text)
    for tl in text.filter_templates():
        if tl.name in ('bots', 'nobots'):
            break
    else:
        return True
    for param in tl.params:
        bots = [x.lower().strip() for x in param.value.split(",")]
        if param.name == 'allow':
            if ''.join(bots) == 'none': return False
            for bot in bots:
                if bot in (user, 'all'):
                    return True
        elif param.name == 'deny':
            if ''.join(bots) == 'none': return True
            for bot in bots:
                if bot in (user, 'all'):
                    return False
    return True


text:
package com.orionplatform.machine_learning.hypothesis.error;

import com.orionplatform.core.abstraction.Orion;

public abstract class ExpectedErrorMinimisationAlgorithm extends Orion
{

}


text:
// Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license

//! Interaction potentials for energy and forces computations
//!
//! # Potentials
//!
//! In classical simulations, the total energy of a system is separated as a
//! sum containing terms from the non-bonded pairs, the bonds, the angles, the
//! dihedral angles in the system; and the electrostatic interactions.
//!
//! Potentials are used to compute the interaction energy in a system. They are
//! represented by a [`Potential`][Potential] trait, used to compute the force
//! and the energy of interaction. In order to add a new potential to lumol,
//! one has to implement the Potential trait, and then indicate how the
//! potential can be used. This is done by implementing one or more of the
//! potentials marker traits:
//!
//! - [`PairPotential`][PairPotential] for non-bonded two body interactions;
//! - [`BondPotential`][BondPotential] for covalent bonds interactions;
//! - [`AnglePotential`][AnglePotential] for covalent angles interactions;
//! - [`DihedralPotential`][DihedralPotential] for covalent dihedral angles
//!   interactions.
//!
//! ```
//! use lumol_core::energy::{Potential, PairPotential, DihedralPotential};
//!
//! #[derive(Clone)]
//! struct OnePotential;
//!
//! // OnePotential is a potential
//! impl Potential for OnePotential {
//!     fn energy(&self, _: f64) -> f64 {1.0}
//!     fn force(&self, _: f64) -> f64 {0.0}
//! }
//!
//! // It can be used for pair and dihedral potentials, but not for angles or
//! // bonds.
//! impl PairPotential for OnePotential {
//!     /* some code omitted */
//!     # fn tail_energy(&self, cutoff: f64) -> f64 {0.0}
//!     # fn tail_virial(&self, cutoff: f64) -> f64 {0.0}
//! }
//! impl DihedralPotential for OnePotential {}
//! ```
//!
//! # Global and Coulombic potentials
//!
//! Global potentials are potentials that have an effect on the whole system at
//! once. They are defined by implementing the [`GlobalPotential`]
//! [GlobalPotential] trait. [`CoulombicPotential`][CoulombicPotential] are a
//! specific version of global potentials used to compute electrostatic
//! interactions.
//!
//! [Potential]: trait.Potential.html
//! [PairPotential]: trait.PairPotential.html
//! [BondPotential]: trait.BondPotential.html
//! [AnglePotential]: trait.AnglePotential.html
//! [DihedralPotential]: trait.DihedralPotential.html
//! [GlobalPotential]: trait.GlobalPotential.html
//! [CoulombicPotential]: trait.CoulombicPotential.html
use crate::{Matrix3, Vector3D};

/// A potential for force and energy computations.
///
/// A potential is defined with two functions that takes a single scalar
/// variable and return the corresponding energy or norm of the force. The
/// scalar variable will be the distance for pair potentials, the angle for
/// angles or dihedral angles potentials, *etc.*
///
/// # Example
///
/// ```
/// # use std::f64;
/// use lumol_core::energy::Potential;
///
/// /// An hard sphere potential
/// #[derive(Clone)]
/// struct HardSphere {
///     /// Sphere radius
///     pub r: f64
/// }
///
/// impl Potential for HardSphere {
///     fn energy(&self, x: f64) -> f64 {
///         if x < self.r {
///             f64::INFINITY
///         } else {
///             0.0
///         }
///     }
///
///     fn force(&self, x: f64) -> f64 {
///         0.0
///     }
/// }
/// ```
pub trait Potential: Sync + Send {
    /// Get the energy corresponding to the variable `x`
    fn energy(&self, x: f64) -> f64;
    /// Get the force norm corresponding to the variable `x`
    fn force(&self, x: f64) -> f64;
}

/// Marker trait for potentials that can be used for non-bonded two body
/// interactions.
///
/// # Example
///
/// ```
/// use lumol_core::energy::{Potential, PairPotential};
///
/// // A no-op potential
/// #[derive(Clone)]
/// struct Null;
///
/// impl Potential for Null {
///     fn energy(&self, x: f64) -> f64 {0.0}
///     fn force(&self, x: f64) -> f64 {0.0}
/// }
///
/// // By implementing this trait, we can use the Null potential for pair
/// // interactions
/// impl PairPotential for Null {
///     fn tail_energy(&self, cutoff: f64) -> f64 {
///         return 0.0;
///     }
///
///     fn tail_virial(&self, cutoff: f64) -> f64 {
///         return 0.0;
///     }
/// }
/// ```
pub trait PairPotential: Potential + BoxClonePair {
    /// Compute the virial contribution corresponding to the distance `r`
    /// between the particles.
    fn virial(&self, r: &Vector3D) -> Matrix3 {
        let fact = self.force(r.norm());
        let rn = r.normalized();
        let force = fact * rn;
        force.tensorial(r)
    }

    /// Compute the tail correction to the energy for the given cutoff.
    ///
    /// Calling `V(r)` the `Potential::energy(r)` function corresponding to this
    /// potential, this function should return the integral from `cutoff` to
    /// infinity of `r^2 V(r)`: `\int_{cutoff}^\infty r^2 V(r) dr`.
    ///
    /// If this integral does not converge for the current potential, this
    /// function should then return 0 to disable tail corrections.
    fn tail_energy(&self, cutoff: f64) -> f64;

    /// Compute the tail correction to the virial for the given cutoff.
    ///
    /// Calling `f(r)` the `Potential::force(r)` function corresponding to this
    /// potential, this function should return the integral from `cutoff` to
    /// infinity of `f(r) r^3`: `\int_{cutoff}^\infty r^3 f(r) dr`.
    ///
    /// If this integral does not converge for the current potential, this
    /// function should then return 0.0 to disable tail corrections.
    fn tail_virial(&self, cutoff: f64) -> f64;
}
impl_box_clone!(PairPotential, BoxClonePair, box_clone_pair);

/// Marker trait for potentials that can be used for molecular bonds.
///
/// # Example
///
/// ```
/// use lumol_core::energy::{Potential, BondPotential};
///
/// // A no-op potential
/// #[derive(Clone)]
/// struct Null;
///
/// impl Potential for Null {
///     fn energy(&self, x: f64) -> f64 {0.0}
///     fn force(&self, x: f64) -> f64 {0.0}
/// }
///
/// // Now we can use the Null potential for bonds
/// impl BondPotential for Null {}
/// ```
pub trait BondPotential: Potential + BoxCloneBond {
    /// Compute the virial contribution corresponding to the distance `r`
    /// between the particles.
    fn virial(&self, r: &Vector3D) -> Matrix3 {
        let fact = self.force(r.norm());
        let rn = r.normalized();
        let force = fact * rn;
        force.tensorial(r)
    }
}
impl_box_clone!(BondPotential, BoxCloneBond, box_clone_bond);

/// Marker trait for potentials that can be used for molecular angles.
///
/// # Example
///
/// ```
/// use lumol_core::energy::{Potential, AnglePotential};
///
/// // A no-op potential
/// #[derive(Clone)]
/// struct Null;
///
/// impl Potential for Null {
///     fn energy(&self, x: f64) -> f64 {0.0}
///     fn force(&self, x: f64) -> f64 {0.0}
/// }
///
/// // Now we can use the Null potential for angles
/// impl AnglePotential for Null {}
/// ```
pub trait AnglePotential: Potential + BoxCloneAngle {}
impl_box_clone!(AnglePotential, BoxCloneAngle, box_clone_angle);

/// Marker trait for potentials that can be used for molecular dihedral angles.
///
/// # Example
///
/// ```
/// use lumol_core::energy::{Potential, DihedralPotential};
///
/// // A no-op potential
/// #[derive(Clone)]
/// struct Null;
///
/// impl Potential for Null {
///     fn energy(&self, x: f64) -> f64 {0.0}
///     fn force(&self, x: f64) -> f64 {0.0}
/// }
///
/// // Now we can use the Null potential for dihedral angles
/// impl DihedralPotential for Null {}
/// ```
pub trait DihedralPotential: Potential + BoxCloneDihedral {}
impl_box_clone!(DihedralPotential, BoxCloneDihedral, box_clone_dihedral);

mod functions;
pub use self::functions::{BornMayerHuggins, Buckingham, Gaussian, Morse, Torsion};
pub use self::functions::{CosineHarmonic, Harmonic, LennardJones, NullPotential};
pub use self::functions::Mie;

mod computations;
pub use self::computations::{Computation, TableComputation};

mod restrictions;
pub use self::restrictions::{PairRestriction, RestrictionInfo, BondPath};

mod global;
pub use self::global::{CoulombicPotential, GlobalCache, GlobalPotential};
pub use self::global::{Ewald, SharedEwald, Wolf};

mod pairs;
pub use self::pairs::PairInteraction;


text:
$LOAD_PATH.unshift File.dirname(__FILE__)
require "rdoc-view/version"

require "net/https"
require "uri"
require "optparse"
require "rdoc"
require "rdoc/markup/to_html"

require "sinatra/base"
require "sinatra-websocket"
require "listen"
require "RedCloth"

module RDocView
  def convert(file, type)
    html = ""
    text = open(file){|f|f.read}
    case type
    when "md", "markdown"
      uri = URI.parse("https://api.github.com/markdown/raw")
      https = Net::HTTP.new(uri.host, uri.port)
      https.use_ssl = true
      https.verify_mode = OpenSSL::SSL::VERIFY_NONE
      #https.set_debug_output $stderr
      https.start do | access |
        resp = access.post(uri.path, text, {"content-type" => "text/plain"})
        html = resp.body
      end
    when "textile"
      html = RedCloth.new(text).to_html
    else
      h = RDoc::Markup::ToHtml.new
      html = h.convert(text)
    end
    return html
  end
  module_function :convert

  class ViewApp < Sinatra::Base

    opt_html = false
    opt_type = nil
    OptionParser.new { |op |
      op.version = VERSION
      op.on('-p port',   'set the port (default is 4567)')           { |val| set :port, Integer(val) }
      op.on('-o addr',   'set the host (default is 0.0.0.0)')        { |val| set :bind, val }
      op.on('-t type',   'set the document type (rdoc,textile,md or markdown)',
                         'if omits, judging from the extension')     { |val| opt_type = val.downcase }
      op.on('-h', '--html', 'convert to html.')                      { |val| opt_html = true }
    }.parse!(ARGV)
    set :environment, :production

    raise "ARGV is empty." if ARGV.empty?
    raise "File Not Found:#{ARGV[0]}" unless File.exists?(ARGV[0])

    set :target_file, File.expand_path(ARGV[0])
    set :server, "thin"
    set :sockets, []

    support_extensions = ["rdoc", "md", "markdown", "textile"]
    set :type, opt_type
    set :type, File.extname(ARGV[0]).downcase().slice(1..-1) unless support_extensions.include?(opt_type)

    # HTMLに変換して終了する
    if opt_html then
      html = RDocView.convert(settings.target_file, settings.type)
      html.force_encoding("utf-8")
      tmpl_file = File.expand_path(File.dirname(__FILE__) + "/views/index-html.erb")
      tmpl = ERB.new(open(tmpl_file){|f|f.read})
      puts tmpl.result(binding)
      exit
    end

    send_func = Proc.new do | ws |
      if File.exists?(settings.target_file) then
        # convert to html
        html = RDocView.convert(settings.target_file, settings.type)
        html.force_encoding("utf-8")

        EM.next_tick do
          if ws then
            ws.send(html)
          else
            settings.sockets.each do |s|
              s.send(html)
            end
          end
        end
      end
    end

    # ファイル監視
    callback = Proc.new do |modified, added, removed|
      if modified.include?(settings.target_file) || added.include?(settings.target_file) then
        send_func.call()
      end
    end
    listener = Listen.to(File.dirname(settings.target_file), :relative_paths => false)
      .change(&callback)
      .start

    # 簡易的なTimer。定期的にPingを飛ばす。
    th_timer = Thread.new() do
      while true
        EM.next_tick do
          settings.sockets.each do |s|
            s.ping()
          end
        end
        sleep 5
      end
    end

    error 500 do
      "Error: Internal Server Error."
    end

    get "/" do
      erb :index
    end

    get "/rdoc" do
      if request.websocket? then
        request.websocket do | ws |
          ws.onopen do
            settings.sockets << ws
            send_func.call(ws)
          end
          ws.onmessage do | msg |
          end
          ws.onclose do
            settings.sockets.delete(ws)
          end
          ws.onerror do
          end
          ws.onping do
          end
          ws.onpong do
          end
        end
      else
        500
      end
    end
  end
  ViewApp.run!
end


text:
; +-------------------------------------------+
; | Program ...... FASMCam                    |
; | Author ....... Marcus Araujo              |
; | Description .. this application shows how |
; |                to access webcam via FASM. |
; +-------------------------------------------+

format PE GUI 4.0
entry codestart

include 'win32a.inc'

  IDD_MAIN                     =  100
  WM_CAP_DRIVER_CONNECT        =  WM_USER + 10
  WM_CAP_DRIVER_DISCONNECT     =  WM_USER + 11
  WM_CAP_FILE_SAVEDIB          =  WM_USER + 25
  WM_CAP_SET_PREVIEW           =  WM_USER + 50
  WM_CAP_SET_PREVIEWRATE       =  WM_USER + 52
  WM_CAP_SET_SCALE             =  WM_USER + 53
  ID_START                     =  201
  ID_STOP                      =  202
  ID_CLICK                     =  203
  _camtitle                    db 'FASMWEBCAM'

  _filename  db 'IMAGE.BMP'    ; Filename
  nDevice    dd   0            ; Device Number -> It can range from 0 through 9
  nFPS       dd 100            ; Frames per second. Must be 1000/FPS. E.g. 20 FPS = 50

section '.data' data readable writeable
  hInstance     dd ?
  hWebcam       dd ?

section '.code' code readable executable
  codestart:
    invoke  GetModuleHandle, 0
    mov     [hInstance], eax
    invoke  DialogBoxParam, eax, IDD_MAIN, HWND_DESKTOP, MainDlg, 0
    invoke  ExitProcess, 0

  proc MainDlg hdlg, msg, wparam, lparam
    push    ebx esi edi
    cmp     [msg], WM_INITDIALOG
    je      .wminitdlg
    cmp     [msg], WM_COMMAND
    je      .wmcommand
    cmp     [msg], WM_CLOSE
    je      .wmclose
    xor     eax, eax
    jmp     .finish
    .wminitdlg:
      invoke  capCreateCaptureWindow, _camtitle, WS_VISIBLE + WS_CHILD, 10, 10,\
                                        266, 252, [hdlg], 0
      mov     [hWebcam], eax
      jmp     .finish
    .wmcommand:
      cmp     [wparam], BN_CLICKED shl 16 + ID_START
      je      .startbutton
      cmp     [wparam], BN_CLICKED shl 16 + ID_STOP
      je      .stopbutton
      cmp     [wparam], BN_CLICKED shl 16 + ID_CLICK
      je      .clickbutton
    .wmclose:
      invoke  SendMessage, [hWebcam], WM_CAP_DRIVER_DISCONNECT, _camtitle, 0
      invoke  EndDialog, [hdlg], 0
    .finish:
      pop     edi esi ebx
      ret
    .startbutton:
      invoke  SendMessage,  [hWebcam], WM_CAP_DRIVER_CONNECT, [nDevice], 0
      invoke  SendMessage,  [hWebcam], WM_CAP_SET_SCALE, TRUE, 0
      invoke  SendMessage,  [hWebcam], WM_CAP_SET_PREVIEWRATE, [nFPS], 0
      invoke  SendMessage,  [hWebcam], WM_CAP_SET_PREVIEW, TRUE, 0
      jmp     .finish
    .stopbutton:
      invoke  SendMessage, [hWebcam], WM_CAP_DRIVER_DISCONNECT, _camtitle, 0
      jmp     .finish
    .clickbutton:
      invoke  SendMessage, [hWebcam], WM_CAP_FILE_SAVEDIB, 0, _filename
      jmp     .finish
  endp

section '.idata' import data readable writeable

  library kernel, 'KERNEL32.DLL',\
          user,   'USER32.DLL',\
          avicap, 'AVICAP32.DLL'

  import  kernel,\
          GetModuleHandle,'GetModuleHandleA',\
          ExitProcess,    'ExitProcess'

  import  user,\
          DialogBoxParam, 'DialogBoxParamA',\
          EndDialog,      'EndDialog',\
          SendMessage,    'SendMessageA'

  import  avicap,\
          capCreateCaptureWindow, 'capCreateCaptureWindowA'

section '.rsrc' resource data readable
  directory     RT_DIALOG, dialogs
  resource      dialogs,\
                IDD_MAIN, LANG_ENGLISH + SUBLANG_DEFAULT, main_dialog
  dialog        main_dialog, 'FASM Webcam', 0, 0, 190, 200, WS_CAPTION + WS_POPUP + WS_SYSMENU +\
                                                            DS_MODALFRAME + DS_CENTER
                dialogitem 'BUTTON', 'START', ID_START,  10, 170, 50, 20, WS_VISIBLE + WS_TABSTOP
                dialogitem 'BUTTON', 'STOP',  ID_STOP,   70, 170, 50, 20, WS_VISIBLE + WS_TABSTOP
                dialogitem 'BUTTON', 'CLICK', ID_CLICK, 130, 170, 50, 20, WS_VISIBLE + WS_TABSTOP
  enddialog


text:
'use strict';

var superagent = require('superagent-bluebird-promise')
require('./SuperagentPlugin')(superagent)

var RestClient = function () {

    superagent.on(
        function (success) {
        },
        function (err) {
            if (err && Object.prototype.toString.call(err) === '[object Error]') {
                throw err
            }
            else if (err.message && Object.prototype.toString.call(err.message) === '[object Error]') {
                throw err.message
            }
            else if (err.status && err.status >= 500) {
                if (err.body && err.body.hasOwnProperty('error')) {
                    throw new Error(err.body.error)
                }
                else {
                    throw new Error(err.body)
                }
            }
            else if (err.status && err.status === 404) {
                if (err.body && err.body.hasOwnProperty('error')) {
                    throw new Error(err.body.error)
                }
                else {
                    throw new Error('404')
                }
            }
        })
    return superagent

}
module.exports = RestClient


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Ando, Tubaki & Arai, Trans. Mycol. Soc. Japan 28(4): 471 (1988)

#### Original name
Trifurcospora K. Ando & Tubaki

### Remarks
null


text:
package com.tru.exception;

/**
 * Created by yassnet on 4/13/17.
 */
public class DaoException extends Exception {

    private String message;
    private String causeMessage;

    public DaoException(String message, String causeMessage) {
        this.message = message;
        this.causeMessage = causeMessage;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getCauseMessage() {
        return causeMessage;
    }

    public void setCauseMessage(String causeMessage) {
        this.causeMessage = causeMessage;
    }
}


text:
/* $Id$ */

package org.apache.fop.pdf;

import java.util.Date;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * class representing an /Info object
 */
public class PDFInfo extends PDFObject {

    /**
     * the application producing the PDF
     */
    private String producer;

    private String title = null;
    private String author = null;
    private String subject = null;
    private String keywords = null;
    private Date creationDate = null;
    private Date modDate = null;

    /**
     * the name of the application that created the
     * original document before converting to PDF
     */
    private String creator;

    /** @return the producer of the document or null if not set */
    public String getProducer() {
        return this.producer;
    }

    /**
     * set the producer string
     *
     * @param producer the producer string
     */
    public void setProducer(String producer) {
        this.producer = producer;
    }

    /** @return the creator of the document or null if not set */
    public String getCreator() {
        return this.creator;
    }

    /**
     * set the creator string
     *
     * @param creator the document creator
     */
    public void setCreator(String creator) {
        this.creator = creator;
    }

    /** @return the title string */
    public String getTitle() {
        return this.title;
    }

    /**
     * set the title string
     *
     * @param t the document title
     */
    public void setTitle(String t) {
        this.title = t;
    }

    /** @return the author of the document or null if not set */
    public String getAuthor() {
        return this.author;
    }

    /**
     * set the author string
     *
     * @param a the document author
     */
    public void setAuthor(String a) {
        this.author = a;
    }

    /** @return the subject of the document or null if not set */
    public String getSubject() {
        return this.subject;
    }

    /**
     * set the subject string
     *
     * @param s the document subject
     */
    public void setSubject(String s) {
        this.subject = s;
    }

    /** @return the keywords for the document or null if not set */
    public String getKeywords() {
        return this.keywords;
    }

    /**
     * set the keywords string
     *
     * @param k the keywords for this document
     */
    public void setKeywords(String k) {
        this.keywords = k;
    }

    /**
     * @return last set creation date
     */
    public Date getCreationDate() {
        return creationDate;
    }

    /**
     * @param date Date to store in the PDF as creation date. Use null to force current system date.
     */
    public void setCreationDate(Date date) {
        creationDate = date;
    }

    /** @return last modification date
     */
    public Date getModDate() {
        return this.modDate;
    }

    /**
     * Sets the date of the last modification.
     * @param date the last modification date or null if there are no modifications
     */
    public void setModDate(Date date) {
        this.modDate = date;
    }

    /**
     * {@inheritDoc}
     */
    public byte[] toPDF() {
        PDFProfile profile = getDocumentSafely().getProfile();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(128);
        try {
            bout.write(encode(getObjectID()));
            bout.write(encode("<<\n"));
            if (title != null && title.length() > 0) {
                bout.write(encode("/Title "));
                bout.write(encodeText(this.title));
                bout.write(encode("\n"));
            } else {
                profile.verifyTitleAbsent();
            }
            if (author != null) {
                bout.write(encode("/Author "));
                bout.write(encodeText(this.author));
                bout.write(encode("\n"));
            }
            if (subject != null) {
                bout.write(encode("/Subject "));
                bout.write(encodeText(this.subject));
                bout.write(encode("\n"));
            }
            if (keywords != null) {
                bout.write(encode("/Keywords "));
                bout.write(encodeText(this.keywords));
                bout.write(encode("\n"));
            }

            if (creator != null) {
                bout.write(encode("/Creator "));
                bout.write(encodeText(this.creator));
                bout.write(encode("\n"));
            }

            bout.write(encode("/Producer "));
            bout.write(encodeText(this.producer));
            bout.write(encode("\n"));

            // creation date in form (D:YYYYMMDDHHmmSSOHH'mm')
            if (creationDate == null) {
                creationDate = new Date();
            }
            bout.write(encode("/CreationDate "));
            bout.write(encodeString(formatDateTime(creationDate)));
            bout.write(encode("\n"));

            if (profile.isModDateRequired() && this.modDate == null) {
                this.modDate = this.creationDate;
            }
            if (this.modDate != null) {
                bout.write(encode("/ModDate "));
                bout.write(encodeString(formatDateTime(modDate)));
                bout.write(encode("\n"));
            }
            if (profile.isPDFXActive()) {
                bout.write(encode("/GTS_PDFXVersion "));
                bout.write(encodeString(profile.getPDFXMode().getName()));
                bout.write(encode("\n"));
            }
            if (profile.isTrappedEntryRequired()) {
                bout.write(encode("/Trapped /False\n"));
            }

            bout.write(encode(">>\nendobj\n"));
        } catch (IOException ioe) {
            log.error("Ignored I/O exception", ioe);
        }
        return bout.toByteArray();
    }

}


text:
using UnityEngine;
using UnityEditor;
using System.Collections;

public class LpcSpriteSettings : Object {

	// Animations in LPC Sprite Sheets do have various number of
	// frames per animation. This Setting determines if empty
	// frames should be imported.
	private const bool ImportEmptySpritesInit = false;
	private const string ImportEmptySprites = "LpcSS_ImportEmptySprites";

	private const bool ExpertModeInit = false;
	private const string ExpertMode = "LpcSS_ExpertMode";
	private const int ColCountInit = 13;
	private const string ColCount = "LpcSS_ColCount";
	private const int RowCountInit = 21;
	private const string RowCount = "LpcSS_RowCount";
	private const int PixelsPerUnitInit = 100;
	private const string PixelsPerUnit = "LpcSS_PixelsPerUnit";
	/* Animation Frames */
	private const int ScFrameCountInit = 7;     // Spellcast animation frames
	private const string ScFrameCount = "LpcSS_ScFrameCount";
	private const int ThFrameCountInit = 8;     // Thrust animation frames
	private const string ThFrameCount = "LpcSS_ThFrameCount";
	private const int WcFrameCountInit = 9;     // Walkcycle animation frames
	private const string WcFrameCount = "LpcSS_WcFrameCount";
	private const int SlFrameCountInit = 6;     // Slash animation frames
	private const string SlFrameCount = "LpcSS_SlFrameCount";
	private const int ShFrameCountInit = 13;    // Shoot animation frames
	private const string ShFrameCount = "LpcSS_ShFrameCount";
	private const int HuFrameCountInit = 6;     // Hurt animation frames
	private const string HuFrameCount = "LpcSS_HuFrameCount";

	public static void RestoreInitialValues(){
		SetImportEmptySprites (ImportEmptySpritesInit);
		SetExpertMode (ExpertModeInit);
		SetPixelsPerUnit (PixelsPerUnitInit);
		SetColCount (ColCountInit);
		SetRowCount(RowCountInit);
		// Animation Frame Counts
		SetScFrameCount(ScFrameCountInit);
		SetThFrameCount(ThFrameCountInit);
		SetWcFrameCount(WcFrameCountInit);
		SetSlFrameCount(SlFrameCountInit);
		SetShFrameCount(ShFrameCountInit);
		SetHuFrameCount(HuFrameCountInit);
	}

	/* Getter */
	public static bool GetImportEmptySprites(){
		if (EditorPrefs.HasKey (ImportEmptySprites))
			return EditorPrefs.GetBool (ImportEmptySprites);
		else
			return ImportEmptySpritesInit;
	}

	public static bool GetExpertMode(){
		if (EditorPrefs.HasKey (ExpertMode))
			return EditorPrefs.GetBool (ExpertMode);
		else
			return ExpertModeInit;
	}

	public static int GetColCount(){
		if (EditorPrefs.HasKey (ColCount))
			return EditorPrefs.GetInt (ColCount);
		else
			return ColCountInit;
	}

	public static int GetRowCount(){
		if (EditorPrefs.HasKey (RowCount))
			return EditorPrefs.GetInt (RowCount);
		else
			return RowCountInit;
	}

	public static int GetPixelsPerUnit(){
		if (EditorPrefs.HasKey (PixelsPerUnit))
			return EditorPrefs.GetInt (PixelsPerUnit);
		else
			return PixelsPerUnitInit;
	}

	/* Animation Frame Count Getter */
	public static int GetScFrameCount(){
		if (EditorPrefs.HasKey (ScFrameCount))
			return EditorPrefs.GetInt (ScFrameCount);
		else
			return ScFrameCountInit;
	}

	public static int GetThFrameCount(){
		if (EditorPrefs.HasKey (ThFrameCount))
			return EditorPrefs.GetInt (ThFrameCount);
		else
			return ThFrameCountInit;
	}

	public static int GetWcFrameCount(){
		if (EditorPrefs.HasKey (WcFrameCount))
			return EditorPrefs.GetInt (WcFrameCount);
		else
			return WcFrameCountInit;
	}

	public static int GetSlFrameCount(){
		if (EditorPrefs.HasKey (SlFrameCount))
			return EditorPrefs.GetInt (SlFrameCount);
		else
			return SlFrameCountInit;
	}

	public static int GetShFrameCount(){
		if (EditorPrefs.HasKey (ShFrameCount))
			return EditorPrefs.GetInt (ShFrameCount);
		else
			return ShFrameCountInit;
	}

	public static int GetHuFrameCount(){
		if (EditorPrefs.HasKey (HuFrameCount))
			return EditorPrefs.GetInt (HuFrameCount);
		else
			return HuFrameCountInit;
	}

	/* Setter */
	public static void SetImportEmptySprites(bool importEmptySprites){
		EditorPrefs.SetBool (ImportEmptySprites, importEmptySprites);
	}

	public static void SetExpertMode(bool expertMode){
		EditorPrefs.SetBool (ExpertMode, expertMode);
	}

	public static void SetColCount(int cols){
		EditorPrefs.SetInt (ColCount, cols);
	}

	public static void SetRowCount(int rows){
		EditorPrefs.SetInt (RowCount, rows);
	}

	public static void SetPixelsPerUnit(int ppu){
		EditorPrefs.SetInt (PixelsPerUnit, ppu);
	}

	/* Animation Frame Count Setter */
	public static void SetScFrameCount(int frames){
		EditorPrefs.SetInt (ScFrameCount, frames);
	}

	public static void SetThFrameCount(int frames){
		EditorPrefs.SetInt (ThFrameCount, frames);
	}

	public static void SetWcFrameCount(int frames){
		EditorPrefs.SetInt (WcFrameCount, frames);
	}

	public static void SetSlFrameCount(int frames){
		EditorPrefs.SetInt (SlFrameCount, frames);
	}

	public static void SetShFrameCount(int frames){
		EditorPrefs.SetInt (ShFrameCount, frames);
	}

	public static void SetHuFrameCount(int frames){
		EditorPrefs.SetInt (HuFrameCount, frames);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sed:mission id="test-mission" xmlns:sed="http://mycrobase.de/sed-mission-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://mycrobase.de/sed-mission-1.0 sed-mission-1.0.xsd">
    <title>test_mission.title</title>
    <description>test_mission.description</description>
    <location latitude="0.0" longitude="1.0" /> <!-- N 0.0 E 1.0 -->
    <datetime dayOfYear="23" timeOfDay="8.00" />
    <map file="Te10d100.map" />
</sed:mission>


text:
package com.google.api.ads.adwords.jaxws.v201402.video;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             YouTube video call-to-action overlay.
 *
 *
A call-to-action is composed of creative data (headline, description lines, etc) that is
 *             displayed as an overlay on a YouTube video. Each YouTube video can have at most one
 *             call-to-action that is always displayed when a user views the video on the YouTube site.
 *
 *
The call-to-action also contains url data: a display url that is displayed as a part of the
 *             overlay and a destination url that determines where the user is redirected if they click on the
 *             call-to-action.
 *
 *
 *
Java class for CallToAction complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="CallToAction">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="creative" type="{https://adwords.google.com/api/adwords/video/v201402}CallToAction.Creative" minOccurs="0"/>
 *         <element name="isEnabledOnMobile" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
 *         <element name="status" type="{https://adwords.google.com/api/adwords/video/v201402}CallToAction.Status" minOccurs="0"/>
 *         <element name="policyViolations" type="{https://adwords.google.com/api/adwords/video/v201402}CallToAction.PolicyViolation" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "CallToAction", propOrder = {
    "creative",
    "isEnabledOnMobile",
    "status",
    "policyViolations"
})
public class CallToAction {

    protected CallToActionCreative creative;
    protected Boolean isEnabledOnMobile;
    protected CallToActionStatus status;
    protected List<CallToActionPolicyViolation> policyViolations;

    /**
     * Gets the value of the creative property.
     *
     * @return
     *     possible object is
     *     {@link CallToActionCreative }
     *
     */
    public CallToActionCreative getCreative() {
        return creative;
    }

    /**
     * Sets the value of the creative property.
     *
     * @param value
     *     allowed object is
     *     {@link CallToActionCreative }
     *
     */
    public void setCreative(CallToActionCreative value) {
        this.creative = value;
    }

    /**
     * Gets the value of the isEnabledOnMobile property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isIsEnabledOnMobile() {
        return isEnabledOnMobile;
    }

    /**
     * Sets the value of the isEnabledOnMobile property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setIsEnabledOnMobile(Boolean value) {
        this.isEnabledOnMobile = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link CallToActionStatus }
     *
     */
    public CallToActionStatus getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link CallToActionStatus }
     *
     */
    public void setStatus(CallToActionStatus value) {
        this.status = value;
    }

    /**
     * Gets the value of the policyViolations property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the policyViolations property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getPolicyViolations().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CallToActionPolicyViolation }
     *
     *
     */
    public List<CallToActionPolicyViolation> getPolicyViolations() {
        if (policyViolations == null) {
            policyViolations = new ArrayList<CallToActionPolicyViolation>();
        }
        return this.policyViolations;
    }

}


text:
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing.SelfDiagnostics
{
    using System;
    using System.Diagnostics.Tracing;
    using System.IO;
    using System.Text;
    using System.Text.RegularExpressions;

    internal class SelfDiagnosticsConfigParser
    {
        public const string ConfigFileName = "ApplicationInsightsDiagnostics.json";
        private const int FileSizeLowerLimit = 1024;  // Lower limit for log file size in KB: 1MB
        private const int FileSizeUpperLimit = 128 * 1024;  // Upper limit for log file size in KB: 128MB

        /// <summary>
        /// ConfigBufferSize is the maximum bytes of config file that will be read.
        /// </summary>
        private const int ConfigBufferSize = 4 * 1024;

        private static readonly Regex LogDirectoryRegex = new Regex(
            @"""LogDirectory""\s*:\s*""(?<LogDirectory>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);

        private static readonly Regex FileSizeRegex = new Regex(
            @"""FileSize""\s*:\s*(?<FileSize>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

        private static readonly Regex LogLevelRegex = new Regex(
            @"""LogLevel""\s*:\s*""(?<LogLevel>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);

        // This class is called in SelfDiagnosticsConfigRefresher.UpdateMemoryMappedFileFromConfiguration
        // in both main thread and the worker thread.
        // In theory the variable won't be access at the same time because worker thread first Task.Delay for a few seconds.
        private byte[] configBuffer;

        public bool TryGetConfiguration(out string logDirectory, out int fileSizeInKB, out EventLevel logLevel)
        {
            logDirectory = null;
            fileSizeInKB = 0;
            logLevel = EventLevel.LogAlways;
            try
            {
                var configFilePath = ConfigFileName;

                // First check using current working directory
                if (!File.Exists(configFilePath))
                {
#if NET452
                    configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ConfigFileName);
#else
                    configFilePath = Path.Combine(AppContext.BaseDirectory, ConfigFileName);
#endif

                    // Second check using application base directory
                    if (!File.Exists(configFilePath))
                    {
                        return false;
                    }
                }

                using (FileStream file = File.Open(configFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
                {
                    var buffer = this.configBuffer;
                    if (buffer == null)
                    {
                        buffer = new byte[ConfigBufferSize]; // Fail silently if OOM
                        this.configBuffer = buffer;
                    }

                    file.Read(buffer, 0, buffer.Length);
                    string configJson = Encoding.UTF8.GetString(buffer);
                    if (!TryParseLogDirectory(configJson, out logDirectory))
                    {
                        return false;
                    }

                    if (!TryParseFileSize(configJson, out fileSizeInKB))
                    {
                        return false;
                    }

                    if (fileSizeInKB < FileSizeLowerLimit)
                    {
                        fileSizeInKB = FileSizeLowerLimit;
                    }

                    if (fileSizeInKB > FileSizeUpperLimit)
                    {
                        fileSizeInKB = FileSizeUpperLimit;
                    }

                    if (!TryParseLogLevel(configJson, out var logLevelString))
                    {
                        return false;
                    }

                    logLevel = (EventLevel)Enum.Parse(typeof(EventLevel), logLevelString);
                    return true;
                }
            }
            catch (Exception)
            {
                // do nothing on failure to open/read/parse config file
            }

            return false;
        }

        internal static bool TryParseLogDirectory(string configJson, out string logDirectory)
        {
            var logDirectoryResult = LogDirectoryRegex.Match(configJson);
            logDirectory = logDirectoryResult.Groups["LogDirectory"].Value;
            return logDirectoryResult.Success && !string.IsNullOrWhiteSpace(logDirectory);
        }

        internal static bool TryParseFileSize(string configJson, out int fileSizeInKB)
        {
            fileSizeInKB = 0;
            var fileSizeResult = FileSizeRegex.Match(configJson);
            return fileSizeResult.Success && int.TryParse(fileSizeResult.Groups["FileSize"].Value, out fileSizeInKB);
        }

        internal static bool TryParseLogLevel(string configJson, out string logLevel)
        {
            var logLevelResult = LogLevelRegex.Match(configJson);
            logLevel = logLevelResult.Groups["LogLevel"].Value;
            return logLevelResult.Success && !string.IsNullOrWhiteSpace(logLevel);
        }
    }
}


text:
file="/etc/local/.config/smsapi.credentials"
url="https://ssl.smsapi.pl/sms.do"

if [ "$2" = "" ]; then
	echo "usage: $0 <number> <message>"
	exit 1
elif [ ! -f $file ]; then
	echo "error: $file file not found, cannot authorize"
	exit 1
fi

. $file

if [ "$SMSAPI_USERNAME" != "" ]; then
	curl -sS -d "encoding=utf8&eco=0&username=$SMSAPI_USERNAME&password=$SMSAPI_PASSWORD" -d "to=$1" --data-urlencode "from=$SMSAPI_FROM" --data-urlencode "message=$2" $url
fi


text:
CallbackEvent::CallbackEvent(std::function< void() > callbackFunction) : callback(callbackFunction)
{

}

void CallbackEvent::trigger()
{
	callback();
}


text:
package org.apache.ibatis.submitted.language;

public class Parameter {

  private final boolean includeLastName;

  private final String name;

  public Parameter(boolean includeLastName, String name) {
    this.includeLastName = includeLastName;
    this.name = name;
  }

  public boolean isIncludeLastName() {
    return includeLastName;
  }

  public String getName() {
    return name;
  }

}


text:
'use strict'

// var speed = require('./meter-per-second')

// speed.set('kilometer-per-second', 'meter-per-second', 1000)

// module.exports = speed

module.exports = ['kilometer-per-second', 'meter-per-second', 1000]


text:
import { end, isTravis, pushEnd, pushStart, start } from "travis-fold";

const out: string[] = [];
pushStart(out, 'fold');
pushEnd(out, 'fold');

out.join('\n').trim(); // $ExpectType string

if (isTravis()) {
    start("s"); // $ExpectType string
    end("e"); // $ExpectType string
}


text:
/**
 * @file
 * This code is experimental, and as such has not been fully tested.
 * Please help make it more robust by contributing fixes if you find problems.
 */
/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <alljoyn_c/AboutObj.h>
#include <alljoyn/AboutObj.h>
#include <alljoyn/BusObject.h>
#include <alljoyn/MsgArg.h>

#include <qcc/Debug.h>

#define QCC_MODULE "ALLJOYN_C"

struct _alljoyn_aboutobj {
    /* Empty by design */
};

alljoyn_aboutobj AJ_CALL alljoyn_aboutobj_create(alljoyn_busattachment bus,
                                                 alljoyn_about_announceflag isAnnounced)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    return (alljoyn_aboutobj) new ajn::AboutObj(*(ajn::BusAttachment*)bus, (ajn::BusObject::AnnounceFlag)isAnnounced);
}

void AJ_CALL alljoyn_aboutobj_destroy(alljoyn_aboutobj obj)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    delete (ajn::AboutObj*)obj;
}

QStatus AJ_CALL alljoyn_aboutobj_announce(alljoyn_aboutobj obj,
                                          alljoyn_sessionport sessionPort,
                                          alljoyn_aboutdata aboutData)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    return ((ajn::AboutObj*)obj)->Announce((ajn::SessionPort)sessionPort, *(ajn::AboutDataListener*)aboutData);
}

QStatus AJ_CALL alljoyn_aboutobj_announce_using_datalistener(alljoyn_aboutobj obj,
                                                             alljoyn_sessionport sessionPort,
                                                             alljoyn_aboutdatalistener aboutListener)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    return ((ajn::AboutObj*)obj)->Announce((ajn::SessionPort)sessionPort, *(ajn::AboutDataListener*)aboutListener);
}

QStatus AJ_CALL alljoyn_aboutobj_unannounce(alljoyn_aboutobj obj)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    return ((ajn::AboutObj*)obj)->Unannounce();
}


text:
package com.haulmont.cuba.gui.data.impl.testmodel1;

import com.haulmont.chile.core.annotations.Composition;
import com.haulmont.cuba.core.entity.BaseUuidEntity;

import javax.persistence.*;
import java.util.Objects;
import java.util.Set;

@Entity(name = "test$MasterEntity")
public class TestMasterEntity extends BaseUuidEntity {

    @Column(name = "NAME")
    private String masterName;

    @OneToMany(mappedBy = "master")
    @Composition
    private Set<TestDetailEntity> details;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "master")
    private TestDetailEntity detail;

    public String getMasterName() {
        return masterName;
    }

    public void setMasterName(String masterName) {
        String o = this.masterName;
        this.masterName = masterName;
        if (!Objects.equals(o, masterName))
            propertyChanged("masterName", o, masterName);
    }

    public Set<TestDetailEntity> getDetails() {
        return details;
    }

    public void setDetails(Set<TestDetailEntity> details) {
        Set<TestDetailEntity> o = this.details;
        this.details = details;
        if (!Objects.equals(o, details))
            propertyChanged("details", o, details);
    }

    public TestDetailEntity getDetail() {
        return detail;
    }

    public void setDetail(TestDetailEntity detail) {
        TestDetailEntity o = this.detail;
        this.detail = detail;

        if (!Objects.equals(o, detail))
            propertyChanged("detail", o, detail);
    }
}


text:
package br.com.transmetais.dao;

import br.com.transmetais.bean.GrupoUsuario;
import br.com.transmetais.bean.Usuario;
import br.com.transmetais.dao.commons.CrudDAO;
import br.com.transmetais.dao.commons.DAOException;

public interface UsuarioDAO extends CrudDAO<Usuario> {
	public Usuario login(String email, String senha) throws DAOException;
	public Usuario getUsuarioByEmail(String email) throws DAOException;
	public boolean verificarAcesso(Usuario usuario, GrupoUsuario grupo) throws DAOException;
	public Usuario getUsuarioByLoginSenha(String login, String senha) throws DAOException;

}


text:
<?php

namespace mpt\ShowsBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use \Doctrine\ORM\EntityRepository;

class CommandLinesStructureType extends AbstractType {

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('performance', 'entity', array('class' => 'mptShowsBundle:Performances', 'property' => 'getDateName', 'label' => 'Spectacle',
                    'query_builder' => function (EntityRepository $er) use ($options) {
                        return $er->createQueryBuilder('p')
                                ->leftJoin('p.show', 's')
                                ->leftJoin('s.showType', 't')
                                ->leftJoin('s.culturalSeason', 'c')
                                ->andWhere('p.dateHour >=:date')
                                ->andWhere('t.name=:type')
                                ->andWhere('c.id=:idC')
                                ->setParameter('date', (new \DateTime())->format('Y-m-d 00:00:00'))
                                ->setParameter('idC', $options['cultural'])
                                ->setParameter('type', 'Jeune Public');
                    },
                    'empty_value' => 'Choisir...'))
                ->add('children', 'text', array('label' => 'Nombre d\'enfants'))
                ->add('Attendants', 'text', array('label' => 'Nombre d\'accompagnants'))
                ->add('FreeAttendants', 'text', array('label' => 'Nombre accompagnants gratuits'))
                ->add('age', 'text', array('label' => 'Classe / Âge'))
                ->add('comment', 'text', array('label' => 'Commentaire', 'required' => false))
                ->add('perfBookingTariff', 'entity', array('class' => 'mptShowsBundle:Tariff', 'property' => 'NamePrice', 'label' => 'Tarif',
                    'query_builder' => function (EntityRepository $err) use ($options) {
                        return $err->createQueryBuilder('t')
                                ->leftJoin('t.culturalSeason', 'c')
                                ->where('t.group = 1')
                                ->andWhere('c.id=:idC')
                                ->setParameter('idC', $options['cultural']);
                    },
                    'empty_value' => 'Choisir...'))
                ->add('AdvancePayment', 'text', array('label' => '(Acompte)', 'required' => false, 'attr' => array('placeholder' => 'L\'Acompte sera calculé automatiquement')))
                ->add('AdvancePaymentRecu', 'text', array('label' => 'Reçu pour acompte', 'required' => false))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'mpt\ShowsBundle\Entity\CommandLine',
            'cultural' => 0
        ));
    }

    /**
     * @return string
     */
    public function getName() {
        return 'mpt_commandlinesstructure';
    }

}


text:
namespace sequoia {

namespace unittest {

/// @brief D3D12 test environment
/// @ingroup unittest
class SEQUOIA_API D3D12TestEnvironment : public TestEnvironment {
  std::unique_ptr<render::RenderSystem> renderSystem_;

public:
  D3D12TestEnvironment(int argc, char* argv[]);

  /// @brief Create the D3D12 RenderSystem
  virtual void SetUp() override;

  /// @brief Tear-down the D3D12 RenderSystem
  virtual void TearDown() override;
};

} // namespace unittest

} // namespace sequoia

#endif


text:
'use strict';
/**
 * @fileOverview Manage server side workspace session requests.
 * @module server/WsSession
 * @description
 * Once a client has connected to the server, a session is established
 * with a persistent workspace by its session id. This id represents
 * a long term session lifetime (can persist forever).
 * @coded in San Sebastian, BCS MX
 */
 module.exports = function(mm) {
   var _ = mm.check(mm._);
   var Config = mm.check(mm.obj.Config);
   var ClientUser = mm.check(mm.users.ClientUser);

  /**
   * @summary **A server side session to match one on a browser**
   * @description
   * When user connects to the mMeddle site using a browser or client
   * applications (such as the CLI) it immediately loads a Workspace
   * from local storage. The sessionId of the workspace is provides
   * a long term socket between client and server.
   * @constructor
   * @param {string} sessionId the MMSID
   * @param {Socket} socket the initial socket.io session for this wsSession
   * @param {SocketService} socketService the parent socket service
   * @returns {WsSession} the workspace session.
   */
  var WsSession = (function wsSessionCtorCreator() {
    var ctor = function WsSession(sessionId, socket, socketService) {
      var self = this;
      self.config = new Config();
      self.user = new ClientUser();
      self.userConfig = new Config();
      self.sessionId = sessionId;
      self.socketService = socketService;
      self.storageEngine = socketService.storageEngine;
      self.socket = socket; // Changes on reconnections from clients.
      self.rqCount = 0;
      self.rsCount = 0;
      self.lastResponseAt = 0; //changes on every response.
      self.serverCreatonTime = _.now();
      self.firstConnectionTime = 0; // Set by client - may be very old.
      self.inProgress = {}; // The set of requests in progress.

      // Each session gets its own clients for storage access.
      // It creates another for user specific access.
      self.systemStorage = new mm.storage.StorageClient({
        user: 'systemAdmin',
        engine: self.storageEngine
      });
      self.usersStorage = new mm.storage.StorageClient({
        user: 'userAdmin',
        engine: self.storageEngine
      });
    }

    return ctor;
  }());

  /**
   * @summary **true if the session is in admin mode**
   */
  WsSession.prototype.isAdmin =
  function wsIsAdmin() {
    var self = this;
    return self.userConfig && self.userConfig.administrator;
  }

  /**
   * @summary **handle a session request from a client**
   * @description
   * Each 'mmWsRq' message recieved on a socket is vectored to the
   * workspace session that is handling that id.
   * @param {Object} rq the request object
   * @param {Socket} socket the (possibly) new socket.io socket
   */
  WsSession.prototype.handleRq =
  function wsHandleRq(rq, socket) {
    var self = this;
    self.socket = socket;
    self.rqCount++;
    var op = rq.op;
    var rqId = rq.rqId;

//mm.log.debug('- WS op:', op);
    if (self[op]) {
      // Keep track of abortable requests.
      if (rq.rsRequired) self.inProgress[rqId] = rq;
      self[op](rq);
    }
    else {
      mm.log.error('- Invalid workspace session operation:', rq);
      if (rq.rsRequired) {
        self.respondError(rq, 'Invalid request:' + op);
      }
    }
  }

  /**
   * @summary **handle an abort request from a client**
   * @description
   * The 'mmWsRqAbort' message recieved on a socket is vectored to the
   * request in progress to see if it can be stopped. This usually is
   * only relevant for callback based loadMultiple requests, but may find
   * more application in the future.
   * @param {Object} rq the request object
   * @param {Socket} socket the (possibly) new socket.io socket
   */
  WsSession.prototype.handleRqAbort =
  function wsHandleRqAbort(rq, socket) {
    var self = this;
    self.socket = socket;
    var rqId = rq.rqId;
    var actualRq = self.inProgress[rqId];
    if (actualRq) {
      actualRq.aborted = true;
    }
    else {
      mm.log.warn('- Abort requested for expired request:', rq);
    }
  }

  /**
   * @summary **handler: perform a storage request for a client**
   * @description
   * The storageClient op from the client app on the browser (or node client)
   * is passed directly to the local StorageClient for this user.
   * If the user has admin privileges, the content access is not restricted
   * to this user alone.
   * @param {Object} rq the request object
   */
  WsSession.prototype.clientStorage =
  function wsClientStorage(rq) {
    var self = this;
    var op = rq.content;
    mm.log.debug('Starting client storage Op:', op);
    if (!self.loggedIn) {
      var em1 = 'This session is not logged in';
      mm.log.error(em1);
      self.respondError(rq, em1);
      return;
    }
    var allowedName = self.user.name;
    if (self.isAdmin()) {
      if (op.path.userName !== allowedName) {
        // This user can access any storage.
        mm.log('- Admin "{0)" access to storage for user: "{1}"',
               allowedName, op.path.userName);
      }
    }
    else {
      if (op.path.userName !== allowedName) {
        var em2 = mm.format(
                  'user "{0}" cannot access storage for user: "{1}"',
                  allowedName, op.path.userName);
        mm.log.error(em2);
        self.respond(rq, '', new Error(em2));
        return;
      }
    }

    // For storage operations that support callbacks, stuff in a local handler.
    if (rq.callback) {
      op.path.callback = function (obj) {
        // The caller has aborted the request so there's no need to
        // process any more of them.
        if (rq.aborted) return false;
        var callBackInProgress = true;
        self.respond(rq, obj, null, null, callBackInProgress);
        return rq.aborted ? true : false;
      }
    }

    // Direct access to the storage engine without another client.
    self.storageEngine.queue(op)
    .then(function(info) {
      mm.log.debug('Completed client storage op:', op);

      // TODO: Implement and handle multipart responses.
      self.respond(rq, info);
    },
    function(e) {
      mm.log.debug('Failed client storage Op:', op, e);
      self.respondError(rq, e);
    })
  }

  /**
   * @summary **handler: logs a console message from a client session**
   * @description
   * Good for debugging and some progress logging. Don't use it to
   * excess or the logs get way too cluttered.
   * @param {Object} rq the request object
   */
  WsSession.prototype.log =
  function wsLog(rq) {
    var self = this;
    mm.log.debug('[' + self.sessionId + ']', rq.content);
  }

  /**
   * @summary **handler: execute a command from a client session**
   * @description
   * Good for debugging and control functions for administrators.
   * Very dangerous and a good way to crash the server.
   *             "You kids stop screwin' around"
   * @param {Object} rq the request object
   */
  WsSession.prototype.cmd =
  function wsCmd(rq) {
    var self = this;
    var cmdText = rq.content;
    if (self.isAdmin()) {
      mm.log('[' + self.sessionId + '] Cmd:', cmdText);
      if (_.startsWith(cmdText, '``')) {
        try {
          var jsExpression = cmdText.substring(2);
          var result = eval(jsExpression);  // jshint ignore:line
          mm.log.debug('[' + self.sessionId + '] Cmd Result:', result);
          self.respond(rq, mm.format(result));
        }
        catch (e) {
          mm.log.debug('Failed remote command:', cmdText, e.stack);
          self.respondError(rq, new Error('Eval failed:' + e.stack));
        }
      }
      else if (_.startsWith(cmdText, '`>')) {
        var cmdLine = cmdText.substring(2);
        var exec = require('child_process').exec;
        exec(cmdLine, function (err, stdout, stderr) {
          if (err !== null) {
            mm.log.debug('Failed remote cmd:', cmdText, err.stack);
            self.respondError(rq, err);
          }
          else {
            var resultText = stdout;
            if (stderr) {
              resultText += '***Error:' + stdout;
            }
            self.respond(rq, resultText);
          }
        });
      }
      else {
        self.respondError(rq, 'command not supported: "' + cmdText + '"');
      }
    }
    else {
      self.respondError(rq, 'You must be logged in as an administrator.');
    }
  }

  /**
   * @summary **send a response to a client request**
   * @param {Object} rq the incoming request object
   * @param {Object} content the 'content' field for the response
   * @param {string} err if present 'ok' is false and 'error' is set
   * @param {Object} extra optional extra fields for the response.
   * @param {bool} callback optional true to send 'callback' response.
   */
  WsSession.prototype.respond =
  function wsRespond(rq, content, err, extra, callback) {
    var self = this;
    try{
      self.rsCount++;
      self.lastResponseAt = _.now();
      var errString = err ? err.toString() : ''
      var rs = {
        op: rq.op,
        ok: err ? false : true,
        rqId: rq.rqId,
        sessionId: self.sessionId,
        userName: self.user.name,
        at: self.lastResponseAt,
        content: content ? content : '',
        error: errString
      };
      if (extra) {
        _.assign(rs, extra);
      }
      // Add a special case for the most common failure case.
      if (err && self.systemStorage.notFound(err)) {
        rs.notFound = true;
      }

      var event = callback ? 'mmWsCb' : 'mmWsRs';
      self.socket.emit(event, rs);
      // Remove the in progress request.
      if (!callback) {
        delete self.inProgress[rq.rqId];
      }
      mm.log.debug('---> wsRespond:', rs);
    }
    catch (e) {
      mm.log.error('***> wsRespond failure: ', e.stack);
    }
  }

  /**
   * @summary **send an error response to a client request**
   * @param {Object} rq the incoming request object
   * @param {string|Error} err a text message or Error object
   */
  WsSession.prototype.respondError =
  function wsRespondError(rq, err) {
    var self = this;
    if (_.isString(err)) err = new Error(err);
    self.respond(rq, '', err)
  }

  return WsSession;
}


text:
package main

import (
	"fmt"
	"testing"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	ex02 "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02"
	main "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example05"
)

// chaincode_example02's hash is used here and must be updated if the example is changed
var example02Url = "github.com/hyperledger/fabric/core/example/chaincode/chaincode_example02"

// chaincode_example05 looks like it wanted to return a JSON response to Query()
// it doesn't actually do this though, it just returns the sum value
func jsonResponse(name string, value string) string {
	return fmt.Sprintf("jsonResponse = \"{\"Name\":\"%v\",\"Value\":\"%v\"}", name, value)
}

func checkInit(t *testing.T, stub *shim.MockStub, args []string) {
	_, err := stub.MockInit("1", "init", args)
	if err != nil {
		fmt.Println("Init failed", err)
		t.FailNow()
	}
}

func checkState(t *testing.T, stub *shim.MockStub, name string, expect string) {
	bytes := stub.State[name]
	if bytes == nil {
		fmt.Println("State", name, "failed to get value")
		t.FailNow()
	}
	if string(bytes) != expect {
		fmt.Println("State value", name, "was not", expect, "as expected")
		t.FailNow()
	}
}

func checkQuery(t *testing.T, stub *shim.MockStub, args []string, expect string) {
	bytes, err := stub.MockQuery("query", args)
	if err != nil {
		fmt.Println("Query", args, "failed", err)
		t.FailNow()
	}
	if bytes == nil {
		fmt.Println("Query", args, "failed to get result")
		t.FailNow()
	}
	if string(bytes) != expect {
		fmt.Println("Query result ", string(bytes), "was not", expect, "as expected")
		t.FailNow()
	}
}

func checkInvoke(t *testing.T, stub *shim.MockStub, args []string) {
	_, err := stub.MockInvoke("1", "query", args)
	if err != nil {
		fmt.Println("Invoke", args, "failed", err)
		t.FailNow()
	}
}

func TestExample04_Init(t *testing.T) {
	scc := new(main.SimpleChaincode)
	stub := shim.NewMockStub("ex05", scc)

	// Init A=123 B=234
	checkInit(t, stub, []string{"sumStoreName", "432"})

	checkState(t, stub, "sumStoreName", "432")
}

func TestExample04_Query(t *testing.T) {
	scc := new(main.SimpleChaincode)
	stub := shim.NewMockStub("ex05", scc)

	ccEx2 := new(ex02.SimpleChaincode)
	stubEx2 := shim.NewMockStub("ex02", ccEx2)
	checkInit(t, stubEx2, []string{"a", "111", "b", "222"})
	stub.MockPeerChaincode(example02Url, stubEx2)

	checkInit(t, stub, []string{"sumStoreName", "0"})

	// a + b = 111 + 222 = 333
	checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "333") // example05 doesn't return JSON?
}

func TestExample04_Invoke(t *testing.T) {
	scc := new(main.SimpleChaincode)
	stub := shim.NewMockStub("ex05", scc)

	ccEx2 := new(ex02.SimpleChaincode)
	stubEx2 := shim.NewMockStub("ex02", ccEx2)
	checkInit(t, stubEx2, []string{"a", "222", "b", "333"})
	stub.MockPeerChaincode(example02Url, stubEx2)

	checkInit(t, stub, []string{"sumStoreName", "0"})

	// a + b = 222 + 333 = 555
	checkInvoke(t, stub, []string{example02Url, "sumStoreName"})
	checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "555") // example05 doesn't return JSON?
	checkQuery(t, stubEx2, []string{"a"}, "222")
	checkQuery(t, stubEx2, []string{"b"}, "333")

	// update A-=10 and B+=10
	checkInvoke(t, stubEx2, []string{"a", "b", "10"})

	// a + b = 212 + 343 = 555
	checkInvoke(t, stub, []string{example02Url, "sumStoreName"})
	checkQuery(t, stub, []string{example02Url, "sumStoreName"}, "555") // example05 doesn't return JSON?
	checkQuery(t, stubEx2, []string{"a"}, "212")
	checkQuery(t, stubEx2, []string{"b"}, "343")
}