text:
"""
desispec.quicklook.quicksky

Here will be the sky computing and sky subtraction routines for QL
"""
import sys
import numpy as np
from desispec.sky import SkyModel
from desispec import util
from desispec import frame as fr
import scipy
from desispec.resolution import Resolution
from desispec.linalg import cholesky_solve

def compute_sky(fframe,fibermap=None,nsig_clipping=4., apply_resolution=False):
    """
    Adding in the offline algorithm here to be able to apply resolution for sky compute.
    We will update this here as needed for quicklook.
    The original weighted sky compute still is the default.

    Args: fframe: fiberflat fielded frame object
          fibermap: fibermap object
          apply_resolution: if True, uses the resolution in the frame object to evaluate
          sky allowing fiber to fiber variation of resolution.
    """
    nspec=fframe.nspec
    nwave=fframe.nwave

    #- Check with fibermap. exit if None
    #- use fibermap from frame itself if exists

    if fframe.fibermap is not None:
        fibermap=fframe.fibermap

    if fibermap is None:
        print("Must have fibermap for Sky compute")
        sys.exit(0)

    #- get the sky
    skyfibers = np.where(fibermap['OBJTYPE'] == 'SKY')[0]
    skyfluxes=fframe.flux[skyfibers]
    skyivars=fframe.ivar[skyfibers]

    nfibers=len(skyfibers)

    if apply_resolution:
        max_iterations=100
        current_ivar=skyivars.copy()
        Rsky = fframe.R[skyfibers]
        sqrtw=np.sqrt(skyivars)
        sqrtwflux=sqrtw*skyfluxes

        chi2=np.zeros(skyfluxes.shape)

        nout_tot=0
        for iteration in range(max_iterations) :

            A=scipy.sparse.lil_matrix((nwave,nwave)).tocsr()
            B=np.zeros((nwave))
            # diagonal sparse matrix with content = sqrt(ivar)*flat of a given fiber
            SD=scipy.sparse.lil_matrix((nwave,nwave))
            # loop on fiber to handle resolution
            for fiber in range(nfibers) :
                if fiber%10==0 :
                    print("iter %d fiber %d"%(iteration,fiber))
                R = Rsky[fiber]

                # diagonal sparse matrix with content = sqrt(ivar)
                SD.setdiag(sqrtw[fiber])

                sqrtwR = SD*R # each row r of R is multiplied by sqrtw[r]

                A = A+(sqrtwR.T*sqrtwR).tocsr()
                B += sqrtwR.T*sqrtwflux[fiber]

            print("iter %d solving"%iteration)

            w = A.diagonal()>0
            A_pos_def = A.todense()[w,:]
            A_pos_def = A_pos_def[:,w]
            skyflux = B*0
            try:
                skyflux[w]=cholesky_solve(A_pos_def,B[w],rcond=None)
            except:
                print("cholesky failed, trying svd in iteration {}".format(iteration))
                skyflux[w]=np.linalg.lstsq(A_pos_def,B[w],rcond=None)[0]

            print("iter %d compute chi2"%iteration)

            for fiber in range(nfibers) :

                S = Rsky[fiber].dot(skyflux)
                chi2[fiber]=current_ivar[fiber]*(skyfluxes[fiber]-S)**2

            print("rejecting")

            nout_iter=0
            if iteration<1 :
                # only remove worst outlier per wave
                # apply rejection iteratively, only one entry per wave among fibers
                # find waves with outlier (fastest way)
                nout_per_wave=np.sum(chi2>nsig_clipping**2,axis=0)
                selection=np.where(nout_per_wave>0)[0]
                for i in selection :
                    worst_entry=np.argmax(chi2[:,i])
                    current_ivar[worst_entry,i]=0
                    sqrtw[worst_entry,i]=0
                    sqrtwflux[worst_entry,i]=0
                    nout_iter += 1
            else :
                # remove all of them at once
                bad=(chi2>nsig_clipping**2)
                current_ivar *= (bad==0)
                sqrtw *= (bad==0)
                sqrtwflux *= (bad==0)
                nout_iter += np.sum(bad)

            nout_tot += nout_iter

            sum_chi2=float(np.sum(chi2))
            ndf=int(np.sum(chi2>0)-nwave)
            chi2pdf=0.
            if ndf>0 :
                chi2pdf=sum_chi2/ndf
            print("iter #%d chi2=%f ndf=%d chi2pdf=%f nout=%d"%(iteration,sum_chi2,ndf,chi2pdf,nout_iter))

            if nout_iter == 0 :
                break

        print("nout tot=%d"%nout_tot)
        # solve once again to get deconvolved sky variance
        #skyflux,skycovar=cholesky_solve_and_invert(A.todense(),B)
        skyflux = np.linalg.lstsq(A.todense(),B,rcond=None)[0]
        skycovar = np.linalg.pinv(A.todense())
        #- sky inverse variance, but incomplete and not needed anyway
        # skyvar=np.diagonal(skycovar)
        # skyivar=(skyvar>0)/(skyvar+(skyvar==0))

        # Use diagonal of skycovar convolved with mean resolution of all fibers
        # first compute average resolution
        #- computing mean from matrix itself
        R= (fframe.R.sum()/fframe.nspec).todia()
        #mean_res_data=np.mean(fframe.resolution_data,axis=0)
        #R = Resolution(mean_res_data)
        # compute convolved sky and ivar
        cskycovar=R.dot(skycovar).dot(R.T.todense())
        cskyvar=np.diagonal(cskycovar)
        cskyivar=(cskyvar>0)/(cskyvar+(cskyvar==0))

        # convert cskyivar to 2D; today it is the same for all spectra,
        # but that may not be the case in the future
        finalskyivar = np.tile(cskyivar, nspec).reshape(nspec, nwave)

        # Convolved sky
        finalskyflux = np.zeros(fframe.flux.shape)
        for i in range(nspec):
            finalskyflux[i] = fframe.R[i].dot(skyflux)

        # need to do better here
        mask = (finalskyivar==0).astype(np.uint32)

    else: #- compute weighted average sky ignoring the fiber/wavelength resolution
        if skyfibers.shape[0] > 1:

            weights=skyivars
            #- now get weighted meansky and ivar
            meanskyflux=np.average(skyfluxes,axis=0,weights=weights)
            wtot=weights.sum(axis=0)
            werr2=(weights**2*(skyfluxes-meanskyflux)**2).sum(axis=0)
            werr=np.sqrt(werr2)/wtot
            meanskyivar=1./werr**2
        else:
            meanskyflux=skyfluxes
            meanskyivar=skyivars

        #- Create a 2d- sky model replicating this
        finalskyflux=np.tile(meanskyflux,nspec).reshape(nspec,nwave)
        finalskyivar=np.tile(meanskyivar,nspec).reshape(nspec,nwave)
        mask=fframe.mask

    skymodel=SkyModel(fframe.wave,finalskyflux,finalskyivar,mask)
    return skymodel

def subtract_sky(fframe,skymodel):
    """
    skymodel: skymodel object.
    fframe: frame object to do the sky subtraction, should be already fiber flat fielded
    need same number of fibers and same wavelength grid
    """
    #- Check number of specs
    assert fframe.nspec == skymodel.nspec
    assert fframe.nwave == skymodel.nwave

    #- check same wavelength grid, die if not
    if not np.allclose(fframe.wave, skymodel.wave):
        message = "frame and sky not on same wavelength grid"
        raise ValueError(message)

    #SK. This wouldn't work since not all properties of the input
    #frame is modified. Just modify input frame directly instead!

    fframe.flux= fframe.flux-skymodel.flux
    fframe.ivar = util.combine_ivar(fframe.ivar.clip(1e-8), skymodel.ivar.clip(1e-8))
    fframe.mask = fframe.mask | skymodel.mask
    #- create a frame object now
    #sframe=fr.Frame(fframe.wave,sflux,sivar,smask,fframe.resolution_data,meta=fframe.meta,fibermap=fframe.fibermap)
    return fframe


text:
import os
import sys
import copy

from repoxplorer.controllers.renderers import CSVRenderer

runtimedir = os.path.join(os.path.expanduser('~'), '.local', 'repoxplorer')

# RepoXplorer configuration file
base_logging = {
    'version': 1,
    'root': {'level': 'DEBUG', 'handlers': ['normal']},
    'loggers': {
        'indexerDaemon': {
            'level': 'DEBUG',
            'handlers': ['normal', 'console'],
            'propagate': False,
        },
        'repoxplorer': {
            'level': 'DEBUG',
            'handlers': ['normal', 'console'],
            'propagate': False,
        },
        'elasticsearch': {
            'level': 'WARN',
            'handlers': ['normal', 'console'],
            'propagate': False,
        },
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',
            'formatter': 'console'
        },
        'normal': {
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'level': 'DEBUG',
            'formatter': 'normal',
            'filename': '',
            'when': 'D',
            'interval': 1,
            'backupCount': 30,
        },
    },
    'formatters': {
        'console': {'format': ('%(levelname)-5.5s [%(name)s] %(message)s')},
        'normal': {'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]'
                              ' %(message)s')},
    }
}

# Internal dev pecan server
server = {
    'port': '51000',
    'host': '0.0.0.0'
}

# Pecan REST and rendering configuration
app = {
    'root': 'repoxplorer.controllers.root.RootController',
    'modules': ['repoxplorer'],
    'custom_renderers': {'csv': CSVRenderer},
    'static_root': '%s/public' % runtimedir,
    'debug': False,
    'errors': {
        404: '/error/e404',
        '__force_dict__': True
    }
}

# Additional RepoXplorer configurations
db_default_file = None
db_path = runtimedir
db_cache_path = db_path
git_store = '%s/git_store' % runtimedir
xorkey = None
elasticsearch_host = 'localhost'
elasticsearch_port = 9200
elasticsearch_index = 'repoxplorer'
elasticsearch_user = None
elasticsearch_password = None
indexer_loop_delay = 60
indexer_skip_projects = []
index_custom_html = ""
users_endpoint = False
admin_token = 'admin_token'
# Absolute path to a helper. If not set or None use the default provided helper
git_credential_helper_path = None

# Logging configuration for the wsgi app
logging = copy.deepcopy(base_logging)
logging['handlers']['normal']['filename'] = (
    '%s/repoxplorer-api.log' % runtimedir)

# Logging configuration for the indexer
indexer_logging = copy.deepcopy(base_logging)
indexer_logging['handlers']['normal']['filename'] = (
    '%s/repoxplorer-indexer.log' % runtimedir)

# Add this to activate OpenID Connect as your authentication method.
oidc = {
    # issuer_url: used to fetch the issuer's configuration by appending
    # .well-known/openid-configuration to it
    'issuer_url': 'https://path/to/idp',
    # Defaults to True, set to False for development
    'verify_ssl': True,
    # This must be equal to the "aud" claim in the tokens sent back by your
    # OpenID Connect provider.
    'audience': 'repoxplorer',
}

redpajama_set_name: RedPajamaGithub


text:
namespace Js
{
    const ushort CallInfo::ksizeofCount =  24;
    const ushort CallInfo::ksizeofCallFlags = 8;
    const uint CallInfo::kMaxCountArgs = (1 << ksizeofCount) - 1 ;

    // For Eval calls the FrameDisplay is passed in as an extra argument.
    // This is not counted in Info.Count. Use this API to get the updated count.
    ArgSlot CallInfo::GetArgCountWithExtraArgs(CallFlags flags, uint count)
    {
        AssertOrFailFastMsg(count < Constants::UShortMaxValue - 1, "ArgList too large");
        ArgSlot argSlotCount = (ArgSlot)count;
        if (CallInfo::HasExtraArg(flags))
        {
            argSlotCount++;
        }
        return argSlotCount;
    }

    uint CallInfo::GetLargeArgCountWithExtraArgs(CallFlags flags, uint count)
    {
        if (CallInfo::HasExtraArg(flags))
        {
            UInt32Math::Inc(count);
        }
        return count;
    }

    ArgSlot CallInfo::GetArgCountWithoutExtraArgs(CallFlags flags, ArgSlot count)
    {
        ArgSlot newCount = count;
        if (CallInfo::HasExtraArg(flags))
        {
            if (count == 0)
            {
                ::Math::DefaultOverflowPolicy();
            }
            newCount = count - 1;
        }
        return newCount;
    }
}


text:
Dotfiles are a set of files in your \*nix-based home directory to personalize and
customize your system. They set up your `$PATH`, customize Vim, configure Ruby's
IRB, customize zsh behavior and many other things. These dotfiles are inpired by
[holman's dotfiles](https://github.com/holman/dotfiles) and [others](http://dotfiles.github.io/).

## Installation

```bash
git clone git://github.com/petk/dotfiles.git --recursive
./dotfiles/install
```

## Documentation

Documentation for using these dotfiles can be found in the [doc](doc) folder.
Contents:

* [Vim](doc/vim.md)
* [Vim cheat sheet](doc/vim/cheatSheet.md)
* [Git](doc/git.md)
* [Atom](doc/atom.md)
* [tmux](doc/tmux.md)

## Keeping configuration files in sync

To copy dotfiles from the current system run the `sync` script from the repository
directory:

```bash
./dotfiles/sync
```

## Features

* Installation script
* [git](http://git-scm.com) configuration
* [Zsh](http://zsh.org) - shell designed for interactive use, also a powerful scripting language - configuration
* Bash configuration
* [Vim](http://vim.org) custom runtime configuration and scripts
* [wget](http://www.gnu.org/s/wget) customization
* [screen](https://www.gnu.org/software/screen) customization
* [Atom](https://atom.io) custom runtime configuration

## Requirements

* Vim 7.4

## Contributing and License

Questions, issue reports and additional contributions to this repository are
most [welcome](CONTRIBUTING.md). This repository is released under the
[MIT license](LICENSE).

![Peter's dotfiles](linux.png "Peter's dotfiles")


text:
import 'ts-helpers';

import 'core-js/es7/reflect';
import 'core-js/es7/object';
import 'zone.js/dist/zone';


text:
package com.jetbrains.python;

import com.intellij.psi.util.QualifiedName;
import com.jetbrains.python.fixtures.PyTestCase;
import com.jetbrains.python.psi.stubs.PyQualifiedNameCompletionMatcher.QualifiedNameMatcher;

import java.util.List;

public class PyNotImportedQualifiedNameCompletionTest extends PyTestCase {
  public void testQualifiedNamesAlwaysMatchedByFirstComponentOfQualifier() {
    myFixture.copyDirectoryToProject(getTestName(false), "");
    myFixture.configureByFile("main.py");
    myFixture.completeBasic();
    List<String> variants = myFixture.getLookupElementStrings();
    assertNotNull(variants);
    assertDoesntContain(variants, "foo.bar.func");
    assertContainsElements(variants, "bar.func", "baz.quux.func");
  }

  public void testQualifiedNamesAlwaysMatchedByFirstComponentOfQualifierWithEmptyAttributeName() {
    myFixture.copyDirectoryToProject(getTestName(false), "");
    myFixture.configureByFile("main.py");
    myFixture.completeBasic();
    List<String> variants = myFixture.getLookupElementStrings();
    assertNotNull(variants);
    assertDoesntContain(variants, "foo.bar.func");
    assertContainsElements(variants, "bar.func", "bar.func1");
  }

  // PY-47281
  public void testVariantsFromInternalThirdPartyModulesExcludedUnlessExported() {
    runWithAdditionalClassEntryInSdkRoots(getTestName(false) + "/site-packages", () -> {
      myFixture.copyDirectoryToProject(getTestName(false) + "/src", "");
      myFixture.configureByFile("main.py");
      myFixture.completeBasic();
      List<String> variants = myFixture.getLookupElementStrings();
      assertNotNull(variants);
      assertDoesntContain(variants, "mypackage._impl.func", "mypackage._vendor.lib.func");
      assertContainsElements(variants, "mypackage.func_exported", "mypackage_util._impl.func");
    });
  }

  // PY-47281
  public void testVariantsFromInternalSkeletonsExcludedUnlessExported() {
    String testName = getTestName(false);
    runWithAdditionalClassEntryInSdkRoots(testName + "/site-packages", () -> {
      runWithAdditionalClassEntryInSdkRoots(testName + "/python_stubs", () -> {
        myFixture.copyDirectoryToProject(testName + "/src", "");
        myFixture.configureByFile("main.py");
        myFixture.completeBasic();
        List<String> variants = myFixture.getLookupElementStrings();
        assertNotNull(variants);
        assertDoesntContain(variants, "mypackage._impl.func");
        assertContainsElements(variants, "mypackage.func_exported", "mypackage_util._impl.func");
      });
    });
  }

  public void testQualifiedNameMatcherTest() {
    QualifiedNameMatcher matcher = new QualifiedNameMatcher(QualifiedName.fromDottedString("foo.bar.baz"));
    assertTrue(matcher.prefixMatches("foo.bar.baz"));
    assertTrue(matcher.prefixMatches("foo.bar.baz"));
    assertTrue(matcher.prefixMatches("fooExtra.bar.baz"));
    assertTrue(matcher.prefixMatches("foo.barExtra.baz"));
    assertTrue(matcher.prefixMatches("foo.bar.bazExtra"));
    assertFalse(matcher.prefixMatches(""));
    assertFalse(matcher.prefixMatches("baz"));
    assertFalse(matcher.prefixMatches("foo.bar"));
    assertFalse(matcher.prefixMatches("bar.baz"));
    assertTrue(matcher.prefixMatches("foo.xxx.bar.baz"));
    assertTrue(matcher.prefixMatches("foo.bar.xxx.baz"));
    assertFalse(matcher.prefixMatches("foo.bar.baz.xxx"));
    assertFalse(matcher.prefixMatches("xxx.foo.bar.baz"));
  }

  public void testImportForModuleFunction() {
    doTestBasicCompletion();
  }

  public void testImportForModuleClass() {
    doTestBasicCompletion();
  }

  public void testImportForAlias() {
    doTestBasicCompletion();
  }

  public void testImportForAliasWithNonEmptyAttribute() {
    doTestBasicCompletion();
  }

  public void testUseImportPriorityWhenAddingImport() {
    doTestBasicCompletion();
  }

  public void testDirectModuleAttributesSuggestedForNonEmptyAttributePrefix() {
    doTestBasicCompletion();
  }

  private void doTestBasicCompletion() {
    final String testName = getTestName(false);
    myFixture.copyDirectoryToProject(testName, "");
    myFixture.configureByFile("main.py");
    myFixture.completeBasic();
    myFixture.checkResultByFile(testName + "/main.after.py");
  }

  @Override
  protected String getTestDataPath() {
    return super.getTestDataPath() + "/completion/notImportedQualifiedName/";
  }
}


text:
package com.sksamuel.elastic4s.mappings

import java.util

import com.sksamuel.elastic4s.analyzers.{CustomAnalyzerDefinition, FrenchLanguageAnalyzer, LowercaseTokenFilter, WhitespaceAnalyzer, WhitespaceTokenizer}
import com.sksamuel.elastic4s.mappings.FieldType._
import com.sksamuel.elastic4s.testkit.ElasticSugar
import org.scalatest.{Matchers, WordSpec}

class MappingTest extends WordSpec with ElasticSugar with Matchers {

  client.execute {
    createIndex("q").mappings {
      mapping("r") as Seq(
        field("a", TextType) stored true analyzer WhitespaceAnalyzer,
        field("b", TextType)
      )
    } analysis {
      CustomAnalyzerDefinition("my_analyzer", WhitespaceTokenizer, LowercaseTokenFilter)
    }
  }.await

  client.execute {
    createIndex("z") mappings(
      mapping("r"),
      mapping("s"),
      mapping("t")
    )
  }.await

  "mapping get" should {
    "return schema" in {

      val mapping = client.execute {
        get mapping "q" / "r"
      }.await

      val map = mapping.mappings("q")("r").sourceAsMap()

      val a = map.get("properties").asInstanceOf[util.Map[String, Any]].get("a").asInstanceOf[util.Map[String, Any]]
      a.get("type") shouldBe "text"
      a.get("store") shouldBe true
      a.get("analyzer") shouldBe "whitespace"

      val b = map.get("properties").asInstanceOf[util.Map[String, Any]].get("b").asInstanceOf[util.Map[String, Any]]
      b.get("type") shouldBe "text"
    }
    "support getting all mappings" in {
      client.execute {
        getMapping("z")
      }.await.mappingsFor("z").keySet shouldBe Set("r", "s", "t")
    }
  }
  "mapping put" should {
    "add new fields" in {

      client.execute {
        put mapping "q" / "r" as Seq(
          field("c", FloatType) boost 1.2,
          field("d", TextType) analyzer FrenchLanguageAnalyzer
        )
      }.await

      val mapping = client.execute {
        get mapping "q" / "r"
      }.await

      val map = mapping.mappings("q")("r").sourceAsMap()

      val c = map.get("properties").asInstanceOf[util.Map[String, _]].get("c").asInstanceOf[util.Map[String, _]]
      c.get("type") shouldBe "float"
      c.get("boost") shouldBe 1.2

      val d = map.get("properties").asInstanceOf[util.Map[String, _]].get("d").asInstanceOf[util.Map[String, _]]
      d.get("type") shouldBe "text"
      d.get("analyzer") shouldBe "french"
    }
  }
}


text:
module Discogs.Types.Release.Video where

import Data.Text
import Data.Aeson

data Video = Video
      { video_duration    :: Int
      , video_description :: Text
      , video_embed       :: Bool
      , video_uri         :: Text
      , video_title       :: Text
      } deriving (Show, Read, Eq)

instance FromJSON Video where
    parseJSON = withObject "video" $ \o -> do
        video_duration    <- o .: "duration"
        video_description <- o .: "description"
        video_embed       <- o .: "embed"
        video_uri         <- o .: "uri"
        video_title       <- o .: "title"
        return Video{..}

instance ToJSON Video where
    toJSON Video{..} = object [
        "duration"    .= video_duration,
        "description" .= video_description,
        "embed"       .= video_embed,
        "uri"         .= video_uri,
        "title"       .= video_title ]


text:
from flask import Flask, g, request, render_template, redirect, abort, url_for
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import current_user, UserMixin, LoginManager
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.bootstrap import Bootstrap
from flask_wtf import Form
from wtforms.validators import DataRequired, Required, ValidationError
from wtforms import StringField, SubmitField
from sqlalchemy import Column, Unicode, Integer, ForeignKey, DateTime, Float, \
    Boolean, func, UnicodeText
from sqlalchemy.orm import relationship, backref
import crypt
import base64
import os
import datetime
import markdown
from markupsafe import Markup

db = SQLAlchemy()

class Location(db.Model):
    __tablename__ = "location"

    id = Column(Integer, primary_key=True)
    name = Column(Unicode)
    address = Column(UnicodeText)
    lat = Column(Float)
    lng = Column(Float)
    url = Column(Unicode)

    def __str__(self):
        return self.name

class Event(db.Model):
    __tablename__ = "event"

    id = Column(Integer, primary_key=True)
    slug = Column(Unicode, unique=True, index=True)
    name = Column(Unicode)
    location_id = Column(Integer, ForeignKey('location.id'))
    location = relationship('Location')

    text = Column(UnicodeText)

    date = Column(DateTime, index=True)

    @property
    def editable(self):
        return self.date > datetime.datetime.now()

class Attendee(db.Model):
    __tablename__ = "attendee"

    id = Column(Integer, primary_key=True)
    event_id = Column(Integer, ForeignKey('event.id'))
    user_id = Column(Integer, ForeignKey('user.id'))
    name = Column(Unicode)
    timestamp = Column(DateTime, default=func.now())
    event = relationship('Event', backref=backref('attendees',
                                                  order_by=timestamp))
    user = relationship('User', backref=backref('attended',
                                                order_by=timestamp))
    client_id = Column(Unicode)

    @property
    def display_name(self):
        if self.user:
            return self.user.name
        else:
            return self.name

    def __init__(self, event, user=None, name=None):
        if user is None:
            self.client_id = g.client_id

        self.user = user
        self.event = event
        self.name = name

class User(UserMixin, db.Model):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True)
    login = Column(Unicode, unique=True, index=True)
    password = Column(Unicode)
    name = Column(Unicode)
    email = Column(Unicode)
    is_admin = Column(Boolean)

    def check_password(self, password):
        if self.password == password or \
           self.password == crypt.crypt(password, self.password):
            return True
        else:
            return False

    def change_password(self, new_password):
        salt = '$1$' + base64.b64encode(os.urandom(6)) + '$'
        self.password = crypt.crypt(new_password, salt)

    @classmethod
    def load_user(cls, user_id):
        u = cls.query.get(user_id)
        if not u:
            return None
        if not u.enabled:
            return None
        return u

    @classmethod
    def authenticate(cls, login, password):
        u = cls.query.filter_by(login=login).first()
        if not u:
            return None
        if not u.enabled:
            return None
        if u.check_password(password):
            return u
        else:
            return None

app = Flask(__name__)
app.config.from_object('default_config')
app.config.from_envvar('PATEK_CONFIG')

Bootstrap(app)

l = LoginManager(app)
db.init_app(app)
admin = Admin(app)

@app.template_filter()
def asmarkdown(s):
    return Markup(markdown.markdown(s))

admin.add_view(ModelView(Location, db.session))
admin.add_view(ModelView(Event, db.session))
admin.add_view(ModelView(User, db.session))

class MyModelView(ModelView):
    def is_accessible(self):
        return login.current_user.is_authenticated()

@app.before_request
def get_client_id():
    client_id = request.cookies.get('client_id')
    if client_id is None:
        client_id = base64.b64encode(os.urandom(18))
    g.client_id = client_id

@app.after_request
def set_client_id(response):
    response.set_cookie('client_id', g.client_id, max_age=86400 * 60)
    return response

class AttendForm(Form):
    name = StringField('Jmeno:', [Required()])
    captcha = StringField('5+3 = (slovy)')
    ok = SubmitField('Prihlasit')
    def validate_captcha(form, field):
        if field.data.lower() != 'osm':
            raise ValidationError('Ne, neni')

@app.route('/', methods=['GET', 'POST'])
@app.route('/<slug>', methods=['GET', 'POST'])
def event(slug=None):
    if slug is None:
        e = Event.query.order_by(Event.date.desc()).first()
    else:
        e = Event.query.filter_by(slug=slug).one()

    f = AttendForm()

    if f.validate_on_submit():
        a = Attendee(e, name=f.name.data)
        db.session.add(a)
        db.session.commit()
        return redirect(request.url)

    return render_template('event.html', e=e, attend_form=f)

@app.route('/attendee/<atid>/delete', methods=['POST'])
def delete_attendee(atid):
    if request.form["client_id"] != g.client_id:
        abort(403)
    a = Attendee.query.get(atid)
    if current_user != a.user and g.client_id != a.client_id:
        abort(403)

    slug = a.event.slug
    db.session.delete(a)
    db.session.commit()
    return redirect(url_for('event', slug=slug))

@app.before_first_request
def init_db():
    db.create_all()

if __name__ == '__main__':
    app.debug = True
    app.run(port=5090, host="0.0.0.0")


text:
package org.apache.flex.forks.batik.css.engine.sac;

import java.util.Set;

import org.w3c.css.sac.Selector;
import org.w3c.css.sac.SimpleSelector;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
 * This class provides an implementation of the
 * {@link org.w3c.css.sac.DescendantSelector} interface.
 *
 * @author Stephane Hillion
 * @version $Id: CSSChildSelector.java 501495 2007-01-30 18:00:36Z dvholten $
 */
public class CSSChildSelector extends AbstractDescendantSelector {

    /**
     * Creates a new CSSChildSelector object.
     */
    public CSSChildSelector(Selector ancestor, SimpleSelector simple) {
        super(ancestor, simple);
    }

    /**
     * SAC: Implements {@link
     * org.w3c.css.sac.Selector#getSelectorType()}.
     */
    public short getSelectorType() {
        return SAC_CHILD_SELECTOR;
    }

    /**
     * Tests whether this selector matches the given element.
     */
    public boolean match(Element e, String pseudoE) {
        Node n = e.getParentNode();
        if (n != null && n.getNodeType() == Node.ELEMENT_NODE) {
            return ((ExtendedSelector)getAncestorSelector()).match((Element)n,
                                                                   null) &&
                   ((ExtendedSelector)getSimpleSelector()).match(e, pseudoE);
        }
        return false;
    }

    /**
     * Fills the given set with the attribute names found in this selector.
     */
    public void fillAttributeSet(Set attrSet) {
        ((ExtendedSelector)getAncestorSelector()).fillAttributeSet(attrSet);
        ((ExtendedSelector)getSimpleSelector()).fillAttributeSet(attrSet);
    }

    /**
     * Returns a representation of the selector.
     */
    public String toString() {
        SimpleSelector s = getSimpleSelector();
        if (s.getSelectorType() == SAC_PSEUDO_ELEMENT_SELECTOR) {
            return String.valueOf( getAncestorSelector() ) + s;
        }
        return getAncestorSelector() + " > " + s;
    }
}


text:
require 'puppet/provider/package'

Puppet::Type.type(:package).provide :dpkg, :parent => Puppet::Provider::Package do
  desc "Package management via `dpkg`.  Because this only uses `dpkg`
    and not `apt`, you must specify the source of any packages you want
    to manage."

  has_feature :holdable

  commands :dpkg => "/usr/bin/dpkg"
  commands :dpkg_deb => "/usr/bin/dpkg-deb"
  commands :dpkgquery => "/usr/bin/dpkg-query"

  def self.instances
    packages = []

    # list out all of the packages
    cmd = "#{command(:dpkgquery)} -W --showformat '${Status} ${Package} ${Version}\\n'"
    Puppet.debug "Executing '#{cmd}'"
    Puppet::Util::Execution.execpipe(cmd) do |process|
      # our regex for matching dpkg output
      regex = %r{^(\S+) +(\S+) +(\S+) (\S+) (\S*)$}
      fields = [:desired, :error, :status, :name, :ensure]
      hash = {}

      # now turn each returned line into a package object
      process.each_line { |line|
        if hash = parse_line(line)
          packages << new(hash)
        end
      }
    end

    packages
  end

  self::REGEX = %r{^(\S+) +(\S+) +(\S+) (\S+) (\S*)$}
  self::FIELDS = [:desired, :error, :status, :name, :ensure]

  def self.parse_line(line)
    if match = self::REGEX.match(line)
      hash = {}

      self::FIELDS.zip(match.captures) { |field,value|
        hash[field] = value
      }

      hash[:provider] = self.name

      if hash[:status] == 'not-installed'
        hash[:ensure] = :purged
      elsif ['config-files', 'half-installed', 'unpacked', 'half-configured'].include?(hash[:status])
        hash[:ensure] = :absent
      end
      hash[:ensure] = :held if hash[:desired] == 'hold'
    else
      Puppet.warning "Failed to match dpkg-query line #{line.inspect}"
      return nil
    end

    hash
  end

  def install
    unless file = @resource[:source]
      raise ArgumentError, "You cannot install dpkg packages without a source"
    end

    args = []

    # We always unhold when installing to remove any prior hold.
    self.unhold

    if @resource[:configfiles] == :keep
      args << '--force-confold'
    else
      args << '--force-confnew'
    end
    args << '-i' << file

    dpkg(*args)
  end

  def update
    self.install
  end

  # Return the version from the package.
  def latest
    output = dpkg_deb "--show", @resource[:source]
    matches = /^(\S+)\t(\S+)$/.match(output).captures
    warning "source doesn't contain named package, but #{matches[0]}" unless matches[0].match( Regexp.escape(@resource[:name]) )
    matches[1]
  end

  def query
    packages = []

    fields = [:desired, :error, :status, :name, :ensure]

    hash = {}

    # list out our specific package
    begin
      output = dpkgquery(
        "-W",
        "--showformat",
        '${Status} ${Package} ${Version}\\n',
        @resource[:name]
      )
    rescue Puppet::ExecutionFailure
      # dpkg-query exits 1 if the package is not found.
      return {:ensure => :purged, :status => 'missing', :name => @resource[:name], :error => 'ok'}
    end

    hash = self.class.parse_line(output) || {:ensure => :absent, :status => 'missing', :name => @resource[:name], :error => 'ok'}

    if hash[:error] != "ok"
      raise Puppet::Error.new(
        "Package #{hash[:name]}, version #{hash[:ensure]} is in error state: #{hash[:error]}"
      )
    end

    hash
  end

  def uninstall
    dpkg "-r", @resource[:name]
  end

  def purge
    dpkg "--purge", @resource[:name]
  end

  def hold
    self.install
    Tempfile.open('puppet_dpkg_set_selection') do |tmpfile|
      tmpfile.write("#{@resource[:name]} hold\n")
      tmpfile.flush
      execute([:dpkg, "--set-selections"], :failonfail => false, :combine => false, :stdinfile => tmpfile.path.to_s)
    end
  end

  def unhold
    Tempfile.open('puppet_dpkg_set_selection') do |tmpfile|
      tmpfile.write("#{@resource[:name]} install\n")
      tmpfile.flush
      execute([:dpkg, "--set-selections"], :failonfail => false, :combine => false, :stdinfile => tmpfile.path.to_s)
    end
  end
end


text:
{% extends 'layout.html' %}
{% block body %}

Fields

            Department
            Name
            Type

          {% for department in departments %}
            {% for field in department.fields %}

                {{ field.department.name }}

                    {{ field.name }}

                {{ field.ftype.name|upper }}

                   Edit

                  Delete

            {% endfor %}
          {% endfor %}

Add a new Field

      <form method="POST" action="{{ url_for('admin.edit_fields') }}" class="form-horizontal">
        {{ form.csrf_token }}

            {{ form.department.label(class='control-label') }}
            {{ form.department(class='form-control') }}

            {{ form.field_type.label(class='control-label') }}
            {{ form.field_type(class='form-control') }}

          {{ form.name(class='form-control', placeholder='Field Name') }}

            <button type="submit" class="btn btn-primary"></button>

      </form>

{% endblock %}


text:
class SocketService {
  constructor($rootScope, $state, userService) {
      this.$rootScope = $rootScope;
      this.$state = $state;
      this.userService = userService;
  }

  connect(userSid) {
    this.socket = io.connect({ query: `userSid=${userSid}` });

    this.socket.emit('conn', null, data => {
      this.userService.userSid = data.userSid;
      this.userService.userPid = data.userPid;
      this.userService.username = data.username;
    });

    this.on('error', e => {
      var error = JSON.parse(e);
    });
  }

  emit(eventName, data, callback) {
    this.socket.emit(eventName, data, (...args) => {
      var cArgs = args;
      this.$rootScope.$apply(() => {
        if (callback) {
          callback.apply(this.socket, cArgs);
        }
      });
    });
  }

  on(eventName, callback) {
    this.socket.on(eventName, (...args) => {
      var cArgs = args;
      this.$rootScope.$apply(() => {
        callback.apply(this.socket, cArgs);
      });
    });
  }

}

SocketService.$inject = ['$rootScope', '$state', 'userService'];

export { SocketService };


text:
bct_test_setup

W = rand(10);
W(logical(eye(10))) = 0;

% threshold_absolute
bct_test("threshold_absolute", threshold_absolute(W, 0.5) == threshold_absolute_cpp(W, 0.5))

% threshold_proportional_dir
bct_test("threshold_proportional_dir", threshold_proportional(W, 0.5) == threshold_proportional_dir_cpp(W, 0.5))

% threshold_proportional_und
W = triu(W) + triu(W)';
bct_test("threshold_proportional_und", threshold_proportional(W, 0.5) == threshold_proportional_und_cpp(W, 0.5))

bct_test_teardown


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

/*! \file rx-delay.hpp

    \brief Return an observable that emits each item emitted by the source observable after the specified delay.

    \tparam Duration      the type of time interval
    \tparam Coordination  the type of the scheduler

    \param period        the period of time each item is delayed
    \param coordination  the scheduler for the delays

    \return  Observable that emits each item emitted by the source observable after the specified delay.

    \sample
    \snippet delay.cpp delay period+coordination sample
    \snippet output.txt delay period+coordination sample
*/

#if !defined(RXCPP_OPERATORS_RX_DELAY_HPP)
#define RXCPP_OPERATORS_RX_DELAY_HPP

#include "../rx-includes.hpp"

namespace rxcpp {

namespace operators {

namespace detail {

template<class... AN>
struct delay_invalid_arguments {};

template<class... AN>
struct delay_invalid : public rxo::operator_base<delay_invalid_arguments<AN...>> {
    using type = observable<delay_invalid_arguments<AN...>, delay_invalid<AN...>>;
};
template<class... AN>
using delay_invalid_t = typename delay_invalid<AN...>::type;

template<class T, class Duration, class Coordination>
struct delay
{
    typedef rxu::decay_t<T> source_value_type;
    typedef rxu::decay_t<Coordination> coordination_type;
    typedef typename coordination_type::coordinator_type coordinator_type;
    typedef rxu::decay_t<Duration> duration_type;

    struct delay_values
    {
        delay_values(duration_type p, coordination_type c)
            : period(p)
            , coordination(c)
        {
        }
        duration_type period;
        coordination_type coordination;
    };
    delay_values initial;

    delay(duration_type period, coordination_type coordination)
        : initial(period, coordination)
    {
    }

    template<class Subscriber>
    struct delay_observer
    {
        typedef delay_observer<Subscriber> this_type;
        typedef rxu::decay_t<T> value_type;
        typedef rxu::decay_t<Subscriber> dest_type;
        typedef observer<T, this_type> observer_type;

        struct delay_subscriber_values : public delay_values
        {
            delay_subscriber_values(composite_subscription cs, dest_type d, delay_values v, coordinator_type c)
                : delay_values(v)
                , cs(std::move(cs))
                , dest(std::move(d))
                , coordinator(std::move(c))
                , worker(coordinator.get_worker())
                , expected(worker.now())
            {
            }
            composite_subscription cs;
            dest_type dest;
            coordinator_type coordinator;
            rxsc::worker worker;
            rxsc::scheduler::clock_type::time_point expected;
        };
        std::shared_ptr<delay_subscriber_values> state;

        delay_observer(composite_subscription cs, dest_type d, delay_values v, coordinator_type c)
            : state(std::make_shared<delay_subscriber_values>(delay_subscriber_values(std::move(cs), std::move(d), v, std::move(c))))
        {
            auto localState = state;

            auto disposer = [=](const rxsc::schedulable&){
                localState->cs.unsubscribe();
                localState->dest.unsubscribe();
                localState->worker.unsubscribe();
            };
            auto selectedDisposer = on_exception(
                [&](){return localState->coordinator.act(disposer);},
                localState->dest);
            if (selectedDisposer.empty()) {
                return;
            }

            localState->dest.add([=](){
                localState->worker.schedule(selectedDisposer.get());
            });
            localState->cs.add([=](){
                localState->worker.schedule(localState->worker.now() + localState->period, selectedDisposer.get());
            });
        }

        void on_next(T v) const {
            auto localState = state;
            auto work = [v, localState](const rxsc::schedulable&){
                localState->dest.on_next(v);
            };
            auto selectedWork = on_exception(
                [&](){return localState->coordinator.act(work);},
                localState->dest);
            if (selectedWork.empty()) {
                return;
            }
            localState->worker.schedule(localState->worker.now() + localState->period, selectedWork.get());
        }

        void on_error(std::exception_ptr e) const {
            auto localState = state;
            auto work = [e, localState](const rxsc::schedulable&){
                localState->dest.on_error(e);
            };
            auto selectedWork = on_exception(
                [&](){return localState->coordinator.act(work);},
                localState->dest);
            if (selectedWork.empty()) {
                return;
            }
            localState->worker.schedule(selectedWork.get());
        }

        void on_completed() const {
            auto localState = state;
            auto work = [localState](const rxsc::schedulable&){
                localState->dest.on_completed();
            };
            auto selectedWork = on_exception(
                [&](){return localState->coordinator.act(work);},
                localState->dest);
            if (selectedWork.empty()) {
                return;
            }
            localState->worker.schedule(localState->worker.now() + localState->period, selectedWork.get());
        }

        static subscriber<T, observer_type> make(dest_type d, delay_values v) {
            auto cs = composite_subscription();
            auto coordinator = v.coordination.create_coordinator();

            return make_subscriber<T>(cs, observer_type(this_type(cs, std::move(d), std::move(v), std::move(coordinator))));
        }
    };

    template<class Subscriber>
    auto operator()(Subscriber dest) const
        -> decltype(delay_observer<Subscriber>::make(std::move(dest), initial)) {
        return      delay_observer<Subscriber>::make(std::move(dest), initial);
    }
};

}

/*! @copydoc rx-delay.hpp
*/
template<class... AN>
auto delay(AN&&... an)
    ->      operator_factory<delay_tag, AN...> {
     return operator_factory<delay_tag, AN...>(std::make_tuple(std::forward<AN>(an)...));
}

}

template<>
struct member_overload<delay_tag>
{
    template<class Observable, class Duration,
        class Enabled = rxu::enable_if_all_true_type_t<
            is_observable<Observable>,
            rxu::is_duration<Duration>>,
        class SourceValue = rxu::value_type_t<Observable>,
        class delay = rxo::detail::delay<SourceValue, rxu::decay_t<Duration>, identity_one_worker>>
    static auto member(Observable&& o, Duration&& d)
        -> decltype(o.template lift<SourceValue>(delay(std::forward<Duration>(d), identity_current_thread()))) {
        return      o.template lift<SourceValue>(delay(std::forward<Duration>(d), identity_current_thread()));
    }

    template<class Observable, class Coordination, class Duration,
        class Enabled = rxu::enable_if_all_true_type_t<
            is_observable<Observable>,
            is_coordination<Coordination>,
            rxu::is_duration<Duration>>,
        class SourceValue = rxu::value_type_t<Observable>,
        class delay = rxo::detail::delay<SourceValue, rxu::decay_t<Duration>, rxu::decay_t<Coordination>>>
    static auto member(Observable&& o, Coordination&& cn, Duration&& d)
        -> decltype(o.template lift<SourceValue>(delay(std::forward<Duration>(d), std::forward<Coordination>(cn)))) {
        return      o.template lift<SourceValue>(delay(std::forward<Duration>(d), std::forward<Coordination>(cn)));
    }

    template<class Observable, class Coordination, class Duration,
        class Enabled = rxu::enable_if_all_true_type_t<
            is_observable<Observable>,
            is_coordination<Coordination>,
            rxu::is_duration<Duration>>,
        class SourceValue = rxu::value_type_t<Observable>,
        class delay = rxo::detail::delay<SourceValue, rxu::decay_t<Duration>, rxu::decay_t<Coordination>>>
    static auto member(Observable&& o, Duration&& d, Coordination&& cn)
        -> decltype(o.template lift<SourceValue>(delay(std::forward<Duration>(d), std::forward<Coordination>(cn)))) {
        return      o.template lift<SourceValue>(delay(std::forward<Duration>(d), std::forward<Coordination>(cn)));
    }

    template<class... AN>
    static operators::detail::delay_invalid_t<AN...> member(const AN&...) {
        std::terminate();
        return {};
        static_assert(sizeof...(AN) == 10000, "delay takes (optional Coordination, required Duration) or (required Duration, optional Coordination)");
    }
};

}

#endif


text:
#pragma once
#ifndef EDITORPROPSDIALOG_H_INCLUDED
#define EDITORPROPSDIALOG_H_INCLUDED

#include "ui_editorpropsdialog.h"

class MarkupEditorPropertiesDialog : public QDialog, public Ui::MarkupEditorPropertiesDialog
{
  Q_OBJECT
  Q_DISABLE_COPY(MarkupEditorPropertiesDialog)

public:
  MarkupEditorPropertiesDialog(QWidget *parent);
  virtual ~MarkupEditorPropertiesDialog();

public:
  static const QColor defaultIdealObjectPenColor;
  static const QColor defaultIdealObjectBrushColor;
  static const int    defaultIdealObjectWidth;

  static const QColor defaultRunObjectPenColor;
  static const QColor defaultRunObjectBrushColor;
  static const int    defaultRunObjectWidth;

  static const QColor defaultStarZonePenColor;
  static const QColor defaultStarZoneBrushColor;
  static const int    defaultStarZoneWidth;

  static const bool   defaultRepeatStar;

public:
  void setIdealObjectEditorProperties(const QColor &penColor, const QColor &brushColor, int width);
  void setRunObjectEditorProperties(const QColor &penColor, const QColor &brushColor, int width);
  void setStarZoneEditorProperties(const QColor &penColor, const QColor &brushColor, int width);
  void setAdditionalProperties(bool repeatStar);

public:
  QColor idealObjectPenColor() const;
  QColor idealObjectBrushColor() const;
  int    idealObjectWidth() const;

  QColor runObjectPenColor() const;
  QColor runObjectBrushColor() const;
  int    runObjectWidth() const;

  QColor starZonePenColor() const;
  QColor starZoneBrushColor() const;
  int    starZoneWidth() const;

  bool   isRepeatStar() const;

private slots:
  void chooseColor();
  void restoreDefaults();
};

#endif  // EDITORPROPSDIALOG_H_INCLUDED


text:
module Multilateration
  class Solver
    attr_reader :receivers, :wave_speed, :time_of_arrival_strategy
    private :receivers, :wave_speed, :time_of_arrival_strategy

    def initialize(unsorted_receivers, time_of_arrival_strategy)
      @receivers  = unsorted_receivers.sort_by { |r| time_of_arrival_strategy.toa(r) }
      @wave_speed = time_of_arrival_strategy.wave_speed
      @time_of_arrival_strategy = time_of_arrival_strategy
    end

    def solved_vector
      Vector.elements (ai_matrix * bi_matrix).flat_map.to_a
    end

    private

    def ai_matrix
      Matrix.rows(middle_receivers.map { |i| ai(i) }).inverse
    end

    def bi_matrix
      Matrix.columns([middle_receivers.map { |i| bi(i) }])
    end

    def ai(i)
      2*(   ( distance(tdoa_between_receivers_first_and_last) * ( i             - first_receiver )) \
          - ( distance(tdoa_between_receivers_first_and(i))   * ( last_receiver - first_receiver )) )
    end

    def bi(i)
        ( distance(tdoa_between_receivers_first_and(i))   * ( distance_sq(tdoa_between_receivers_first_and_last) - inner_product_sq(last_receiver)                  )) \
      + ( inner_product_sq(first_receiver)                * ( distance(tdoa_between_receivers_first_and(i))      - distance(tdoa_between_receivers_first_and_last)  )) \
      + ( distance(tdoa_between_receivers_first_and_last) * ( inner_product_sq(i)                                - distance_sq(tdoa_between_receivers_first_and(i)) ))
    end

    def middle_receivers
      receivers - [first_receiver, last_receiver]
    end

    def first_receiver
      receivers.first
    end

    def last_receiver
      receivers.last
    end

    def tdoa_between_receivers_first_and_last
      tdoa_between_receivers_first_and(last_receiver)
    end

    def tdoa_between_receivers_first_and(other_receiver)
      time_of_arrival_strategy.tdoa(other_receiver, first_receiver)
    end

    def distance(time, exp=1)
      (wave_speed**exp) * (time**exp)
    end

    def distance_sq(time)
      distance(time, 2)
    end

    def inner_product_sq(vector)
      vector.inner_product(vector)
    end

  end
end


text:
using Synology.FileStation.Common.Results;

namespace Synology.FileStation.List.Results
{
    /// <summary>
    /// File perm acl result.
    /// </summary>
    public interface IFilePermAclResult : ITaskFilePermAclResult
    {
    }
}


text:
package com.ait.lienzo.client.core.animation;

public interface AnimationTweener
{
    public static final AnimationTweener LINEAR      = TweenerBuilder.MAKE_LINEAR();

    public static final AnimationTweener EASE_IN     = TweenerBuilder.MAKE_EASE_IN(3.0);

    public static final AnimationTweener EASE_OUT    = TweenerBuilder.MAKE_EASE_OUT(3.0);

    public static final AnimationTweener EASE_IN_OUT = TweenerBuilder.MAKE_EASE_IN_OUT();

    public static final AnimationTweener ELASTIC     = TweenerBuilder.MAKE_ELASTIC(3);

    public static final AnimationTweener BOUNCE      = TweenerBuilder.MAKE_BOUNCE(3);

    public double tween(double percent);

    public static final class TweenerBuilder
    {
        public static final AnimationTweener MAKE_EASE_IN(double strength)
        {
            return MAKE_EASE_IN_P(Math.min(6.0, Math.max(1.0, strength)));
        }

        public static final AnimationTweener MAKE_EASE_OUT(double strength)
        {
            return MAKE_EASE_OUT_P(Math.min(6.0, Math.max(1.0, strength)));
        }

        private static final AnimationTweener MAKE_LINEAR()
        {
            return new AnimationTweener()
            {
                @Override
                public double tween(double percent)
                {
                    return percent;
                }
            };
        }

        private static final AnimationTweener MAKE_EASE_IN_P(final double strength)
        {
            return new AnimationTweener()
            {
                @Override
                public double tween(double percent)
                {
                    return Math.pow(percent, strength * 2.0);
                }
            };
        }

        private static final AnimationTweener MAKE_EASE_OUT_P(final double strength)
        {
            return new AnimationTweener()
            {
                @Override
                public double tween(double percent)
                {
                    return (1.0 - Math.pow(1.0 - percent, strength * 2.0));
                }
            };
        }

        private static final AnimationTweener MAKE_EASE_IN_OUT()
        {
            return new AnimationTweener()
            {
                @Override
                public double tween(double percent)
                {
                    return (percent - Math.sin(percent * 2.0 * Math.PI) / (2.0 * Math.PI));
                }
            };
        }

        public static final AnimationTweener MAKE_ELASTIC(final int passes)
        {
            return new AnimationTweener()
            {
                @Override
                public double tween(double percent)
                {
                    return (((1.0 - Math.cos(percent * Math.PI * passes)) * (1.0 - percent)) + percent);
                }
            };
        }

        public static final AnimationTweener MAKE_BOUNCE(int bounces)
        {
            final AnimationTweener elastic = MAKE_ELASTIC(bounces);

            return new AnimationTweener()
            {
                @Override
                public double tween(double percent)
                {
                    percent = elastic.tween(percent);

                    return ((percent <= 1.0) ? (percent) : (2.0 - percent));
                }
            };
        }
    }
}


text:
package meli

//Client struct
type Client struct {
	GrantType    string `json:"grant_type,omitempty"`
	Code         string `json:"code"`
	ClientID     int    `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	RedirectUri  string `json:"redirect_uri"`
	MLToken      MLToken
}

//MLToken struct
type MLToken struct {
	AccessToken  string `json:"access_token,omitempty"`
	TokenType    string `json:"token_type,omitempty"`
	ExpiresIn    int    `json:"expires_in,omitempty"`
	Scope        string `json:"scope,omitempty"`
	UserId       int    `json:"user_id,omitempty"`
	RefreshToken string `json:"refresh_token,omitempty"`
}

//MLError struct
type MLError struct {
	Message string `json:"message"`
	Error   string `json:"error"`
	Status  int    `json:"status"`
}

//New
func New(clientID int, clientSecret string) *Client {
	return &Client{
		ClientID:     clientID,
		ClientSecret: clientSecret,
	}
}

//NewWithAccessToken
func NewWithAccessToken(clientID int, clientSecret, accessToken, refreshToken string) *Client {
	return &Client{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		MLToken: MLToken{
			AccessToken:  accessToken,
			RefreshToken: refreshToken,
		},
	}
}


text:
interface StrategyOverrides {
    shouldRejectClick?: (lastTouchEventTimestamp: Date, clickEventTimestamp: Date) => boolean;
}

declare var injectTapEventPlugin: (strategyOverrides?: StrategyOverrides) => void;

export = injectTapEventPlugin;


text:
const {ipcRenderer} = require('electron');
process.once('loaded', function() {
  global.ipc= ipcRenderer;
});


text:
layout: post
title: "Language"
description: ""
category:
tags: []
---
{% include JB/setup %}

## Unicode Han Database (Unihan)
- [Unihan](http://www.unicode.org/reports/tr38/)
- [Unihan Database Lookup](http://unicode.org/charts/unihan.html)

## CEDICT
[CEDICT](http://cc-cedict.org/wiki/)
[CEDICT Format](http://cc-cedict.org/wiki/format:syntax)
[Hanzi to Pinyin Online Tool](http://www.mdbg.net/chindict/chindict.php)

## Chinese to Pinyin
- [pinyin4j](https://github.com/belerweb/pinyin4j)

### Cjklib
- [Home Page](http://cjklib.org/)
- [Pypi Index](https://pypi.python.org/pypi/cjklib/0.3.2)

Make sure `SQLite 3+` and `SQLAlchemy 0.5+` are installed.

The following code:

```
# -*- coding: utf-8 -*-
import cjklib
from cjklib.characterlookup import CharacterLookup

c = u'好'

cjk = CharacterLookup('T')
readings = cjk.getReadingForCharacter(c, 'Pinyin')
for r in readings:
    print r
```
produce:
```
hāo
hǎo
hào
```

```
>>> from cjklib import characterlookup
>>> cjk = characterlookup.CharacterLookup('C')
>>> cjk.getStrokeOrder(u'说')
[u'\u31d4', u'\u31ca', u'\u31d4', u'\u31d2', u'\u31d1', u'\u31d5', u'\u31d0', u'\u31d3', u'\u31df']
```

The code for `Access a dictionary` in pypi page does work.

```
>>> from cjklib.dictionary import EDICT
>>> d = EDICT()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/cjklib-0.3.2-py2.7.egg/cjklib/dictionary/__init__.py", line 271, in __init__
    % self.DICTIONARY_TABLE)
```

Stackoverfow has a
[solution](http://stackoverflow.com/questions/10476140/after-successful-installation-of-cjklib-and-cedict-when-i-use-it-it-throw-erro)

```
>>> from cjklib.dictionary import CEDICT
>>> from cjklib.dbconnector import getDBConnector
>>> db = getDBConnector({'sqlalchemy.url': 'sqlite://', 'attach': ['cjklib']})
>>> d=CEDICT(dbConnectInst=db)
>>> it=d.getFor(u'朋友')
>>> it
<itertools.imap object at 0x7fa2d30cb050>
>>> for x in it:
...   print x
...
EntryTuple(HeadwordTraditional=u'\u670b\u53cb',
HeadwordSimplified=u'\u670b\u53cb', Reading=u'p\xe9ng you',
Translation=u'/friend/CL:\u500b|\u4e2a[ge4],\u4f4d[wei4]/')
```

## Encoding Conversion
JSON uses UTF-8 by default. For Unicode code points in the range of
U+0000 to U+FFFF, a single esape is enough. For code points in the range
of U+10000 to U+10FFFF, two escapes using UTF-16 are needed.

```
Face with tears of joy:  😂
Unicode code point: U+1F602
UTF-16:
  encoding: D83D DE02
  escapes: \uD83D\uDE02
  showed in xxd: 3DD8 02DE
  showed in xxd with a BOM: FFFE 3DD8 02DE, BOM is FEFF
  UTF-8: F09F9882
  showed with xxd -u:
    0000000: F09F 9882
```


text:
package com.ua.viktor.amp.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.facebook.stetho.okhttp.StethoInterceptor;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ua.viktor.amp.R;
import com.ua.viktor.amp.activity.DecoderActivity;
import com.ua.viktor.amp.activity.TestActivity;
import com.ua.viktor.amp.dao.Choice;
import com.ua.viktor.amp.dao.ChoiceDao;
import com.ua.viktor.amp.dao.DaoMaster;
import com.ua.viktor.amp.dao.DaoSession;
import com.ua.viktor.amp.dao.Question;
import com.ua.viktor.amp.dao.QuestionDao;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

public class HomeFragment extends Fragment {

    public static final String TAG = HomeFragment.class.getName();
    private ImageButton mQrButton;
    private Button mEnterButton;
    private boolean isEnterValid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        mQrButton = (ImageButton) view.findViewById(R.id.imageButton);
        mEnterButton = (Button) view.findViewById(R.id.button);

        final EditText editText = (EditText) view.findViewById(R.id.code);
        editText.setCursorVisible(false);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                validateEnter(s.toString());
                updateEnterButtonState();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mEnterButton.setEnabled(false); // default state should be disabled

        if (!isNetworkOn(getActivity())) {
            Toast.makeText(getActivity(),
                    "No network connection", Toast.LENGTH_SHORT).show();
        } else {

            mQrButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent = new Intent(getActivity(), DecoderActivity.class);
                    startActivity(intent);
                }
            });

            mEnterButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getActivity(), "lease-db", null);
                    SQLiteDatabase db = helper.getWritableDatabase();
                    DaoMaster daoMaster = new DaoMaster(db);
                    DaoSession daoSession = daoMaster.newSession();
                    ChoiceDao leaseDao = daoSession.getChoiceDao();

                    String id = editText.getText().toString();

                    List<Choice> mChoices = leaseDao._queryQuestion_Question(Long.parseLong(id));
                    if (mChoices.isEmpty()) {
                        getTestData(id);
                    } else {
                        onTestDataExisted();
                    }
                    final ProgressDialog progressDialog = new ProgressDialog(getActivity());
                    progressDialog.setIndeterminate(true);
                    progressDialog.setMessage("Request...");
                    progressDialog.show();
                    new android.os.Handler().postDelayed(
                            new Runnable() {
                                public void run() {
                                    // On complete call either onLoginSuccess or onLoginFailed
                                    // onLoginSuccess();
                                    // onLoginFailed();
                                    progressDialog.dismiss();
                                }
                            }, 1000);
                }
            });

        }

        return view;
    }

    public void onTestDataFailed() {
        Toast.makeText(getActivity(), "Request failed", Toast.LENGTH_SHORT).show();
    }

    public void onTestDataExisted() {
        Toast.makeText(getActivity(), "Request failed,quiz exist", Toast.LENGTH_SHORT).show();
    }

    public void getTestData(final String id) {
        String movieUrl = "http://192.168.57.1:3000/questions/" + id;
        if (isNetworkOn(getActivity())) {
            OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url(movieUrl)
                    .addHeader("Accept", "application/json")
                    .build();
            client.networkInterceptors().add(new StethoInterceptor());
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                             @Override
                             public void onFailure(Request request, IOException e) {
                                 Log.v("ERRor", "lolka");
                             }

                             @Override
                             public void onResponse(Response response) throws IOException {
                                 try {
                                     if (response.isSuccessful()) {
                                         final String json = response.body().string();
                                         Log.v("JSON", json);
                                         if (!json.isEmpty()) {

                                             getQuestionData(json, id);
                                         }
                                         getActivity().runOnUiThread(new Runnable() {
                                             @Override
                                             public void run() {
                                                 //    movieUI();
                                                 if (!json.isEmpty()) {
                                                     Intent intent = new Intent(getActivity(), TestActivity.class);
                                                     intent.putExtra(TAG, id);
                                                     intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                                                     startActivity(intent);
                                                 } else {
                                                     onTestDataFailed();
                                                 }
                                             }
                                         });
                                     }
                                 } catch (IOException e) {
                                     Log.e(TAG, "EROR", e);
                                 } catch (JSONException e) {
                                     e.printStackTrace();
                                 }

                             }
                         }

            );
        } else {
            Toast.makeText(getActivity(), "Network isn't available", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean isNetworkOn(Context context) {
        ConnectivityManager connMgr =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

    private void updateEnterButtonState() {
        if (isEnterValid) {
            mEnterButton.setEnabled(true);
        } else {
            mEnterButton.setEnabled(false);
        }
    }

    private void validateEnter(String text) {
        isEnterValid = !text.isEmpty();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void getQuestionData(String jsonData, String id) throws JSONException {

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getActivity(), "lease-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        ChoiceDao leaseDao = daoSession.getChoiceDao();

        List<Choice> mChoices = leaseDao._queryQuestion_Question(Long.parseLong(id));

        if (mChoices.isEmpty()) {
            JSONObject jsonObject = new JSONObject(jsonData);

            Question question = new Question();
            question.setText(jsonObject.getString("text"));
            question.setID(jsonObject.getInt("id"));
            question.setId(Long.parseLong(id));

            JSONArray data = jsonObject.getJSONArray("choices");

            ArrayList<Choice> notes = new ArrayList<Choice>();

            for (int i = 0; i < data.length(); i++) {
                JSONObject jsonChoices = data.getJSONObject(i);
                Choice choice = new Choice();
                choice.setCount(0);
                choice.setItem(jsonChoices.getString("text"));
                choice.setID(jsonChoices.getInt("id"));
                choice.setQuestionId(Long.parseLong(id));
                notes.add(choice);

            }

            ChoiceDao choiceDao = daoSession.getChoiceDao();
            choiceDao.insertInTx(notes);
            QuestionDao questionDao = daoSession.getQuestionDao();
            questionDao.insertOrReplace(question);
        }
    }

}


text:
            Nom:
            <input type="text" class="alright"  name="attr_CharacterName" value="Nom du Personnage" />

            Niveau:
            <input type="number" class="alright" name="attr_Level" class="short" value="1"/>

            Experience:
            <input type="number" name="attr_Experience" class="medium" value="0"/>XP

            Classe:
            <input type="text" name="attr_Class" value="Classe" />

            Origine:
            <input type="text" name="attr_Race" value="Race" />

            Langue(s) Parlée(s)
            <input type="text" name="attr_Langue" value="Commun" />

            Point(s) de Resistance:
            <input type="number" name="attr_PR" value="0"> / <input type="number" name="attr_PRMax" value="0" class="boldme alcenter">PR

            Energie Vitale :
            <input type="number" name="attr_EV" style="text-align: left;" value="0" /> / <input type="number" name="attr_EVMax" style="text-align: left;" value="0" class="boldme alleft">PV

            Energie Astrale :
            <input type="number" name="attr_EA" value="0" /> / <input type="number" name="attr_EAMax" value="0" class="boldme alcenter">PA

            Point(s) de Destin :
            <input type="number" name="attr_PointDestin" class="medium" value="0"/>

            Monnaie :

            <input type="number" name="attr_PO" class="medium" value="0"/> Or

            <input type="number" name="attr_PA" class="medium" value="0"/> Argent

            Caracteristiques
            Calcul
            Valeur
            + / -
            Epreuve

            Courage
            1D6+7
            <input type="number" name="attr_Courage" value="0">
            <input type="number" name="attr_CourageMod" value="0">
            <button type="roll" value="/roll d20<[[@{Courage}+@{CourageMod}]] (Epreuve de Courage)"/>

            Intelligence
            1D6+7
            <input type="number" name="attr_Intelligence" value="0">
            <input type="number" name="attr_IntelligenceMod" value="0">
            <button type="roll" value="/roll d20<[[@{Intelligence}+@{IntelligenceMod}]] (Epreuve d'Intelligence)"/>

            Charisme
            1D6+7
            <input type="number" name="attr_Charisme" value="0" >
            <input type="number" name="attr_CharismeMod" value="0" >
            <button type="roll" value="/roll d20<[[@{Charisme}+@{CharismeMod}]] (Epreuve de Charisme)"/>

            Adresse
            1D6+7
            <input type="number" name="attr_Adresse" value="0">
            <input type="number" name="attr_AdresseMod" value="0">
            <button type="roll" value="/roll d20<[[@{Adresse}+@{AdresseMod}]] (Epreuve d'Adresse)"/>

            Force
            1D6+7
            <input type="number" name="attr_Force" value="0">
            <input type="number" name="attr_ForceMod" value="0">
            <button type="roll" value="/roll d20<[[@{Force}+@{ForceMod}]] (Epreuve de Force)"/>

            Resistance Magique
            Moy. COU/INT/FO
            <input type="number" name="attr_ResiMagie" value="ceil((@{Courage}+@{Intelligence}+@{Force})/3)" disabled="true">
            <input type="number" name="attr_ResiMagieMod" value="0">
            <button type="roll" value="/roll d20<[[@{ResiMagie}+@{ResiMagieMod}]] (Resitance à la Magie)"/>

            Attaque
            "Origine/Metier"
            <input type="number" name="attr_ValAttaque" value="0">
            <input type="number" name="attr_ValAttaqueMod" value="0">
            <button type="roll" value="/roll d20<[[@{ValAttaque}+@{ValAttaqueMod}]] (Epreuve d'Attaque)"/>

            Parade
            "Origine/Metier"
            <input type="number" name="attr_ValParade" value="0">
            <input type="number" name="attr_ValParadeMod" value="0">
            <button type="roll" value="/roll d20<[[@{ValParade}+@{ValParadeMod}]] (Epreuve de Parade)"/>

            Magie Physique
            Moy. INT/AD
            <input type="number" name="attr_MagiePhy" value="ceil((@{Intelligence}+@{Adresse})/2)" disabled="true"/>
            <input type="number" name="attr_MagiePhyMod" value="0">
            <button type="roll" value="/roll d20<[[@{MagiePhy}+@{MagiePhyMod}]] (Epreuve de Magie Physique)"/>

            Magie Psychique
            Moy. INT/CHA
            <input type="number" name="attr_MagiePsy" value="ceil((@{Intelligence}+@{Charisme})/2)" disabled="true">
            <input type="number" name="attr_MagiePsyMod" value="0">
            <button type="roll" value="/roll d20<[[@{MagiePsy}+@{MagiePsyMod}]] (Epreuve de Magie Psychique)"/>

Informations Récuperation et Prise de Niveau

<input class="sheet-useUp" type="checkbox" name="attr_showUp">

Énergie vitale

            De base, 1 point récupéré pour deux heures de repos, règle sujette aux modifications suivantes :

            ➢ Récupération basse en mauvaises conditions de sommeil ou repos : 1 PV/4H

            ➢ Récupération normale : 1 PV/2H

            ➢ Récupération excellente, en bonne condition de sommeil ou repos : 1PV/1H

            Repas : Comptez également 2 points de vie récupérés par repas (maximum 3 par jour)

Énergie Astrale

            De base, 3 points récupérés pour une heure de repos, règle sujette aux modifications suivantes :

            ➢ Récupération basse en mauvaises conditions de sommeil ou repos : 2 PA/1H

            ➢ Récupération normale : 3 PA/1H

            ➢ Récupération excellente, en bonne condition de sommeil ou repos : 4PA/1H

            Étude : 4 points récupérés pour une heure d'étude (lecture de livre, prière, passage dans une guilde, etc.)

Prise de Niveau

            Pour chaque niveau gagné : Ajouter 1D6 à son énergie vitale OU astrale

                A chaque niveau pairs : Ajouter 1 point au choix sur un score de base de : FORCE, ADRESSE, COURAGE, INTELLIGENCE

                A chaque niveau impairs : Ajouter 1 point au choix sur le score de base d'ATTAQUE ou sur le score de base de PARADE

                Au niveau 3 : Choisir une compétence supplémentaire

                Au niveau 5 : Deuxieme spécialisation pour un mage

                Au niveau 6 : Choisir une compétence supplémentaire

                Au niveau 10 : Choisir une compétence supplémentaire

                Au niveau 10 : Troisieme Spécialisation pour un mage

Experience/Niveau

                0 / 1

                100 / 2

                300 / 3

                600 / 4

                1000 / 5

                1500 / 6

                2100 / 7

                2800 / 8

                3600 / 9

                4500 / 10

                9100 / 14

                10500 / 15

                12000 / 16

                13600 / 17

                15300 / 18

                17100 / 19

                19000 / 20

                21000 / 21

                24000 / 22

                29000 / 23

                35000 / 24

                45000 / 25

Dégats Physique

<input class="sheet-useCac" type="checkbox" name="attr_showCac">

Lancers de dés

Nom de l'arme

AT

PRD

? x D6

+ ?

    <fieldset class="repeating_cac">

				<button type="roll" value="/roll {1d20}<[[@{ValAttaque}+@{ValAttaqueMod}+@{ArmeAT}]] Attaque avec @{ArmeNom}" name="roll_ArmeAttaque" /> Attaque

                <button type="roll" value="/roll {1d20}<[[@{ValParade}+@{ValParadeMod}+@{ArmePRD}]] Pare avec @{ArmeNom}" name="roll_ArmeAttaque" /> Parade

                <button type="roll" value="/roll @{ArmeDes}d6+@{ArmeDegats} Blesse à hauteur de" name="roll_SpellDmgOne"/> Dégats

				<input type="text" name="attr_ArmeNom" value="" style="width: 200px;"/>

				<input type="number" name="attr_ArmeAT" value="0" style="width: 50px;" />

				<input type="number" name="attr_ArmePRD" value="0" style="width: 50px;" />

				<input type="number" name="attr_ArmeDes" value="0" style="width: 50px;" />

				<input type="number" name="attr_ArmeDegats" value="0" style="width: 50px;" />

	</fieldset>

    Pour chaque point de FORCE supérieur à 12 : +1 point d'impact

        Si l'ADRESSE est supérieure à 12 : +1 à l'attaque OU à la parade (un seul point quel que soit le score)

Dégats Magique

<input class="sheet-useSpells" type="checkbox" name="attr_showSpells">

Lancers de dés

Nom du sort

Type de Magie

Incantation
(? x D6)

Incantation
 (+ ?)

Dégats
(? x D6)

Dégats
(+ ?)

Cout

	<fieldset class="repeating_spells">

				<button type="roll" value="/roll {1d20}<[[@{MagieType}+@{SortDesAttaque_1}d6+@{SortDesBonusAttaque_1}]] Incantation @{SortNom_1}" name="roll_SortAttaque_1" /> Incanter
				<button type="roll" value="/roll @{SortDegatDes_1}d6+@{SortDegatBonus_1} Blesse à hauteur de" name="roll_SpellDmgOne"/> Dégats

				<input type="text" name="attr_SortNom_1" value="" style="width: 170px;"/>

                <select name="attr_MagieType" style="width: 70px;">
		            <option value="[[@{MagiePhy}]]">Phy.</option>
		            <option value="[[@{MagiePsy}]]">Psy.</option>
                </select>

				<input type="number" name="attr_SortDesAttaque_1" value="0" style="width: 60px;" />

    			<input type="number" name="attr_SortDesBonusAttaque_1" value="0" style="width: 60px;" />

				<input type="number" name="attr_SortDegatDes_1" value="1" style="width: 55px;" />

				<input type="number" name="attr_SortDegatBonus_1" value="0" style="width: 55px;" />

				<input type="number" name="attr_SortCout_1" value="0" style="width: 55px;" />

	</fieldset>

    Pour chaque point d'INTELLIGENCE supérieur à 12 : +1 point de dégâts des sorts (selon sortilège)

Invocation

<input class="sheet-useInvoc" type="checkbox" name="attr_showInvoc">

Lancers de dés

Nom de la créature

Magie Psy.
 + / -

Contrôle
(? x D6)

Révocation
(? x D6)

Cout

	<fieldset class="repeating_spells">

                <button type="roll" value="/roll {1d20}<[[@{MagiePsy}+@{InvocBonus_1}]] Invoque @{CreatureNom_1}" name="roll_Invoquer_1" /> Invoquer
				<button type="roll" value="[[@{MagiePsy}+@{InvocControle_1}d6]] Tente de contrôler @{CreatureNom_1}" name="roll_Controle_1" /> Controler
				<button type="roll" value="[[@{MagiePsy}+@{InvocRevoc_1}d6]] Tente de révoquer @{CreatureNom_1}" name="roll_Revoquer_1"/> Révoquer

				<input type="text" name="attr_CreatureNom_1" value="" style="width: 170px;"/>

                <input type="number" name="attr_InvocBonus_1" value="0" style="width: 75px;" />

				<input type="number" name="attr_InvocControle_1" value="0" style="width: 60px;" />

    			<input type="number" name="attr_InvocRevoc_1" value="0" style="width: 60px;" />

				<input type="number" name="attr_InvocCout_1" value="0" style="width: 55px;" />

	</fieldset>

    L'invocation en 3 étapes :

            1) Appel de la créature : Une simple épreuve utilisant la Magie Psychique (Bonus/Malus)

            2) Contrôle de la créature : MagiePsy contre Res. Magie : le mage confronte son score de MagiePsy (+2D6) à la Résistance à la Magie de la créature (+2D6).

            3) Révocation de la créature : MagiePsy contre Res. Magie : le mage confronte son score de MagiePsy (+3D6) à la Résistance à la Magie de la créature (+3D6)

            Attention à l'horloge : Le contrôle sur une créature invoquée doit être testé toutes les heures.

Arme(s)

            <input type="text" name="attr_Arme01" class="long" />
            <input type="text" name="attr_Arme02" class="long" />
            <input type="text" name="attr_Arme03" class="long" />
            <input type="text" name="attr_Arme04" class="long" />
                <fieldset class="repeating_Arme">
                  <input type="text" name="attr_Armes" class="long" />
                </fieldset>

Protection(s)/Equipement(s)

            <input type="text" name="attr_Equip01" class="long" />
            <input type="text" name="attr_Equip02" class="long" />
            <input type="text" name="attr_Equip03" class="long" />
            <input type="text" name="attr_Equip04" class="long" />
               <fieldset class="repeating_Equipement">
                  <input type="text" name="attr_Equipement" class="long" />
               </fieldset>

Inventaire

<input class="sheet-useInventaire" type="checkbox" name="attr_showInventaire">

            <input type="text" name="attr_Inv01" class="long" />
            <input type="text" name="attr_Inv02" class="long" />
            <input type="text" name="attr_Inv03" class="long" />
            <input type="text" name="attr_Inv04" class="long" />
                <fieldset class="repeating_Inventaire">
                    <input type="text" name="attr_Inventaire" class="long" />
                </fieldset>

Compétence(s) Innée(s)

            <input type="text" name="attr_RaceAbility01" class="long" />
            <input type="text" name="attr_RaceAbility02" class="long" />
            <input type="text" name="attr_RaceAbility03" class="long" />
            <input type="text" name="attr_RaceAbility04" class="long" />
               <fieldset class="repeating_CompIn">
                  <input type="text" name="attr_CompIn" class="long" />
               </fieldset>

Compétence(s) Acquise(s)

            <input type="text" name="attr_ClassAbility01" class="long" />
            <input type="text" name="attr_ClassAbility02" class="long" />
            <input type="text" name="attr_ClassAbility03" class="long" />
            <input type="text" name="attr_ClassAbility04" class="long" />
               <fieldset class="repeating_classabilities">
                  <input type="text" name="attr_ClassAbilities" class="long" />
               </fieldset>

Résumé des Compétences

<input class="sheet-useComp" style="text-align:center;" type="checkbox" style="vertical-align:middle;" name="attr_showComp">


text:
layout: conference_by_tag
tag: interoperability
permalink: conferences/tag/interoperability/
---


text:
package eu.leads.processor.common.infinispan;

import org.infinispan.notifications.cachelistener.filter.CacheEventConverter;
import org.infinispan.notifications.cachelistener.filter.CacheEventConverterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by vagvaz on 9/29/14.
 */
public class LeadsProcessorConverterFactory implements CacheEventConverterFactory{
//public class LeadsProcessorConverterFactory implements ConverterFactory {

    Logger log = LoggerFactory.getLogger(LeadsProcessorConverterFactory.class);

    @Override
     public <K, V, C> CacheEventConverter<K, V, C> getConverter(Object[] objects) {
        log.error("Get Converter Called");
        return new LeadsProcessorConverter();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ * Copyright 2018 Red Hat, Inc. and/or its affiliates
  ~ * and other contributors as indicated by the @author tags.
  ~ *
  ~ * Licensed under the Apache License, Version 2.0 (the "License");
  ~ * you may not use this file except in compliance with the License.
  ~ * You may obtain a copy of the License at
  ~ *
  ~ * http://www.apache.org/licenses/LICENSE-2.0
  ~ *
  ~ * Unless required by applicable law or agreed to in writing, software
  ~ * distributed under the License is distributed on an "AS IS" BASIS,
  ~ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ * See the License for the specific language governing permissions and
  ~ * limitations under the License.
  -->

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>org.keycloak.testsuite.adapter.servlet.CustomerServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Error Servlet</servlet-name>
        <servlet-class>org.keycloak.testsuite.adapter.servlet.ErrorServlet</servlet-class>
    </servlet>

    <filter>
        <filter-name>AdapterActionsFilter</filter-name>
        <filter-class>org.keycloak.testsuite.adapter.filter.AdapterActionsFilter</filter-class>
    </filter>

    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>Error Servlet</servlet-name>
        <url-pattern>/error.html</url-pattern>
    </servlet-mapping>

    <filter-mapping>
        <filter-name>AdapterActionsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Users</web-resource-name>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>user</role-name>
        </auth-constraint>
    </security-constraint>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Errors</web-resource-name>
            <url-pattern>/error.html</url-pattern>
        </web-resource-collection>
    </security-constraint>
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Unsecured</web-resource-name>
            <url-pattern>/unsecured/*</url-pattern>
        </web-resource-collection>
    </security-constraint>

    <login-config>
        <auth-method>KEYCLOAK</auth-method>
        <realm-name>demo</realm-name>
    </login-config>

    <security-role>
        <role-name>user</role-name>
    </security-role>
</web-app>


text:
package au.com.gridstone.grex;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
 * Class which can provide {@link java.io.Reader} and {@link java.io.Writer}
 * instances as well as clear any storage for a given key.
 *

 * Most uses of this interface will probably use the {@link FileIODelegate}
 * implementation.
 *
 * @author Joseph Cooper
 */
public interface IODelegate {

    /**
     * Returns a {@link java.io.Reader} to allow reading from the storage
     * associated with the given key.
     *

     * Should return null if and only if there is no storage for the given key.
     *
     * @param key the key to look up in storage.
     */
    public Reader getReader(final String key) throws IOException;

    /**
     * Returns a {@link java.io.Writer} to allow writing to the storage
     * associated with the given key.
     *

     * Must not return null.
     *
     * @param key the key to use to write to storage.
     */
    public Writer getWriter(final String key) throws IOException;

    /**
     * Deletes the storage associated to the the given key.
     *
     * @param key the key to clear
     * @return true if the storage was deleted
     */
    public boolean clear(final String key);

}


text:
require_relative '../../../../../lib/objects/local_string_encoder.rb'
require 'sshkey'
class SSHKeyPairGenerator < StringEncoder

  def initialize
    super
    self.module_name = 'SSH Key Pair Generator'
  end

  def encode_all
    key = SSHKey.generate(type: "RSA", bits: 2048)
    self.outputs << {'private' => key.private_key, 'public' => key.ssh_public_key}.to_json
  end

end

SSHKeyPairGenerator.new.run


text:
package com.github.mdr.mash.subprocesses

import java.io.{ IOException, PrintStream }
import java.lang.ProcessBuilder.Redirect
import java.nio.charset.StandardCharsets
import java.nio.file.Path
import java.time.Instant

import com.github.mdr.mash.Singletons
import com.github.mdr.mash.evaluator.{ EvaluatorException, ToStringifier }
import com.github.mdr.mash.runtime.MashValue
import com.github.mdr.mash.terminal.ansi.EscapeSequence
import org.apache.commons.io.IOUtils

object ProcessRunner {

  private val terminalControl = Singletons.terminalControl
  private val output: PrintStream = System.out

  def runProcess(args: Seq[MashValue],
                 captureProcess: Boolean = false,
                 stdinRedirectOpt: Option[Path] = None,
                 stdinImmediateOpt: Option[String] = None,
                 stdoutRedirectOpt: Option[Path] = None): ProcessResult = {
    val stringArgs = args.map(ToStringifier.stringify)
    val outputRedirect = getOutputRedirect(captureProcess, stdoutRedirectOpt)
    val inputRedirect = getInputRedirect(stdinRedirectOpt, stdinImmediateOpt)
    terminalControl.externalProcess {
      val builder = new ProcessBuilder(stringArgs: _*)
        .redirectInput(inputRedirect)
        .redirectOutput(outputRedirect)
        .redirectError(ProcessBuilder.Redirect.INHERIT)
      setEnvironment(builder.environment())
      val start = Instant.now
      val process =
        try
          builder.start()
        catch {
          case e: IOException ⇒ throw EvaluatorException(e.getMessage)
        }

      for (stdinImmediate ← stdinImmediateOpt)
        writeStdinImmediate(process, stdinImmediate)

      val stdout = if (captureProcess) IOUtils.toString(process.getInputStream, StandardCharsets.UTF_8) else ""

      val statusCode = process.waitFor()
      val stop = Instant.now
      clearPartialOutput()

      ProcessResult(statusCode, stdout, start, stop)
    }
  }

  // Clear out any partial output
  def clearPartialOutput() {
    output.write(("\r" + EscapeSequence.EraseLineFromCursor).getBytes)
    output.flush()
  }

  def writeStdinImmediate(process: Process, stdinImmediate: String): Unit = {
    IOUtils.write(stdinImmediate, process.getOutputStream, StandardCharsets.UTF_8)
    process.getOutputStream.close()
  }

  def getOutputRedirect(captureProcess: Boolean, stdoutRedirectOpt: Option[Path]): Redirect = {
    stdoutRedirectOpt match {
      case Some(path)          ⇒ ProcessBuilder.Redirect.to(path.toFile)
      case _ if captureProcess ⇒ ProcessBuilder.Redirect.PIPE
      case _                   ⇒ ProcessBuilder.Redirect.INHERIT
    }
  }

  def getInputRedirect(stdinRedirectOpt: Option[Path], stdinImmediateOpt: Option[String]): Redirect = {
    stdinRedirectOpt match {
      case Some(path) ⇒ ProcessBuilder.Redirect.from(path.toFile)
      case _          ⇒
        stdinImmediateOpt match {
          case Some(_) ⇒ ProcessBuilder.Redirect.PIPE
          case _       ⇒ ProcessBuilder.Redirect.INHERIT
        }
    }
  }

  private def setEnvironment(env: java.util.Map[String, String]) = {
    env.clear()
    for ((k, v) ← Singletons.environment.immutableFields)
      env.put(ToStringifier.stringify(k), ToStringifier.stringify(v))
  }

}

case class ProcessResult(exitStatus: Int, stdout: String, start: Instant, stop: Instant)