text:
module.exports.createCommands = (world) => {
  return [
    new world.Command({
      name: `look`,
      positions: world.constants().positionsAwake,
      execute: async (world, user, buffer, args) => {
        if ( typeof args[0] == `string` ) {
          /** If the first argument is 'in'... */
          if ( `in`.startsWith(args[0]) ) {
            /** If no second argument was provided, send error and return */
            if ( typeof args[1] != `string` ) {
              user.send(`Look in what?\r\n`);
              return;
            }

            /** Parse container name and count from second argument */
            const [name, count] = world.parseName(user, args, 1);

            /** Create array of all items in user's inventory with name matching second argument */
            let items = user.inventory().filter(x => x.names().some(y => y.toLowerCase().startsWith(name)));

            /** Concatenate with all items in user's equipment with name matching second argument  */
            items = items.concat(user.room().items().filter(x => x.names().some(y => y.toLowerCase().startsWith(name))));

            /** If number of items is less than count, send error */
            if ( items.length < count ) {
              user.send(`You can't find that item anywhere.\r\n`);
            }

            /** Otherwise, if item is not a container, send error */
            else if ( !items[count - 1].flags().includes(world.constants().itemFlags.CONTAINER) ) {
              user.send(`That item is not a container.\r\n`);
            }

            /** Otherwise... */
            else {
              /** Send header for container contents */
              user.send(`Contents of ${items[count - 1].name()}:\r\n`);

              /** Keep track of items already included in item counts */
              const itemsIncluded = [];

              /** Loop through each item in container */
              items[count - 1].contents().forEach((content) => {
                /** If item is already included, skip it */
                if ( itemsIncluded.includes(content.name()) )
                  return;

                /** Count number of items of the same name in the container */
                const numItems = items[count - 1].contents().filter(x => x.name() == content.name()).length;

                /** If the number of items is greater than, send quantity and name */
                if ( numItems > 1 )
                  user.send(`  (${numItems}) ${content.name()}\r\n`);

                /** Otherwise, just send name */
                else
                  user.send(`  ${content.name()}\r\n`);

                /** Add item to items included */
                itemsIncluded.push(content.name());
              });

              /** If there are no items in the container, send none */
              if ( items[count - 1].contents().length == 0 )
                user.send(`  None\r\n`);
            }
          }

          /** Otherwise... */
          else {
            /** Parse container name and count from argument */
            const [name, count] = world.parseName(user, args, 0);

            /** Create array of users with name matching the arugment */
            const users = user.room().users().filter(x => x.name().toLowerCase().startsWith(name) || ( name == `self` && x == user ) );

            /** Create array of mobiles with name matching the arugment */
            const mobiles = user.room().mobiles().filter(x => x.names().some(y => y.toLowerCase().startsWith(name)));

            /** Create array of items in user's inventory with name matching the arugment */
            const inventory = user.inventory().filter(x => x.names().some(y => y.toLowerCase().startsWith(name)));

            /** Create array of items in user's equipemnt with name matching the arugment */
            const equipment = user.equipment().filter(x => x.names().some(y => y.toLowerCase().startsWith(name)));

            /** Create array of items in user's room with name matching the arugment */
            const items = user.room().items().filter(x => x.names().some(y => y.toLowerCase().startsWith(name)));

            /** Create array of all characters and items with name matching the argument combined */
            const targets = users.concat(mobiles.concat(inventory.concat(equipment.concat(items))));

            /** If number of targets is less than count, send error and return */
            if ( targets.length < count )
              return user.send(`You can't find that anywhere.\r\n`);

            /** Define target */
            const target = targets[count - 1];

            /** If the target is a user... */
            if ( target instanceof world.User ) {
              /** Send target user's name */
              user.send(`${target.name()} is standing here.\r\n\r\n`);

              /** Send target user's equipment */
              world.sendUserEquipment(user, target);
            }

            /** Otherwise, if target is a mobile... */
            else if ( target instanceof world.MobileInstance ) {
              /** Send target mobile's description */
              user.send(`${world.terminalWrap(world.colorize(target.name()))}\r\n`);
              user.send(`${world.terminalWrap(world.colorize(target.description()))}\r\n\r\n`);

              /** Send target mobile's equipment */
              world.sendUserEquipment(user, target);
            }

            /** Otherwise, if there is a second argument */
            else if ( typeof args[1] == `string` ) {
              /** If the detail name is not valid, send error */
              if ( !args[1].match(/^[a-z0-9]+$/i) )
                return user.send(`You can't find that anywhere.\r\n`);

              /** Parse detail name and count */
              const [detailName, detailCount] = world.parseName(user, args, 1);

              /** Attempt to find detail on target */
              const detail = Object.keys(target.details()).filter(x => x.startsWith(detailName))[detailCount - 1];

              /** If detail doesn't exist, send error */
              if ( !detail )
                return user.send(`You can't find that anywhere.\r\n`);

              /** Send detail description */
              user.send(`${world.terminalWrap(world.colorize(target.details()[detail]))}\r\n`);
            }

            /** Otherwise... */
            else {
              /** Send item description */
              user.send(`${world.terminalWrap(world.colorize(target.description()))}\r\n`);

              /** Define array of stats */
              const stats = [target.accuracy(), target.air(), target.armor(), target.deflection(), target.dodge(),
                             target.earth(), target.fire(), target.life(), target.power(), target.speed(), target.water()];

              if ( stats.some(x => x > 0) )
                user.send(`\r\n`);

              /** If the target is an item... */
              if ( target instanceof world.ItemInstance ) {
                /** If the item has accuracy, show it */
                if ( target.accuracy() > 0 )
                  user.send(world.colorize(`  #OAccuracy#n    +${target.accuracy()}\r\n`));

                /** If the item has air, show it */
                if ( target.air() > 0 )
                  user.send(world.colorize(`  Air         +${target.air()}\r\n`));

                /** If the item has armor, show it */
                if ( target.armor() > 0 )
                  user.send(world.colorize(`  #KArmor#n       +${target.armor()}\r\n`));

                /** If the item has deflection, show it */
                if ( target.deflection() > 0 )
                  user.send(world.colorize(`  #PDeflection#n  +${target.deflection()}\r\n`));

                /** If the item has dodge, show it */
                if ( target.dodge() > 0 )
                  user.send(world.colorize(`  #cDodge#n       +${target.dodge()}\r\n`));

                /** If the item has earth, show it */
                if ( target.earth() > 0 )
                  user.send(world.colorize(`  #yEarth#n       +${target.earth()}\r\n`));

                /** If the item has fire, show it */
                if ( target.fire() > 0 )
                  user.send(world.colorize(`  #RFire#n        +${target.fire()}\r\n`));

                /** If the item has life, show it */
                if ( target.life() > 0 )
                  user.send(world.colorize(`  #gLife#n        +${target.life()}\r\n`));

                /** If the item has power, show it */
                if ( target.power() > 0 )
                  user.send(world.colorize(`  #oPower#n       +${target.power()}\r\n`));

                /** If the item has speed, show it */
                if ( target.speed() > 0 )
                  user.send(world.colorize(`  #YSpeed#n       +${target.speed()}\r\n`));

                /** If the item has water, show it */
                if ( target.water() > 0 )
                  user.send(world.colorize(`  #BWater#n       +${target.water()}\r\n`));
              }

              /** Create array of detail keys */
              const keys = Object.keys(target.details());

              /** If there are details, output heading */
              if ( keys.length > 0 )
                user.send(`\r\nDetails: `);

              /** Loop through each detail key and output */
              keys.forEach((key, index) => {
                user.send(`${key} `);

                /** Output new line after every fifth key */
                if ( (index + 1) % 6 == 0 && index != keys.length - 1 )
                  user.send(`\r\n`);
              });

              /** If we output some detail keys, send new line */
              if ( keys.length > 0 )
                user.send(`\r\n`);
            }
          }
        } else {
          /** Send room name */
          user.send(`${user.room().name()}\r\n`);

          /** Start exits */
          let exits = `#G[Exits:`;

          /** Loop through exits in user's room */
          user.room().exits().forEach((exit) => {
            /** Append exit names separated by spaces */
            exits += ` ${world.constants().directionNames[exit.direction()]}`;
          });

          /** If there are no exits, append none */
          if ( user.room().exits().length == 0 )
            exits += ` None`;

          /** Finish exits */
          exits += `]\r\n`;

          /** Colorize and send exits */
          user.send(world.colorize(exits));

          /** Send room description */
          user.send(world.terminalWrap(world.colorize(`#w${user.room().description()}\r\n`)));

          /** Keep track of items already included in item counts */
          const itemsIncluded = [];

          /** Loop through each item in the user's room */
          user.room().items().forEach((item) => {
            /** If item is already included, skip it */
            if ( itemsIncluded.includes(item.roomDescription()) )
              return;

            /** Count number of items of the same name in the room */
            const count = user.room().items().filter(x => x.roomDescription() == item.roomDescription()).length;

            /** If the number of items is greater than, send quantity and room description */
            if ( count > 1 )
              user.send(`    (${count}) ${item.roomDescription()}\r\n`);

            /** Otherwise, just send room description */
            else
              user.send(`    ${item.roomDescription()}\r\n`);

            /** Add item to items included */
            itemsIncluded.push(item.roomDescription());
          });

          /** Loop through each mobile in user's room... */
          user.room().mobiles().forEach((mobile) => {
            /** Send description based on mobile's position and who they're fighting */
            if ( mobile.position() == world.constants().positions.INCAPACITATED )
              user.send(` ${mobile.name()} is lying here incapacitated!\r\n`);
            else if ( mobile.position() == world.constants().positions.SLEEPING )
              user.send(` ${mobile.name()} is lying here sleeping\r\n`);
            else if ( mobile.position() == world.constants().positions.MEDITATING )
              user.send(` ${mobile.name()} is meditating here\r\n`);
            else if ( mobile.position() == world.constants().positions.LYING_DOWN )
              user.send(` ${mobile.name()} is lying down here\r\n`);
            else if ( mobile.position() == world.constants().positions.KNEELING )
              user.send(` ${mobile.name()} is kneeling here\r\n`);
            else if ( mobile.position() == world.constants().positions.SITTING )
              user.send(` ${mobile.name()} is sitting here\r\n`);
            else if ( mobile.fighting() && mobile.fighting() == user )
              user.send(` ${mobile.name()} is here fighting YOU!\r\n`);
            else if ( mobile.fighting() )
              user.send(` ${mobile.name()} is here fighting ${mobile.fighting().name()}!\r\n`);
            else
              user.send(` ${mobile.roomDescription()}\r\n`);
          });

          /** Loop through each other user in the user's room... */
          user.room().users().forEach((other) => {
            /** If user in room is not the looking user... */
            if ( user != other ) {
              /** Send description based on user's position and who they're fighting */
              if ( other.position() == world.constants().positions.INCAPACITATED )
                user.send(` ${other.name()} is lying here incapacitated!\r\n`);
              else if ( other.position() == world.constants().positions.SLEEPING )
                user.send(` ${other.name()} is lying here sleeping\r\n`);
              else if ( other.position() == world.constants().positions.MEDITATING )
                user.send(` ${other.name()} is meditating here\r\n`);
              else if ( other.position() == world.constants().positions.LYING_DOWN )
                user.send(` ${other.name()} is lying down here\r\n`);
              else if ( other.position() == world.constants().positions.KNEELING )
                user.send(` ${other.name()} is kneeling here\r\n`);
              else if ( other.position() == world.constants().positions.SITTING )
                user.send(` ${other.name()} is sitting here\r\n`);
              else if ( other.position() == world.constants().positions.FIGHTING && other.fighting() == user )
                user.send(` ${other.name()} is here fighting YOU!\r\n`);
              else if ( other.position() == world.constants().positions.FIGHTING && other.fighting() && other.fighting() != user )
                user.send(` ${other.name()} is here fighting ${other.fighting().name()}!\r\n`);
              else if ( other.position() == world.constants().positions.STANDING )
                user.send(` ${other.name()} is standing here\r\n`);
            }
          });
        }
      },
      priority: 999
    }),
    new world.Command({
      name: `equipment`,
      positions: world.constants().positionsAwake,
      execute: async (world, user, buffer) => {
        /** Send user's equipment */
        world.sendUserEquipment(user, user);
      },
      priority: 998
    }),
    new world.Command({
      name: `inventory`,
      positions: world.constants().positionsAwake,
      execute: async (world, user, buffer) => {
        /** Send inventory header */
        user.send(`Inventory:\r\n`);

        /** Keep track of items already included in item counts */
        const itemsIncluded = [];

        /** Loop through each item in the user's inventory */
        user.inventory().forEach((item) => {
            /** If item is already included, skip it */
          if ( itemsIncluded.includes(item.name()) )
            return;

          /** Count number of items of the same name in the user's inventory */
          const count = user.inventory().filter(x => x.name() == item.name()).length;

          /** If the number of items is greater than one, send quantity and name */
          if ( count > 1 )
            user.send(`  (${count}) ${item.name()}\r\n`);

          /** Otherwise, just send name */
          else
            user.send(`  ${item.name()}\r\n`);

          /** Add item to items included */
          itemsIncluded.push(item.name());
        });

        /** If there are no items in the user's inventory, send nothing */
        if ( user.inventory().length == 0 )
          user.send(`  nothing\r\n`);
      },
      priority: 999
    }),
    new world.Command({
      name: `who`,
      execute: async (world, user, buffer) => {
        /** Send top border */
        user.send(world.colorize(`#r~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n\r\n`));

        /** Keep track of the number of visible other users */
        let count = 0;

        /** Loop through each other user in the world... */
        world.users().forEach((other) => {
          /** If the other user is not the user looking and the other user is cloaked, return */
          if ( other != user && other.affects().includes(world.constants().AFFECT_CLOAKED))
            return;

          /** If the other user is named xodin, send who entry with title 'The Designer' */
          if ( other.name().toLowerCase() == `xodin` )
            user.send(world.colorize(` #y[The Designer ] #W${other.name()} #w${other.title()}`.padEnd(86) + `\r\n`));

          /** Otherwise, send who entry with title 'Honored Guest' */
          else
            user.send(world.colorize(` #y[Honored Guest] #W${other.name()} #w${other.title()}`.padEnd(86) + `\r\n`));

          /** Increment visible user count by one */
          count++;
        });

        /** Send first bottom border */
        user.send(world.colorize(`\r\n#r~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n`));

        /** If visible user count is equal to one, send only visible user */
        if ( count == 1 )
          user.send(world.colorize(`#wYou are the only Avatar that you can sense in this world.\r\n`));

        /** If visible user count is equal to two, send only one other visible user */
        else if ( count == 2 )
          user.send(world.colorize(`#wYou can sense one other Avatar in this world.\r\n`));

        /** Otherwise, send visible user count */
        else
          user.send(world.colorize(`#wYou can sense ${count - 1} other Avatars in this world.\r\n`));

        /** Send second bottom border */
        user.send(world.colorize(`#r~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n`));
      },
      priority: 0
    })
  ];
};


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>Spring Loaders | Demo 4</title>
		<meta name="description" content="Demo 4 of loading spinner made with inscribed polygons and animated with Rebound spring motion." />
		<meta name="keywords" content="loader, spinner, polygon, animation, rebound, spring motion, web development, web design" />
		<meta name="author" content="Claudio Calautti for Codrops" />
		<link rel="shortcut icon" href="favicon.ico">
		<link rel="stylesheet" type="text/css" href="css/normalize.css" />
		<link rel="stylesheet" type="text/css" href="css/demo.css" />

					Previous Demo
					Back to the Codrops article

Spring Loaders with Rebound and Canvas

					Demo 1
					Demo 2
					Demo 3
					Demo 4
					Demo 5
					Others

				<button class="button button--trigger" onclick="demo.init()">Show Loader</button>

redpajama_set_name: RedPajamaGithub


text:
classdef ReceptiveField1D < sa_labs.protocols.stage.ReceptiveField1D  & sa_labs.common.ProtocolLogger

    % This file contains the protocol documentation
    % The actual protocol lives in lib/sa-labs-extension/src/main/matlab/+sa_labs/+protocols/+stage

    methods

        function prepareRun(obj)
            prepareRun@sa_labs.protocols.stage.ReceptiveField1D(obj);
            import sa_labs.common.DaqLogger;
            DaqLogger.addLogTableHeader('positionX');
            DaqLogger.addLogTableHeader('positionY');
            obj.logPrepareRun();
        end

        function prepareEpoch(obj, epoch)
            prepareEpoch@sa_labs.protocols.stage.ReceptiveField1D(obj, epoch);
            import sa_labs.common.DaqLogger;
            DaqLogger.addLogTableColumn('positionX', epoch.parameters('positionX'));
            DaqLogger.addLogTableColumn('positionY', epoch.parameters('positionY'));
            obj.logPrepareEpoch(epoch);
        end

        function completeEpoch(obj, epoch)
            completeEpoch@sa_labs.protocols.stage.ReceptiveField1D(obj, epoch);
            obj.logCompleteEpoch(epoch);
        end

        function completeRun(obj)
            completeRun@sa_labs.protocols.stage.ReceptiveField1D(obj);
            obj.logCompleteRun();
        end
    end
end


text:
<title>Fractal No neighbor</title>

 Fractal No Neighbor.

Generates amazing Mandelbrot and Julia fractals from a CA that uses complex numbers as values for each cell.

Each cell in this simulation ignores its neighbors, and some would therefore argue that this isn't a cellular
automaton at all. Generally speaking, a CA is a function of the cell and its neighbors. At an extreme, that
can include functions which look only at the cell and ignores the neighbors altogether.  Certainly it is
not unusual for CA to ignore particular neighbors, or to ignore different neighbors at different time steps.
So ignoring all of the neighbors is just one end of the spectrum of possibilities. Considered in this light,
almost all iterative functions can be cast as CA. Just apply a function to the cell itself, over and over.
Is that reasonable?  Perhaps.  It's certainly extreme.  But it does point out the close relationship
between CA and fractals.  Many fractals, like the ones created by this rule, are just iterative applications
of functions on the complex plane.

This particular CA rule (which acts only on the cell) applies the function f(z) to the complex numbered cell value z.
The function f is "i sinh(z)" by default, but may be reset
in the "More Properties" window to other complex functions like f = i sin, (i+1) cos, i tan, (i+1) tanh, etc.
After a series of steps, the cell's value is just the iterative application of f, as f(f(f(f(...f(z)))). For example,
i sinh(i sinh(i sinh(i sinh(...z)))).  The result is stunningly beautiful fractals when viewed properly.

In fact, from a CA perspective, what is particularly interesting is not this rule but the way in which the cell's are viewed.
Each cell can be viewed as either the complex modulus (a shaded value that
depends on the distance from origin) or as a fractal.  Fractals are derived from
the equation z = z2 + c where z (the value of the cell) is iterated repeatedly.
If the value diverges, the cell is given a light (or empty) color.  If the value
converges, the cell is given a dark (or full) color.  The rate at which it diverges
determines shades in between -- the faster the divergence then the lighter the color,
and the slower the divergence then the darker the color.

The Mandelbrot set is derived when c is set to the initial value of the cell.  A
Julia set is derived when c is a fixed value for all cells.  For Julia sets, the
value of c may be set in the "More Properties" window.

Clearly, a relatively simple CA can take fascinating shapes and patterns when
viewed in a "different light" as a fractal.  In fact, that's the real lesson here.
There
is no one correct way to display a cellular automaton, and different displays may highlight
otherwise hidden information.


text:
import PageFooter from './Footer.vue';
import PageHeader from './Header.vue';
import FunButton from './FunButton.vue';
export default {
	components: {FunButton}
}


text:
require "loterias/version"
require "loterias/sena"

module Loterias
  # Your code goes here...
end


text:
typedef NS_ENUM(NSUInteger, EACodeReleaseAttachmentsOrReferencesCellType) {
    EACodeReleaseAttachmentsOrReferencesCellTypeAttachments = 0,
    EACodeReleaseAttachmentsOrReferencesCellTypeReferences,
};

@interface EACodeReleaseAttachmentsOrReferencesCell : UITableViewCell

@property (copy, nonatomic) void(^itemClickedBlock)(id item);

- (void)setupCodeRelease:(EACodeRelease *)curR type:(EACodeReleaseAttachmentsOrReferencesCellType)type;

+ (CGFloat)cellHeightWithObj:(EACodeRelease *)obj type:(EACodeReleaseAttachmentsOrReferencesCellType)type;

@end


text:
package scryetek.gl

import org.scalajs.dom.raw.{WebGLRenderingContext => GL}
import org.scalajs.dom.html.Image

class ImageCache(gl: GL, val width: Int, val height: Int) {
  import ImageCache._

  var layers = Seq.empty[Layer]
  var images = Seq.empty[SubImage]
  var currentLayer = 0

  def add(image: Image): SubImage = {
    val img = new SubImage(image, null, 0, 0)
    images :+= img
    img
  }

  def addPacked(image: Image): SubImage = {
    val img = new SubImage(image, null, 0, 0)
    images :+= img
    packImage(img)
    img
  }

  private def findLevel(width: Int, height: Int): Option[Level] = {
    if(width + 2 > this.width || height + 2 > this.height)
      None // texture is too large!
    else
      layers(currentLayer).findLevel(width, height).orElse {
        layers :+= new Layer(gl, this)
        currentLayer += 1
        layers(currentLayer).findLevel(width, height)
      }
  }

  def pack(gl: GL): Unit = {
    layers.foreach { layer => layer.texture.release(gl) }
    layers = Seq(new Layer(gl, this))
    currentLayer = 0

    for (image <- images.sortBy(-_.height))
      packImage(image)
  }

  private def packImage(image: SubImage): Unit =
    findLevel(image.width, image.height).foreach { level =>
      image.x = width - level.remain + 1
      image.y = level.y + 1
      image.layer = level.layer
      level.remain -= image.width + 2
      level.height = level.height max (image.height + 2)
      gl.texSubImage2D(GL.TEXTURE_2D, 0, image.x.toInt, image.y.toInt, GL.RGBA, GL.UNSIGNED_BYTE, image.image)
    }
}

object ImageCache {
  class Layer(gl: GL, val imageCache: ImageCache) {
    var levels = Seq.empty[Level]
    var y = 0
    val texture = new Texture(gl, imageCache.width, imageCache.height)

    def findLevel(width: Int, height: Int): Option[Level] = {
      for (level <- levels.reverseIterator if level.height >= height && level.remain >= width)
        return Some(level)
      y += levels.lastOption.map(_.height).getOrElse(0)
      if (y + height >= imageCache.height)
        return None
      val level = new Level(this, y, height, imageCache.width)
      levels :+= level
      Some(level)
    }
  }
  class Level(val layer: Layer, var y: Int, var height: Int, var remain: Int)

}

class SubImage(var image: Image, var layer: ImageCache.Layer, var x: Float, var y: Float) {
  def width = image.naturalWidth
  def height = image.naturalHeight

  def release = layer.imageCache
}


text:
<!DOCTYPE html>
<html>
<head>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="support/frame-ancestors-test.sub.js"></script>
</head>
<body>
  <script>
    async_test(t => {
      window.addEventListener('securitypolicyviolation', t.step_func(function(e) {
        if (e.violatedDirective === 'frame-ancestors')
          assert_unreached('No securitypolicyviolation event shoud be raised in the parent.');
      }));
      t.step_timeout(function() { t.done(); }, 2000);
    });

    test = async_test("A 'frame-ancestors' CSP directive with a value 'none' should block rendering.");

    sameOriginFrameShouldBeBlocked("'none'");
  </script>
</body>
</html>


text:
================
Production Setup
================

This is an example of a production setup, your personal flavor may vary.

- Nginx as a frontend server
- Supervisor as process manager and monitor
- Gunicorn as WSGI Server
- RabbitMQ as Background Queue Broker
- Solr as Search Engine

Protect admin site
------------------

Setup your front end server to serve the admin site behind basic authentication.
Here is an example for Nginx::

  location /custom-admin-url {
    auth_basic "Restricted";
    auth_basic_user_file  /var/www/froide/conf/htadminsitepasswd;
    proxy_pass http://127.0.0.1:29000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Protocol https;
  }

Also note that we forward the HTTPS protocol. This sh

- Protect the admin by setting a Basic Authentication via Nginx for the URL
- Make the URL secret via the `SECRET_URLS` setting

Acces to Documents
------------------

Nginx is able to serve your uploads behind authentication/authorization. Activate the following settings::

  # Use nginx to serve uploads authenticated
  USE_X_ACCEL_REDIRECT = True
  X_ACCEL_REDIRECT_PREFIX = '/protected'

Nginx will forward the request to Froide which will in turn check for authentication and authorization. If everything is good Froide replies to Nginx with an internal redirect and Nginx will then serve the file to the user.

A sample configuration looks like this::

  location /protected {
    internal;
    alias /var/www/froide/public;
  }


text:
var DBInterface, MongoInterface, path,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

DBInterface = require('../db_interface');

path = require('path');

MongoInterface = (function(_super) {
  __extends(MongoInterface, _super);

  function MongoInterface() {
    return MongoInterface.__super__.constructor.apply(this, arguments);
  }

  MongoInterface.prototype.doPull = function(env, callback) {
    var command, conn, fileName;
    if (env == null) {
      env = 'local';
    }
    console.log("Pull the mongo contents from '" + env + "'");
    conn = this.config['env'][env].connection;
    fileName = this._getFileName(env);
    command = "mongodump ";
    if (conn.host != null) {
      command += "--host " + conn.host + " ";
    }
    if (conn.port != null) {
      command += "--port " + conn.port + " ";
    }
    if (conn.username != null) {
      command += "--username " + conn.username + " ";
    }
    if (conn.password != null) {
      command += "--password " + conn.password + " ";
    }
    if (conn.dbpath != null) {
      command += "--dbpath " + conn.dbpath + " ";
    }
    command += "--db " + conn.database + " ";
    command += "--out " + fileName;
    return this.exec(command, (function(_this) {
      return function(e, stdout, stderr) {
        if (e != null) {
          _this._errors.push(e);
        }
        return callback(_this._errors);
      };
    })(this));
  };

  MongoInterface.prototype.doPush = function(env, callback) {
    var command, conn, fileName;
    if (env == null) {
      env = 'local';
    }
    console.log("Push the mongo contents to '" + env + "'");
    conn = this.config['env'][env].connection;
    fileName = this._getFileName(env);
    command = "mongorestore ";
    if (conn.host != null) {
      command += "--host " + conn.host + " ";
    }
    if (conn.port != null) {
      command += "--port " + conn.port + " ";
    }
    if (conn.username != null) {
      command += "--username " + conn.username + " ";
    }
    if (conn.password != null) {
      command += "--password " + conn.password + " ";
    }
    if (conn.dbpath != null) {
      command += "--dbpath " + conn.dbpath + " ";
    }
    command += "--db " + conn.database + " ";
    command += "" + fileName + "/*";
    return this.exec(command, (function(_this) {
      return function(e, stdout, stderr) {
        if (e != null) {
          _this._errors.push(e);
        }
        return callback(_this._errors);
      };
    })(this));
  };

  return MongoInterface;

})(DBInterface);

module.exports = MongoInterface;


text:
<?php

namespace Test\Interfax;

use GuzzleHttp\Psr7\Response;
use Interfax\Outbound;

class OutboundTest extends BaseTest
{
    public function test_completed()
    {
        $response = [['id' =>  12, 'senderCSID' => 'Interfax'],['id' => 14, 'senderCSID' => 'Interfax']];
        $container = [];
        $client = $this->getClientWithResponses(
            $container,
            [
                new Response('200', ['Content-type' => 'text/json'], json_encode($response))
            ]
        );

        $fax1 = $this->getMockBuilder('Interfax\Outbound\Fax')->disableOriginalConstructor()->getMock();
        $fax2 = $this->getMockBuilder('Interfax\Outbound\Fax')->disableOriginalConstructor()->getMock();
        $factory = $this->getFactory([
            [$fax1, [$client, 12, $response[0]]],
            [$fax2, [$client, 14, $response[1]]]
        ]);

        $outbound = new Outbound($client, $factory);

        $res = $outbound->completed(['12', '14']);

        $this->assertEquals([$fax1, $fax2], $res);
        $transaction = $container[0];
        $this->assertEquals('GET', $transaction['request']->getMethod());
        $this->assertEquals('/outbound/faxes/completed', $transaction['request']->getUri()->getPath());
        $this->assertEquals('ids=' . urlencode('12,14'), $transaction['request']->getUri()->getQuery());
    }

    public function test_recent()
    {
        $response = [['id' =>  21]];
        $container = [];
        $client = $this->getClientWithResponses(
            $container,
            [
                new Response('200', ['Content-type' => 'text/json'], json_encode($response))
            ]
        );

        $fax = $this->getMockBuilder('Interfax\Outbound\Fax')->disableOriginalConstructor()->getMock();

        $factory = $this->getFactory([[$fax, [$client, 21, $response[0]]]]);

        $outbound = new Outbound($client, $factory);

        $res = $outbound->recent(['limit' => 5]);

        $this->assertEquals([$fax], $res);
        $transaction = $container[0];
        $this->assertEquals('GET', $transaction['request']->getMethod());
        $this->assertEquals('/outbound/faxes', $transaction['request']->getUri()->getPath());
        $this->assertEquals('limit=5', $transaction['request']->getUri()->getQuery());
    }

    public function test_resend_uses_outbound_fax()
    {
        $fax = $this->getMockBuilder('Interfax\Outbound\Fax')
            ->disableOriginalConstructor()
            ->setMethods(['resend'])
            ->getMock();

        $resent_fax = $this->getMockBuilder('Interfax\Outbound\Fax')->disableOriginalConstructor()->getMock();

        $fax->expects($this->once())
            ->method('resend')
            ->will($this->returnValue($resent_fax));

        $factory = $this->getFactory([$fax]);

        $client = $this->getMockBuilder('Interfax\Client')->disableOriginalConstructor()->getMock();

        $outbound = new Outbound($client, $factory);

        $this->assertEquals($resent_fax, $outbound->resend(34552));
    }

    public function test_resend_with_new_number_uses_outbound_fax()
    {
        $fax = $this->getMockBuilder('Interfax\Outbound\Fax')
            ->disableOriginalConstructor()
            ->setMethods(['resend'])
            ->getMock();

        $fax_number = '+112122323';

        $resent_fax = $this->getMockBuilder('Interfax\Outbound\Fax')->disableOriginalConstructor()->getMock();

        $fax->expects($this->once())
            ->method('resend')
            ->with($fax_number)
            ->will($this->returnValue($resent_fax));

        $factory = $this->getFactory([$fax]);

        $client = $this->getMockBuilder('Interfax\Client')->disableOriginalConstructor()->getMock();

        $outbound = new Outbound($client, $factory);

        $this->assertEquals($resent_fax, $outbound->resend(34552, $fax_number));
    }

    public function test_search()
    {
        $container = [];

        $search_results = [
            ['id' => 5, 'status' => -32],
            ['id' => 9, 'status' => 40],
        ];

        $client = $this->getClientWithResponses(
            $container,
            [
                new Response(200, ['Content-Type' => 'text/json'], json_encode($search_results))
            ]
        );

        $test_params = ['status' => 'Inprocess'];

        $factory = $this->getFactory([
            [new Outbound\Fax($client, 5),[$client, 5, $search_results[0]] ],
            [new Outbound\Fax($client, 9),[$client, 9, $search_results[1]] ]
        ]);

        $outbound = new Outbound($client, $factory);

        $this->assertCount(2, $outbound->search($test_params));
        $transaction = $container[0];
        $this->assertEquals('GET', $transaction['request']->getMethod());
        $this->assertEquals('/outbound/search', $transaction['request']->getUri()->getPath());
        $this->assertEquals('status=Inprocess', $transaction['request']->getUri()->getQuery());
    }

    public function test_find()
    {
        $response = ['id' =>  42, 'status' => 0, 'duration' => 4];
        $container = [];
        $client = $this->getClientWithResponses(
            $container,
            [
                new Response('200', ['Content-type' => 'text/json'], json_encode($response))
            ]
        );

        $fax = new Outbound\Fax($client, 42, $response);
        $factory = $this->getFactory(
            [
                [$fax, [$client, 42, $response]],
            ]
        );

        $outbound = new Outbound($client, $factory);

        $this->assertEquals($fax, $outbound->find(12));
        $transaction = $container[0];
        $this->assertEquals('GET', $transaction['request']->getMethod());
        $this->assertEquals('/outbound/faxes/12', $transaction['request']->getUri()->getPath());
        $this->assertEquals('', $transaction['request']->getUri()->getQuery());
    }
}


text:
//Using delegates write a class Timer that can execute certain method at each t seconds.

namespace Timer
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;

    public delegate void RepeatDelegate(int t);

    class Timer
    {
        static void Main()
        {
            RepeatDelegate t = delegate(int time)
            {
                while (true)
                {
                    Thread.Sleep(time);
                    var repeatDelegate = "Repeat Delegate :)";
                    Console.WriteLine("{0}",repeatDelegate);
                }
            };
            t(500);
        }
    }
}


text:
{{'WELCOME' | translate}}

            <form class="form-horizontal form-bordered form-row-stripped" id="loginForm">

                                {{'USER_NAME' | translate}}:

                                    <input type="text" id="username" name="username" placeholder="{{'USER_NAME' | translate}}" class="form-control" ng-model="filterStr"/>

                                 {{'PASSWORD' | translate}}:

                                    <input type="password" name="password" id="password"
                                           value="" placeholder="{{'PASSWORD' | translate}}"
                                           class="form-control" />

            </form>

                <button class="btn btn-raised btn-sm btn-primary" type="button" ng-click="login()">{{'LOGIN' | translate}}</button>


text:
using System.Collections.Generic;

namespace Transavia.Api.FlightOffers.Client.Model
{
    public class FlightOfferResponse
    {
        /// <summary>
        /// Info about the result.
        /// </summary>
        public ResultSet ResultSet { get; set; }

        /// <summary>
        /// Flight offers.
        /// </summary>
        public List<FlightOffer> FlightOffer { get; set; }
    }
}


text:
package Amazon::EC2::Model::DescribeInstancesResult;

use base qw (Amazon::EC2::Model);

    #
    # Amazon::EC2::Model::DescribeInstancesResult
    #
    # Properties:
    #
    #
    # Reservation: Amazon::EC2::Model::Reservation
    #
    #
    #
    sub new {
        my ($class, $data) = @_;
        my $self = {};
        $self->{_fields} = {

            Reservation => {FieldValue => [], FieldType => ["Amazon::EC2::Model::Reservation"]},
        };

        bless ($self, $class);
        if (defined $data) {
           $self->_fromHashRef($data);
        }

        return $self;
    }

        sub getReservation {
        return shift->{_fields}->{Reservation}->{FieldValue};
    }

    sub setReservation {
        my $self = shift;
        foreach my $reservation (@_) {
            if (not $self->_isArrayRef($reservation)) {
                $reservation =  [$reservation];
            }
            $self->{_fields}->{Reservation}->{FieldValue} = $reservation;
        }
    }

    sub withReservation {
        my ($self, $reservationArgs) = @_;
        foreach my $reservation (@$reservationArgs) {
            $self->{_fields}->{Reservation}->{FieldValue} = $reservation;
        }
        return $self;
    }

    sub isSetReservation {
        return  scalar (@{shift->{_fields}->{Reservation}->{FieldValue}}) > 0;
    }

1;


text:
<?php

namespace ck\RecipesBundle\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Collections\ArrayCollection;

use ck\RecipesBundle\Entity\IngredientsCategory;

class IngredientsCategoriesToStringTransformer implements DataTransformerInterface
{
    /**
     * @var ObjectManager
     */
    private $om;
    private $is_multiple;
    private $collection;

    /**
     * @param ObjectManager $om
     */
    public function __construct(ObjectManager $om, $is_multiple = true)
    {
        $this->om = $om;
        $this->is_multiple = $is_multiple;
    }

    /**
     * Transforms an object (ingredient category) to a string
     *
     * @param  ingredient category|null $ingredient category
     * @return string
     */
    public function transform($ingredientsCategories)
    {
        $this->collection = $ingredientsCategories;

        if (null === $ingredientsCategories) {
            return "";
        }

        $ingredientsCategoriesList = array();

        foreach ($ingredientsCategories as $ingredientCategory)
        {
            $ingredientsCategoriesList[] = $ingredientCategory->getId();
        }

        if(sizeof($ingredientsCategoriesList) > 0)
            return implode(",", $ingredientsCategoriesList);

        return $ingredientsCategoriesList;
    }

    /**
     * Transforms a string (ids) to an object (ingredient category).
     *
     * @param  string $ids
     * @return ingredient category|null
     * @throws TransformationFailedException if object (ingredient category) is not found.
     */
    public function reverseTransform($ids)
    {
        if (!$ids) {
            return null;
        }

        if(preg_match("/,/", $ids))
            $ingredientsCategories = $this->om->getRepository('ckRecipesBundle:IngredientsCategory')->findBy(array('id' => explode(",", $ids)));
        elseif($this->is_multiple)
            $ingredientsCategories = $this->om->getRepository('ckRecipesBundle:IngredientsCategory')->findBy(array('id' => $ids));
        else
            $ingredientsCategories = $this->om->getRepository('ckRecipesBundle:IngredientsCategory')->find($ids);

        if (null === $ingredientsCategories) {
            throw new TransformationFailedException(sprintf(
                'Recipes #%s can\' be found',
                $ids
            ));
        }

        // for many to many relations
        if($this->is_multiple && !is_null($this->collection))
        {
            // Process diff with bindings changes
            if(!is_array($ingredientsCategories))
                $ingredientsCategories = array($ingredientsCategories);

            // Transforms array into arrayCollection
            $col = new ArrayCollection();

            foreach ($ingredientsCategories as $u)
            {
                $col->add($u);
            }

            // Add ingredient category if doesn't exist in collection
            foreach ($ingredientsCategories as $u)
            {
                if(!$this->collection->contains($u))
                    $this->collection->add($u);
            }

            // Remove ingredient category if no longer present
            foreach ($this->collection as $past_u)
            {
                if(!$col->contains($past_u))
                    $this->collection->removeElement($past_u);
            }

            return $this->collection;
        }

        return $ingredientsCategories;
    }
}


text:
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Reflection.Helper2.Wrappers;
using Reflection.Helper2.Types;
using System.Reflection;

namespace Reflection.Tests
{
    [TestClass()]
    public class DemoTests
    {

        #region Test attributes

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        //Use ClassInitialize to run code before running the first test in the class
        //[ClassInitialize()]
        //public static void MyClassInitialize(TestContext testContext)
        //{
        //}
        //
        //Use ClassCleanup to run code after all tests in a class have run
        //[ClassCleanup()]
        //public static void MyClassCleanup()
        //{
        //}
        //
        //Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize()
        //{
        //}
        //
        //Use TestCleanup to run code after each test has run
        //[TestCleanup()]
        //public void MyTestCleanup()
        //{
        //}
        //

        #endregion

        #region Test Methods

        [TestMethod]
        public void CreateObjectFromType()
        {
            var obj = new object();

            var constructor = typeof(object).GetConstructors().First();
            var instance = constructor.Invoke(new object[] { });

            Assert.IsNotNull(instance);
            Assert.IsInstanceOfType(instance, typeof(object));
        }

        [TestMethod]
        public void EvaluateFields()
        {
            var model = new FieldsModel();
            model.internalInt = 10;
            model.publicInt = 5;

            var type = typeof(FieldsModel);
            var publicIntField = type.GetField("publicInt", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            var internalIntField = type.GetField("internalInt", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var privateIntField = type.GetField("privateInt", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var privateStaticIntField = type.GetField("privateStaticInt", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);

            Assert.IsNotNull(publicIntField);
            Assert.IsNotNull(internalIntField);
            Assert.IsNotNull(privateIntField);
            Assert.IsNotNull(privateStaticIntField);

            Assert.AreEqual(model.publicInt, publicIntField.GetValue(model));

            int internalIntValue = 3;
            int privateIntValue = 12;
            int privateStaticIntValue = 20;

            internalIntField.SetValue(model, internalIntValue);
            privateIntField.SetValue(model, privateIntValue);
            privateStaticIntField.SetValue(null, privateStaticIntValue);

            Assert.AreEqual(internalIntField.GetValue(model), internalIntValue);
            Assert.AreEqual(privateIntField.GetValue(model), privateIntValue);
            Assert.AreEqual(privateStaticIntField.GetValue(null), privateStaticIntValue);
        }

        [TestMethod]
        public void EvaluateFieldsBad()
        {
            var model = new FieldsModel();

            var type = typeof(FieldsModel);
            var publicIntField = type.GetField("publicInt", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            Assert.IsNotNull(publicIntField);

            try
            {
                publicIntField.SetValue(model, model);
            }
            catch (ArgumentException)
            {
            }

            try
            {
                publicIntField.SetValue(model, byte.MaxValue);
            }
            catch (ArgumentException)
            {
            }

            try
            {
                publicIntField.SetValue(model, true);
            }
            catch (ArgumentException)
            {
            }

            try
            {
                publicIntField.SetValue(model, (long)0);
            }
            catch (ArgumentException)
            {
            }

            try
            {
                publicIntField.SetValue(model, long.MaxValue);
            }
            catch (ArgumentException)
            {
            }

        }

        [TestMethod]
        public void EvaluateMethods()
        {
            var model = new MethodsModel();

            var point = model.CreatePoint();
            Assert.AreEqual(point.X, model.x);
            Assert.AreEqual(point.Y, model.y);

            var createPointMethod = typeof(MethodsModel).GetMethod("CreatePoint");
            Assert.IsNotNull(createPointMethod);

            var refPoint = (System.Drawing.Point)createPointMethod.Invoke(model, null);
            Assert.AreEqual(refPoint.X, model.x);
            Assert.AreEqual(refPoint.Y, model.y);

            try
            {
                typeof(MethodsModel).GetMethod("CreatePoint", BindingFlags.Instance | BindingFlags.NonPublic);
            }
            catch (AmbiguousMatchException) { }

            var createPoint2Method = typeof(MethodsModel).GetMethod("CreatePoint", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(int) }, null);
            var createPoint3Method = typeof(MethodsModel).GetMethod("CreatePoint", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(int), typeof(int) }, null);

            Assert.IsNotNull(createPoint2Method);
            Assert.IsNotNull(createPoint3Method);

            var refPoint2 = (System.Drawing.Point)createPoint2Method.Invoke(model, new object[] { 5 });
            Assert.AreEqual(refPoint2.X, 5);
            Assert.AreEqual(refPoint2.Y, model.y);
        }

        [TestMethod]
        public void EvaluateProperties()
        {
            var model = new PropertiesModel();
            var type = model.GetType();

            var xProperty = type.GetProperty("X");
            var yProperty = type.GetProperty("Y");
            var zProperty = type.GetProperty("Z");
            var wProperty = type.GetProperty("W");

            Assert.IsNotNull(xProperty);
            Assert.IsTrue(xProperty.CanRead);
            Assert.IsFalse(xProperty.CanWrite);

            Assert.IsNotNull(yProperty);
            Assert.IsTrue(yProperty.CanRead);
            Assert.IsTrue(yProperty.CanWrite);

            Assert.IsNotNull(zProperty);
            Assert.IsFalse(zProperty.CanRead);
            Assert.IsTrue(zProperty.CanWrite);

            Assert.IsNotNull(wProperty);
            Assert.IsTrue(wProperty.CanRead);
            Assert.IsTrue(wProperty.CanWrite);

            Assert.AreEqual(xProperty.GetValue(model), model.X);

            var xGetMethod = xProperty.GetGetMethod();
            Assert.IsNotNull(xGetMethod);
            Assert.AreEqual((int)xGetMethod.Invoke(model, null), model.X);

            zProperty.SetValue(model, 20);
            Assert.AreEqual(model.GetZ(), 20);

            var zSetMethod = zProperty.GetSetMethod();
            Assert.IsNotNull(zSetMethod);
            zSetMethod.Invoke(model, new object[] { 12 });
            Assert.AreEqual(model.GetZ(), 12);

            wProperty.SetValue(model, 99);
            Assert.AreEqual(model.W, 99);

            var indexerProperty = type.GetProperty("Item");
            Assert.IsNotNull(indexerProperty);
            Assert.IsTrue(indexerProperty.GetIndexParameters().Any());
            Assert.AreEqual(model[64], indexerProperty.GetValue(model, new object[] { 64 }));
        }

        [TestMethod]
        public void CreateWithGetType()
        {
            var noType = Type.GetType("Reflection.Helper2.Wrappers.TypeWrapper");
            Assert.IsNull(noType);

            var type = Type.GetType("Reflection.Helper2.Wrappers.TypeWrapper, Reflection.Helper2");
            Assert.IsNotNull(type);

            var instance = Activator.CreateInstance(type, new object[] { type });
            Assert.IsNotNull(instance);

            var allPropertiesProperty = type.GetProperty("AllProperties");
            var allProperties = (IEnumerable)allPropertiesProperty.GetValue(instance, null);
            Assert.IsTrue(allProperties.Cast<object>().Any());
        }

        [TestMethod]
        public void CallInternalClass()
        {
            var type = Type.GetType("System.SR, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
            Assert.IsNotNull(type);

            var arg_emptyOrNullString = type.GetField("Arg_EmptyOrNullString", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            Assert.IsNotNull(arg_emptyOrNullString);

            var getStringMethod = type.GetMethod("GetString", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, new Type[] { typeof(string) }, null);
            Assert.IsNotNull(getStringMethod);

            var msg = getStringMethod.Invoke(null, new object[] { arg_emptyOrNullString.GetValue(null) });
            Assert.IsInstanceOfType(msg, typeof(string));
            Assert.IsTrue(!string.IsNullOrEmpty((string)msg));
        }

        [TestMethod]
        public void EvaluateInterfaces()
        {
            var model = new InterfacesModel();
            model.Value = 255;
            var type = typeof(InterfacesModel);

            var allInterfaces = type.GetInterfaces();
            Assert.IsTrue(allInterfaces.Any());

            var icomparableInterface = type.GetInterface("IComparable");
            Assert.IsNotNull(icomparableInterface);

            var compareTo = (int)icomparableInterface.GetMethod("CompareTo").Invoke(model, new object[] { 0 });
            Assert.IsTrue(compareTo > 0);
            compareTo = (int)icomparableInterface.GetMethod("CompareTo").Invoke(model, new object[] { new System.Drawing.Rectangle() });
            Assert.AreEqual(compareTo, 0);

            var icomparableGenericInterface = type.GetInterface("IComparable`1");
            Assert.IsNotNull(icomparableGenericInterface);
            compareTo = (int)icomparableInterface.GetMethod("CompareTo").Invoke(model, new object[] { int.MaxValue });
            Assert.IsTrue(compareTo < 0);
        }

        [TestMethod]
        public void CreateGenerics()
        {
            var type = typeof(List<int>);
            var list1 = (List<int>)Activator.CreateInstance(type);
            Assert.IsNotNull(list1);

            var constructor = type.GetConstructor(new Type[] { });
            Assert.IsNotNull(constructor);
            var list2 = (List<int>)constructor.Invoke(new object[] { });
            Assert.IsNotNull(list2);

            type = Type.GetType("System.Collections.Generic.List`1");
            Assert.IsNotNull(type);
            var longListType = type.MakeGenericType(new Type[] { typeof(long) });
            constructor = longListType.GetConstructor(new Type[] { });
            var list3 = (List<long>)constructor.Invoke(new object[] { });
            Assert.IsNotNull(list3);
        }

        [TestMethod]
        public void EvaluateEvents()
        {
            var model = new EventsModel();
            var type = typeof(EventsModel);

            model.Value = 10;
            model.Promoted += model_Promoted;
            model.RaisePromoted();

            var promotedEvent = type.GetEvent("Promoted");
            Assert.IsNotNull(promotedEvent);

            var addMethod = promotedEvent.AddMethod;
            var removeMethod = promotedEvent.RemoveMethod;
            Assert.IsNotNull(addMethod);
            Assert.IsNotNull(removeMethod);

            removeMethod.Invoke(model, new object[] { (EventHandler)model_Promoted });
            addMethod.Invoke(model, new object[] { (EventHandler)model_Promoted2 });

            model.Value = 15;
            model.RaisePromoted();

            var eventField = type.GetField("Promoted", BindingFlags.NonPublic | BindingFlags.Instance);
            Assert.IsNotNull(eventField);

            var eventHandler = eventField.GetValue(model);
            Assert.IsNotNull(eventHandler);

            var invokeMethod = eventHandler.GetType().GetMethod("Invoke");
            Assert.IsNotNull(invokeMethod);

            invokeMethod.Invoke(eventHandler, new object[] { model, EventArgs.Empty });

            var eventHandlerDelegate = ((Delegate)eventHandler);
            eventHandlerDelegate.DynamicInvoke(new object[] { model, EventArgs.Empty });

            var invokeList = eventHandlerDelegate.GetInvocationList();
            foreach (var item in invokeList)
            {
                item.DynamicInvoke(model, EventArgs.Empty);
            }
        }
        private void model_Promoted(object sender, EventArgs e)
        {
            var model = sender as EventsModel;
            Assert.IsNotNull(model);
            Assert.AreEqual(model.Value, 10);
        }
        private void model_Promoted2(object sender, EventArgs e)
        {
            var model = sender as EventsModel;
            Assert.IsNotNull(model);
            Assert.AreEqual(model.Value, 15);
        }

        [TestMethod]
        public void CreateAppDomain()
        {
            const string BadPath = @"..\..\..\Reflection.Helper.Bad\Reflection.Common.dll";
            const string BadPath2 = @"..\..\..\Reflection.Helper.Bad\Reflection.Helper.dll";
            var settings = new AppDomainSetup();

            settings.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            var domain = AppDomain.CreateDomain("Awesome", null, settings);
            try
            {
                var loadedAssemblies = domain.GetAssemblies();
                Assert.IsTrue(loadedAssemblies.Length == 1);

                domain.Load(typeof(FieldsModel).Assembly.GetName());
                loadedAssemblies = domain.GetAssemblies();
                Assert.IsTrue(loadedAssemblies.Length == 2);

                var intRef = domain.CreateInstance(typeof(int).Assembly.FullName, typeof(int).FullName, null);
                var intUnwrap = intRef.Unwrap();

                var modelRef = domain.CreateInstance(typeof(MarshalByRefModel).Assembly.FullName, typeof(MarshalByRefModel).FullName, null);
                var modelUnwrap = (MarshalByRefModel)modelRef.Unwrap();
                modelUnwrap.Value = 12;
                //modelUnwrap.Throw();

                var proxyRef = domain.CreateInstance(typeof(AssemblyProxy).Assembly.FullName, typeof(AssemblyProxy).FullName, null);
                var proxyUnwrap = (AssemblyProxy)proxyRef.Unwrap();
                proxyUnwrap.LoadAssembly(System.IO.Path.GetFullPath(BadPath));
                proxyUnwrap.LoadAssembly(System.IO.Path.GetFullPath(BadPath2));

                var helperRef = domain.CreateInstance("Reflection.Helper", "Reflection.Helper.HelperUtility", null);
                var helperUnwrap = (ICommonClass)helperRef.Unwrap();
                var helperString = helperUnwrap.ToString();
            }
            finally
            {
                AppDomain.Unload(domain);
            }
        }

        //[TestMethod]
        //public void CreateObjectFromTypeWrapper()
        //{
        //    var objectType = new TypeWrapper(typeof(object));
        //    var constructor = objectType.AllConstructors.First();
        //    var instance = constructor.Info.Invoke(new object[] { });

        //    Assert.IsNotNull(instance);
        //    Assert.IsInstanceOfType(instance, typeof(object));
        //}

        #endregion

    }

}


text:
**JarRet**
==========

***M1 IT Network Project***
----------------------------------------

###  *What is it?*

###  *Configuration*

###  *Installation*

###  *Operating Instructions*

###  *Workflow*
![Workflow](doc/resources/Workflow.png)

###  *File Manifest*
> *Note:* Considers to open this file with [StackEdit.io](https://stackedit.io)
>
> 1. Open the menu panel with
> 2. Select  **Import from disk**
> 3. Browse or Drop this file (`.md`)
> 4. Edit as your wishes
> 5. Use  **Export to disk**
    - Select  **Using template** to export as HTML viewer
    - Select  **As Markdown** to export as Mardown file
>

###  *Known Bugs*

###  *Troubleshooting*

###  *Credits and Acknowledgements*

###  *Changelog*

###  *Contact*
[WhyT Swag](mailto:whyt.swag@gmail.com)

###  *Copyright And Licensing Information*
MIT © [WhyT](https://github.com/WhyTSwag)

----------


text:
This directory contains the main thread animation engine. This implements the
Web Animations timing model that drives CSS Animations, Transitions and exposes
the Web Animations API (`element.animate()`) to Javascript.

## Contacts

As of 2018 Blink animations is maintained by the
[cc/ team](https://cs.chromium.org/chromium/src/cc/OWNERS).

## Specifications Implemented

*   [CSS Animations Level 1](https://www.w3.org/TR/css-animations-1/)
*   [CSS Transitions](https://www.w3.org/TR/css-transitions-1/)
*   [Web Animations](https://www.w3.org/TR/web-animations-1/)
*   [CSS Properties and Values API Level 1 - Animation Behavior of Custom Properties](https://www.w3.org/TR/css-properties-values-api-1/#animation-behavior-of-custom-properties)
*   Individual CSS property animation behaviour [e.g. transform interolation](https://www.w3.org/TR/css-transforms-1/#interpolation-of-transforms).

## Integration with Chromium

The Blink animation engine interacts with Blink/Chrome in the following ways:

*   ### [Blink's Style engine](../css)

    The most user visible functionality of the animation engine is animating
    CSS values. This means animations have a place in the [CSS cascade][] and
    influence the [ComputedStyle][]s returned by [styleForElement()][].

    The implementation for this lives under [ApplyAnimatedStandardProperties()][]
    for standard properties and [ApplyAnimatedCustomProperties()][] for custom
    properties. Custom properties have more complex application logic due to
    dynamic dependencies introduced by [variable references].

    Animations can be controlled by CSS via the [`animation`](https://www.w3.org/TR/css-animations-1/#animation)
    and [`transition`](https://www.w3.org/TR/css-transitions-1/#transition-shorthand-property) properties.
    In code this happens when [styleForElement()][] uses [CalculateAnimationUpdate()][]
    and [CalculateTransitionUpdate()][] to build a [set of mutations][] to make
    to the animation engine which gets [applied later][].

[CSS cascade]: https://www.w3.org/TR/css-cascade-3/#cascade-origin
[ComputedStyle]: https://cs.chromium.org/search/?q=class:blink::ComputedStyle$
[styleForElement()]: https://cs.chromium.org/search/?q=function:StyleResolver::styleForElement
[ApplyAnimatedStandardProperties()]: https://cs.chromium.org/?type=cs&q=function:StyleResolver::ApplyAnimatedStandardProperties
[ApplyAnimatedCustomProperties()]: https://cs.chromium.org/?type=cs&q=function:ApplyAnimatedCustomProperties
[variable references]: https://www.w3.org/TR/css-variables-1/#using-variables
[CalculateAnimationUpdate()]: https://cs.chromium.org/search/?q=function:CSSAnimations::CalculateAnimationUpdate
[CalculateTransitionUpdate()]: https://cs.chromium.org/search/?q=function:CSSAnimations::CalculateTransitionUpdate
[MaybeApplyPendingUpdate()]: https://cs.chromium.org/search/?q=function:CSSAnimations::MaybeApplyPendingUpdate
[set of mutations]: https://cs.chromium.org/search/?q=class:CSSAnimationUpdate
[applied later]: https://cs.chromium.org/search/?q=function:Element::StyleForLayoutObject+MaybeApplyPendingUpdate

*   ### [Chromium's Compositor](../../../../../cc/README.md)

    Chromium's compositor has a separate, more lightweight [animation
    engine](../../../../../cc/animation/README.md) that runs separate to the
    main thread. Blink's animation engine delegates animations to the compositor
    where possible for better performance and power utilisation.

    #### Compositable animations

    A subset of style properties (currently transform, opacity, filter, and
    backdrop-filter) can be mutated on the compositor thread. Animations that
    mutate only these properties are candidates for being accelerated and run
    on the compositor thread which ensures they are isolated from Blink's main
    thread work.

    Whether or not an animation can be accelerated is determined by
    [CheckCanStartAnimationOnCompositor()][] which looks at several aspects
    such as the composite mode, other animations affecting same property, and
    whether the target element can be promoted and mutated in compositor.
    Reasons for not compositing animations are captured in [FailureCodes][].

    #### Lifetime of a compositor animation

    Animations that can be accelerated get added to the [PendingAnimations][]
    list. The pending list is updated as part of document lifecycle and ensures
    each pending animation gets a corresponding [cc::AnimationPlayer][]
    representing the animation on the compositor. The player is initialized with
    appropriate timing values and corresponding effects.

    Note that changing that animation playback rate, start time, or effect,
    simply adds the animation back on to the pending list and causes the
    compositor animation to be cancelled and a new one to be started. See
    [Animation::PreCommit()][] for more details.

    An accelerated animation is still running on main thread ensuring that its
    effective output is reflected in the Element style. So while the compositor
    animation updates the visuals the main thread animation updates the computed
    style. There is a special case logic to ensure updates from such accelerated
    animations do not cause spurious commits from main to compositor (See
    [CompositedLayerMapping::UpdateGraphicsLayerGeometry()][], or
    [FragmentPaintPropertyTreeBuilder::UpdateTransform()][],
    [FragmentPaintPropertyTreeBuilder::UpdateEffect()][], and
    [FragmentPaintPropertyTreeBuilder::UpdateFilter()][] for
    [BlinkGenPropertyTrees mode][])

    A compositor animation provides updates on its playback state changes (e.g.,
    on start, finish, abort) to its blink counterpart via
    [CompositorAnimationDelegate][] interface. Blink animation uses the start
    event callback to obtain an accurate start time for the animation which is
    important to ensure its output accurately reflects the compositor animation
    output.

[CheckCanStartAnimationOnCompositor()]: https://cs.chromium.org/search/?q=file:animation.h+function:CheckCanStartAnimationOnCompositor
[FailureCodes]: https://cs.chromium.org/search/?q=return%5Cs%2B(CompositorAnimations::)?FailureCode
[cc::AnimationPlayer]: https://cs.chromium.org/search/?q=file:src/cc/animation/animation_player.h+class:AnimationPlayer
[PendingAnimations]: https://cs.chromium.org/search/?q=file:pending_animations.h+class:PendingAnimations
[Animation::PreCommit()]: https://cs.chromium.org/search/?q=file:animation.h+function:PreCommit
[CompositorAnimationDelegate]: https://cs.chromium.org/search/?q=file:compositor_animation_delegate.h
[CompositedLayerMapping::UpdateGraphicsLayerGeometry()]: https://cs.chromium.org/search/?q=file:composited_layer_mapping.h+function:UpdateGraphicsLayerGeometry
[FragmentPaintPropertyTreeBuilder::UpdateTransform()]: https://cs.chromium.org/search/?q=class:FragmentPaintPropertyTreeBuilder+function:UpdateTransform
[FragmentPaintPropertyTreeBuilder::UpdateEffect()]: https://cs.chromium.org/search/?q=class:FragmentPaintPropertyTreeBuilder+function:UpdateEffect
[FragmentPaintPropertyTreeBuilder::UpdateFilter()]: https://cs.chromium.org/search/?q=class:FragmentPaintPropertyTreeBuilder+function:UpdateFilter
[BlinkGenPropertyTrees mode]: https://chromium.googlesource.com/chromium/src/+/HEAD/third_party/blink/renderer/core/paint/README.md

*   ### Javascript

    [EffectInput](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/animation/effect_input.cc)
    contains the helper functions that are used to
    [process a keyframe argument](https://drafts.csswg.org/web-animations/#processing-a-keyframes-argument)
    which can take an argument of either object or array form.

    [PlayStateUpdateScope](https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/animation/animation.h?l=323):
    whenever there is a mutation to the animation engine from JS level, this
    gets created and the destructor has the logic that handles everything. It
    keeps the old and new state of the animation, checks the difference and
    mutate the properties of the animation, at the end it calls
    SetOutdatedAnimation() to inform the animation timeline that the time state
    of this animation is dirtied.

    There are a couple of other integration points that are less critical to everyday browsing:

*   ### DevTools

    The animations timeline uses [InspectorAnimationAgent][] to track all active
    animations. This class has interfaces for pausing, adjusting
    DocumentTimeline playback rate, and seeking animations.

    InspectorAnimationAgent clones the inspected animation in order to avoid
    firing animation events, and suppresses the effects of the original
    animation. From this point on, modifications can be made to the cloned
    animation without having any effect on the underlying animation or its
    listeners.

[InspectorAnimationAgent]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/inspector/InspectorAnimationAgent.h

*   ### SVG

    The `element.animate()` API supports targeting SVG attributes in its
    keyframes. This is an experimental implementation guarded by the
    WebAnimationsSVG flag and not exposed on the web.

    This feature should provide a high fidelity alternative to our SMIL
    implementation.

## Architecture

### Animation Timing Model

The animation engine is built around the
[timing model](https://www.w3.org/TR/web-animations-1/#timing-model) described
in the Web Animations spec.

This describes a hierarchy of entities:

*   __[DocumentTimeline][]__: Represents the wall clock time.
    *   __[Animation][]__: Represents an individual animation and when it
        started playing.
        *   __[AnimationEffect][]__: Represents the effect an animation has
            during the animation (e.g. updating an element's color property).

Time trickles down from the [DocumentTimeline][] and is transformed at each
stage to produce some progress fraction that can be used to apply the effects of
the animations.

For example:

```javascript
// Page was loaded at 2:00:00PM, the time is currently 2:00:10PM.
// document.timeline.currentTime is currently 10000 (10 seconds).

let animation = element.animate([
    {transform: 'none'},
    {transform: 'rotate(200deg)'},
  ], {
    duration: 20000,  // 20 seconds
  });

animation.startTime = 6000;  // 6 seconds
```

*   __[DocumentTimeline][]__ notifies that the time is 10 seconds.
    *   __[Animation][]__ computes that its currentTime is 4 seconds due to its
        startTime being at 6 seconds.
        *   __[AnimationEffect][]__ has a duration of 20 seconds and computes
            that it has a progress of 20% from the parent animation being 4
            seconds into the animation.

            The effect is animating an element from `transform: none` to
            `transform: rotate(200deg)` so it computes the current effect to be
            `transfrom: rotate(40deg)`.

[Animation]: https://cs.chromium.org/search/?q=class:blink::Animation$
[AnimationEffect]: https://cs.chromium.org/search/?q=class:blink::AnimationEffect$
[DocumentTimeline]: https://cs.chromium.org/search/?q=class:blink::DocumentTimeline$
[EffectStack]: https://cs.chromium.org/search/?q=class:blink::EffectStack

### Lifecycle of an Animation

![Lifecycle]

1.  An [Animation][] is created via CSS1 or `element.animate()`.
2.  At the start of the next frame the [Animation][] and its [AnimationEffect][]
    are updated with the currentTime of the [DocumentTimeline][].
3.  The [AnimationEffect][] gets sampled with its computed localTime, pushes a
    [SampledEffect][] into its target element's [EffectStack][] and marks the
    elements style as dirty to ensure it gets updated later in the document
    lifecycle.
4.  During the next [style resolve][styleForElement()] on the target element all
    the [SampledEffect][]s in its [EffectStack][] are incorporated into building
    the element's [ComputedStyle][].

One key takeaway here is to note that timing updates are done in a separate
phase to effect application. Effect application must occur during style
resolution which is a highly complex process with a well defined place in the
document lifecycle. Updates to animation timing will request style updates
rather than invoke them directly.

1 CSS animations and transitions are actually created/destroyed
during style resolve (step 4). There is special logic for forcing these
animations to have their timing updated and their effects included in
the same style resolve. An unfortunate side effect of this is that style
resolution can cause style to get dirtied, this is currently a
[code health bug](http://crbug.com/492887).

[Lifecycle]: images/lifecycle.png
[SampledEffect]: https://cs.chromium.org/search/?q=class:blink::SampledEffect

### [KeyframeEffect][]

Currently all animations use [KeyframeEffect][] for their [AnimationEffect][].
The generic [AnimationEffect][] from which it inherits is an extention point in
Web Animations where other kinds of animation effects can be defined later by
other specs (for example Javascript callback based effects).

#### Structure of a [KeyframeEffect][]

*   __[KeyframeEffect][]__ represents the effect an animation has (without any
    details of when it started or whether it's playing) and is comprised of
    three things:
    *   Some __[Timing][]__ information (inherited from [AnimationEffect][]).
        [Example](http://jsbin.com/nuyohulojo/edit?js,output):
        ```javascript
        {
          duration: 4000,
          easing: 'ease-in-out',
          iterations: 8,
          direction: 'alternate',
        }
        ```
        This is used to [compute][UpdateInheritedTime()] the percentage progress
        of the effect given the duration of time that the animation has been
        playing for.

    *   The DOM __[Element][]__ that is being animated.

    *   A __[KeyframeEffectModel][]__ that holds a sequence of keyframes to
        specify the properties being animated and what values they pass
        through.
        [Example](http://jsbin.com/wiyefaxiru/1/edit?js,output):
        ```javascript
        [
          {backgroundColor: 'red', transform: 'rotate(0deg)'},
          {backgroundColor: 'yellow'},
          {backgroundColor: 'lime'},
          {backgroundColor: 'blue'},
          {backgroundColor: 'red', transform: 'rotate(360deg)'},
        ]
        ```

        These keyframes are used to compute:
        *   A __[PropertySpecificKeyframe map][KeyframeGroupMap]__ that simply
            breaks up the input multi-property keyframes into per-property
            keyframe lists.
        *   An __[InterpolationEffect][]__ which holds a set of
            [Interpolation][]s, each one representing the animated values
            between adjacent pairs of [PropertySpecificKeyframe][]s, and where
            in the percentage progress they are active.
            In the example keyframes above the [Interpolations][] generated
            would include, among the 5 different property specific keyframe
            pairs, one for `backgroundColor: 'red'` to
            `backgroundColor: 'yellow'` that applied from 0% to 25% and one for
            `transform: 'rotate(0deg)'` to `transform: 'rotate(360deg)'` that
            applied from 0% to 100%.

[Element]: https://cs.chromium.org/search/?q=class:blink::Element$
[KeyframeGroupMap]: https://cs.chromium.org/search/?q=class:blink::KeyframeEffectModelBase+KeyframeGroupMap
[PropertySpecificKeyframe]: https://cs.chromium.org/search/?q=class:blink::Keyframe::PropertySpecificKeyframe
[KeyframeEffect]: https://cs.chromium.org/search/?q=class:blink::KeyframeEffect$
[KeyframeEffectModel]: https://cs.chromium.org/search/?q=class:blink::KeyframeEffectModelBase$
[Timing]: https://cs.chromium.org/search/?q=class:blink::Timing$
[UpdateInheritedTime()]: https://cs.chromium.org/search/?q=function:%5CbAnimationEffect::UpdateInheritedTime

#### Lifecycle of an [Interpolation][]

[Interpolation][] is the data structure that [style
resolution][styleForElement()] uses to resolve what animated value to apply
to an animated element's [ComputedStyle][].

1.   [Interpolation][]s are lazily
     [instantiated][EnsureInterpolationEffectPopulated()] prior to sampling.
2.   [KeyframeEffectModel][]s are [sampled][Sample()] every frame (or as
     necessary) for a stack of [Interpolation][]s to
     [apply][ApplyAnimatedStandardProperties()] to the associated [Element][]
     and stashed away in the [Element][]'s [ElementAnimations][]'
     [EffectStack][]'s [SampledEffect][]s.
3.   During [style resolution][styleForElement()] on the target [Element][] all
     the [Interpolation][]s are [collected and organised by
     category][AdoptActiveInterpolations] according to whether it's a transition
     or not (transitions in Blink are
     [suppressed][CalculateTransitionUpdateForProperty()] in the presence of
     non-transition animations on the same property) and whether it affects
     custom properties or not (animated custom properties are
     [animation-tainted](https://www.w3.org/TR/css-variables-1/#animation-tainted)
     and affect the [processing of animation
     properties][animation-tainted-processing].
4.   TODO(alancutter): Describe what happens in processing a stack of
     interpolations.

[AdoptActiveInterpolations]: https://cs.chromium.org/search/?q=AdoptActiveInterpolations%5Cw%2B
[animation-tainted-processing]: https://cs.chromium.org/search/?q=function:blink::StyleBuilder::ApplyProperty+animation_tainted
[CalculateTransitionUpdateForProperty()]: https://cs.chromium.org/search/?q=function:blink::CSSAnimations::CalculateTransitionUpdateForProperty
[ElementAnimations]: https://cs.chromium.org/search/?q=class:blink::ElementAnimations
[EnsureInterpolationEffectPopulated()]: https://cs.chromium.org/search/?q=function:KeyframeEffectModelBase::EnsureInterpolationEffectPopulated
[Interpolation]: https://cs.chromium.org/search/?q=class:blink::Interpolation$
[InterpolationEffect]: https://cs.chromium.org/search/?q=class:blink::InterpolationEffect
[Sample()]: https://cs.chromium.org/search/?q=function:KeyframeEffectModelBase::Sample

## Testing pointers

Test new animation features using end to end web-platform-tests to ensure
cross-browser interoperability. Use unit testing when access to chrome internals
is required. Test chrome specific features such as compositing of animation
using web tests or unit tests.

### End to end testing

Features in the Web Animations spec are tested in
[web-animations][web-animations-tests]. [Writing web platform tests][] has
pointers for how to get started. If Chrome does not correctly implement the
spec, add a corresponding -expected.txt file with your test listing the expected
failure in Chrome.

[Web tests](../../../../../docs/testing/writing_web_tests.md) are located
in [third_party/blink/web_tests][]. These should be written when needing end
to end testing but either when testing chrome specific features (i.e.
non-standardized) such as compositing or when the test requires access to chrome
internal features not easily tested by web-platform-tests.

[web-animations-tests]: https://cs.chromium.org/chromium/src/third_party/blink/web_tests/external/wpt/web-animations/
[Writing web platform tests]: ../../../../../docs/testing/web_platform_tests.md#Writing-tests
[third_party/blink/web_tests]: https://cs.chromium.org/chromium/src/third_party/blink/web_tests/animations/

### Unit testing

Unit testing of animations can range from [extending Test][] when you will
manually construct an instance of your object to [extending RenderingTest][]
where you can load HTML, [enable compositing][] if necessary, and run assertions
about the state.

[extending Test]: https://cs.chromium.org/search/?q=public%5C+testing::Test+file:core%5C/animation&sq=package:chromium&type=cs
[extending RenderingTest]: https://cs.chromium.org/search/?q=public%5C+RenderingTest+file:core%5C/animation&type=cs
[enable compositing]: https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/animation/compositor_animations_test.cc?type=cs&sq=package:chromium&q=file:core%5C/animation%5C/.*test%5C.cpp+EnableCompositing

## Ongoing work

### Properties And Values API

TODO: Summarize properties and values API.

### Web Animations API

TODO: Summarize Web Animations API.

### [Animation Worklet](../../modules/animationworklet/README.md)

AnimationWorklet is a new primitive for creating high performance procedural
animations on the web. It is being incubated as part of the
[CSS Houdini task force](https://github.com/w3c/css-houdini-drafts/wiki), and if
successful will be transferred to that task force for full standardization.

A [WorkletAnimation][] behaves and exposes the same animation interface as other
web animation but it allows the animation itself to be highly customized in
Javascript by providing an `animate` callback. These animations run inside an
isolated worklet global scope.

[WorkletAnimation]: https://cs.chromium.org/search/?q=file:animationworklet/worklet_animation.h+class:WorkletAnimation


text:
<?php

namespace Esier\Models\Endpoints;

trait ChecksParameters
{
    /*
    *	Checks that a parameter should be added to the given array and adds it
    *
    *	@param &array $array
    *	@param string $key
    *	@param mixed $value
    *
    *	@return void
    */
    private function addParameter(array &$array, string $key, $value)
    {
        if ($value !== null) {
            $array[$key] = $value;
        }
    }
}


text:
from __future__ import print_function
from __future__ import division
import sys
from builtins import zip
import nineml.units as un
from argparse import ArgumentParser
import ninemlcatalog
import quantities as pq
import numpy as np
import neo
import nest
import pype9.utils.logging.handlers.sysout  # @UnusedImport

min_delay = 0.1
max_delay = 10.0

def argparser():
    parser = ArgumentParser()
    parser.add_argument('--fast_spiking', action='store_true', default=False,
                        help=("Whether to use the \"fast-spiking\" version of "
                              "the Izhikevich neuron or not"))
    parser.add_argument('--simtime', type=float, default=200.0,
                        help="The length of the simulation in ms")
    parser.add_argument('--timestep', type=float, default=0.001,
                        help="Simulation timestep")
    parser.add_argument('--simulators', type=str, nargs='+',
                        default=['neuron', 'nest'],
                        help="Which simulators to simulate the 9ML network")
    parser.add_argument('--plot_start', type=float, default=0.0,
                        help=("The time to start plotting from"))
    parser.add_argument('--build_mode', type=str, default='lazy',
                        help=("The build mode with which to construct the "
                              "network. 'lazy' will only regenerate and "
                              "compile the source files if the network has "
                              "changed, whereas 'force' will always rebuild "
                              "the network"))
    parser.add_argument('--seed', type=int, default=None,
                        help="Random seed passed to the simulators")
    parser.add_argument('--reference', action='store_true', default=False,
                        help="Plot a reference NEST implementation alongside")
    parser.add_argument('--save_fig', type=str, default=None,
                        help=("Location to save the generated figures"))
    parser.add_argument('--figsize', nargs=2, type=float, default=(10, 15),
                        help="The size of the figures")
    parser.add_argument('--input_start', type=float, default=50.0,
                        help="Time step input current starts")
    parser.add_argument('--input_amplitude', type=float, default=None,
                        help="Amplitude of the input current step (pA)")
    return parser

def run(argv):

    args = argparser().parse_args(argv)

    if args.reference and args.fast_spiking:
        raise Exception(
            "--reference and --fast_spiking options cannot be used together as"
            " there is no reference implementation for the fast-spiking model")

    # Set the random seed
    np.random.seed(args.seed)
    seeds = np.asarray(
        np.floor(np.random.random(len(args.simulators)) * 1e5), dtype=int)

    # Set of simulators to run
    simulators_to_run = set(args.simulators)
    if args.reference:
        simulators_to_run.add('nest')

    MetaClasses = {}
    Simulations = {}
    if 'neuron' in simulators_to_run:
        from pype9.simulate.neuron import (
            CellMetaClass as CellMetaClassNEURON,
            Simulation as SimulationNEURON)
        Simulations['neuron'] = SimulationNEURON
        MetaClasses['neuron'] = CellMetaClassNEURON
    if 'nest' in simulators_to_run:
        from pype9.simulate.nest import (
            CellMetaClass as CellMetaClassNEST,
            Simulation as SimulationNEST)
        Simulations['nest'] = SimulationNEST
        MetaClasses['nest'] = CellMetaClassNEST

    if args.fast_spiking:
        model = ninemlcatalog.load('neuron/Izhikevich',
                                   'IzhikevichFastSpiking')
        properties = ninemlcatalog.load('neuron/Izhikevich',
                                        'SampleIzhikevichFastSpiking')
        initial_states = {'U': -1.625 * pq.pA, 'V': -70.0 * pq.mV,
                          'regime_': 'subthreshold'}
        input_port_name = 'iSyn'
        if args.input_amplitude is None:
            input_amp = 100 * pq.pA
        else:
            input_amp = args.input_amplitude * pq.pA
        # Designate 'iSyn' as an "external" current so that we can play
        # signals into it.
        metaclass_kwargs = {'external_currents': ['iSyn']}
    else:
        model = ninemlcatalog.load('neuron/Izhikevich', 'Izhikevich')
        properties = ninemlcatalog.load('neuron/Izhikevich',
                                        'SampleIzhikevich')
        initial_states = {'U': -14.0 * pq.mV / pq.ms, 'V': -70.0 * pq.mV}
        input_port_name = 'Isyn'
        if args.input_amplitude is None:
            input_amp = 15 * pq.pA
        else:
            input_amp = args.input_amplitude * pq.pA
        metaclass_kwargs = {}  # Isyn should be guessed as an external current

    # Create an input step current
    # NB: The analog signal needs to be offset > "device delay" (i.e. the
    #     delay from the current source) when playing into NEST cells
    offset = min_delay + args.timestep
    num_preceding = int(np.floor((args.input_start - offset) /
                                 args.timestep))
    num_remaining = int(np.ceil((args.simtime - args.input_start) /
                                args.timestep))
    amplitude = float(pq.Quantity(input_amp, 'nA'))
    input_signal = neo.AnalogSignal(
        np.concatenate((np.zeros(num_preceding),
                        np.ones(num_remaining) * amplitude)),
        sampling_period=args.timestep * pq.ms, units='nA', time_units='ms',
        t_start=offset * pq.ms)

    cells = {}
    for simulator, seed in zip(simulators_to_run, seeds):
        with Simulations[simulator](
            min_delay=min_delay * un.ms, max_delay=max_delay * un.ms,
            dt=args.timestep * un.ms,
                seed=seed) as sim:
            # Construct the cells and set up recordings and input plays
            if simulator in args.simulators:
                Cell = MetaClasses[simulator](model, **metaclass_kwargs)
                cells[simulator] = Cell(properties, **initial_states)
                # Play input current into cell
                cells[simulator].play(input_port_name, input_signal)
                # Record voltage
                cells[simulator].record('V')
            if args.reference:
                _, ref_multi, _ = construct_reference(input_signal,
                                                      args.timestep)
            sim.run(args.simtime * un.ms)

    # Plot the results
    if args.save_fig is not None:
        import matplotlib
        matplotlib.use('Agg')
    # Needs to be imported after the args.save_fig argument is parsed to
    # allow the backend to be set
    from matplotlib import pyplot as plt  # @IgnorePep8

    print("Plotting the results")
    plt.figure(figsize=args.figsize)
    if args.fast_spiking:
        title = "Izhikevich Fast Spiking"
    else:
        title = "Izhikevich Original"
    plt.title(title)
    legend = []
    for simulator in args.simulators:
        v = cells[simulator].recording('V')
        v = v.time_slice(args.plot_start * pq.ms, v.t_stop)
        plt.plot(v.times, v)
        legend.append(simulator.upper())
    if args.reference:
        events = nest.GetStatus(ref_multi, ["events"])[0]
        t, v = np.asarray(events['times']), np.asarray(events['V_m'])
        inds = t > args.plot_start
        plt.plot(t[inds], v[inds])
        legend.append('Ref. NEST')
    plt.xlabel('Time (ms)')
    plt.ylabel('Membrane Voltage (mV)')
    plt.legend(legend)
    if args.save_fig is not None:
        plt.savefig(args.save_fig)
    else:
        plt.show()
    print("done")

def construct_reference(input_signal, dt):
    params = {
        'a': 0.2,
        'b': 0.025,
        'c': -75.0,
        'd': 0.2,
        'V_th': -50.0,
        'U_m': -14.0,
        'V_m': -70.0}
    cell = nest.Create('izhikevich', 1, params)
    generator = nest.Create(
        'step_current_generator', 1,
        {'amplitude_values': pq.Quantity(input_signal, 'pA'),
         'amplitude_times': (input_signal.times.rescale(pq.ms) -
                             min_delay * pq.ms),
         'start': float(input_signal.t_start.rescale(pq.ms)),
         'stop': float(input_signal.t_stop.rescale(pq.ms))})
    nest.Connect(generator, cell, syn_spec={'delay': min_delay})
    multimeter = nest.Create('multimeter', 1, {"interval": dt})
    nest.SetStatus(multimeter, {'record_from': ['V_m']})
    nest.Connect(multimeter, cell)
    return (cell, multimeter, generator)

if __name__ == "__main__":
    run(sys.argv[1:])


text:
cask 'font-odor-mean-chey' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/odormeanchey/OdorMeanChey.ttf'
  name 'Odor Mean Chey'
  homepage 'https://www.google.com/fonts/specimen/Odor+Mean+Chey'

  font 'OdorMeanChey.ttf'
end


text:
package org.spotter.eclipse.ui.handlers;

import java.util.Map;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.spotter.eclipse.ui.Activator;
import org.spotter.eclipse.ui.navigator.SpotterProjectResults;

/**
 * A refresh handler for the refresh command which refreshes the elements shown
 * in the navigator.
 *
 * @author Denis Knoepfle
 *
 */
public class RefreshHandler extends AbstractHandler implements ISelectionChangedListener {

	/**
	 * The id of the refresh command.
	 */
	public static final String REFRESH_COMMAND_ID = "org.spotter.eclipse.ui.commands.refresh";

	private boolean isEnabled;

	/**
	 * Constructor.
	 */
	public RefreshHandler() {
		super();
		selectionChanged(null);
		Activator.getDefault().addProjectSelectionListener(this);
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		Activator activator = Activator.getDefault();
		Map<String, SpotterProjectResults> historyElements = activator.getProjectHistoryElements();

		for (IProject project : activator.getSelectedProjects()) {
			String projectName = project.getName();
			SpotterProjectResults history = historyElements.get(projectName);
			if (history != null) {
				history.refreshChildren();
			}
		}

		activator.getNavigatorViewer().refresh();

		return null;
	}

	/**
	 * Only enable refresh if at least one project is the current selected
	 * project.
	 *
	 * @return true when at least one project is selected
	 */
	@Override
	public boolean isEnabled() {
		return isEnabled;
	}

	@Override
	public void selectionChanged(SelectionChangedEvent event) {
		this.isEnabled = !Activator.getDefault().getSelectedProjects().isEmpty();
	}

}


text: google-site-verification: google3d2f3cd4cc2bb44b.html


text:
EPUBJS.Hooks.register("beforeChapterDisplay").music = function(callback, chapter){

		var trans = chapter.doc.querySelectorAll('audio'),
			items = Array.prototype.slice.call(trans),
			playing = false;

		items.forEach(function(item){
			var onSpread = 0;

			function getPage() {
				left = item.getBoundingClientRect().left;
				onSpread = Math.floor(left / chapter.spreadWidth) + 1; //-- pages start at 1
				//console.log("left", left, onPage)
				// width = orginal_width;
				// height = orginal_height;
				//
				// if(width > chapter.colWidth){
				// 	ratio = chapter.colWidth / width;
				//
				// 	width = chapter.colWidth;
				// 	height = height * ratio;
				// }
				//
				// iframe.width = width;
				// iframe.height = height;
			}

			function shouldPlay(e) {
				page = 1;
				if(e) page = e.msg;

				if(page != onSpread) return;

				if(playing) playing.pause();

				item.play();

				playing = item;

				console.log("start", item.src)

			}

			//-- resize event

			chapter.book.listenUntil("book:resized", "book:chapterDestroy", getPage);

			chapter.book.listenUntil("book:pageChanged", "book:chapterDestroy", shouldPlay);

			item.removeAttribute("controls");

			getPage();
			shouldPlay();

		});

		if(callback) callback();

}


text:
require_dependency "cohesive_admin/application_controller"

# Controller providing simple management of image and file assets for the Froala WYSIWYG editor
module CohesiveAdmin
  class S3AssetsController < ApplicationController

    before_action :load_bucket

    def index

      @items = []
      # , encoding_type: 'url'
      @bucket.objects({ prefix: @prefix }).each do |o|
        @items << { url: o.public_url, thumb: o.public_url, key: o.key }
      end

      respond_to do |format|
        format.html {
          render json: @items
        }
      end
    end

    def delete
      # attempt to prevent manipulation
      if params["data-key"].index(@prefix) == 0
        @item = @bucket.object(params["data-key"])
        if @item.exists?
          # good to delete
          begin
            @item.delete
            respond_to do |format|
              format.html {
                render json: { status: 'success' }
              }
            end and return
          rescue => exception
            error = "Delete failed. AWS Error."
          end
        else
          error = "File not found: #{params["data-key"]}"
        end
      else
        error = "Invalid file key: #{params["data-key"]}"
      end

      respond_to do |format|
        format.html {
          render json: { error: error }
        }
      end
    end

    private
      def load_bucket
        @bucket = Aws::S3::Bucket.new(CohesiveAdmin.config.aws[:bucket])
        type = %w{images files}.include?(params[:type]) ? params[:type] : 'images'
        @prefix = %Q{#{CohesiveAdmin.config.aws[:key_start]}#{type}/}
      end

  end
end


text:
package ru.roborox.itunesconnect.api;

import org.testng.annotations.Test;
import ru.roborox.itunesconnect.api.analytics.model.App;
import ru.roborox.itunesconnect.api.analytics.model.TimeSeriesGroup;
import ru.roborox.itunesconnect.api.analytics.model.TimeSeriesRequest;
import ru.roborox.itunesconnect.api.analytics.model.TimeSeriesResponse;
import ru.roborox.itunesconnect.api.analytics.model.enums.Dimension;
import ru.roborox.itunesconnect.api.analytics.model.enums.Measure;
import ru.roborox.itunesconnect.api.analytics.model.enums.Period;
import ru.roborox.itunesconnect.api.common.Sort;

import java.io.IOException;

public class AnalyticsApiTest extends AbstractItunesConnectApiTest {

    @Test
    public void getUnitsForAllApps() throws IOException {
        getTimeSeriesForAllApps(adamId -> new TimeSeriesRequest(adamId, Period.DAY, Measure.UNITS, start, end, null));
    }

    @Test
    public void getUnitsForAllAppsByTerritory() throws IOException {
        final TimeSeriesGroup group = new TimeSeriesGroup(Measure.UNITS, Dimension.TERRITORY, Sort.ASCENDING, 3);
        getTimeSeriesForAllApps(adamId -> new TimeSeriesRequest(adamId, Period.DAY, Measure.UNITS, start, end, group));
    }

    private void getTimeSeriesForAllApps(IOFunction<String, TimeSeriesRequest> requestFunction) throws IOException {
        int total = 0;
        for (App app : getAnalyticsApi().getApps().getResults()) {
            logger.info("processing {}", app.getName());
            final TimeSeriesResponse byTerritory = getAnalyticsApi().getTimeSeries(requestFunction.apply(app.getAdamId()));
            if (byTerritory.getResults() != null) {
                final int sum = byTerritory.getResults().stream()
                        .flatMap(t -> t.getData().stream())
                        .mapToInt(item -> item.getValue().intValue())
                        .sum();
                logger.info("total sum for {} is {}", app.getName(), sum);
                total += sum;
            } else {
                logger.info("no results for {}", app.getName());
            }
        }
        logger.info("total sum for all apps is {}", total);
    }

    private interface IOFunction<T, R> {
        R apply(T t) throws IOException;
    }
}