text:
using CoSales.Model.PO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;

namespace CoSales.BLL
{
    /// <summary>
    /// 全局变量的保存
    /// </summary>
    public class ContextObjects
    {
        /// <summary>
        /// 静态变量 保存当前用户
        /// </summary>
        public static User CurrentUser
        {
            get { return HttpContext.Current.Session["CurUser"] as User; }
            set { HttpContext.Current.Session["CurUser"] = value; }
        }

        /// <summary>
        /// 所有附件资源保存的根路径
        /// 在web.config中配置
        /// </summary>
        private static string baseFilePath;
        public static string BaseFilePath
        {
            get
            {
                if (string.IsNullOrEmpty(baseFilePath))
                {
                    baseFilePath = System.Web.Configuration.WebConfigurationManager.AppSettings["FilePath"];
                }
                return baseFilePath;
            }
        }

        /// <summary>
        /// 用户头像保存位置
        /// </summary>
        public static string UserImagePath
        {
            get
            {
                return Path.Combine(BaseFilePath, "UserImage");
            }
        }

        /// <summary>
        /// 产品描述相关图片
        /// </summary>
        public static string ProductImagePath
        {
            get
            {
                return Path.Combine(BaseFilePath, "ProductImage");
            }
        }
    }
}


text:
:LastChangedDate: $LastChangedDate$
:LastChangedRevision: $LastChangedRevision$
:LastChangedBy: $LastChangedBy$

Creating a custom server
========================
The builtin DNS server plugin is useful,
but the beauty of Twisted Names is that you can build your own custom servers and clients using the names components.

 - In this section you will learn about the components required to build a simple DNS server.
 - You will then learn how to create a custom DNS server which calculates responses dynamically.

A simple forwarding DNS server
------------------------------
Lets start by creating a simple forwarding DNS server, which forwards all requests to an upstream server (or servers).

:download:`simple_server.py <listings/names/simple_server.py>`

.. literalinclude:: listings/names/simple_server.py

In this example we are passing a :api:`twisted.names.client.Resolver <client.Resolver>` instance
to the :api:`twisted.names.server.DNSServerFactory <DNSServerFactory>`
and we are configuring that client to use the upstream DNS servers which are specified in a local ``resolv.conf`` file.

Also note that we start the server listening on both UDP and TCP ports.
This is a standard requirement for DNS servers.

You can test the server using ``dig``.
For example:

.. code-block:: console

    $ dig -p 10053 @127.0.0.1 example.com SOA +short
    sns.dns.icann.org. noc.dns.icann.org. 2013102791 7200 3600 1209600 3600

A server which computes responses dynamically
---------------------------------------------
Now suppose we want to create a bespoke DNS server which responds to certain hostname queries
by dynamically calculating the resulting IP address, while passing all other queries to another DNS server.
Queries for hostnames matching the pattern **workstation{0-9}+**
will result in an IP address where the last octet matches the workstation number.

We'll write a custom resolver which we insert before the standard client resolver.
The custom resolver will be queried first.

Here's the code:

:download:`override_server.py <listings/names/override_server.py>`

.. literalinclude:: listings/names/override_server.py

Notice that ``DynamicResolver.query`` returns a :api:`twisted.internet.defer.Deferred <Deferred>`.
On success, it returns three lists of DNS records (answers, authority, additional),
which will be encoded by :api:`twisted.names.dns.Message <dns.Message>` and returned to the client.
On failure, it returns a :api:`twisted.names.error.DomainError <DomainError>`,
which is a signal that the query should be dispatched to the next client resolver in the list.

.. note::
   The fallback behaviour is actually handled by :api:`twisted.names.resolve.ResolverChain <ResolverChain>`.

   ResolverChain is a proxy for other resolvers.
   It takes a list of :api:`twisted.internet.interfaces.IResolver <IResolver>` providers
   and queries each one in turn until it receives an answer, or until the list is exhausted.

   Each :api:`twisted.internet.interfaces.IResolver <IResolver>` in the chain may return a deferred :api:`twisted.names.error.DomainError <DomainError>`,
   which is a signal that :api:`twisted.names.resolve.ResolverChain <ResolverChain>` should query the next chained resolver.

   The :api:`twisted.names.server.DNSServerFactory <DNSServerFactory>` constructor takes a list of authoritative resolvers, caches and client resolvers
   and ensures that they are added to the :api:`twisted.names.resolve.ResolverChain <ResolverChain>` in the correct order.

Let's use ``dig`` to see how this server responds to requests that match the pattern we specified:

.. code-block:: console

    $ dig -p 10053 @127.0.0.1 workstation1.example.com A +short
    172.0.2.1

    $ dig -p 10053 @127.0.0.1 workstation100.example.com A +short
    172.0.2.100

And if we issue a request that doesn't match the pattern:

.. code-block:: console

    $ dig -p 10053 @localhost www.example.com A +short
    93.184.216.119

Further Reading
---------------
For simplicity, the examples above use the ``reactor.listenXXX`` APIs.
But your application will be more flexible if you use the :doc:`Twisted Application APIs <../../core/howto/application>`,
along with the :doc:`Twisted plugin system <../../core/howto/plugin>` and ``twistd``.
Read the source code of :api:`twisted.names.tap <names.tap>` to see how the ``twistd names`` plugin works.

redpajama_set_name: RedPajamaGithub


text:
class CreateDanvanthiriCoreMedicineOrders < ActiveRecord::Migration
  def change
    create_table :danvanthiri_core_medicine_orders do |t|
      t.integer :owner_id
      t.string :owner_type
      t.integer :orderable_id
      t.string :orderable_type
      t.string :first_name
      t.string :last_name
      t.string :addr_line_1
      t.string :addr_line_2
      t.string :addr_city
      t.string :addr_state
      t.string :addr_pin
      t.string :phone_number
      t.integer :status

      t.timestamps null: false
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>package</id>
    <includeBaseDirectory>false</includeBaseDirectory>
    <fileSets>
        <fileSet>
            <directory>${project.build.outputDirectory}</directory>
            <outputDirectory>.</outputDirectory>
            <useDefaultExcludes>false</useDefaultExcludes>
        </fileSet>
    </fileSets>
</assembly>


text:
package net.radai.beanz.util;

import java.lang.reflect.Type;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;

public class ReflectionUtilTest {
    @SuppressWarnings("unused") //it is, via reflection
    private Map<String, String> map;

    @Test
    public void testErase() throws Exception {
        Type mapType = getClass().getDeclaredField("map").getGenericType();
        Assert.assertNotEquals(Map.class, mapType);
        Assert.assertEquals(Map.class, ReflectionUtil.erase(mapType));
    }
}


text:
package tfm.examples

import cats.FlatMap
import cats.state.State
import cats.std.function._
import cats.syntax.flatMap._
import cats.syntax.functor._

import tfm.{fin, local}

@fin("TerminalIO")
trait TerminalInterpreter[F[_]] {
  @local def F: FlatMap[F]
  def join[A](lhs: F[A], rhs: F[A]): F[A] = lhs

  // Not valid algebra - `f` has type containing `F[_]`, namely `Function1[A, F[B]]`
  // def flatMap[A, B](fa: F[A])(f: A => F[B]): F[B] = ???

  val readLine: F[String]
  def writeLine(string: String): F[Unit]
}

object TerminalInterpreter {
  val io: TerminalInterpreter[IO] =
    new TerminalInterpreter[IO] {
      val console = System.console()

      val F: FlatMap[IO] = FlatMap[IO]
      val readLine: IO[String] = IO { console.readLine() }
      def writeLine(string: String): IO[Unit] = IO { println(string) }
    }

  type MockState[A] = State[Mock, A]
  val mock: TerminalInterpreter[MockState] =
    new TerminalInterpreter[MockState] {
      val F: FlatMap[MockState] = FlatMap[MockState]
      val readLine: MockState[String] = State(Mock.read)
      def writeLine(string: String): MockState[Unit] = State.modify(Mock.write(string))
    }

  implicit val terminalIOFlatMap: FlatMap[TerminalIO] =
    new FlatMap[TerminalIO] {
      def flatMap[A, B](fa: TerminalIO[A])(f: A => TerminalIO[B]): TerminalIO[B] =
        new TerminalIO[B] {
          def run[F[_]](interpreter: TerminalInterpreter[F]): F[B] =
            interpreter.F.flatMap(fa.run(interpreter))(a => f(a).run(interpreter))
        }

      def map[A, B](fa: TerminalIO[A])(f: A => B): TerminalIO[B] =
        new TerminalIO[B] {
          def run[F[_]](interpreter: TerminalInterpreter[F]): F[B] =
            interpreter.F.map(fa.run(interpreter))(f)
        }
    }
}

object TerminalIOApp extends App {
  import TerminalInterpreter.language._

  val program =
    for {
      _ <- writeLine("Enter something")
      x <- readLine
      _ <- writeLine("Enter another thing")
      y <- readLine
      _ <- writeLine(x ++ " " ++ y)
    } yield ()

  // Mock
  val init = Mock(in = List("Hello", "World"), out = List())
  println("Mock: " ++ program.run(TerminalInterpreter.mock).runS(init).run.toString)

  val program2 = join(writeLine("join1"), writeLine("join2"))
  val init2 = Mock(List(), List())
  println("Join: " ++ program2.run(TerminalInterpreter.mock).runS(init2).run.toString)

  // Real
  program.run(TerminalInterpreter.io).unsafePerformIO()
}

trait IO[A] { def unsafePerformIO(): A }

object IO {
  def apply[A](a: => A): IO[A] = new IO[A] { def unsafePerformIO(): A = a }

  implicit val ioMonad: FlatMap[IO] =
    new FlatMap[IO] {
      def flatMap[A, B](fa: IO[A])(f: A => IO[B]): IO[B] =
        f(fa.unsafePerformIO())

      def map[A, B](fa: IO[A])(f: A => B): IO[B] =
        new IO[B] { def unsafePerformIO(): B = f(fa.unsafePerformIO()) }
    }
}

case class Mock(in: List[String], out: List[String])

object Mock {
  def read(mock: Mock): (Mock, String) = mock.in match {
    case Nil => (mock, "")
    case h :: t => (mock.copy(in = t), h)
  }

  def write(value: String)(mock: Mock): Mock =
    mock.copy(out = value :: mock.out)
}


text:
% [INPUT]
% handle = A handle to the plotting function to be executed.

function safe_plot(varargin)

    persistent ip;

    if (isempty(ip))
        ip = inputParser();
        ip.addRequired('handle',@(x)validateattributes(x,{'function_handle'},{'scalar'}));
    end

    ip.parse(varargin{:});
    ipr = ip.Results;

    nargoutchk(0,0);

    safe_plot_internal(ipr.handle);

end

function safe_plot_internal(handle)

    persistent ids;

    name = func2str(handle);
    name = regexprep(name,'^@\([^)]*\)','');
    name = regexprep(name,'\([^)]*\)$','');

    try
        id = [upper(name) '-' upper(char(java.util.UUID.randomUUID()))];
    catch
        id = randi([0 10000000]);

        while (ismember(id,ids))
            id = randi([0 100000]);
        end

        ids = [ids; id];
        id = [upper(name) '-' sprintf('%08s',num2str(id))];
    end

    try
        handle(id);
    catch e
        delete(findobj('Type','Figure','Tag',id));

        try
            r = getReport(e,'Extended','Hyperlinks','off');
            r = strsplit(r,new_line());
            r = cellfun(@(x)['  ' x],r,'UniformOutput',false);
            r = strjoin(r,new_line());
            r = clear_text(r);

            warning('MATLAB:SystemicRisk',['The following exception occurred in the plotting function ''' name ''':' new_line() r]);
        catch
            warning('MATLAB:SystemicRisk',['The following exception occurred in the plotting function ''' name ''':' new_line() e.message]);
        end
    end

end


text:
var mongoose = require('mongoose'),
    Q        = require('q'),
    helper   = require('../helpers/mongoose_helper.js'),
    app      = require('../app.js'),
    config   = require('../config.js');

/**
 * Repository route.
 * @param {Object} params
 * @returns {Object}
 */
var repos = function(params) {

    if (!config.github.login) {
        throw new Error('Configuration parameter "github.login" must be set.');
    }

    if (!config.cacheDuration && config.cacheDuration !== 0) {
        throw new Error('Configuration parameter "cacheDuration" must be set.');
    }

    // Repository schema.
    var repoSchema = mongoose.Schema({
        name: String,
        full_name: String,
        description: String,
        fork: Boolean,
        url: String,
        owner_name: String,
        owner_url: String,
        owner_avatar_url: String,
        num_watchers: Number,
        num_forks: Number,
        num_issues: Number,
        sizs: Number,
        tags: Array,
        gh_updated_at: Date,
        gh_created_at: Date,
        gh_pushed_at: Date,
        visible: Boolean,
        created_at: Date
    });

    // Repository model.
    var Repo = mongoose.model('Repo', repoSchema);

    // Stargazer schema.
    var stargazerSchema = mongoose.Schema({
        name: String,
        url: String,
        repo_name: String,
        avatar_url: String,
        created_at: Date
    });

    var Stargazer = mongoose.model('Stargazer', stargazerSchema);

    /**
     * Creates or updates a repository.
     * @param {Object} data
     * @returns {promise}
     */
    var upsertRepo = function(data) {
        return helper.upsert(Repo, {
            name: data.name,
            owner_name: data.owner.login
        }/* conds */, {
            name: data.name,
            full_name: data.full_name,
            description: data.description,
            fork: data.fork,
            url: data.html_url,
            owner_name: data.owner.login,
            owner_url: data.owner.html_url,
            owner_avatar_url: data.owner.avatar_url,
            num_watchers: data.watchers_count,
            num_forks: data.forks_count,
            num_issues: data.open_issues_count,
            size: data.size,
            gh_updated_at: data.updated_at,
            gh_created_at: data.created_at,
            gh_pushed_at: data.pushed_at,
            visible: true,
            created_at: new Date()
        }/* attrs */);
    };

    /**
     * Creates or updates all stargazers for a repository.
     * @param {Object} data
     * @returns {promise}
     */
    var upsertRepos = function(data) {
        return helper.upsertAll(upsertRepo, data);
    };

    // Exposed methods.
    return {
        /**
         * Lists all repositories.
         * @param req
         * @param res
         */
        findRepos: function(req, res) {
            var ownerName = config.github.login;

            /**
             * Fetches all repositories.
             * @returns {promise}
             */
            var find = function() {
                return helper.find(Repo, {
                    fork: false
                });
            };

            /**
             * Checks if repository models have expired and fetches new data from github if necessary.
             * @param {Array} repos
             * @returns {promise}
             */
            var checkExpired = function(repos) {
                var deferred = Q.defer(),
                    nowTime = new Date().getTime(),
                    expiresAt = new Date(nowTime - config.cacheDuration);
                if (repos.length && (repos[0].created_at > expiresAt)) {
                    console.log('repositories for user "' + ownerName + '" finded from cache (expires at ' + expiresAt + ').');
                    deferred.resolve(repos);
                } else {
                    console.log('synchronizing repositories for user "' + ownerName + '".');
                    params.github.repos(ownerName)
                        .then(upsertRepos)
                        .then(find)
                        .then(function(repos) {
                            deferred.resolve(repos);
                        }, function(err) {
                            deferred.reject(err);
                        });
                }
                return deferred.promise;
            };

            // Fetch all repositories, synchronize from github if the cached models have expired
            // and send the repositories through the response object.
            find()
                .then(checkExpired)
                .then(function(repos) {
                    res.send(repos);
                }, function(err) {
                    console.log('error: ' + err);
                });
        },
        /**
         * Lists all repositories.
         * @param req
         * @param res
         */
        findForks: function(req, res) {
            if (!req.params.repo) {
                throw new Error('Request parameter "repo" must be given.');
            }

            var ownerName = config.github.login,
                repoName = req.params.repo;

            /**
             * Fetches all forks for a repository.
             * @returns {promise}
             */
            var find = function() {
                return helper.find(Repo, {
                    name: repoName,
                    fork: true
                });
            };

            /**
             * Checks if fork models have expired and fetches new data from github if necessary.
             * @param {Array} forks
             * @returns {promise}
             */
            var checkExpired = function(forks) {
                var deferred = Q.defer(),
                    nowTime = new Date().getTime(),
                    expiresAt = new Date(nowTime - config.cacheDuration);
                if (forks.length && (forks[0].created_at > expiresAt)) {
                    console.log('forks for repository "' + repoName + '" fetched from cache (expires at ' + expiresAt + ').');
                    deferred.resolve(forks);
                } else {
                    console.log('synchronizing forks for repository "' + repoName + '".');
                    params.github.forks(ownerName, repoName)
                        .then(upsertRepos)
                        .then(find)
                        .then(function(forks) {
                            deferred.resolve(forks);
                        }, function(err) {
                            deferred.reject(err);
                        });
                }
                return deferred.promise;
            };

            // Fetch all forks, synchronize from github if the cached models have expired
            // and send the forks through the response object.
            find()
                .then(checkExpired)
                .then(function(forks) {
                    res.send(forks);
                }, function(err) {
                    console.log('error: ' + err);
                });
        },
        /**
         * Lists all stargazers.
         * @param req
         * @param res
         */
        findStargazers: function(req, res) {
            if (!req.params.repo) {
                throw new Error('Request parameter "repo" must be given.');
            }

            var ownerName = config.github.login,
                repoName = req.params.repo;

            /**
             * Fetches all stargazers for a repository.
             * @returns {promise}
             */
            var find = function() {
                return helper.find(Stargazer, {
                    repo_name: repoName
                });
            };

            /**
             * Creates or updates a stargazer.
             * @param {Object} data
             * @returns {promise}
             */
            var upsert = function(data) {
                return helper.upsert(Stargazer, {
                    name: data.login,
                    repo_name: repoName
                }/* conds */, {
                    name: data.login,
                    url: data.html_url,
                    repo_name: repoName,
                    avatar_url: data.avatar_url,
                    created_at: new Date()
                }/* attrs */);
            };

            /**
             * Creates or updates stargazers for a repository.
             * @param {Object} data
             * @returns {promise}
             */
            var upsertAll = function(data) {
                return helper.upsertAll(upsert, data);
            };

            /**
             * Checks if stargazer models have expired and fetches new data from github if necessary.
             * @param {Array} stargazers
             * @returns {promise}
             */
            var checkExpired = function(stargazers) {
                var deferred = Q.defer(),
                    nowTime = new Date().getTime(),
                    expiresAt = new Date(nowTime - config.cacheDuration);
                if (stargazers.length && (stargazers[0].created_at > expiresAt)) {
                    console.log('stargazers for repository "' + repoName + '" finded from cache (expires at ' + expiresAt + ').');
                    deferred.resolve(stargazers);
                } else {
                    console.log('synchronizing stargazers for repository "' + repoName + '".');
                    params.github.stargazers(ownerName, repoName)
                        .then(upsertAll)
                        .then(find)
                        .then(function(stargazers) {
                            deferred.resolve(stargazers);
                        }, function(err) {
                            deferred.reject(err);
                        });
                }
                return deferred.promise;
            };

            // Fetch all stargazers, synchronize from github if the cached models have expired
            // and send the stargazers through the response object.
            find()
                .then(checkExpired)
                .then(function(stargazers) {
                    res.send(stargazers);
                }, function(err) {
                    console.log('error: ' + err);
                });
        }
    };
};

module.exports = repos;


text:
import { prop, computed, container } from 'frptools';

import {
    subscribeToRender,
    defineView,
    nodeParentWithType,
    fullViewportSize,
    defineElement as el,
    injectView as iv
} from '../utils/domvm.js';

import { router } from '../services/router.js';
import { ImageType } from '../data/image.js';
import { pouchDocHash, pick } from '../utils/conversion.js';
import { AttachmentImageView } from './components/attachmentImage.js';
import { Overlay } from './components/overlay.js';
import { Icon } from './components/icon.js';
import { AppBar } from './components/appbar.js';
import { styled, injectStyle } from '../services/style.js';
import { error } from '../services/console.js';
import { CLICKABLE, FILL_STYLE } from './styles.js';

export function FocusView(vm, params) {
    const id = prop();
    const doc = prop({}, pouchDocHash);
    const nextLink = prop();
    const prevLink = prop();
    const mouseActive = prop(true);
    let mouseMoveTimeout = null;

    const appBarStyle = computed(
        mA => ({
            position: 'fixed',
            opacity: mA ? 1 : 0,
            backgroundImage: 'linear-gradient(0deg,rgba(0,0,0,0),rgba(0,0,0,0.4))'
        }),
        [mouseActive],
        s => s.opacity
    );
    const imageStyle = computed(({ width: iw, height: ih }, { width: vw, height: vh }) => {
        const imageRatio = iw / ih;
        const windowRatio = vw / vh;
        if (iw < vw && ih < vh) {
            return {
                height: ih,
                width: iw
            }
        }
        if (windowRatio > imageRatio) {
            return {
                height: vw / windowRatio,
                width: vw / windowRatio * imageRatio
            }
        }
        return {
            height: vh * windowRatio / imageRatio,
            width: vh * windowRatio
        }
    }, [doc, fullViewportSize]);

    function navBack() {
        router.goto('home');
    }

    async function clickTrash() {
        if (confirm('Delete this image?')) {
            await ImageType.delete(id());
            navBack();
        }
    }

    const mouseLeave = () => {
        mouseActive(false);
    };

    const mouseMove = () => {
        if (mouseMoveTimeout !== null) {
            clearTimeout(mouseMoveTimeout);
        }
        mouseMoveTimeout = setTimeout(mouseLeave, 3000);
        mouseActive(true);
    };

    const mouseClick = () => {
        if (mouseMoveTimeout !== null) {
            clearTimeout(mouseMoveTimeout);
        }
        mouseActive(!mouseActive());
    }

    // Subscribe to our changables.
    subscribeToRender(vm, [
        doc,
        nextLink,
        prevLink,
        appBarStyle,
        // Look for our image and set it.
        () => id.subscribe(async _id => {
            if (!_id) {
                return;
            }
            doc(await ImageType.find(_id));

            const n = await ImageType.find({
                originalDate: {$gte: doc().originalDate}
            }, {
                limit: 1,
                skip: 1,
                index: 'originalDate',
                sort: [{'originalDate': 'asc'}]
            });

            const p = await ImageType.find({
                originalDate: {$lte: doc().originalDate}
            }, {
                limit: 1,
                skip: 1,
                index: 'originalDate',
                sort: [{'originalDate': 'desc'}]
            });

            nextLink(n.length ? router.href('focus', {id: n[0]._id}) : null);
            prevLink(p.length ? router.href('focus', {id: p[0]._id}) : null);
        })
    ], true);

    // Watch for focus changes
    vm.config({ hooks: { willUpdate: (vm, { vars }) => id(vars.id) }});

    // Start navigation
    id(params.vars.id);
    mouseMove();

    return function() {
        const _id = doc() && doc()._id;

        if (!_id) {
            return Overlay('Loading...');
        }

        return focusContainer({
            class: 'focus',
            onmousemove: mouseMove,
            onmouseleave: mouseLeave,
            onclick: mouseClick,
        }, [
            AppBar({
                style: appBarStyle(),
                title: '',
                up: { action: navBack, fill: 'white' },
                actions: [
                    trashButtonContainer({
                        onclick: clickTrash
                    }, [
                        Icon({
                            name: "trash" ,
                            size: 0.75,
                            fill: 'white',
                            style: {verticalAlign: 'middle'}
                        })
                    ])
                ]
            }),
            focusContent([
                (
                    prevLink()
                    ? prevClickZone({href: prevLink()}, [
                        Icon({
                            name: "chevron_left" ,
                            size: 0.75,
                            fill: 'white'
                        })
                    ])
                    : null
                ),
                AttachmentImageView({
                    src: _id ? doc().sizes.full : null,
                    style: imageStyle
                }),
                (
                    nextLink()
                    ? nextClickZone({href: nextLink()}, [
                        Icon({
                            name: "chevron_right" ,
                            size: 0.75,
                            fill: 'white',
                        })
                    ])
                    : null
                )
            ])
        ]);
    };
}

const WIDE = injectStyle({width: "100%"});
const TALL = injectStyle({height: "100%"});
const CSS_CLICK_ZONE = {
    'position': 'absolute',
    'width': '33%',
    'height': '70%',
    'display': 'flex',
    'alignItems': 'center',
    'padding': '2em',
    'top': '15%',
    'transition': 'opacity .13s cubic-bezier(0.0,0.0,0.2,1)',
    'opacity': 0,
    'cursor': 'pointer',
    ':hover': {
        opacity: 1
    }
};

const trashButtonContainer = styled({
    marginRight: '1em',
}, CLICKABLE);

const focusContainer = styled({
    display: 'flex',
    overflow: 'hidden',
    flexDirection: 'column',
    alignItems: 'center',
    backgroundColor: 'black'
}, FILL_STYLE);

const focusContent = styled({
    flex: 1,
    overflow: 'hidden',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center'
});

const nextClickZone = styled('a', {
    right: '0px',
    justifyContent: 'flex-end'
}, CSS_CLICK_ZONE);

const prevClickZone = styled('a', {
    left: '0px',
    justifyContent: 'flex-start',
}, CSS_CLICK_ZONE);


text:
/**
 * check platform information
 */
package helper

/**
 * @author ShiZhan
 * gather platform information
 */
object Platform {
  import com.hp.hpl.jena.Jena.{ VERSION => JENAVER, BUILD_DATE => JENABUILD }
  import com.hp.hpl.jena.tdb.TDB.{ VERSION => TDBVER, BUILD_DATE => TDBBUILD }
  import JVMstates.{ MEMFREE, MEMUSED, MEMTOTAL, MEMMAX }

  val HOSTNAME = java.net.InetAddress.getLocalHost.getHostName
  val OS = System.getProperty("os.name")
  val isWindows = OS.startsWith("Windows")
  val JAVAVER = System.getProperty("java.version")
  val SCALAVER = scala.util.Properties.versionMsg
  val BRIEFING = {
    s"""
Jena core:   $JENAVER $JENABUILD
Jena TDB:    $TDBVER $TDBBUILD
Scala:       $SCALAVER
Java:        $JAVAVER
  MEM FREE:  $MEMFREE MB
  MEM USED:  $MEMUSED MB
  MEM TOTAL: $MEMTOTAL MB
  MEM MAX:   $MEMMAX MB
OS:          $OS
HOSTNAME:    $HOSTNAME
"""
  }
}


text:
"""Tests for google3.firebase.app.client.cpp.binary_to_array."""

from google3.testing.pybase import googletest
from google3.firebase.app.client.cpp import binary_to_array

EXPECTED_SOURCE_FILE = """\
// Copyright 2016 Google Inc. All Rights Reserved.

#include <stdlib.h>

namespace test_outer_namespace {
namespace test_inner_namespace {

extern const size_t test_array_name_size;
extern const char test_fileid[];
extern const unsigned char test_array_name[];

const unsigned char test_array_name[] = {
  0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  0x00  // Extra \\0 to make it a C string
};

const size_t test_array_name_size =
  sizeof(test_array_name) - 1;

const char test_fileid[] =
  "test_filename";

}  // namespace test_inner_namespace
}  // namespace test_outer_namespace
"""

EXPECTED_HEADER_FILE = """\
// Copyright 2016 Google Inc. All Rights Reserved.

#ifndef TEST_HEADER_GUARD
#define TEST_HEADER_GUARD

#include <stdlib.h>

namespace test_outer_namespace {
namespace test_inner_namespace {

extern const size_t test_array_name_size;
extern const unsigned char test_array_name[];
extern const char test_fileid[];

}  // namespace test_inner_namespace
}  // namespace test_outer_namespace

#endif  // TEST_HEADER_GUARD
"""

namespaces = ["test_outer_namespace", "test_inner_namespace"]
array_name = "test_array_name"
array_size_name = "test_array_name_size"
fileid = "test_fileid"
filename = "test_filename"
input_bytes = [1, 2, 3, 4, 5, 6, 7]
header_guard = "TEST_HEADER_GUARD"

class BinaryToArrayTest(googletest.TestCase):

  def test_source_file(self):
    result_source = binary_to_array.source(
        namespaces, array_name, array_size_name, fileid, filename, input_bytes)
    self.assertEqual("\n".join(result_source), EXPECTED_SOURCE_FILE)

  def test_header_file(self):
    result_header = binary_to_array.header(header_guard, namespaces, array_name,
                                           array_size_name, fileid)
    self.assertEqual("\n".join(result_header), EXPECTED_HEADER_FILE)

if __name__ == "__main__":
  googletest.main()


text:
package com.sherry.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by zxin on 16/11/21.
 */
public class DBConnetctionTest {

    public static void main(String[] args){
        try {
            getDBConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static Connection getDBConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        String username = "root";
        String password = "root";
        String url = "jdbc:mysql://127.0.0.1:3306/beauty?connectTimeout=3000";

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url, username, password);
        return conn;
    }
}


text:
<?php require 'inc/config.php'; require 'inc/frontend_config.php'; ?>
<?php require 'inc/views/template_head_start.php'; ?>
<?php require 'inc/views/template_head_end.php'; ?>
<?php require 'inc/views/frontend_head.php'; ?>

<div class="bg-image" style="background-image: url('<?php echo $one->assets_folder; ?>/img/various/hero1.jpg');">

Your idea is great, imagine your product come to life.

Then make it happen. It's never been easier.

                    <img class="img-responsive pull-b" src="<?php echo $one->assets_folder; ?>/img/various/promo2.jpg" alt="">

 Reliable

It just works

                <?php $one->get_text('small'); ?>

 Passion

Crafted with Love

                <?php $one->get_text('small'); ?>

 Clean

Design & Coding

                <?php $one->get_text('small'); ?>

 Professional

Based on Your Feedback

                <?php $one->get_text('small'); ?>

Products

Web Apps

Bootstrap Powered

Bootstrap is a sleek, intuitive, and powerful mobile first front-end framework for faster and easier web development. OneUI was built on top, extending it to a large degree.

Fully Responsive

The User Interface will adjust to any screen size. It will look great on mobile devices and desktops at the same time. No need to worry about the UI, just stay focused on the development.

Save time

OneUI will save you hundreds of hours of extra development. Start right away coding your functionality and watch your project come to life months sooner.

Frontend Pages

Premium and fully responsive frontend pages are included in OneUI package, too. They use the same resources with the backend, so you can build your web application in one go using all available components wherever you like.

                    {less}

LessCSS

OneUI was built from scratch with LessCSS. Completely modular design with components, variables and mixins that with help you customize and extend your framework to the maximum.

Grunt Tasks

Grunt tasks will make your life easier. You can use them to live-compile your Less files to CSS as you work or build your custom color themes and framework.

<div class="bg-image" style="background-image: url('<?php echo $one->assets_folder; ?>/img/photos/photo17@2x.jpg');">

Improve your conversions in a few days.

Our product can make you succeed.

<canvas class="js-features-chartjs-lines"></canvas>

 Layout

Powerful and Flexible

                    <?php $one->get_text('small'); ?>

 Responsive

Super Fast GPU Enabled Animations

                    <?php $one->get_text('small'); ?>

                <img class="img-responsive visibility-hidden" data-toggle="appear" data-offset="-250" data-class="animated fadeInRight" src="<?php echo $one->assets_folder; ?>/img/various/promo3.jpg" alt="">

Crafted with  by pixelcave.

            Get Started Today

<?php require 'inc/views/frontend_footer.php'; ?>
<?php require 'inc/views/template_footer_start.php'; ?>

<?php require 'inc/views/template_footer_end.php'; ?>


text:
package org.jkiss.dbeaver.ext.db2.model.cache;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.ext.db2.model.DB2Trigger;
import org.jkiss.dbeaver.ext.db2.model.DB2TriggerDep;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCStatement;
import org.jkiss.dbeaver.model.impl.jdbc.cache.JDBCObjectCache;

import java.sql.SQLException;

/**
 * Cache for dependencies on DB2 Triggers
 *
 * @author Denis Forveille
 */
public class DB2TriggerDepCache extends JDBCObjectCache<DB2Trigger, DB2TriggerDep> {

    private static final String SQL = "SELECT * FROM SYSCAT.TRIGDEP WHERE TRIGSCHEMA = ? AND TRIGNAME = ? ORDER BY BSCHEMA,BNAME WITH UR";

    @NotNull
    @Override
    protected JDBCStatement prepareObjectsStatement(@NotNull JDBCSession session, @NotNull DB2Trigger db2Trigger) throws SQLException
    {
        final JDBCPreparedStatement dbStat = session.prepareStatement(SQL);
        dbStat.setString(1, db2Trigger.getParentObject().getName());
        dbStat.setString(2, db2Trigger.getName());
        return dbStat;
    }

    @Override
    protected DB2TriggerDep fetchObject(@NotNull JDBCSession session, @NotNull DB2Trigger db2Trigger, @NotNull JDBCResultSet resultSet)
        throws SQLException, DBException
    {
        return new DB2TriggerDep(session.getProgressMonitor(), db2Trigger, resultSet);
    }
}


text:
import './body.ts';
import './main-table.ts';
import './menu.ts';


text:
/**
 * init#inquire
 *
 * This file asks the user for the inputs specified by the init template author
 * and adds the answers into the current state
 */

import co from 'co';
import Q from 'q';
import gutil from 'gulp-util';
import inquirer from 'inquirer';
import rimraf from 'rimraf';
import { basename, join } from 'path';

module.exports = co.wrap(state => {
  gutil.log('Searching for .init in folder', initFile);

  // Create a async deferred object
  const deferred = Q.defer();
  const initFile = `./${state.meta.folder}/.init`;

  // Import questions from local init file
  state.questions = require(join(process.cwd(), initFile));

  // And unshift to include the name question by default
  state.questions.unshift({
    type: 'input',
    name: 'name',
    message: 'What\'s the name of the project?',
    validate: input => input !== '',
    default: basename(process.cwd()),
  });

  gutil.log('Found and imported .init file. Deleting it now.');

  // First remove the init file
  rimraf(initFile, () => {
    gutil.log('Sucessfully deleted .init file.');
    gutil.log('Starting the user input now...');

    // And then send the questionaire to the users shell
    inquirer.prompt(state.questions, answers => {
      state.data = answers;
      gutil.log('Using answers now to populate template files');
      return deferred.resolve(state);
    });
  });

  return deferred.promise;
});


text:
require 'spec_helper'

RSpec.describe 'regexp extension' do
  context 'not matched' do
    let(:db) { ActiveRecord::Base.connection }

    it 'return position if matched and -1 if not matched' do
      expect(db.select_values("SELECT 'efg' REGEXP '^abc$'")).to eq([0])
      expect(db.select_values("SELECT 'abc' REGEXP '^abc$'")).to eq([1])
    end
  end
end


text:
package com.limpygnome.parrot.component.sync;

import com.limpygnome.parrot.component.sync.ssh.SshSyncProfile;
import com.limpygnome.parrot.component.ui.WebStageInitService;
import com.limpygnome.parrot.event.DatabaseChangingEvent;
import com.limpygnome.parrot.library.log.Log;
import com.limpygnome.parrot.library.log.LogItem;
import com.limpygnome.parrot.library.log.LogLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Used to hold sync result data (to prevent GC) and pass it to the front-end through events.
 */
@Service
public class SyncResultService implements DatabaseChangingEvent
{
    @Autowired
    private WebStageInitService webStageInitService;

    // Stores results to prevent GC
    private Map<String, SyncResult> resultMap;

    // Cache of results; again, prevents GC and also improves performance
    private SyncResult[] results;

    public SyncResultService()
    {
        this.resultMap = new HashMap<>();
        this.results = new SyncResult[0];
    }

    public synchronized void add(SyncResult syncResult)
    {
        if (syncResult != null)
        {
            resultMap.put(syncResult.getHostName(), syncResult);
            updateCache();
            raiseEventChanged();
        }
    }

    public synchronized void clear()
    {
        resultMap.clear();
        updateCache();
        raiseEventChanged();
    }

    public SyncResult[] getResults()
    {
        return results;
    }

    public String getResultsAsText()
    {
        StringBuilder sb = new StringBuilder();
        String ls = System.getProperty("line.separator");
        for (SyncResult syncResult : results)
        {
            sb.append(syncResult.asText()).append(ls);
        }
        return sb.toString();
    }

    @Override
    public void eventDatabaseChanged(boolean open)
    {
        // Wipe data when database changing
        clear();
    }

    private void raiseEventChanged()
    {
        webStageInitService.triggerEvent("document", "syncResults.change", results);
    }

    private void updateCache()
    {
        results = resultMap.values().toArray(new SyncResult[resultMap.size()]);
    }

}


text:
function divsol_collect_feats(exp_dir, feat_collection, img_names, numsol_2collect,overwrite)
  feat_types = sol_feat_config(feat_collection);
  for i =1:numel(feat_types)
    if(strcmp(feat_types{i}, 'pairwise_category_centroid_diff'))
      pars =[];
      pars.name = 'pairwise_category_centroid_diff';
      pars.numsol_2collect = numsol_2collect;
      Segm_collect_measurements_on_sol('pairwise_category', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i}, 'pairwise_category_sum_of_pixels'))
      pars =[];
      pars.name = 'pairwise_category_sum_of_pixels';
      pars.numsol_2collect = numsol_2collect;
      pars.chi2_hom_kernel=false;
      Segm_collect_measurements_on_sol('pairwise_category', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i},'pairwise_category_sum_of_pixels_chi2_hom_kern'))
      pars =[];
      pars.name = 'pairwise_category_sum_of_pixels_chi2_hom_kern';
      pars.numsol_2collect = numsol_2collect;
      pars.chi2_hom_kernel=true;
      Segm_collect_measurements_on_sol('pairwise_category', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i}, 'pairwise_category_cooccurrence'))
      pars =[];
      pars.name = 'pairwise_category_cooccurrence';
      pars.numsol_2collect = numsol_2collect;
      pars.chi2_hom_kernel=false;
      Segm_collect_measurements_on_sol('pairwise_category', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i}, 'pairwise_category_cooccurrence_chi2_hom_kern'))
      pars =[];
      pars.name = 'pairwise_category_cooccurrence_chi2_hom_kern';
      pars.numsol_2collect = numsol_2collect;
      pars.chi2_hom_kernel=true;
      Segm_collect_measurements_on_sol('pairwise_category', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i},'uva_segment_classification_score'))
      pars =[];
      pars.name = 'uva_segment_classification_score';
      pars.numsol_2collect = numsol_2collect;
      Segm_collect_measurements_on_sol('classification', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i},'globalpb_chamfer_distance_fore'))
      pars =[];
      pars.name = 'globalpb_chamfer_distance_fore';
      pars.numsol_2collect = numsol_2collect;
      Segm_collect_measurements_on_sol('globalpb', pars, img_names, exp_dir,overwrite);
    elseif(strcmp(feat_types{i},'globalpb_chamfer_distance_segm'))
      pars =[];
      pars.name = 'globalpb_chamfer_distance_segm';
      pars.numsol_2collect = numsol_2collect;
      Segm_collect_measurements_on_sol('globalpb', pars, img_names, exp_dir,overwrite);
    else
      error('No such feature available.');
    end
  end

end


text:
$title$

Hi, welcome to my personal website. This is where I post interesting things I've found, or write about what I'm currently working on.

Recent posts

        $posts$


text:
#ifndef _IPXE_XFERBUF_H
#define _IPXE_XFERBUF_H

/** @file
 *
 * Data transfer buffer
 *
 */

FILE_LICENCE ( GPL2_OR_LATER );

#include <stdint.h>
#include <ipxe/iobuf.h>
#include <ipxe/xfer.h>

/** A data transfer buffer */
struct xfer_buffer {
	/** Data */
	void *data;
	/** Size of data */
	size_t len;
	/** Current offset within data */
	size_t pos;
};

extern void xferbuf_done ( struct xfer_buffer *xferbuf );
extern int xferbuf_deliver ( struct xfer_buffer *xferbuf,
			     struct io_buffer *iobuf,
			     struct xfer_metadata *meta );

#endif /* _IPXE_XFERBUF_H */


text:
package F::Property;

use warnings;
use strict;
use parent qw(F::NodeExpression F::Assignable F::PropertyOwner);

sub desc {
    my $prop = shift;
    my $name = !$prop->{is_index} ?
        "'$$prop{prop_name}'"            :
        '(name evaluated at runtime)';
    return ($prop->is_special ? 'special ' : '')."property $name";
}

sub is_special {
    return substr(shift->{prop_name} || '', 0, 1) eq '*';
}

sub prop_name { shift->{prop_name} }
sub left      { shift->first_child->perl_fmt_do }
sub index_fmt { (shift->children)[1]->first_child->perl_fmt_do }

sub property_owner_code { shift->left }
sub property_name       { shift->{prop_name}  }
sub property_name_code  {
    my $prop = shift;
    $prop->{is_index} or return;
    return $prop->index_fmt;
}

sub perl_fmt {
    my $prop = shift;

    return property_idx => {
        index => $prop->index_fmt,
        left  => $prop->left,
        pos   => $prop->{create_pos}
    } if $prop->{is_index};

    return property => {
        name => $prop->prop_name,
        left => $prop->left,
        pos   => $prop->{create_pos}
    };
}

1


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="`width`=device-width, initial-scale=1.0">
  <title>Niloofar Khodabakhsh - Homepage</title>
  <link rel="stylesheet" href="../css/foundation.css">
  <link rel="stylesheet" href="../css/app.css">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Lora" rel="stylesheet">

Niloo Khodabakhsh

UI / UX Designer

Portfolio

About

Asanak Book Design Project

Iranian indigenous cultures are unlimited sources for contemporary artistic creations. Among these, tribes culture has a special place.
The concept of Qashqai tribe literature has such a strong connection to Iranian mythology and traditions that it is true to say that the only dissimilarity is the Turkish language.

The oldest poem form among Qashqai people is Asanak. Containing visual elements and expressing widespread concepts such as love, separation, and life makes Asanaks a potential basis for artworks. Asanak book design project is my BA thesis project in which I tried to visualize the spirit of poems.

Mixed Media

  Book Size: 10×10 inches

Copyright 2017 by Niloofar Khodabakhsh. All Rights Reserved.


text:
from typing import Dict, List, Optional
from joueur.base_game import BaseGame

# import game objects
from games.pirates.game_object import GameObject
from games.pirates.player import Player
from games.pirates.port import Port
from games.pirates.tile import Tile
from games.pirates.unit import Unit

# <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# you can add additional import(s) here
# <<-- /Creer-Merge: imports -->>

class Game(BaseGame):
    """The class representing the Game in the Pirates game.

    Steal from merchants and become the most infamous pirate.
    """

    def __init__(self):
        """Initializes a Game with basic logic as provided by the Creer code generator.
        """
        BaseGame.__init__(self)

        # private attributes to hold the properties so they appear read only
        self._bury_interest_rate = 0
        self._crew_cost = 0
        self._crew_damage = 0
        self._crew_health = 0
        self._crew_moves = 0
        self._crew_range = 0
        self._current_player = None
        self._current_turn = 0
        self._game_objects = {}
        self._heal_factor = 0
        self._map_height = 0
        self._map_width = 0
        self._max_turns = 100
        self._merchant_gold_rate = 0
        self._merchant_interest_rate = 0
        self._min_interest_distance = 0
        self._players = []
        self._ports = []
        self._rest_range = 0
        self._session = ""
        self._ship_cost = 0
        self._ship_damage = 0
        self._ship_health = 0
        self._ship_moves = 0
        self._ship_range = 0
        self._tiles = []
        self._time_added_per_turn = 0
        self._units = []

        self.name = "Pirates"

        self._game_object_classes = {
            'GameObject': GameObject,
            'Player': Player,
            'Port': Port,
            'Tile': Tile,
            'Unit': Unit
        }

    @property
    def bury_interest_rate(self) -> float:
        """float: The rate buried gold increases each turn.
        """
        return self._bury_interest_rate

    @property
    def crew_cost(self) -> int:
        """int: How much gold it costs to construct a single crew.
        """
        return self._crew_cost

    @property
    def crew_damage(self) -> int:
        """int: How much damage crew deal to each other.
        """
        return self._crew_damage

    @property
    def crew_health(self) -> int:
        """int: The maximum amount of health a crew member can have.
        """
        return self._crew_health

    @property
    def crew_moves(self) -> int:
        """int: The number of moves Units with only crew are given each turn.
        """
        return self._crew_moves

    @property
    def crew_range(self) -> float:
        """float: A crew's attack range. Range is circular.
        """
        return self._crew_range

    @property
    def current_player(self) -> 'games.pirates.player.Player':
        """games.pirates.player.Player: The player whose turn it is currently. That player can send commands. Other players cannot.
        """
        return self._current_player

    @property
    def current_turn(self) -> int:
        """int: The current turn number, starting at 0 for the first player's turn.
        """
        return self._current_turn

    @property
    def game_objects(self) -> Dict[str, 'games.pirates.game_object.GameObject']:
        """dict[str, games.pirates.game_object.GameObject]: A mapping of every game object's ID to the actual game object. Primarily used by the server and client to easily refer to the game objects via ID.
        """
        return self._game_objects

    @property
    def heal_factor(self) -> float:
        """float: How much health a Unit recovers when they rest.
        """
        return self._heal_factor

    @property
    def map_height(self) -> int:
        """int: The number of Tiles in the map along the y (vertical) axis.
        """
        return self._map_height

    @property
    def map_width(self) -> int:
        """int: The number of Tiles in the map along the x (horizontal) axis.
        """
        return self._map_width

    @property
    def max_turns(self) -> int:
        """int: The maximum number of turns before the game will automatically end.
        """
        return self._max_turns

    @property
    def merchant_gold_rate(self) -> float:
        """float: How much gold merchant Ports get each turn.
        """
        return self._merchant_gold_rate

    @property
    def merchant_interest_rate(self) -> float:
        """float: When a merchant ship spawns, the amount of additional gold it has relative to the Port's investment.
        """
        return self._merchant_interest_rate

    @property
    def min_interest_distance(self) -> float:
        """float: The Euclidean distance buried gold must be from the Player's Port to accumulate interest.
        """
        return self._min_interest_distance

    @property
    def players(self) -> List['games.pirates.player.Player']:
        """list[games.pirates.player.Player]: List of all the players in the game.
        """
        return self._players

    @property
    def ports(self) -> List['games.pirates.port.Port']:
        """list[games.pirates.port.Port]: Every Port in the game. Merchant ports have owner set to None.
        """
        return self._ports

    @property
    def rest_range(self) -> float:
        """float: How far a Unit can be from a Port to rest. Range is circular.
        """
        return self._rest_range

    @property
    def session(self) -> str:
        """str: A unique identifier for the game instance that is being played.
        """
        return self._session

    @property
    def ship_cost(self) -> int:
        """int: How much gold it costs to construct a ship.
        """
        return self._ship_cost

    @property
    def ship_damage(self) -> int:
        """int: How much damage ships deal to ships and ports.
        """
        return self._ship_damage

    @property
    def ship_health(self) -> int:
        """int: The maximum amount of health a ship can have.
        """
        return self._ship_health

    @property
    def ship_moves(self) -> int:
        """int: The number of moves Units with ships are given each turn.
        """
        return self._ship_moves

    @property
    def ship_range(self) -> float:
        """float: A ship's attack range. Range is circular.
        """
        return self._ship_range

    @property
    def tiles(self) -> List['games.pirates.tile.Tile']:
        """list[games.pirates.tile.Tile]: All the tiles in the map, stored in Row-major order. Use `x + y * mapWidth` to access the correct index.
        """
        return self._tiles

    @property
    def time_added_per_turn(self) -> int:
        """int: The amount of time (in nano-seconds) added after each player performs a turn.
        """
        return self._time_added_per_turn

    @property
    def units(self) -> List['games.pirates.unit.Unit']:
        """list[games.pirates.unit.Unit]: Every Unit in the game. Merchant units have targetPort set to a port.
        """
        return self._units

    def get_tile_at(self, x: int, y: int) -> Optional['games.pirates.tile.Tile']:
        """Gets the Tile at a specified (x, y) position.

        Args:
            x (int): An integer between 0 and the map_width.
            y (int): An integer between 0 and the map_height.

        Returns:
            games.pirates.tile.Tile or None: The Tile at (x, y) or None if out of bounds.
        """
        if x < 0 or y < 0 or x >= self.map_width or y >= self.map_height:
            # out of bounds
            return None

        return self.tiles[x + y * self.map_width]

    # <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
    # if you want to add any client side logic (such as state checking functions) this is where you can add them
    # <<-- /Creer-Merge: functions -->>


text:
import { ConfigService } from './../shared/services/config.service';
import { Component, OnInit, Input } from '@angular/core';
import { UserService } from '../shared/services/user.service';
import { User } from '../shared/models/user';
import { TenantInfo } from '../shared/models/tenant-info';
import { Constants } from '../shared/models/constants';
import { GlobalStateService } from '../shared/services/global-state.service';
import { ArmSiteDescriptor, ArmFunctionDescriptor } from '../shared/resourceDescriptors';

@Component({
  selector: 'top-bar',
  templateUrl: './top-bar.component.html',
  styleUrls: ['./top-bar.component.scss'],
  inputs: ['isFunctionSelected'],
})
export class TopBarComponent implements OnInit {
  @Input()
  gettingStarted: boolean;
  public user: User;
  public tenants: TenantInfo[];
  public currentTenant: TenantInfo;
  public inIFrame: boolean;
  public inTab: boolean;
  public isStandalone: boolean;

  public visible = false;

  public resourceId: string;
  public appName: string;
  public fnName: string;

  constructor(private _userService: UserService, private _globalStateService: GlobalStateService, private _configService: ConfigService) {
    this.inIFrame = this._userService.inIFrame;
    this.inTab = this._userService.inTab;
    this.isStandalone = this._configService.isStandalone();

    if (this.inTab) {
      _userService
        .getStartupInfo()
        .first()
        .subscribe(info => {
          this.resourceId = info.resourceId;
          const descriptor = new ArmSiteDescriptor(this.resourceId);
          this.appName = descriptor.site;
          const fnDescriptor = new ArmFunctionDescriptor(this.resourceId);
          this.fnName = fnDescriptor.name;
        });
    }

    this._setVisible();
  }

  public get showTryView() {
    return this._globalStateService.showTryView;
  }

  private _setVisible() {
    if (this.inIFrame) {
      this.visible = false;
    } else if (!this._globalStateService.showTryView) {
      this.visible = true;
    }
  }

  ngOnInit() {
    if (!this.showTryView) {
      // nothing to do if we're running in an iframe
      if (this.inIFrame) return;

      this._userService.getUser().subscribe(u => {
        this.user = u;
        // this.setVisible();
      });

      this._userService.getTenants().subscribe(t => {
        this.tenants = t;
        this.currentTenant = this.tenants.find(e => e.Current);
        // this.setVisible();
      });
    } else {
      // this.setVisible();
    }
  }

  selectTenant(tenant: TenantInfo) {
    window.location.href = Constants.serviceHost + `api/switchtenants/${tenant.TenantId}`;
  }
}


text:
module Rafa
  module Util

    # Converts the specified radians to degrees
    def radians_to_degrees(radians)
      return radians * (180 / Math::PI)
    end

    module ArrayExtensions # :nodoc: all

      # Handy method to be able to pass arguments to a javascript function.
      # Differs from a simple +to_json+ by removing the enclosing brackets
      def to_js_args(separator = ', ')
        map(&:to_json).join(separator)
      end
    end

  end
end

class Array # :nodoc:

  # Monkeypatch Array class to include the method
  include Rafa::Util::ArrayExtensions

end


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

  <meta name="description" content="Documentation for Mule Cloud Connector." />

<link rel="shortcut icon" type="image/x-icon" href="../../../../../favicon.ico" />
<title>

  com.mulesoft.marklogic.adapters

| Mule Cloud Connector

</title>
<link href="../../../../../assets/mule-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/mule-developer-prettify.css" rel="stylesheet" type="text/css" />
<link href="../../../../../assets/customizations.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Ubuntu:300' rel='stylesheet' type='text/css'>

      Mule Cloud Connector

	    	Install Guide

	    	Java API Reference

	    	Mule API Reference

          <form accept-charset="utf-8" class="gsc-search-box"
                onsubmit="return submit_search()">

                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../../../')"
                      onkeyup="return search_changed(event, false, '../../../../../')" />

                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />

          </form>

                Package Index |
                Class Index

  com.mulesoft.marklogic

  com.mulesoft.marklogic.adapters

  com.mulesoft.marklogic.agents

  com.mulesoft.marklogic.config

  com.mulesoft.marklogic.process

  com.mulesoft.marklogic.processors

Classes

MarkLogicCapabilitiesAdapter

MarkLogicLifecycleAdapter

MarkLogicMetadataAdapater

MarkLogicProcessAdapter

            Package Index |
            Class Index

  package

com.mulesoft.marklogic.adapters

Classes

              MarkLogicCapabilitiesAdapter
              A MarkLogicCapabilitiesAdapter is a wrapper around MarkLogic that implements org.mule.api.Capabilities interface.

              MarkLogicLifecycleAdapter
              A MarkLogicLifecycleAdapter is a wrapper around MarkLogic that adds lifecycle methods to the pojo.

              MarkLogicMetadataAdapater
              A MarkLogicMetadataAdapater is a wrapper around MarkLogic that adds support for querying metadata about the extension.

              MarkLogicProcessAdapter
              A MarkLogicProcessAdapter is a wrapper around MarkLogic that enables custom processing strategies.

Generated by Mule DevKit. Document generation technology based on Google's Doclava.


text:
layout: page
title: "Approval of NIH PO1"
teaser: "Under Project PI Brian Ross, PhD of University of Michigan"
categories:
    - award
tags:
    - members
    - news
    - awards
    - grants
    - nih
    - gbm
    - r_verhaak
date: 2013-06-20T10:14:27-05:00
comments: true
show_meta: true
---

Our P01 application that aims to relate therapeutic efficacy, tumor evolution and imaging in glioblastoma, of which the overall PI is [Brian Ross](http://medicine.umich.edu/dept/biochem/brian-ross-phd), PhD, University of Michigan, was approved for funding.

*   [Project Information: 5P01CA085878-11 #6716](http://projectreporter.nih.gov/project_info_description.cfm?aid=8745106&icde=24987280&ddparam=&ddvalue=&ddsub=&cr=1&csb=default&cs=ASC)
*   [NIH RePORT page - all funded grants](http://projectreporter.nih.gov/Reporter_Viewsh.cfm?sl=13EDC003498FCED77598B8961CAA4A01A2FFCEB861BF)


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.orc;

import com.google.common.annotations.VisibleForTesting;

public class DoubleVector
        implements Vector
{
    public final boolean[] isNull;
    public final double[] vector;

    public DoubleVector(int length)
    {
        if (length > MAX_VECTOR_LENGTH) {
            throw new IllegalArgumentException("length greater than max vector length");
        }
        vector = new double[length];
        isNull = new boolean[length];
    }

    @Override
    @VisibleForTesting
    public ObjectVector toObjectVector(int size)
    {
        ObjectVector objectVector = new ObjectVector(vector.length);
        for (int i = 0; i < size; i++) {
            if (!isNull[i]) {
                objectVector.vector[i] = vector[i];
            }
        }
        return objectVector;
    }
}


text:
use liquid::ObjectView;
use liquid::ValueView;

#[derive(ObjectView, ValueView, serde::Serialize, serde::Deserialize, Debug)]
struct TestEmpty {}

#[test]
fn test_empty_value() {
    let uut = TestEmpty {};

    assert_eq!(uut.render().to_string(), "");
    assert_eq!(uut.source().to_string(), "{}");
    assert_eq!(uut.type_name(), "object");
    assert_eq!(uut.query_state(liquid::model::State::Truthy), true);
    assert_eq!(uut.query_state(liquid::model::State::DefaultValue), true);
    assert_eq!(uut.query_state(liquid::model::State::Empty), true);
    assert_eq!(uut.query_state(liquid::model::State::Blank), true);
    assert_eq!(uut.to_kstr(), "");
    assert_eq!(uut.to_value(), liquid::model::value!({}));
    assert!(uut.as_object().is_some());
}

#[test]
fn test_empty_object() {
    let uut = TestEmpty {};

    assert_eq!(uut.size(), 0);
    assert!(uut.keys().next().is_none());
    assert!(uut.values().next().is_none());
    assert!(uut.iter().next().is_none());
    assert_eq!(uut.contains_key("non-existent"), false);
    assert!(uut.get("non-existent").is_none());
}

#[derive(ObjectView, ValueView, serde::Serialize, serde::Deserialize, Debug)]
struct TestStatic {
    boolean: bool,
    int: i64,
    float: f64,
    static_str: &'static str,
    string: String,
    kstring: liquid::model::KString,
    array: Vec<i64>,
}

impl TestStatic {
    fn non_default() -> Self {
        Self {
            boolean: true,
            int: 5,
            float: 4.2,
            static_str: "Hello world",
            string: String::from("Goodbye world"),
            kstring: liquid::model::KString::from_static("foo"),
            array: vec![1, 2, 3],
        }
    }
}

#[test]
fn test_static_value() {
    let uut = TestStatic::non_default();

    assert_ne!(uut.render().to_string(), "");
    assert_ne!(uut.source().to_string(), "{}");
    assert_eq!(uut.type_name(), "object");
    assert_eq!(uut.query_state(liquid::model::State::Truthy), true);
    assert_eq!(uut.query_state(liquid::model::State::DefaultValue), false);
    assert_eq!(uut.query_state(liquid::model::State::Empty), false);
    assert_eq!(uut.query_state(liquid::model::State::Blank), false);
    assert_ne!(uut.to_kstr(), "");
    assert_ne!(uut.to_value(), liquid::model::value!({}));
    assert!(uut.as_object().is_some());
}

#[test]
fn test_static_object() {
    let uut = TestStatic::non_default();

    assert_eq!(uut.size(), 7i64);
    assert!(uut.keys().next().is_some());
    assert!(uut.values().next().is_some());
    assert!(uut.iter().next().is_some());
    assert_eq!(uut.contains_key("non-existent"), false);
    assert_eq!(uut.contains_key("boolean"), true);
    assert!(uut.get("boolean").is_some());
}

#[derive(ObjectView, ValueView, serde::Serialize, serde::Deserialize, Debug)]
struct TestBorrow<'s> {
    s: &'s str,
}

#[test]
fn test_borrow_value() {
    let fixture = String::from("foo");
    let uut = TestBorrow {
        s: fixture.as_str(),
    };

    assert!(uut.as_object().is_some());
}

#[test]
fn test_borrow_object() {
    let fixture = String::from("foo");
    let uut = TestBorrow {
        s: fixture.as_str(),
    };

    assert_eq!(uut.size(), 1i64);
    assert!(uut.keys().next().is_some());
    assert!(uut.values().next().is_some());
    assert!(uut.iter().next().is_some());
    assert_eq!(uut.contains_key("non-existent"), false);
    assert_eq!(uut.contains_key("s"), true);
    assert!(uut.get("s").is_some());
}


text:
<?php

use app\components\CmsMigration;
use yii\db\Migration;

class m160807_200425_version1 extends CmsMigration
{
    public function up()
    {

    }

    public function down()
    {
        echo "m160807_200425_version1 cannot be reverted.\n";
        return false;
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
//
//  PumpChatViewController.m
//  RileyLink
//
//  Created by Pete Schwamb on 8/8/15.
//  Copyright (c) 2015 Pete Schwamb. All rights reserved.
//

#import "PumpChatViewController.h"
#import "MinimedPacket.h"
#import "NSData+Conversion.h"
#import "Config.h"
#import "RileyLinkBLEManager.h"

@interface PumpChatViewController () {
  IBOutlet UILabel *resultsLabel;
  IBOutlet UILabel *batteryVoltage;
  IBOutlet UILabel *pumpIdLabel;
}

@end

@implementation PumpChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(packetReceived:)
                                               name:RILEY_LINK_EVENT_PACKET_RECEIVED
                                             object:self.device];

  pumpIdLabel.text = [NSString stringWithFormat:@"PumpID: %@", [[Config sharedInstance] pumpID]];
}

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver: self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)queryPumpButtonPressed:(id)sender {
  [self queryPumpForVersion];
}

- (void)queryPumpForVersion {
  resultsLabel.text = @"Sending wakeup packets...";

  NSString *pumpId = [[Config sharedInstance] pumpID];

  NSString *packetStr = [@"a7" stringByAppendingFormat:@"%@5D00", pumpId];
  NSData *data = [NSData dataWithHexadecimalString:packetStr];
  [_device sendPacketData:[MinimedPacket encodeData:data] withCount:100 andTimeBetweenPackets:0.078];
}

- (void)handlePacketFromPump:(MinimedPacket*)p {
  if (p.messageType == MESSAGE_TYPE_PUMP_STATUS_ACK) {
    resultsLabel.text = @"Pump acknowleged wakeup!";
    // Send query for pump model #
    NSString *packetStr = [@"a7" stringByAppendingFormat:@"%@%02x00", [[Config sharedInstance] pumpID], MESSAGE_TYPE_GET_PUMP_MODEL];
    NSData *data = [NSData dataWithHexadecimalString:packetStr];
    [_device sendPacketData:[MinimedPacket encodeData:data]];
  } else if (p.messageType == MESSAGE_TYPE_GET_PUMP_MODEL) {
    //unsigned char len = [p.data bytes][6];
    NSString *version = [NSString stringWithCString:&[p.data bytes][7] encoding:NSASCIIStringEncoding];
    resultsLabel.text = [@"Pump Model: " stringByAppendingString:version];

    // Send query for battery status
    NSString *packetStr = [@"a7" stringByAppendingFormat:@"%@%02x00", [[Config sharedInstance] pumpID], MESSAGE_TYPE_GET_BATTERY];
    NSData *data = [NSData dataWithHexadecimalString:packetStr];
    [_device sendPacketData:[MinimedPacket encodeData:data]];

  } else if (p.messageType == MESSAGE_TYPE_GET_BATTERY) {
    unsigned char *data = (unsigned char *)[p.data bytes] + 6;

    NSInteger volts = (((int)data[1]) << 8) + data[2];
    NSString *indicator = data[0] ? @"Low" : @"Normal";
    batteryVoltage.text = [indicator stringByAppendingFormat:@"%0.02f", volts/100.0];
  }

}

- (void)packetReceived:(NSNotification*)notification {
  if (notification.object == self.device) {
    MinimedPacket *packet = notification.userInfo[@"packet"];
    if (packet && [packet.address isEqualToString:[[Config sharedInstance] pumpID]]) {
      [self handlePacketFromPump:packet];
    }
  }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.N317.html">

Redirecting to type.N317.html...


text:
#include "../include/vrHashMap.h"
#include "../include/vr.h"

vrHashTable * vrHashTableAlloc()
{
	return vrAlloc(sizeof(vrHashTable));
}

vrHashTable * vrHashTableInit(vrHashTable * table, int size)
{
	table->buckets = vrArrayInit(vrArrayAlloc(), sizeof(vrHashEntry*));
	int prime_size = getPrime(size);

	for (int i = 0; i < prime_size; i++)
	{
		vrArrayPush(table->buckets, NULL);
	}
	table->hash = &vrHashFuncDefault;
	table->deleteFunc = NULL;
	table->hashPool = vrArrayInit(vrArrayAlloc(), sizeof(vrHashEntry*));

	for (int i = 0; i < 100; i++)
	{
		vrArrayPush(table->hashPool, vrAlloc(sizeof(vrHashEntry)));
	}
	return table;
}

void * vrHashTableLookup(vrHashTable * table, unsigned int key)
{
	vrHashValue hashv = table->hash(key);
	int index = hashv%table->buckets->sizeof_active;

	vrHashEntry* head = table->buckets->data[index];
	while(head)
	{
		if (key == head->key)
			return head->data;
		head = head->next;
	}
	return NULL;
}

void vrHashTableInsert(vrHashTable * table, void* data, unsigned int key)
{
	vrHashEntry* entry;
	if (table->hashPool->sizeof_active > 0)
	{
		entry = table->hashPool->data[table->hashPool->sizeof_active - 1];
		vrArrayPop(table->hashPool);
	}
	else
	{
		entry = vrAlloc(sizeof(vrHashEntry));
	}
	entry->key = key;
	entry->data = data;
	entry->next = NULL;

	vrHashValue hashv = table->hash(key);
	int index = hashv%table->buckets->sizeof_active;
	vrHashTableRemove(table, key);

	vrHashEntry* head = table->buckets->data[index];
	if (table->buckets->data[index] == NULL)
		table->buckets->data[index] = entry;
	else
	{
		vrHashEntry* current = table->buckets->data[index];
		while (current)
		{
			if (current->next == NULL)
			{
				current->next = entry;
				break;
			}
			current = current->next;
		}
	}

}

void vrHashTableRemove(vrHashTable * table, unsigned int key)
{
	vrHashValue hashv = table->hash(key);
	int index = hashv%table->buckets->sizeof_active;

	while(1)
	{
		vrHashEntry* current = table->buckets->data[index];
		vrHashEntry** prev = &table->buckets->data[index];

		while (current && current->key != key)
		{
			prev = &current->next;
			current = current->next;
		}

		if (current)
		{
			*prev = current->next;
			vrArrayPush(table->hashPool, current);
		}
		if (!current)
			break;
	}

}

vrHashValue vrHashFuncDefault(unsigned int key)
{
	key = ((key >> 16) ^ key) * 0x45d9f3b;
	key = ((key >> 16) ^ key) * 0x45d9f3b;
	key = ((key >> 16) ^ key);
	return key;
}

void vrHashTableResize(vrHashTable * table)
{
	/*
	int newPrime = getPrime(table->buckets->sizeof_array);

	vrHashEntry** buckets = (vrLinkedList**)vrCalloc(sizeof(vrLinkedList*), newPrime);
	for (int i = 0; i < newPrime; i++)
	{
		buckets[i] = vrLinkedListInit(vrLinkedListAlloc());
	}
	int n = 0;
	for (int i = 0; i < table->buckets->sizeof_active; i++)
	{
		if (table->buckets->data[i])
		{

			vrLinkedList* list = table->buckets->data[i];
			vrNode* node = list->head;
			while (node)
			{
				vrHashEntry* entry = ((vrHashEntry*)node->data);

				vrHashValue hashv = table->hash(entry->key);;
				int index = hashv%newPrime;
				vrLinkedListAddBack(buckets[i], node);

				node = node->next;
			}
		}
	}
	for (int i = 0; i < table->buckets->sizeof_active; i++)
	{
		vrFree(table->buckets->data[i]);
	}
	vrFree(table->buckets->data);
	table->buckets->data = buckets;
	table->buckets->sizeof_array = newPrime;
	table->buckets->sizeof_active = newPrime;
	*/
}

unsigned int getPrime(int current_prime)
{
	//If current_prime is not a prime, return first prime
	//Larger than it
	int highest = 0;
	vrBOOL larger = vrFALSE;
	for (int i = 0; i < NUM_PRIMES; i++)
	{
		if (primes[i] == current_prime && i < 25)
		{
			return primes[i + 1];

		}
		if(primes[i] > current_prime && !larger)
		{
			highest = primes[i];
			larger = vrTRUE;
		}
	}
	return highest;
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Angular Demo</title>

<cytochromosome></cytochromosome>


text:
<!DOCTYPE HTML>

                <title>All You Need To Know About Android Espresso Testing (Part III)</title>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="generator" content="Hugo 0.25.1" />

    <link rel="apple-touch-icon-precomposed"
        href='https://www.lvguowei.me/favicon/apple-touch-icon-precomposed.png'>
    <link rel="icon" href='https://www.lvguowei.me/favicon/favicon.png'>

    <meta name="msapplication-TileColor" content="#da532c">
    <meta name="msapplication-TileImage"
        content='/favicon/mstile.png'>

                <meta name="description" content="Guowei Lv">

  <meta name="twitter:card" content="summary"/>

<meta name="twitter:text:title" content="All You Need To Know About Android Espresso Testing (Part III)"/>
<meta name="twitter:title" content="All You Need To Know About Android Espresso Testing (Part III)"/>
<meta name="twitter:description" content="In part II, we wrote a test case to verify that the app can create a task and the task will be seen on the screen. In this part III, we will demonstrate one technique on writing tests that involves a RecyclerView.
First we repeatly add some tasks, and then we verify that the last added task is on display. Note that since we are using a RecyclerView, the last item might not be seen, so we need to scroll the RecyclerView before checking."/>

        <meta property="og:title" content="All You Need To Know About Android Espresso Testing (Part III)" />
<meta property="og:description" content="In part II, we wrote a test case to verify that the app can create a task and the task will be seen on the screen. In this part III, we will demonstrate one technique on writing tests that involves a RecyclerView.
First we repeatly add some tasks, and then we verify that the last added task is on display. Note that since we are using a RecyclerView, the last item might not be seen, so we need to scroll the RecyclerView before checking." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.lvguowei.me/post/all-you-need-to-know-about-android-espresso-testing-3/" />

<meta property="article:published_time" content="2017-07-21T16:44:41+03:00"/>
<meta property="article:modified_time" content="2017-07-21T16:44:41+03:00"/>

<meta itemprop="name" content="All You Need To Know About Android Espresso Testing (Part III)">
<meta itemprop="description" content="In part II, we wrote a test case to verify that the app can create a task and the task will be seen on the screen. In this part III, we will demonstrate one technique on writing tests that involves a RecyclerView.
First we repeatly add some tasks, and then we verify that the last added task is on display. Note that since we are using a RecyclerView, the last item might not be seen, so we need to scroll the RecyclerView before checking.">

<meta itemprop="dateModified" content="2017-07-21T16:44:41+03:00" />
<meta itemprop="wordCount" content="213">

<meta itemprop="keywords" content="Android,Espresso,Testing," />

            <link rel="stylesheet" href="https://www.lvguowei.me/css/google-font.css" />
            <link rel="stylesheet" href="https://www.lvguowei.me/css/font-awesome.min.css" />
            <link rel="stylesheet" href="https://www.lvguowei.me/css/main.css" />
            <link rel="stylesheet" href="https://www.lvguowei.me/css/add-on.css" />
            <link rel="stylesheet" href="https://www.lvguowei.me/css/monokai-sublime.css">

Guowei Lv

                             Blog

                        Categories

                        About

                Share

                Search
                <form id="search" method="get" action="//google.com/search">
                  <input type="text" name="q" placeholder="Search" />
                  <input type="hidden" name="as_sitesearch" value="https://www.lvguowei.me/">
                </form>

                Menu

            <form class="search" method="get" action="//google.com/search">
                <input type="text" name="q" placeholder="Search" />
                <input type="hidden" name="q" value="site:https://www.lvguowei.me/">
            </form>

                                Blog

                                Categories

                                About

Recent Posts

All You Need To Know About Android Espresso Testing (Part IV)

All You Need To Know About Android Espresso Testing (Part III)

All You Need To Know About Android Espresso Testing (Part II)

How To Follow Hand Made Hero On Linux

All You Need To Know About Android Espresso Testing (Part I)

Share this post

Twitter

Google+

Facebook

Reddit

LinkedIn

StumbleUpon

Email

All You Need To Know About Android Espresso Testing (Part III)

        <time class="published"
            datetime='2017-07-21'>
            July 21, 2017</time>

1 minute read

Twitter

Google+

Facebook

Reddit

LinkedIn

StumbleUpon

Email

In part II, we wrote a test case to verify that the app can create a task and the task will be seen on the screen. In this part III, we will demonstrate one technique on writing tests that involves a RecyclerView.

First we repeatly add some tasks, and then we verify that the last added task is on display. Note that since we are using a RecyclerView, the last item might not be seen, so we need to scroll the RecyclerView before checking.

In order to use RecyclerView related test utils, we have to include the espresso contrib library.

androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2') {
        exclude module: 'appcompat-v7'
        exclude module: 'support-v4'
        exclude module: 'support-annotations'
        exclude module: 'recyclerview-v7'
    }

Notice that we have to exclude some modules, otherwise there will be conflicts.

Let’s refactor out a addTask() function that will create a new task:

private void addTask(String name) {
    // go to new task screen
    onView(withId(R.id.menu_main_new_task)).perform(click());

    // enter task name
    onView(withId(R.id.new_task_task_name)).perform(click());
    onView(withId(R.id.new_task_task_name)).perform(typeText(name));

    // enter task desc
    onView(withId(R.id.new_task_task_desc)).perform(click());
    onView(withId(R.id.new_task_task_desc)).perform(typeText("some task"));

    // click add button
    Espresso.closeSoftKeyboard();
    onView(withId(R.id.action_button)).perform(click());
}

Then we rewrite the original test to be:

@Test
public void shouldBeAbleToAddTasksAndHaveThemVisible() {
    for (int i = 0; i < 11; i++) {
        addTask("task " + i);
    }

    onView(withId(R.id.task_list)).perform(RecyclerViewActions.scrollToPosition(10));
    onView(withText("task 10")).check(matches(isDisplayed()));
}

Source code can be found here.

~To be continued~

                        Category

Android Development

All You Need To Know About Android Espresso Testing (Part II)

All You Need To Know About Android Espresso Testing (Part IV)

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

Guowei Lv

Keep sane and code

Recent Posts

All You Need To Know About Android Espresso Testing (Part IV)

                                <time class="published" datetime=
                                    '2017-07-21'>
                                    July 21, 2017</time>

All You Need To Know About Android Espresso Testing (Part III)

                                <time class="published" datetime=
                                    '2017-07-21'>
                                    July 21, 2017</time>

All You Need To Know About Android Espresso Testing (Part II)

                                <time class="published" datetime=
                                    '2017-07-21'>
                                    July 21, 2017</time>

How To Follow Hand Made Hero On Linux

                                <time class="published" datetime=
                                    '2017-07-20'>
                                    July 20, 2017</time>

All You Need To Know About Android Espresso Testing (Part I)

                                <time class="published" datetime=
                                    '2017-07-13'>
                                    July 13, 2017</time>

View more posts

Categories

                                programming kata
                                15

                                Android Development
                                12

                                Finnish Learning
                                10

                                Object Oriented Design
                                7

                                Android Library
                                3

                                C++ Primer
                                3

                                Clojure
                                3

                                Painting
                                3

                                Ranting
                                3

                                Refactoring
                                3

                                Hand Made Hero
                                2

                                SICP
                                2

                                Test Driven Development
                                2

                                Android Programming
                                1

                                Books
                                1

                                Concurrent Programming
                                1

                                Perfume
                                1

About

Welcome to my personal website. In here, I talk about programming in general and other cool stuff. Stay tuned!

Learn More

© Guowei Lv.


text:
/* ###
 * IP: GHIDRA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.feature.vt.gui.provider.matchtable;

import docking.widgets.table.DisplayStringProvider;
import ghidra.program.model.symbol.Symbol;

public class DisplayableLabel implements DisplayStringProvider, Comparable<DisplayableLabel> {

	protected final Symbol symbol;

	public DisplayableLabel(Symbol symbol) {
		this.symbol = symbol;
	}

	public Symbol getSymbol() {
		return symbol;
	}

	@Override
	public String getDisplayString() {
		if (symbol == null) {
			return "<No Symbol>";
		}
		return symbol.getName();
	}

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

	@Override
	public int compareTo(DisplayableLabel otherDisplayableLabel) {
		if (otherDisplayableLabel == null) {
			return 1;
		}
		Symbol otherSymbol = otherDisplayableLabel.getSymbol();
		if (symbol == null) {
			return (otherSymbol == null) ? 0 : -1;
		}
		if (otherSymbol == null) {
			return 1;
		}
		return symbol.getName().compareToIgnoreCase(otherSymbol.getName());
	}

}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!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, maximum-scale=1, user-scalable=no">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

	<meta name="description" content="">
    <meta name="author" content="">

    <title>Transaction</title>

	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
	<link href="https://fonts.googleapis.com/css?family=Questrial" rel="stylesheet">

	<link rel="stylesheet" href="<?php echo base_url(); ?>/assets/css/dataTables.bootstrap.min.css">

	<link rel="stylesheet" href="<?php echo base_url(); ?>/assets/css/pembantu.css">

  <img src="<?php echo base_url(); ?>/assets/assets/list.svg" style="margin-bottom:10px;width:40%">
  Report

<a class="active text-center paddingnav putih tebal" href="<?php echo base_url(); ?>index.php/Admin">
  Account

  <img src="<?php echo base_url(); ?>/assets/assets/bread.svg" style="margin-bottom:3px;width:55%">
  Bread

<a class="text-center paddingnav putih" href="<?php echo base_url(); ?>/Admin/logout">
  Signout

<form action="addUser" method="post">

 INPUT USER

 ID User

						<input type="text" class="form-control" name="id_user">

 Name

						<input type="text" class="form-control" name="name" value="">

 Address

						<input type="text" class="form-control" name="address">

 Date of Birth

						<select class="form-control" id="day" style="width:100%">
							<option> DD </option>
							<option value="1"> 1 </option>
							<option value="2"> 2 </option>
							<option value="3"> 3 </option>
							<option value="4"> 4 </option>
							<input type="hidden" name="selected_day" id="selected_day" value="" />
						</select>

						<select class="form-control" id="month" style="width:100%" name="month">
							<option value="a"> MM </option>
							<option value="January"> January </option>
							<option value="February"> February </option>
							<option value="March"> March</option>
							<option value="April"> April </option>
							<option value="May"> May </option>
							<option value="June"> June </option>
							<option value="July"> July </option>
							<option value="August"> August </option>
							<option value="September"> September </option>
							<option value="October"> October </option>
							<option value="November"> November </option>
							<option value="December"> December </option>
						</select>

					<input type="hidden" name="selected_month" id="selected_month"
					value="" />

							<input type="text" class="form-control" placeholder="YYYY" name="year">

 Gender

							<input type="radio" name="optradio" id="gender" name="gender" class="cbGender" value="Male">Male

							<input type="radio" name="optradio" id="gender" name="gender" class="cbGender" value="Female">Female

						<input type="hidden" name="selected_gender" id="selected_gender" value="" />

 E-mail

						<input type="text" class="form-control" name="email">

 Username

						<input type="text" class="form-control" name="username">

 Password

						<input type="text" class="form-control" name="password">

 Level

						<input type="text" class="form-control" name="id_level">

					<a href="<?php echo base_url();?>index/Admin"><button class="btn btn-biruout"> CANCEL </button>
					<button class="btn btn-biru" type="submit" name="btnSubmit"> SUBMIT </button>

</form>


text:
package egoscale

// https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/configuration/Resource.java

// ResourceTypeName represents the name of a resource type (for limits)
type ResourceTypeName string

const (
	// VirtualMachineTypeName is the resource type name of a VM
	VirtualMachineTypeName ResourceTypeName = "user_vm"
	// IPAddressTypeName is the resource type name of an IP address
	IPAddressTypeName = "public_ip"
	// VolumeTypeName is the resource type name of a volume
	VolumeTypeName = "volume"
	// SnapshotTypeName is the resource type name of a snapshot
	SnapshotTypeName = "snapshot"
	// TemplateTypeName is the resource type name of a template
	TemplateTypeName = "template"
	// ProjectTypeName is the resource type name of a project
	ProjectTypeName = "project"
	// NetworkTypeName is the resource type name of a network
	NetworkTypeName = "network"
	// VPCTypeName is the resource type name of a VPC
	VPCTypeName = "vpc"
	// CPUTypeName is the resource type name of a CPU
	CPUTypeName = "cpu"
	// MemoryTypeName is the resource type name of Memory
	MemoryTypeName = "memory"
	// PrimaryStorageTypeName is the resource type name of primary storage
	PrimaryStorageTypeName = "primary_storage"
	// SecondaryStorageTypeName is the resource type name of secondary storage
	SecondaryStorageTypeName = "secondary_storage"
)

// ResourceType represents the ID of a resource type (for limits)
type ResourceType int64

const (
	// VirtualMachineType is the resource type ID of a VM
	VirtualMachineType ResourceType = iota
	// IPAddressType is the resource type ID of an IP address
	IPAddressType
	// VolumeType is the resource type ID of a volume
	VolumeType
	// SnapshotType is the resource type ID of a snapshot
	SnapshotType
	// TemplateType is the resource type ID of a template
	TemplateType
	// ProjectType is the resource type ID of a project
	ProjectType
	// NetworkType is the resource type ID of a network
	NetworkType
	// VPCType is the resource type ID of a VPC
	VPCType
	// CPUType is the resource type ID of a CPU
	CPUType
	// MemoryType is the resource type ID of Memory
	MemoryType
	// PrimaryStorageType is the resource type ID of primary storage
	PrimaryStorageType
	// SecondaryStorageType is the resource type ID of secondary storage
	SecondaryStorageType
)

// ListResourceLimits lists the resource limits
//
// CloudStack API: http://cloudstack.apache.org/api/apidocs-4.10/apis/listResourceLimits.html
type ListResourceLimits struct {
	Account          string           `json:"account,omittempty"`
	DomainID         string           `json:"domainid,omitempty"`
	ID               string           `json:"id,omitempty"`
	IsRecursive      *bool            `json:"isrecursive,omitempty"`
	Keyword          string           `json:"keyword,omitempty"`
	ListAll          *bool            `json:"listall,omitempty"`
	Page             int              `json:"page,omitempty"`
	PageSize         int              `json:"pagesize,omitempty"`
	ProjectID        string           `json:"projectid,omitempty"`
	ResourceType     ResourceType     `json:"resourcetype,omitempty"`
	ResourceTypeName ResourceTypeName `json:"resourcetypename,omitempty"`
}

func (*ListResourceLimits) name() string {
	return "listResourceLimits"
}

func (*ListResourceLimits) response() interface{} {
	return new(ListResourceLimitsResponse)
}

// ListResourceLimitsResponse represents a list of resource limits
type ListResourceLimitsResponse struct {
	Count         int             `json:"count"`
	ResourceLimit []ResourceLimit `json:"resourcelimit"`
}

// ResourceLimit represents the limit on a particular resource
type ResourceLimit struct {
	Account          string           `json:"account,omitempty"`
	Domain           string           `json:"domain,omitempty"`
	DomainID         string           `json:"domainid,omitempty"`
	Max              int64            `json:"max,omitempty"` // -1 means the sky is the limit
	Project          string           `json:"project,omitempty"`
	ProjectID        string           `json:"projectid,omitempty"`
	ResourceType     ResourceType     `json:"resourcetype,omitempty"`
	ResourceTypeName ResourceTypeName `json:"resourcetypename,omitempty"`
}


text:
"use strict";
function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
var compiler_host_1 = require('./src/compiler_host');
exports.DecoratorDownlevelCompilerHost = compiler_host_1.DecoratorDownlevelCompilerHost;
exports.MetadataWriterHost = compiler_host_1.MetadataWriterHost;
var main_1 = require('./src/main');
exports.UserError = main_1.UserError;
exports.main = main_1.main;
__export(require('./src/cli_options'));
__export(require('./src/collector'));
__export(require('./src/schema'));
//# sourceMappingURL=index.js.map