text:
<?php

/*
 * This file is part of the Active Collab DatabaseStructure project.
 *
 * (c) A51 doo <info@activecollab.com>. All rights reserved.
 */

namespace ActiveCollab\DatabaseStructure\Field\Composite;

use ActiveCollab\DatabaseStructure\Field\Scalar\IntegerField;
use ActiveCollab\DatabaseStructure\Field\Scalar\StringField as ScalarStringField;
use ActiveCollab\DatabaseStructure\Field\Scalar\Traits\AddIndexInterface;
use ActiveCollab\DatabaseStructure\Field\Scalar\Traits\AddIndexInterface\Implementation as AddIndexInterfaceImplementation;
use ActiveCollab\DatabaseStructure\Field\Scalar\Traits\RequiredInterface;
use ActiveCollab\DatabaseStructure\Field\Scalar\Traits\RequiredInterface\Implementation as RequiredInterfaceImplementation;
use ActiveCollab\DatabaseStructure\TypeInterface;
use ActiveCollab\User\IdentifiedVisitor;
use ActiveCollab\User\UserInterface;
use Doctrine\Inflector\Inflector;
use Doctrine\Inflector\InflectorFactory;
use InvalidArgumentException;

class ActionByField extends CompositeField implements AddIndexInterface, RequiredInterface
{
    use AddIndexInterfaceImplementation, RequiredInterfaceImplementation;

    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $user_class_name;

    /**
     * @var string
     */
    private $identified_visitor_class_name;

    /**
     * @param string $name
     * @param string $user_class_name
     * @param string $identified_visitor_class_name
     * @param bool   $add_index
     */
    public function __construct($name, $user_class_name, $identified_visitor_class_name = IdentifiedVisitor::class, $add_index = true)
    {
        if (empty($name)) {
            throw new InvalidArgumentException("Value '$name' is not a valid field name");
        }

        $name_len = strlen($name);

        if ($name_len <= 6 || substr($name, $name_len - 6) != '_by_id') {
            throw new InvalidArgumentException("Value '$name' needs to be in action_by_id format");
        }

        if (empty($user_class_name)) {
            throw new InvalidArgumentException('User class name is required');
        }

        if (empty($identified_visitor_class_name)) {
            throw new InvalidArgumentException('Anonymous user class name is required');
        }

        $this->name = $name;
        $this->user_class_name = '\\' . ltrim($user_class_name, '\\');
        $this->identified_visitor_class_name = '\\' . ltrim($identified_visitor_class_name, '\\');
        $this->addIndex($add_index);
    }

    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getUserClassName()
    {
        return $this->user_class_name;
    }

    /**
     * @return string
     */
    public function getIdentifiedvisitorClassName()
    {
        return $this->identified_visitor_class_name;
    }

    public function getFields(): array
    {
        $id_field = (new IntegerField($this->getName(), 0))
            ->unsigned();

        if ($this->isRequired()) {
            $id_field->required();
        }

        return [
            $id_field,
            new ScalarStringField($this->getActionName() . '_by_name'),
            new EmailField($this->getActionName() . '_by_email'),
        ];
    }

    /**
     * Return methods that this field needs to inject in base class.
     *
     * @param string $indent
     * @param array  $result
     */
    public function getBaseClassMethods(string $indent, array &$result): void
    {
        $inflector = $this->getInflector();

        $id_getter_name = 'get' . $inflector->classify($this->name);
        $id_setter_name = 'set' . $inflector->classify($this->name);

        $email_getter_name = 'get' . $inflector->classify($this->getActionName() . '_by_email');
        $email_setter_name = 'set' . $inflector->classify($this->getActionName() . '_by_email');

        $name_getter_name = 'get' . $inflector->classify($this->getActionName() . '_by_name');
        $name_setter_name = 'set' . $inflector->classify($this->getActionName() . '_by_name');

        $instance_getter_name = 'get' . $inflector->classify(substr($this->name, 0, strlen($this->name) - 3));
        $instance_setter_name = 'set' . $inflector->classify(substr($this->name, 0, strlen($this->name) - 3));

        $type_hint = '\\' . UserInterface::class . '|' . $this->identified_visitor_class_name . '|' . $this->user_class_name . '|null';

        $methods = [];

        $methods[] = '/**';
        $methods[] = ' * @param  bool' . str_pad('$use_cache', strlen($type_hint) + 7, ' ', STR_PAD_LEFT);
        $methods[] = ' * @return ' . $type_hint;
        $methods[] = ' */';
        $methods[] = 'public function ' . $instance_getter_name . '($use_cache = true)';
        $methods[] = '{';
        $methods[] = '    if ($id = $this->' . $id_getter_name . '()) {';
        $methods[] = '        return $this->pool->getById(' . var_export($this->user_class_name, true). ', $id, $use_cache);';
        $methods[] = '    } elseif ($email = $this->' . $email_getter_name . '()) {';
        $methods[] = '        return new ' . $this->identified_visitor_class_name . '($this->' . $name_getter_name . '(), $email);';
        $methods[] = '    } else {';
        $methods[] = '        return null;';
        $methods[] = '    }';
        $methods[] = '}';
        $methods[] = '';

        if ($this->isRequired()) {
            $methods[] = '/**';
            $methods[] = ' * Set ' . $this->action_name . '.';
            $methods[] = ' *';
            $methods[] = ' * @param  \\' . UserInterface::class . '|' . $this->user_class_name .' $value';
            $methods[] = ' * @return $this';
            $methods[] = ' */';
            $methods[] = 'public function &' . $instance_setter_name . '(\\' . UserInterface::class . ' $value)';
            $methods[] = '{';
            $methods[] = '    if ($value instanceof ' . $this->user_class_name . ' && $value->isLoaded()) {';
            $methods[] = '        $this->' . $id_setter_name . '($value->getId());';
            $methods[] = '        $this->' . $name_setter_name . '($value->getFullName());';
            $methods[] = '        $this->' . $email_setter_name . '($value->getEmail());';
            $methods[] = '    } else {';
            $methods[] = '        throw new \InvalidArgumentException(' . var_export("Instance of '$this->user_class_name' expected", true) . ');';
            $methods[] = '    }';
            $methods[] = '';
            $methods[] = '    return $this;';
            $methods[] = '}';
        } else {
            $methods[] = '/**';
            $methods[] = ' * Set ' . $this->action_name . '.';
            $methods[] = ' *';
            $methods[] = ' * @param  ' . $type_hint . ' $value';
            $methods[] = ' * @return $this';
            $methods[] = ' */';
            $methods[] = 'public function &' . $instance_setter_name . '(\\' . UserInterface::class . ' $value = null)';
            $methods[] = '{';
            $methods[] = '    if ($value instanceof ' . $this->user_class_name . ') {';
            $methods[] = '        if ($value->isLoaded()) {';
            $methods[] = '            $this->' . $id_setter_name . '($value->getId());';
            $methods[] = '            $this->' . $name_setter_name . '($value->getFullName());';
            $methods[] = '            $this->' . $email_setter_name . '($value->getEmail());';
            $methods[] = '        } else {';
            $methods[] = '            throw new \InvalidArgumentException(' . var_export("Instance of '$this->user_class_name' expected") . ');';
            $methods[] = '        }';
            $methods[] = '    } elseif ($value instanceof ' . $this->identified_visitor_class_name . ') {';
            $methods[] = '        $this->' . $id_setter_name . '(0);';
            $methods[] = '        $this->' . $name_setter_name . '($value->getFullName());';
            $methods[] = '        $this->' . $email_setter_name . '($value->getEmail());';
            $methods[] = '    } else {';
            $methods[] = '        $this->' . $id_setter_name . '(0);';
            $methods[] = '        $this->' . $name_setter_name . '(null);';
            $methods[] = '        $this->' . $email_setter_name . '(null);';
            $methods[] = '    }';
            $methods[] = '';
            $methods[] = '    return $this;';
            $methods[] = '}';
        }

        foreach ($methods as $line) {
            if ($line) {
                $result[] = "$indent$line";
            } else {
                $result[] = '';
            }
        }
    }

    /**
     * Return methods that this field needs to inject in base class.
     *
     * @param string $indent
     * @param array  $result
     */
    public function getBaseInterfaceMethods(string $indent, array &$result): void
    {
        $inflector = $this->getInflector();

        $instance_getter_name = 'get' . $inflector->classify(substr($this->name, 0, strlen($this->name) - 3));
        $instance_setter_name = 'set' . $inflector->classify(substr($this->name, 0, strlen($this->name) - 3));

        $type_hint = '\\' . UserInterface::class . '|' . $this->identified_visitor_class_name . '|' . $this->user_class_name . '|null';

        $methods = [];

        $methods[] = '/**';
        $methods[] = ' * @param  bool' . str_pad('$use_cache', strlen($type_hint) + 7, ' ', STR_PAD_LEFT);
        $methods[] = ' * @return ' . $type_hint;
        $methods[] = ' */';
        $methods[] = 'public function ' . $instance_getter_name . '($use_cache = true);';
        $methods[] = '';

        if ($this->isRequired()) {
            $methods[] = '/**';
            $methods[] = ' * Set ' . $this->action_name . '.';
            $methods[] = ' *';
            $methods[] = ' * @param  \\' . UserInterface::class . '|' . $this->user_class_name .' $value';
            $methods[] = ' * @return $this';
            $methods[] = ' */';
            $methods[] = 'public function &' . $instance_setter_name . '(\\' . UserInterface::class . ' $value);';
        } else {
            $methods[] = '/**';
            $methods[] = ' * Set ' . $this->action_name . '.';
            $methods[] = ' *';
            $methods[] = ' * @param  ' . $type_hint . ' $value';
            $methods[] = ' * @return $this';
            $methods[] = ' */';
            $methods[] = 'public function &' . $instance_setter_name . '(\\' . UserInterface::class . ' $value = null);';
        }

        foreach ($methods as $line) {
            if ($line) {
                $result[] = "$indent$line";
            } else {
                $result[] = '';
            }
        }
    }

    /**
     * @var string
     */
    private $action_name;

    /**
     * Return action name (name without _by_id).
     *
     * @return string
     */
    private function getActionName()
    {
        if (empty($this->action_name)) {
            $this->action_name = substr($this->name, 0, strlen($this->name) - 6);
        }

        return $this->action_name;
    }
    public function onAddedToType(TypeInterface $type): void
    {
        parent::onAddedToType($type);

        $type->serialize($this->name);
    }

    private ?Inflector $inflector = null;

    private function getInflector(): Inflector
    {
        if ($this->inflector === null) {
            $this->inflector = InflectorFactory::create()->build();
        }

        return $this->inflector;
    }
}


text:
==========================
Frequently Asked Questions
==========================

.. contents::

.. _faq-entries:

Entries
=======

.. _custom-markups:

I want to write my entries in `MarkDown`_, `RestructuredText`_ or any lightweight markup language, is it possible ?
-------------------------------------------------------------------------------------------------------------------

Yes of course, Zinnia currently support `MarkDown`_, `Textile`_ and
`reStructuredText`_ as markup languages, but if you want to write your
entries in a custom markup language a solution is to disable the WYSIWYG
editor in the admin site with the :setting:`ZINNIA_WYSIWYG` setting, and
use the appropriate template filter in your templates.

I want to have multilingual support on the entries, is it possible ?
--------------------------------------------------------------------

Due to the extending capabilities of Zinnia, many solutions on this
problematic are possible, but you must keep in mind that multiplingual
entries is just a concept, the needs and the implementations can differ
from a project to another. But you should take a look on this excellent
tutorial to `convert Zinnia into a multilingual Weblog`_ with
`django-modeltranslation`_, which can be a good starting point for your
needs.

.. _multiple-authors:

Is Zinnia able to allow multiple users to edit it's own blog ?
--------------------------------------------------------------

Zinnia is designed to be multi-site. That's mean you can publish entries on
several sites or share an admin interface for all the sites handled.

Zinnia also provides a new permission that's allow or not the user to
change the authors. Useful for collaborative works.

But if you want to restrict the edition of the entries by site, authors or
whatever you want, it's your job to implement this functionality in your
project.

The simple way to do that, respecting the Django rules, is to override the
admin classes provided by Zinnia, and register those classes in another
admin site.

.. _faq-images:

Images
======

.. _image-thumbnails:

How can I use the image field for fitting to my skin ?
------------------------------------------------------

Take a looks at `sorl.thumbnail`_ and use his templatetags.

You can do something like this in your templates:

.. code-block:: html+django

  <img src="{% thumbnail object.image 250x250 %}" />

.. _image-gallery:

I want an image gallery in my posts, what can I do ?
----------------------------------------------------

Simply create a new application with a model named :class:`EntryImage` with a
:class:`~django.db.models.ForeignKey` to the
:class:`~zinnia.models.entry.Entry` model.

Then in the admin module of your app, unregister the
:class:`~zinnia.admin.entry.EntryAdmin` class, and use
:class:`~django.contrib.admin.InlineModelAdmin` in your new admin class.

Here an simple example : ::

  # The model
  from django.db import models
  from django.utils.translation import ugettext_lazy as _

  from zinnia.models.entry import Entry

  class EntryImage(models.Model):
      """Image Model"""
      entry = models.ForeignKey(Entry, verbose_name=_('entry'))

      image = models.ImageField(_('image'), upload_to='uploads/gallery')
      title = models.CharField(_('title'), max_length=250)
      description = models.TextField(_('description'), blank=True)

      def __unicode__(self):
          return self.title

  # The admin

  from django.contrib import admin

  from zinnia.admin import EntryAdmin
  from zinnia.models.entry import Entry
  from gallery.models import EntryImage

  class EntryImageInline(admin.TabularInline):
      model = EntryImage

  class EntryAdminImage(EntryAdmin):
      inlines = (EntryImageInline,)

  admin.site.unregister(Entry)
  admin.site.register(Entry, EntryAdminImage)

Another and better solution is to extend the :class:`~zinnia.models.entry.Entry`
model like described in :doc:`/how-to/extending_entry_model`.

.. _faq-comments:

Comments
========

.. _customizing-comments:

Is it possible have a different comment system, with reply feature for example ?
--------------------------------------------------------------------------------

Yes the comment system integrated in Zinnia is based on
:mod:`django_comments` and can be extended or replaced if doesn't
quite fit your needs. You should take a look on the
`customizing the comments framework`_ documentation for more information.

.. warning::

   The custom comment Model must be inherited from
   :class:`~django_comments.models.Comment` and implement the
   :class:`~django_comments.managers.CommentManager` to properly
   work with Zinnia.

If you want the ability to reply on comments, you can take a look at
`zinnia-threaded-comments`_ or at `django-threadcomments`_.

.. _`MarkDown`: http://daringfireball.net/projects/markdown/
.. _`Textile`: http://redcloth.org/hobix.com/textile/
.. _`reStructuredText`: http://docutils.sourceforge.net/rst.html
.. _`convert Zinnia into a multilingual Weblog`:  http://www.codeispoetry.me/django-blog-zinnia-multilanguage-support-with-django-modeltranslation/
.. _`django-modeltranslation`:
.. _`sorl.thumbnail`: http://thumbnail.sorl.net/
.. _`customizing the comments framework`: http://django-contrib-comments.readthedocs.org/en/latest/custom.html
.. _`zinnia-threaded-comments`: https://github.com/django-blog-zinnia/zinnia-threaded-comments
.. _`django-threadcomments`: https://github.com/HonzaKral/django-threadedcomments

redpajama_set_name: RedPajamaGithub


text:
![playground](https://cloud.githubusercontent.com/assets/2652413/12503252/005c7be8-c0d3-11e5-9621-5e98cd08478d.jpg)

Just Another Promises Playground.

Here are [the promises' tests](https://muzietto.github.io/japp/Promizzes_Mocha.html):
- promizzes.js: first naive attempt; promise contains logic to handle value and dependencies
- promizzes2.js: all logic is outside promises and is handled by static methods `depend` & `fulfill`
- promizzes2b.js: identical to [what Robotlolita did]( http://robotlolita.me/2015/11/15/how-do-promises-work.html#a-minimal-promise-implementation)
- promizzes3.js: promises with `then` (aka `bind`) as instance method

Here are [the Either monad tests](https://muzietto.github.io/japp/Eitherz_Mocha.html):
- eitherz2.js: all logic is outside promises and is handled by static methods `depend`, `resolve` & `reject`
- eitherz2b.js: all logic is outside promises and is handled by static methods `depend`, `resolve` & `reject`, heavily inspired to [what Robotlolita did]( http://robotlolita.me/2015/11/15/how-do-promises-work.html#handling-errors-with-promises)
- eitherz3.js: promises with `then` (aka `bind`) as instance method and error handling


text:
var app = angular.module('SupervisorApp',['ui.router','angular.filter'])
    .config(['$stateProvider','$urlRouterProvider','$locationProvider',function($stateProvider,$urlRouterProvider,$locationProvider) {
        $locationProvider.html5Mode(true);
        $urlRouterProvider
            .otherwise('/supervisor/');

        $stateProvider
            .state('home',{
                url: '/supervisor/',
                templateUrl: 'supervisor/partials/home',
                controller: 'HomeController',
                redirectTo: 'home'
            })
            .state('metrics',{
                url: '/supervisor/',
                templateUrl: 'supervisor/partials/metrics',
                controller: 'MetricsController',
                redirectTo: 'metrics'
            })
            .state('config',{
                url: '/supervisor/#config',
                templateUrl: 'supervisor/partials/config',
                controller: 'ConfigController',
                redirectTo: 'config'
            })
            .state('peripherals',{
                url: '/supervisor/#peripherals',
                templateUrl: 'supervisor/partials/peripherals',
                controller: 'PeripheralsController',
                redirectTo: 'peripherals'
            })
            .state('commands',{
                url: '/supervisor/#commands',
                templateUrl: 'supervisor/partials/commands',
                controller: 'CommandsController',
                redirectTo: 'commands'
            })
            .state('schedules',{
                url: '/supervisor/#schedules',
                templateUrl: 'supervisor/partials/schedules',
                controller: 'SchedulesController',
                redirectTo: 'schedules'
            })
            .state('status',{
                url: '/supervisor/#status',
                templateUrl: 'supervisor/partials/status',
                controller: 'StatusController',
                redirectTo: 'status'
            })
            .state('shell',{
                url: '/supervisor/#shell',
                templateUrl: 'supervisor/partials/shell',
                controller: 'ShellController',
                redirectTo: 'shell'
            });
    }])
    .run(['$rootScope','$http','$interval','$location',function($rootScope,$http,$interval,$location) {
        $rootScope.instanceID = 0;
        $rootScope.globalMessages = {};
        $rootScope.globalValues = {};
        $rootScope.globalStatus = {label: 'Status: Pending...',css: 'label-default'};

        $rootScope.checkStatus = function(){
            $http.get('/supervisor/api/status')
                .success(function(result){
                    var total = 0;
                    var success = 0;
                    _.each(result,function(value){
                        total++;
                        if (value) success++;
                    });
                    if (total > success)
                        $rootScope.globalStatus = {label: 'Status: ERRORS',css: 'label-warning',breakdown: result};
                    else
                        $rootScope.globalStatus = {label: 'Status: OK',css: 'label-success',breakdown: result};
                    $rootScope.globalStatus.breakdown = _.pairs(result);
                })
                .error(function(){
                    $rootScope.globalStatus = {label: 'Status: DOWN',css: 'label-danger',error: 'Server connection failed'};
                })
        };
        $rootScope.checkStatus();
        $interval($rootScope.checkStatus,15*1000);

        $rootScope.setupSocket = function(flavor,callback) {
            if (!$rootScope.socket) {
                $rootScope.socket = io($location.host() + ':' + $location.port(),{path: '/supervisor/socket'});
                $rootScope.socket.flavors = {};

                $rootScope.socket.on('identified',function(data){
                    console.log('identified: ' + JSON.stringify(data));
                });
                $rootScope.socket.on('close',function(data){
                    console.log('close: ' + JSON.stringify(data));
                });
                $rootScope.socket.on('connect',function(){
                    console.log('connect');
                });
                $rootScope.socket.on('disconnect',function(){
                    console.log('disconnect');
                });
                $rootScope.socket.on('error',function(error){
                    console.log('error:' + error);
                });
                $rootScope.socket.on('reconnect',function(number){
                    console.log('reconnect:' + number);
                });
                $rootScope.socket.on('reconnect_attempt',function(){
                    console.log('reconnect_attempt');
                });
                $rootScope.socket.on('reconnecting',function(number){
                    console.log('reconnecting:' + number);
                });
                $rootScope.socket.on('reconnect_failed',function(){
                    console.log('reconnect_failed');
                });
                $rootScope.socket.on('ready',function(){
                    console.log('ready');
                });
                $rootScope.socket.on('busy',function(){
                    console.log('busy');
                });
            }
            if (!$rootScope.socket.flavors[flavor]) {
                $rootScope.socket.flavors[flavor] = true;
                callback && callback($rootScope.socket);
            }
            return $rootScope.socket;
        }

    }]);


text:
<form novalidate>
    <pe-steps [(activeIndex)]="activeIndex" (change)="onChangeStep($event)">

        <pe-step label="Default Toolbar">

Default Toolbar

Content: {{basictext}}

        </pe-step>

        <pe-step label="Custom Toolbar" [styleClass]="'multicheckbox-height'">

Custom Toolbar

            <button class="ql-bold"></button>
            <button class="ql-italic"></button>
            <button class="ql-underline"></button>
            <button class="ql-clean"></button>

Content: {{customtext}}

        </pe-step>

        <pe-step label="Events">

Events

Content: {{eventstext}}

        </pe-step>

        <pe-step label="ReadOnly">

ReadOnly

Content: {{readonlytext}}

        </pe-step>

    </pe-steps>
</form>


text:
require('./base');

module.exports = {
  Procedures: require('./procedures'),
  Info:       require('./info'),
  Content:    require('./content'),
  Query:      require('./query'),
  Structure:  require('./structure'),
  Users:      require('./users'),
  Extensions: require('./extensions'),
}


text:
module Blogo
  class Config
    attr_accessor :site_title
    attr_accessor :site_subtitle

    attr_accessor :table_name_prefix

    attr_accessor :posts_per_page
    attr_accessor :paginator_size
    attr_accessor :recent_posts

    attr_accessor :keywords

    attr_accessor :disqus_shortname
    attr_accessor :twitter_username
    attr_accessor :facebook_username
    attr_accessor :site_url
    attr_accessor :site_icon
    attr_accessor :site_logo
    attr_accessor :widget_id
    attr_accessor :github_username
    attr_accessor :show_rss_icon
    attr_accessor :google_analytics_id

    attr_accessor :use_ckeditor

    attr_reader :markup_lang

    # Set default values.
    def initialize
      @site_title          = 'Blogo'
      @site_subtitle       = 'Mountable blog engine for Ruby on Rails'
      @table_name_prefix   = 'blogo_'
      @posts_per_page      = 10
      @paginator_size      = 5
      @recent_posts        = 5
      @disqus_shortname    = nil
      @google_analytics_id = nil
      @use_ckeditor        = true
      @keywords            = %w(blog)
      @markup_lang         = :html
      @show_rss_icon       = true
    end

    def markup_lang=(lang)
      # Try to find a renderer for the format otherwise raise
      Blogo::Renderer.get(lang.to_sym)
      @format = lang.to_sym
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>Members | Greenpeace Greenwire</title>
    <meta name="description" content="Greenpeace Greenwire - Events map widget demo"/>
    <meta name="keywords" content="greenpeace, greenwire"/>
    <meta name="viewport" content="width=device-width"/>
    <meta name="robots" content="all"/>
    <link rel="stylesheet" type="text/css" href="css/greenwire.css"/>
    <link rel="stylesheet" type="text/css" href="css/icons.css"/>
    <link rel="stylesheet" type="text/css" href="css/map.css"/>
    <link rel="stylesheet" type="text/css" href="css/leaflet.css" />
    <link rel="stylesheet" type="text/css" href="css/leaflet.markercluster.css" />


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package com.google.zxing.oned.rss (ZXing Core 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2014-02-17">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
com.google.zxing.oned.rss

Packages that use com.google.zxing.oned.rss

com.google.zxing.oned.rss

com.google.zxing.oned.rss.expanded

Classes in com.google.zxing.oned.rss used by com.google.zxing.oned.rss

AbstractRSSReader

Classes in com.google.zxing.oned.rss used by com.google.zxing.oned.rss.expanded

AbstractRSSReader

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2007–2014. All rights reserved.


text:
const ipc = require('electron').ipcMain
const dialog = require('electron').dialog

ipc.on('open-information-dialog', function (event) {
  const options = {
    type: 'info',
    title: 'Information',
    message: "This is an information dialog. Isn't it nice?",
    buttons: ['Yes', 'No']
  }
  dialog.showMessageBox(options, function (index) {
    event.sender.send('information-dialog-selection', index)
  })
})


text:
import json
import os

from sync_query import main

PROJECT = os.environ['GCLOUD_PROJECT']

def test_sync_query(capsys):
    query = (
        'SELECT corpus FROM publicdata:samples.shakespeare '
        'GROUP BY corpus;')

    main(
        project_id=PROJECT,
        query=query,
        timeout=30,
        num_retries=5,
        use_legacy_sql=True)

    out, _ = capsys.readouterr()
    result = out.split('\n')[0]

    assert json.loads(result) is not None

def test_sync_query_standard_sql(capsys):
    query = 'SELECT [1, 2, 3] AS arr;'  # Only valid in standard SQL

    main(
        project_id=PROJECT,
        query=query,
        timeout=30,
        num_retries=5,
        use_legacy_sql=False)

    out, _ = capsys.readouterr()
    result = out.split('\n')[0]

    assert json.loads(result) is not None


text:
@extends('LaravelAdmin::layouts.withsidebar')
@section('pageTitle')
{{isset($pageTitle) ? $pageTitle : 'Artículos'}}
@endsection
@section('content')

         Artículos del blog de noticas

                 @include('flash::message')

                  Crear Artículo

         {!! $table !!}

@endsection


text:
package git4idea.branch;

import com.intellij.notification.Notification;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsNotifier;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ui.UIUtil;
import com.intellij.xml.util.XmlStringUtil;
import git4idea.*;
import git4idea.commands.Git;
import git4idea.merge.GitConflictResolver;
import git4idea.repo.GitRepository;
import git4idea.ui.ChangesBrowserWithRollback;
import git4idea.util.GitSimplePathsBrowser;
import git4idea.util.GitUntrackedFilesHelper;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class GitBranchUiHandlerImpl implements GitBranchUiHandler {

  @NotNull private final Project myProject;
  @NotNull private final Git myGit;
  @NotNull private final GitPlatformFacade myFacade;
  @NotNull private final ProgressIndicator myProgressIndicator;

  public GitBranchUiHandlerImpl(@NotNull Project project, @NotNull GitPlatformFacade facade, @NotNull Git git, @NotNull ProgressIndicator indicator) {
    myProject = project;
    myGit = git;
    myFacade = facade;
    myProgressIndicator = indicator;
  }

  @Override
  public boolean notifyErrorWithRollbackProposal(@NotNull final String title, @NotNull final String message,
                                                 @NotNull final String rollbackProposal) {
    final AtomicBoolean ok = new AtomicBoolean();
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        StringBuilder description = new StringBuilder();
        if (!StringUtil.isEmptyOrSpaces(message)) {
          description.append(message).append("
");
        }
        description.append(rollbackProposal);
        ok.set(Messages.YES == DialogManager.showOkCancelDialog(myProject, XmlStringUtil.wrapInHtml(description), title,
                                                                "Rollback", "Don't rollback", Messages.getErrorIcon()));
      }
    });
    return ok.get();
  }

  @Override
  public void showUnmergedFilesNotification(@NotNull final String operationName, @NotNull final Collection<GitRepository> repositories) {
    String title = unmergedFilesErrorTitle(operationName);
    String description = unmergedFilesErrorNotificationDescription(operationName);
    VcsNotifier.getInstance(myProject).notifyError(title, description,
      new NotificationListener() {
        @Override
        public void hyperlinkUpdate(@NotNull Notification notification,
                                    @NotNull HyperlinkEvent event) {
          if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED && event.getDescription().equals("resolve")) {
            GitConflictResolver.Params params = new GitConflictResolver.Params().
              setMergeDescription(String.format("The following files have unresolved conflicts. You need to resolve them before %s.",
                                                operationName)).
              setErrorNotificationTitle("Unresolved files remain.");
            new GitConflictResolver(myProject, myGit, myFacade, GitUtil.getRootsFromRepositories(repositories), params).merge();
          }
        }
      }
    );
  }

  @Override
  public boolean showUnmergedFilesMessageWithRollback(@NotNull final String operationName, @NotNull final String rollbackProposal) {
    final AtomicBoolean ok = new AtomicBoolean();
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        String description = String.format("You have to resolve all merge conflicts before %s.
%s",
                                           operationName, rollbackProposal);
        // suppressing: this message looks ugly if capitalized by words
        //noinspection DialogTitleCapitalization
        ok.set(Messages.YES == DialogManager.showOkCancelDialog(myProject, description, unmergedFilesErrorTitle(operationName),
                                                                "Rollback", "Don't rollback", Messages.getErrorIcon()));
      }
    });
    return ok.get();
  }

  @Override
  public void showUntrackedFilesNotification(@NotNull String operationName, @NotNull VirtualFile root, @NotNull Collection<String> relativePaths) {
    GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(myProject, root, relativePaths, operationName, null);
  }

  @Override
  public boolean showUntrackedFilesDialogWithRollback(@NotNull String operationName, @NotNull final String rollbackProposal,
                                                      @NotNull VirtualFile root, @NotNull final Collection<String> relativePaths) {
    return GitUntrackedFilesHelper.showUntrackedFilesDialogWithRollback(myProject, operationName, rollbackProposal, root, relativePaths);
  }

  @NotNull
  @Override
  public ProgressIndicator getProgressIndicator() {
    return myProgressIndicator;
  }

  @Override
  public int showSmartOperationDialog(@NotNull Project project, @NotNull List<Change> changes, @NotNull Collection<String> paths,
                                      @NotNull String operation, @Nullable String forceButtonTitle) {
    JComponent fileBrowser;
    if (!changes.isEmpty()) {
      fileBrowser = new ChangesBrowserWithRollback(project, changes);
    }
    else {
      fileBrowser = new GitSimplePathsBrowser(project, paths);
    }
    return GitSmartOperationDialog.showAndGetAnswer(myProject, fileBrowser, operation, forceButtonTitle);
  }

  @Override
  public boolean showBranchIsNotFullyMergedDialog(@NotNull Project project, @NotNull final Map<GitRepository, List<GitCommit>> history,
                                                  @NotNull final String unmergedBranch, @NotNull final List<String> mergedToBranches,
                                                  @NotNull final String baseBranch) {
    final AtomicBoolean forceDelete = new AtomicBoolean();
    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
      @Override
      public void run() {
        forceDelete.set(GitBranchIsNotFullyMergedDialog.showAndGetAnswer(myProject, history, unmergedBranch, mergedToBranches, baseBranch));
      }
    });
    return forceDelete.get();
  }

  @NotNull
  private static String unmergedFilesErrorTitle(@NotNull String operationName) {
    return "Can't " + operationName + " because of unmerged files";
  }

  @NotNull
  private static String unmergedFilesErrorNotificationDescription(String operationName) {
    return "You have to resolve all merge conflicts before " + operationName + ".
" +
           "After resolving conflicts you also probably would want to commit your files to the current branch.";
  }
}


text:
CGFloat const XMGTitlesViewH = 35;
CGFloat const XMGTitlesVIewY = 64;


text:
<?php
/**
 * This file is a part of the Event-Band project
 * @author Kirill chebba Chebunin
 * @author Vasil coylOne Kulakov <kulakov@vasiliy.pro>
 */

namespace EventBand\Bundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;

/**
 * Class SectionConfiguration
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
interface SectionConfiguration
{
    /**
     * @return ArrayNodeDefinition
     */
    public function getSectionDefinition();
}


text:
'use strict';

import mongoose from 'mongoose';

import {config} from './util';

const {DB_HOST, DB_PORT, DB_NAME, DB_OPTIONS} = config;
const CONNECTION_STRING = `mongodb://${DB_HOST}:${DB_PORT}/${DB_NAME}`;

export function open(){
    return new Promise((resolve, reject) => {
        console.log(`Connect to MongoDB ${CONNECTION_STRING}`);
        mongoose.connect(CONNECTION_STRING, DB_OPTIONS, resolve);
    });
}

export function close(){
    return new Promise((resolve, reject) => {
        mongoose.disconnect(resolve);
    });
}


text:
-include ../../makefiles/common.mk

# list of objects that. This will alwyas be <ComponentName>.o and depeneding on implementation
# <ComponentName>_SW.o and/or <ComponentName>_HW.o
OBJECTS=SoundToControlComponent_SW.o SoundToControlComponent.o

# all: <nameofyoursharedlibrary>.so
all: libsoundtocontrol.so

# <nameofyoursharelibrary>.so: $(OBJECTS)
libsoundtocontrol.so: $(OBJECTS)
	# just leave this like this
	$(CC) -g3 -Wno-unused-variable -shared $(OBJECTS) -o $@

# You also need to add a line to ../makefiles/Makefile to include this folder!


text:
package com.sfp.extJsMVColors.utils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * String related helper methods
 */
public class StringHelper {

    /**
     * Join the given strings with given glue
     *
     * @param   s
     * @param   glue
     * @return  String
     */
	public static String join(String s[], String glue) {
		StringBuilder buffer	= new StringBuilder();
		List list				= Arrays.asList(s);
		Iterator iterator		= list.iterator();

		while (iterator.hasNext()) {
			buffer.append(iterator.next());
			if (iterator.hasNext())	buffer.append(glue);
		}

		return buffer.toString();
	}

    /**
     * @param   s
     * @param   wrap
     * @return  String
     */
	public static String wrap(String s, String wrap) {
		return wrap + s + wrap;
	}

    /**
     * @param   s
     * @param   wrap
     * @return  String
     */
	public static String wrap(String s, char wrap) {
		return wrap(s, Character.toString(wrap));
	}

    /**
     * Replace last occurrence of given sub string
     *
     * @param s
     * @param search
     * @return
     */
    public static String removeLast(String s, String search) {
        int pos = s.lastIndexOf(search);

        if( pos > -1 ) {
            return s.substring(0, pos) + s.substring(pos + search.length(), s.length());
        }

        return s;
    }

}


text:
Contributions to Temple must be accompanied by sign-off text that indicates
acceptance of the Contributor License Agreement (see [CLA](CLA) for full
text), which is closely derived from the Apache Individual Contributor License
Agreement. The sign-off text must be included once per commit, in the commit
message. The sign-off can be automatically inserted using a command such as
`git commit -s`, which will generate the text in the form:
`Signed-off-by: Random J Developer <random@developer.example.org>`

By adding this sign-off, you are certifying:

_By signing-off on this submission, I agree to be bound by the terms of the
Contributor License Agreement located at the root of the project repository,
and I agree that this submission constitutes a "Contribution" under that
Agreement._

Please note that this project and any contributions to it are public and that
a record of all contributions (including any personal information submitted
with it, including a sign-off) is maintained indefinitely and may be
redistributed consistent with this project or the open source license(s)
involved.

## Quick guidelines

* Keep a clean commit history. This means no merge commits, and no long series
  of "fixup" patches (rebase or squash as appropriate). Structure work as a
  series of logically ordered, atomic patches. `git rebase -i` is your friend.
* Changes should be made via pull request, with review. Do not commit until
  you've had an explicit "looks good to me". We don't yet have, but plan to
  create a policy describing code owners and the like. In the meantime use your
  best judgement. If you're submitting a change against something that was 90%
  authored by a single person, you'll want to get their ACK before committing.
* When changes are restricted to a specific area, you are recommended to add a
  tag to the beginning of the first line of the commit message in square
  brackets. e.g. "[UART] Fix bug #157".
* Code review is not design review and doesn't remove the need for discussing
  implementation options. If you would like to make a large-scale change or
  discuss multiple implementation options, discuss on the mailing list.
* Create pull requests from a fork rather than making new branches in
  `github.com/lowrisc/temple`.
* Do not force push.
* Do not attempt to commit code with a non-Apache license without discussing
  first.
* If a relevant bug or tracking issue exists, reference it in the pull request
  and commits.


text:
This project is a tutorial that walks through the steps required to deploy and
[serve a TensorFlow model](https://www.tensorflow.org/serving/serving_basic)
using [Kubernetes (K8s)](https://kubernetes.io/). The latest version runs the
entire exercise on a K8s cluster using [KubeFlow](kubeflow.org).

The key concepts covered in this tutorial are as follows:

* Convert a TensorFlow(TF) graph trained through various APIs into a servable
model
* Serve the model using Tensorflow Serving
* Send online prediction requests to the cluster via a client. Profile latency
and throughput. Experiment with different batch sizes.
* Visualize image pixel contributions to model predictions to explain how the
model sees the world.

## Setup

Before the fun begins, we need to setup our environment and K8s clusters.

As a developer, it often helps to create a local deployment prior to deploying
on the cloud. We offer some guides on setting up a local K8s cluster, as well
as setting up a cluster on Google Cloud Platform (GCP) below. You can also
experiment with this tutorial on [Amazon EKS](https://aws.amazon.com/eks/) or
[Microsoft AKS](https://azure.microsoft.com/en-us/services/kubernetes-service/).
Feedback is welcomed!

* [Local: Minikube](LOCAL_SETUP.md)
* [Cloud: Google K8s Engine](GKE_SETUP.md)

### Additional Required Software

* [Python 2.7+](https://www.python.org/): The TensorFlow Serving API currently
runs in Python 2, so you will need to make client requests to your model server
using Python 2.
* [Docker](https://www.docker.com/): to build images that can be deployed on K8s
* [Git](https://git-scm.com/): so you can access this project and other projects
* [Pip](https://pip.pypa.io/en/stable/installing/): to install Python packages
required for the tutorial
* [Ksonnet](https://github.com/ksonnet/ksonnet): follow the install instructions
in github

## Deploy KubeFlow onto your cluster

[KubeFlow](kubeflow.org) is always in an active stage of development. For this
exercise, we will be using a stable tag v0.2.5. Run the following command to deploy
KubeFlow onto your Kubernetes cluster:

```
cd ~
curl https://raw.githubusercontent.com/kubeflow/kubeflow/v0.2.5/scripts/deploy.sh | bash
```

Next, run the following command to check on your pods and services. The services
should be up almost immediately, but pods may take longer to create.

```
kubectl get svc
```

```
kubectl get pods
```

Once your pods are all up and running, continue.

**Troubleshooting:** see [here](TROUBLESHOOTING.md#kubeflow-install).

## Accessing JupyterHub and Spinning up a Notebook

![notebook everywhere](img/notebook_everywhere.png)

JupyterHub is a popular K8s notebook spawner that can spin up Jupyter
servers on demand for an entire team of data scientists, each server having its
isolated set of customized resources (disk, memory, accelerators).
When a data scientist is finally done training and fine-tuning a model for
production, it is important to be able to export this model for serving. The
following exercises will be running through how to export a model from a local
Jupyter server into a location that K8s can access and serve using the
TensorFlow Serving app.

To access your Jupyter notebook environment, you will need to use port forwarding
from your local computer.

```
JUPYTER_POD=`kubectl get pods --selector="app=tf-hub" --output=template --template="{{with index .items 0}}{{.metadata.name}}{{end}}"`
kubectl port-forward ${JUPYTER_POD} 8000:8000
```

Go to your browser and access JupyterHub here:

```
localhost:8000
```

You should see a login screen like this:
![jupyter login](img/jupyterhub_login.png)

Type in any username and password to spin up a local environment (Note: if the
username does not exist, a new Jupyter server will be created for that user
with its own isolated resources. If the username already exists, the password
will be required to match the one used to create the server, and you will end up
in the previously created server environment.)

The next page, if you are creating a new environment, should have a drop down
menu with images, and separate CPU, memory, and extra resource text boxes.
In the dropdown menu, select the TensorFlow 1.8 CPU image:

![jupyterhub tf 1.8 cpu](img/jupyterhub_kubeflow_img.png)

Set CPU and memory to whatever your cluster can handle. 1 CPU and 2Gi memory is
sufficient, but if you are on a cluster and can afford more resources, more CPU
and memory will allow you to spin up and run notebooks faster without having to
shut down notebook kernels. (The minikube setup used above will probably only
allow 1 CPU for Jupyter without interfering with the model serving process.)

The notebook server may take a few minutes to spin up depending on cluster
resources, so be patient. Once it has spun up, go into the work directory,
and upload the local notebook `./jupyter/download_models_and_notebooks.ipynb`
into this directory. In your notebook, run all the cells to download the
Resnet50 models, project notebooks, and library dependencies required for the
next part of this exercise.

## Create a Servable Resnet Model from Estimator and Keras APIs

### Motivation

Your data scientists have used JupyterHub to scale out training and exploration
of datasets, and have finally built a few lovely models that meet performance
requirements. It is now time to serve models live in production! The first step
is to take their trained models, at whatever checkpoint they deem most optimal,
and package it for optimal serving performance using
[TensorFlow Serving](https://www.tensorflow.org/serving/).

As a data scientist or production engineer, it helps to understand how to bridge
the gap between training and serving. The following exercises will guide you on
doing so.

### Exercises

[Run the exercises here](SERVABLE_MODEL.md) (solutions included).

## Serving Your Model

Now that you've packaged your data scientists' models into a servable format,
you're faced with an issue: JupyterHub by default, keeps each Jupyter
environment and resources separate from all other environments (for good
reason). In K8s, this works as follows:

JupyterHub creates a
[persistent volume (pv)](https://kubernetes.io/docs/concepts/storage/persistent-volumes/)
and attaches a
[persistent volume claim (pvc)](https://kubernetes.io/docs/concepts/storage/persistent-volumes/#persistentvolumeclaims)
to that volume which only allows the user who spawned the notebook to access
that volume. (To be more precise, the pv and pvc are attached to the
[pod](https://kubernetes.io/docs/concepts/workloads/pods/pod/) that is used to
hold the user's requested cluster resources and isolate the user's work
environment). Unfortunately, no other users/pods are allowed to access this
environment without setting permissions without reconfiguring the volume to
accept multiple pods to read and write.

Fortunately, we have two options to handle this: by changing options for PVs
(general solution that works on most if not all clusters), or by serving the
model from a cloud storage system (s3, gs, etc.). The steps in the below
section will guide you through the process for serving on prem or on cloud.

### Setting up TF Serving for your Model

To deploy TensorFlow Serving with KubeFlow, we will need a number of steps.
First cd into your `kubeflow-ks-app` directory, and generate a tf-serving
template fron the KubeFlow repository.

```
ks generate tf-serving my-tf-serving
```

`tf-serving` is the KubeFlow template name, and `my-tf-serving` is the
app name (which you can name whatever you want).

Next, we will need to configure the app using [ksonnet](ksonnet.io). Follow the
two options below depending on where you running this exercise:

[Follow the instructions here](SERVING_ON_PREM.md) for a general TensorFlow
Serving deployment using KubeFlow for local (minikube) and on-prem clusters.

[Follow the instructions here](SERVING_ON_GKE.md) for serving on the Google
Cloud Platform using GKE. Note that the on-prem instructions above also work
for GKE, but serving your model from cloud storage offers flexibility to
securely share your models with other users, projects, and k8s clusters, in case
there is a need to scale out to other environments.

## TF Client

### Setup

**Note:** If you choose to use Google cloud to host a client, you can spin up
the VM using [compute engine](https://cloud.google.com/compute/), ssh into it,
and run a [setup script](gcp/setup_client_vm.sh) to deploy all required
libraries. There's no need to follow the rest of the steps in the setup steps
below. However, you may want to change your `my-tf-serving` application type to
`LoadBalancer` to ensure that your VM can reach it, since you are not running
kubectl from the VM. For simplicity and best practice however, we recommend
running your client locally if possible.

The following steps below are for setting up a client locally.

Setup port forwarding on port 9000 to enable secure access to your model server
via a local port:

```
SERVING_POD=`kubectl get pods --selector="app=my-tf-serving" --output=template --template="{{with index .items 0}}{{.metadata.name}}{{end}}"`
kubectl port-forward ${SERVING_POD} 9000:9000
```

Since your port forwarding must be kept alive, open up a new terminal shell to
continue.

First, create a *Python 2* virtual environment.

```
deactivate  # Run only if you need to exit the Python 3 virtual environment.
virtualenv <path/to/client-virtualenv>
source <path/to/client-virtualenv>/bin/activate
```

cd into the tutorial project directory (`tf-serving-k8s-tutorial`), and run:

```
pip install -r client_requirements.txt
```

Then cd into the client directory within the tutorial project:

```
cd client
```

To test the client, make sure you have your shell variable pointing to the type
of model you generated. This is because the default pre-trained models for
Estimator and Keras APIs have classes that are labeled slightly differently,
so the client needs to interpret the results that it receives from the models.
If the `MODEL_TYPE` variable is unset, set it again:

```
MODEL_TYPE=<estimator | keras>  # choose one
```

Then enter the command (note that 127.0.0.1 is used below assuming
you have set up port forwarding with kubectl):

```
python resnet_client.py \
--server 127.0.0.1 \
--port 9000 \
--model_type ${MODEL_TYPE} \
cat_sample.jpg
```

The server should return a list of the 5 top classes and confidences
(probabilities) that the model thinks the image belongs to each class.

You can also batch predict by specifying multiple image paths/urls. For example:

```
python resnet_client.py \
--server 127.0.0.1 \
--port 9000 \
--model_type ${MODEL_TYPE} \
cat_sample.jpg \
"https://www.popsci.com/sites/popsci.com/files/styles/1000_1x_/public/images/2017/09/depositphotos_33210141_original.jpg?itok=MLFznqbL&fc=50,50"
```

will do batch prediction on a local cat image and a squirrel image online.

Congratulations!

![you just got served](img/you_got_served.png)

### Profiling Latency

**Exercise:**: Look at the profiler [resnet_profiler.py](client/resnet_profiler.py).
Try sending requests with the profiler and compute latency and throughput.
Latency is simply the round trip delay returned by the profiler. An
approximation of throughput is the number of batches divided by latency when a
large batch size is used. Try varying batch sizes between 1 and 256.
Here is an example configuration:

```
python resnet_profiler.py \
--server 127.0.0.1 \
--port 9000 \
--model_type ${MODEL_TYPE} \
--replications 16 \
--num_trials 10 \
cat_sample.jpg
```

What do you notice about CPU/GPU performance with different batch sizes?

**Remark:** Profiling is a very important step when you are trying to setup a
robust server. GPUs are great performers, but stop providing gains after a
certain batch size. Furthermore, servers can run out of memory, in which case TF
serving often crashes silently, i.e. `kubectl logs <pod>` won't return anything
useful. When you deploy your own Kubernetes system, you will need to ensure that
your machine can load your model and process requested batch sizes.

## Model Understanding and Visualization

As a bonus feature, we offer ways to validate a served model through
visualization! Run this notebook:

```
resnet_model_understanding.ipynb
```

The notebook runs a visualization of pixels that are important in determining
that the image belongs to a particular class. More specifically, the visible
pixels correspond to the highest partial derivatives of the logit of the most
probable class as a function of each pixel, integrated over a path of image
pixels from a blank image (e.g. all grey pixels) to the actual image.
The visualization is based on a recent research paper by M. Sundararajan,
 A. Taly, and Q. Yan: [Axiomatic Attribution for Deep Networks](https://arxiv.org/pdf/1703.01365.pdf).

## General Disclaimers and Pitfalls

* TensorFlow Server is written in c++, so any Tensorflow code in your
model that has python libraries embedded in it (e.g. using tf.py_func()) will
FAIL! Make sure that your entire TensorFlow graph that is being imported, runs
in the TensorFlow c++ environment.
* Security is an issue! If you decide not to use port forwarding and instead
reconfigure your `my-tf-serving` k8s service to `LoadBalancer` on a Cloud k8s
engine, make sure to enable identity aware control for your K8s cluster,
such as Google Cloud IAP.
[See the Kubeflow IAP documentation](https://github.com/kubeflow/kubeflow/blob/master/docs/gke/iap.md)
for more information.

## Additional KubeFlow Resources

To better appreciate KubeFlow, it is important to have a firm grasp of
[k8s](kubernetes.io), and a good understanding of how to use
[ksonnet](https://ksonnet.io) to create apps and deployments on k8s.

For more KubeFlow examples, go to [kubeflow.org](kubeflow.org). Also,
[join the community](https://github.com/kubeflow/community) for discussions,
updates, or ways to help contribute and improve the project.


text:
namespace Envoy {
namespace Upstream {

CdsApiPtr CdsApiImpl::create(const envoy::api::v2::core::ConfigSource& cds_config,
                             const absl::optional<envoy::api::v2::core::ConfigSource>& eds_config,
                             ClusterManager& cm, Event::Dispatcher& dispatcher,
                             Runtime::RandomGenerator& random,
                             const LocalInfo::LocalInfo& local_info, Stats::Scope& scope) {
  return CdsApiPtr{
      new CdsApiImpl(cds_config, eds_config, cm, dispatcher, random, local_info, scope)};
}

CdsApiImpl::CdsApiImpl(const envoy::api::v2::core::ConfigSource& cds_config,
                       const absl::optional<envoy::api::v2::core::ConfigSource>& eds_config,
                       ClusterManager& cm, Event::Dispatcher& dispatcher,
                       Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info,
                       Stats::Scope& scope)
    : cm_(cm), scope_(scope.createScope("cluster_manager.cds.")) {
  Config::Utility::checkLocalInfo("cds", local_info);

  subscription_ =
      Config::SubscriptionFactory::subscriptionFromConfigSource<envoy::api::v2::Cluster>(
          cds_config, local_info.node(), dispatcher, cm, random, *scope_,
          [this, &cds_config, &eds_config, &cm, &dispatcher, &random,
           &local_info]() -> Config::Subscription<envoy::api::v2::Cluster>* {
            return new CdsSubscription(Config::Utility::generateStats(*scope_), cds_config,
                                       eds_config, cm, dispatcher, random, local_info);
          },
          "envoy.api.v2.ClusterDiscoveryService.FetchClusters",
          "envoy.api.v2.ClusterDiscoveryService.StreamClusters");
}

void CdsApiImpl::onConfigUpdate(const ResourceVector& resources, const std::string& version_info) {
  cm_.adsMux().pause(Config::TypeUrl::get().ClusterLoadAssignment);
  Cleanup eds_resume([this] { cm_.adsMux().resume(Config::TypeUrl::get().ClusterLoadAssignment); });
  for (const auto& cluster : resources) {
    MessageUtil::validate(cluster);
  }
  // We need to keep track of which clusters we might need to remove.
  ClusterManager::ClusterInfoMap clusters_to_remove = cm_.clusters();
  for (auto& cluster : resources) {
    const std::string cluster_name = cluster.name();
    clusters_to_remove.erase(cluster_name);
    if (cm_.addOrUpdateCluster(cluster, version_info)) {
      ENVOY_LOG(debug, "cds: add/update cluster '{}'", cluster_name);
    }
  }

  for (auto cluster : clusters_to_remove) {
    const std::string cluster_name = cluster.first;
    if (cm_.removeCluster(cluster_name)) {
      ENVOY_LOG(debug, "cds: remove cluster '{}'", cluster_name);
    }
  }

  version_info_ = version_info;
  runInitializeCallbackIfAny();
}

void CdsApiImpl::onConfigUpdateFailed(const EnvoyException*) {
  // We need to allow server startup to continue, even if we have a bad
  // config.
  runInitializeCallbackIfAny();
}

void CdsApiImpl::runInitializeCallbackIfAny() {
  if (initialize_callback_) {
    initialize_callback_();
    initialize_callback_ = nullptr;
  }
}

} // namespace Upstream
} // namespace Envoy


text:
package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class MountainSurfaceGrid extends StdGrid
{
	@Override public String ID(){return "MountainSurfaceGrid";}
	public MountainSurfaceGrid()
	{
		super();
		name="the mountains";
		basePhyStats.setWeight(5);
		recoverPhyStats();
	}
	@Override public int domainType(){return Room.DOMAIN_OUTDOORS_MOUNTAINS;}

	@Override public String getGridChildLocaleID(){return "MountainSurface";}
	@Override public List<Integer> resourceChoices(){return Mountains.roomResources;}
}


text:
import sys

import Rational, math
R = Rational.rational

def train(text):
    """text -> 0-order probability statistics as a dictionary

    Text must not contain the NUL (0x00) character because that's
    used to indicate the end of data.
    """
    assert "\x00" not in text
    counts = {}
    for c in text:
        counts[c]=counts.get(c,0)+1
    counts["\x00"] = 1
    tot_letters = sum(counts.values())

    tot = 0
    d = {}
    prev = R(0)
    for c, count in counts.items():
        next = R(tot + count, tot_letters)
        d[c] = (prev, next)
        prev = next
        tot = tot + count
    assert tot == tot_letters

    return d

def encode(text, probs):
    """text and the 0-order probability statistics -> longval, nbits

    The encoded number is rational(longval, 2**nbits)
    """
    minval = R(0)
    maxval = R(1)
    for c in text + "\x00":
        prob_range = probs[c]
        delta = maxval - minval
        maxval = minval + prob_range[1] * delta
        minval = minval + prob_range[0] * delta

    # I tried without the /2 just to check.  Doesn't work.
    # Keep scaling up until the error range is >= 1.  That
    # gives me the minimum number of bits needed to resolve
    # down to the end-of-data character.
    delta = (maxval - minval)/2
    nbits = 0L
    while delta < 1:
        nbits = nbits + 1
        delta = delta << 1
    if nbits == 0:
        return 0, 0
    else:
        avg = (maxval + minval)<<(nbits-1)  # using -1 instead of /2
    # Could return a rational instead ...
    return avg.n//avg.d, nbits  # the division truncation is deliberate

def decode(longval, nbits, probs):
    """decode the number to a string using the given statistics"""
    val = R(longval, 1L<<nbits)
    letters = []
    probs_items = [(c, minval, maxval) for (c, (minval, maxval))
                                 in probs.items()]

    while 1:
        for (c, minval, maxval) in probs_items:
            if minval <= val < maxval:
                break
        else:
            raise AssertionError("not found")

        if c == "\x00":
            break
        letters.append(c)
        delta = maxval - minval
        val = (val - minval)/delta
    return "".join(letters)

if __name__ == "__main__":
    # getopt? optparse? What are they?
    import sys
    trainfilename = sys.argv[1]  # must give a filename
    phrase = sys.argv[2]  # must give text to compress (slowly!)
    probs = train(open(trainfilename).read())
    n, nbits = encode(phrase, probs)
    # +1 for the NUL terminator or equivalent
    print "Orig. %d bits, compr. %d bits, ratio = %3.f%%" % (
        (len(phrase)+1)*8, nbits, (100.*nbits) / (len(phrase)*8+1))
    print n
    new_phrase = decode(n, nbits, probs)
    print "Was it '%s'?" % (new_phrase,)
    if phrase == new_phrase:
        print "Guess so."
    else:
        print "Why not?!"


text:
"""Unit tests for domain objects related to Oppia improvement tasks."""

from __future__ import annotations

import datetime

from core import feconf
from core import utils
from core.domain import improvements_domain
from core.domain import user_services
from core.platform import models
from core.tests import test_utils

MYPY = False
if MYPY: # pragma: no cover
    from mypy_imports import improvements_models

(improvements_models,) = (
    models.Registry.import_models([models.NAMES.improvements]))

class TaskEntryTests(test_utils.GenericTestBase):
    """Unit tests for the TaskEntry domain object."""

    MOCK_DATE = datetime.datetime(2020, 6, 15, 9, 0, 0, 123456)

    def setUp(self) -> None:
        super(TaskEntryTests, self).setUp()
        self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME)
        self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL) # type: ignore[no-untyped-call]
        self.exp_id = 'eid'
        self.save_new_valid_exploration(self.exp_id, self.owner_id) # type: ignore[no-untyped-call]
        self.maxDiff = 0

    def test_task_id_has_expected_value(self) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_RESOLVED, self.owner_id,
            self.MOCK_DATE)
        self.assertEqual(
            task_entry.task_id,
            'exploration.eid.1.high_bounce_rate.state.Introduction')

    def test_composite_entity_id_has_expected_value(self) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_RESOLVED, self.owner_id,
            self.MOCK_DATE)
        self.assertEqual(task_entry.composite_entity_id, 'exploration.eid.1')

    def test_to_dict_has_expected_value(self) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_RESOLVED, self.owner_id,
            self.MOCK_DATE)
        self.assertEqual(task_entry.to_dict(), {
            'entity_type': 'exploration',
            'entity_id': self.exp_id,
            'entity_version': 1,
            'task_type': 'high_bounce_rate',
            'target_type': 'state',
            'target_id': 'Introduction',
            'issue_description': 'issue description',
            'status': 'resolved',
            'resolver_username': self.OWNER_USERNAME,
            'resolver_profile_picture_data_url': (
                user_services.DEFAULT_IDENTICON_DATA_URL),
            'resolved_on_msecs': utils.get_time_in_millisecs(self.MOCK_DATE),
        })

    def test_to_dict_with_non_existing_resolver_id_raises_exception(
        self
    ) -> None:
        invalid_resolver_id = 'non_existing_user_id'
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_RESOLVED, invalid_resolver_id,
            self.MOCK_DATE)
        with self.assertRaisesRegexp(Exception, 'User not found'): # type: ignore[no-untyped-call]
            task_entry.to_dict()

    def test_can_create_open_task_with_corresponding_values(self) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_OPEN, None, None)

        self.assertEqual(task_entry.entity_type, 'exploration')
        self.assertEqual(task_entry.entity_id, self.exp_id)
        self.assertEqual(task_entry.entity_version, 1)
        self.assertEqual(task_entry.task_type, 'high_bounce_rate')
        self.assertEqual(task_entry.target_type, 'state')
        self.assertEqual(task_entry.target_id, 'Introduction')
        self.assertEqual(task_entry.issue_description, 'issue description')
        self.assertEqual(task_entry.status, 'open')
        self.assertIsNone(task_entry.resolver_id)
        self.assertIsNone(task_entry.resolved_on)

    def test_can_create_obsolete_task_with_corresponding_values(self) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_OBSOLETE, None, None)

        self.assertEqual(task_entry.entity_type, 'exploration')
        self.assertEqual(task_entry.entity_id, self.exp_id)
        self.assertEqual(task_entry.entity_version, 1)
        self.assertEqual(task_entry.task_type, 'high_bounce_rate')
        self.assertEqual(task_entry.target_type, 'state')
        self.assertEqual(task_entry.target_id, 'Introduction')
        self.assertEqual(task_entry.issue_description, 'issue description')
        self.assertEqual(task_entry.status, 'obsolete')
        self.assertIsNone(task_entry.resolver_id)
        self.assertIsNone(task_entry.resolved_on)

    def test_can_create_resolved_task_with_corresponding_value(self) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_RESOLVED, self.owner_id,
            self.MOCK_DATE)

        self.assertEqual(task_entry.entity_type, 'exploration')
        self.assertEqual(task_entry.entity_id, self.exp_id)
        self.assertEqual(task_entry.entity_version, 1)
        self.assertEqual(task_entry.task_type, 'high_bounce_rate')
        self.assertEqual(task_entry.target_type, 'state')
        self.assertEqual(task_entry.target_id, 'Introduction')
        self.assertEqual(task_entry.issue_description, 'issue description')
        self.assertEqual(task_entry.status, 'resolved')
        self.assertEqual(task_entry.resolver_id, self.owner_id)
        self.assertEqual(task_entry.resolved_on, self.MOCK_DATE)

    def test_constructor_ignores_resolution_args_when_task_is_open(
        self
    ) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_OPEN, self.owner_id, self.MOCK_DATE)

        self.assertEqual(task_entry.entity_type, 'exploration')
        self.assertEqual(task_entry.entity_id, self.exp_id)
        self.assertEqual(task_entry.entity_version, 1)
        self.assertEqual(task_entry.task_type, 'high_bounce_rate')
        self.assertEqual(task_entry.target_type, 'state')
        self.assertEqual(task_entry.target_id, 'Introduction')
        self.assertEqual(task_entry.issue_description, 'issue description')
        self.assertEqual(task_entry.status, 'open')
        self.assertIsNone(task_entry.resolver_id)
        self.assertIsNone(task_entry.resolved_on)

    def test_constructor_ignores_resolution_args_when_task_is_obsolete(
        self
    ) -> None:
        task_entry = improvements_domain.TaskEntry(
            improvements_models.TASK_ENTITY_TYPE_EXPLORATION, self.exp_id, 1,
            improvements_models.TASK_TYPE_HIGH_BOUNCE_RATE,
            improvements_models.TASK_TARGET_TYPE_STATE,
            feconf.DEFAULT_INIT_STATE_NAME, 'issue description',
            improvements_models.TASK_STATUS_OBSOLETE, self.owner_id,
            self.MOCK_DATE)

        self.assertEqual(task_entry.entity_type, 'exploration')
        self.assertEqual(task_entry.entity_id, self.exp_id)
        self.assertEqual(task_entry.entity_version, 1)
        self.assertEqual(task_entry.task_type, 'high_bounce_rate')
        self.assertEqual(task_entry.target_type, 'state')
        self.assertEqual(task_entry.target_id, 'Introduction')
        self.assertEqual(task_entry.issue_description, 'issue description')
        self.assertEqual(task_entry.status, 'obsolete')
        self.assertIsNone(task_entry.resolver_id)
        self.assertIsNone(task_entry.resolved_on)


text:
package net.jawr.web.resource.bundle.generator.classpath;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;

import net.jawr.web.config.JawrConfig;
import net.jawr.web.exception.BundlingProcessException;
import net.jawr.web.resource.bundle.IOUtils;
import net.jawr.web.resource.bundle.JoinableResourceBundle;
import net.jawr.web.resource.bundle.JoinableResourceBundleImpl;
import net.jawr.web.resource.bundle.generator.AbstractCSSGenerator;
import net.jawr.web.resource.bundle.generator.ConfigurationAwareResourceGenerator;
import net.jawr.web.resource.bundle.generator.GeneratorContext;
import net.jawr.web.resource.bundle.generator.GeneratorRegistry;
import net.jawr.web.resource.bundle.generator.ResourceGenerator;
import net.jawr.web.resource.bundle.generator.resolver.ResourceGeneratorResolver;
import net.jawr.web.resource.bundle.generator.resolver.ResourceGeneratorResolverFactory;
import net.jawr.web.resource.bundle.postprocess.BundleProcessingStatus;
import net.jawr.web.resource.bundle.postprocess.impl.CSSURLPathRewriterPostProcessor;
import net.jawr.web.resource.handler.reader.WorkingDirectoryLocationAware;

/**
 * This class defines the generator for the CSS defined in the classpath.
 *
 * @author Jordi Hernández Sellés
 * @author Ibrahim Chaehoi
 */
public class ClassPathCSSGenerator extends AbstractCSSGenerator implements
		ConfigurationAwareResourceGenerator, WorkingDirectoryLocationAware {

	/** the class path generator helper  */
	private static final String CLASSPATH_GENERATOR_HELPER_PREFIX = "";

	/**
	 * The name of the directory which contain the CSS defined in classpath for
	 * the DEBUG mode
	 */
	private static final String TEMP_CSS_CLASSPATH_SUBDIR = "cssClasspath";

	/** The resolver */
	protected ResourceGeneratorResolver resolver;

	/** The classpath generator helper */
	private ClassPathGeneratorHelper helper;

	/** The working directory */
	private String workingDir;

	/**
	 * The flag indicating if the generator is handling the Css Image ressources
	 */
	private boolean isHandlingCssImage;

	/**
	 * Constructor
	 */
	public ClassPathCSSGenerator() {
		helper = new ClassPathGeneratorHelper(getClassPathGeneratorHelperPrefix());
		resolver = createResolver(getGeneratorPrefix());
	}

	/**
	 * create the resource generator resolver
	 *
	 * @param  generatorPrefix the generator prefix
	 * @return the resource generator resolver
	 */
	protected ResourceGeneratorResolver createResolver(String generatorPrefix) {
		return ResourceGeneratorResolverFactory.createPrefixResolver(generatorPrefix);
	}

	/**
	 * Returns the class path generator helper
	 * @return the class path generator helper
	 */
	protected String getClassPathGeneratorHelperPrefix() {
		return CLASSPATH_GENERATOR_HELPER_PREFIX;
	}

	/**
	 * Returns the generator prefix
	 * @return the generator prefix
	 */
	protected String getGeneratorPrefix() {
		return GeneratorRegistry.CLASSPATH_RESOURCE_BUNDLE_PREFIX;
	}

	/**
	 * Returns the temporary directory which will be created under the working directory application server
	 * @return the temporary directory
	 */
	protected String getTempDirectoryName() {
		return TEMP_CSS_CLASSPATH_SUBDIR;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.jawr.web.resource.bundle.generator.ConfigurationAwareResourceGenerator
	 * #setConfig(net.jawr.web.config.JawrConfig)
	 */
	public void setConfig(JawrConfig config) {
		this.isHandlingCssImage = config
				.isCssClasspathImageHandledByClasspathCss();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * net.jawr.web.resource.bundle.generator.BaseResourceGenerator#getPathMatcher
	 * ()
	 */
	public ResourceGeneratorResolver getResolver() {

		return resolver;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see net.jawr.web.resource.bundle.generator.CssResourceGenerator#
	 * isHandlingCssImage()
	 */
	public boolean isHandlingCssImage() {
		return isHandlingCssImage;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see net.jawr.web.resource.handler.TemporaryResourceLocationAware#
	 * setTemporaryDirectory(java.lang.String)
	 */
	public void setWorkingDirectory(String workingDir) {
		this.workingDir = workingDir;
	}

	/* (non-Javadoc)
	 * @see net.jawr.web.resource.bundle.generator.AbstractCSSGenerator#generateResourceForBundle(net.jawr.web.resource.bundle.generator.GeneratorContext)
	 */
	@Override
	protected Reader generateResourceForBundle(GeneratorContext context) {

		Reader reader = helper.createResource(context);

		if (reader != null) {
			reader = createTempResource(context, reader);
		}

		return reader;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see net.jawr.web.resource.bundle.generator.AbstractCSSGenerator#
	 * generateResourceForDebug
	 * (net.jawr.web.resource.bundle.generator.GeneratorContext)
	 */
	@SuppressWarnings("resource")
	@Override
	protected Reader generateResourceForDebug(GeneratorContext context) {

		Reader rd = null;
		// The following section is executed in DEBUG mode to retrieve the
		// classpath CSS from the temporary folder,
		// if the user defines that the image servlet should be used to retrieve
		// the CSS images.
		// It's not executed at the initialization process to be able to read
		// data from classpath.
		if (context.getConfig().isCssClasspathImageHandledByClasspathCss()) {

			FileInputStream fis = null;
			try {
				fis = new FileInputStream(new File(workingDir + "/"
						+ getTempDirectoryName(), context.getPath()));
			} catch (FileNotFoundException e) {
				throw new BundlingProcessException(
						"An error occured while creating temporary resource for "
								+ context.getPath(), e);
			}
			if (fis != null) {
				FileChannel inchannel = fis.getChannel();
				rd = Channels.newReader(inchannel, context.getConfig()
						.getResourceCharset().newDecoder(), -1);
			}
		} else {

			rd = helper.createResource(context);
		}

		return rd;

	}

	/**
	 * Creates the temporary resource which will be processed and used to
	 * retrieve the content for the path.
	 *
	 * @param generatorContext
	 *            the context
	 * @param rd
	 *            the reader
	 * @return the reader to the temporary processed resource
	 */
	private Reader createTempResource(GeneratorContext generatorContext,
			Reader rd) {

		Reader result = null;

		// Here we create a new context where the bundle name is the Jawr
		// generator CSS path
		// The version of the CSS classpath for debug mode will be different
		// compare to the standard one
		JoinableResourceBundle tempBundle = new JoinableResourceBundleImpl(
				ResourceGenerator.CSS_DEBUGPATH, null, null, null, null, null,
				generatorContext.getConfig().getGeneratorRegistry());
		BundleProcessingStatus tempStatus = new BundleProcessingStatus(
				BundleProcessingStatus.FILE_PROCESSING_TYPE, tempBundle,
				generatorContext.getResourceReaderHandler(),
				generatorContext.getConfig());

		CSSURLPathRewriterPostProcessor postProcessor = new CSSURLPathRewriterPostProcessor();
		String resourcePath = generatorContext.getPath();
		tempStatus.setLastPathAdded(getGeneratorPrefix()+GeneratorRegistry.PREFIX_SEPARATOR
				+ resourcePath);
		FileWriter fWriter = null;
		try {
			StringWriter writer = new StringWriter();
			IOUtils.copy(rd, writer, true);
			result = new StringReader(writer.getBuffer().toString());
			StringBuffer resourceData = postProcessor.postProcessBundle(
					tempStatus, writer.getBuffer());

			String tempCssClasspathDir = workingDir + "/"
					+ getTempDirectoryName();
			File cssTempFile = new File(tempCssClasspathDir, resourcePath);
			File tempCssDir = cssTempFile.getParentFile();
			if (!tempCssDir.exists()) {
				if (!tempCssDir.mkdirs()) {
					throw new BundlingProcessException(
							"An error occured while creating temporary resource for "
									+ resourcePath + ".\n"
									+ "Enable to create temporary directory '"
									+ tempCssClasspathDir + "'");
				}
			}

			fWriter = new FileWriter(cssTempFile);
			IOUtils.copy(new StringReader(resourceData.toString()), fWriter,
					true);
		} catch (IOException e) {
			throw new BundlingProcessException(
					"An error occured while creating temporary resource for "
							+ resourcePath, e);
		}

		return result;
	}

}


text:
#ifndef _LINUX_SECCOMP_H
#define _LINUX_SECCOMP_H

#ifdef CONFIG_SECCOMP

#include <linux/thread_info.h>
#include <asm/seccomp.h>

typedef struct { int mode; } seccomp_t;

extern void __secure_computing(int);
static inline void secure_computing(int this_syscall)
{
	if (unlikely(test_thread_flag(TIF_SECCOMP)))
		__secure_computing(this_syscall);
}

extern long prctl_get_seccomp(void);
extern long prctl_set_seccomp(unsigned long);

static inline int seccomp_mode(seccomp_t *s)
{
	return s->mode;
}

#else /* CONFIG_SECCOMP */

#include <linux/errno.h>

typedef struct { } seccomp_t;

#define secure_computing(x) do { } while (0)

static inline long prctl_get_seccomp(void)
{
	return -EINVAL;
}

static inline long prctl_set_seccomp(unsigned long arg2)
{
	return -EINVAL;
}

static inline int seccomp_mode(seccomp_t *s)
{
	return 0;
}

#endif /* CONFIG_SECCOMP */

#endif /* _LINUX_SECCOMP_H */


text:
@interface ViewArticleViewController : UIViewController <MBProgressHUDDelegate, UIAlertViewDelegate>

@property (nonatomic,strong) Article* article;

@end


text:
<personName xmlns="http://www.example.org/ns/personName/1">
    <given>Dave</given>
    <family>Orchard</family>
    <given>Dave</given>
</personName>


text:
{% load crispy_forms_field %}

{% if field.is_hidden %}
	{{ field }}
{% else %}
	<{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" class="control-group{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} error{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}">
		{% if field.label and not field|is_checkbox and form_show_labels %}

                {% include 'hqwebapp/crispy/layout/help_bubble.html' %}
				{{ field.label|safe }}{% if field.field.required %}*{% endif %}

		{% endif %}

        {% if field|is_checkboxselectmultiple %}
            {% include 'bootstrap/layout/checkboxselectmultiple.html' %}
        {% endif %}

        {% if field|is_checkbox and help_bubble_text %}

                    {% include 'hqwebapp/crispy/layout/help_bubble.html' %}

        {% endif %}

        {% if field|is_radioselect %}
            {% include 'bootstrap/layout/radioselect.html' %}
        {% endif %}

        {% if not field|is_checkboxselectmultiple and not field|is_radioselect %}

                {% if field|is_checkbox and form_show_labels %}

                        {% crispy_field field %}
                        {{ field.label|safe }}
                        {% include 'bootstrap/layout/help_text_and_errors.html' %}

                {% else %}
                    {% crispy_field field %}
                    {% include 'bootstrap/layout/help_text_and_errors.html' %}
                {% endif %}

        {% endif %}
	</{% if tag %}{{ tag }}{% else %}div{% endif %}>
{% endif %}


text:
# [Conreign](http://conreign.win)

Conreign is a multiplayer turn-based strategy game. The gameplay was highly inspired by
[Konquest](https://www.kde.org/applications/games/konquest).

The main goal is to conquer all other player's planets on a rectangle map
by sending fleets from one planet to another.

**Try playing [here](http://conreign.win).** Use **[github](http://conreign.win/github)** room when in doubt 🙂.

## Technologies Used

Conreign is built with [Orleans](https://github.com/dotnet/orleans) which is .NET libary for building
distributed applications. [ASP.NET SignalR](https://www.asp.net/signalr) is used as a proxy to expose
APIs to a browser client. Browser client is written in JavaScript and uses [React](https://reactjs.org) for UI.

## Development

The following things are needed to build the project:

- Visual Studio 2017 Community Edition with C# and F# installed
- Node.js 8.x
- Windows Azure SDK 2.9 (optional)


text:
from app.model.post import handler as post
from app.model.static_page import handler as static_page
from app.model.health_check import handler as health_check
from app.util import handler_util as base
from app.util.config_util import config

ROUTERS = [
    (r"/ping", health_check.HealthCheckHandler),
    (r"/v1/posts", post.PostsHandler),
    (r"/i/", static_page.IndexHandler),
    (r"/i/post/(.*)", post.PostHandler),
    (r"/i/achive", static_page.AchiveHandler),
    (r"/i/project", static_page.ProjectHandler),
    (r"/i/movie", static_page.MovieHandler),
    (r"/i/about", static_page.AboutHandler),
    (r"/i/.*", base.PageNotFoundHandler),
    (r"/(.*\..*)", base.StaticHandler, {"path": config.static_path}),
    (r"/(.*)", static_page.IframeHandler),
]


text:
using System.Collections.Generic;

namespace Entitas {

    public interface ICollector {

        int count { get; }

        void Activate();
        void Deactivate();
        void ClearCollectedEntities();

        IEnumerable<TCast> GetCollectedEntities<TCast>() where TCast : class, IEntity;
    }

    public interface ICollector<TEntity> : ICollector where TEntity : class, IEntity {

        HashSet<TEntity> collectedEntities { get; }
    }
}


text:
#import "NSObject-Protocol.h"

@protocol PTSRowObserver <NSObject>

@optional
- (void)rowDidChangeImage:(id)arg1;
- (void)rowDidChangeTitle:(id)arg1;
- (void)rowDidChangeValue:(id)arg1;
@end


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Util;
using Grpc.Core;
using Grpc.Core.Utils;

namespace Grpc.Auth
{
    public static class OAuth2Interceptors
    {
        /// <summary>
        /// Creates OAuth2 interceptor that will obtain access token from GoogleCredentials.
        /// </summary>
        public static MetadataInterceptorDelegate FromCredential(GoogleCredential googleCredential)
        {
            var interceptor = new OAuth2Interceptor(googleCredential, SystemClock.Default);
            return new MetadataInterceptorDelegate(interceptor.InterceptHeaders);
        }

        /// <summary>
        /// Creates OAuth2 interceptor that will use given OAuth2 token.
        /// </summary>
        /// <param name="oauth2Token"></param>
        /// <returns></returns>
        public static MetadataInterceptorDelegate FromAccessToken(string oauth2Token)
        {
            Preconditions.CheckNotNull(oauth2Token);
            return new MetadataInterceptorDelegate((authUri, metadata) =>
            {
                metadata.Add(OAuth2Interceptor.CreateBearerTokenHeader(oauth2Token));
            });
        }

        /// <summary>
        /// Injects OAuth2 authorization header into initial metadata (= request headers).
        /// </summary>
        private class OAuth2Interceptor
        {
            private const string AuthorizationHeader = "Authorization";
            private const string Schema = "Bearer";

            private ITokenAccess credential;
            private IClock clock;

            public OAuth2Interceptor(ITokenAccess credential, IClock clock)
            {
                this.credential = credential;
                this.clock = clock;
            }

            /// <summary>
            /// Gets access token and requests refreshing it if is going to expire soon.
            /// </summary>
            /// <param name="cancellationToken"></param>
            /// <returns></returns>
            public string GetAccessToken(string authUri, CancellationToken cancellationToken)
            {
                // TODO(jtattermusch): Rethink synchronous wait to obtain the result.
                return credential.GetAccessTokenForRequestAsync(authUri, cancellationToken: cancellationToken).GetAwaiter().GetResult();
            }

            public void InterceptHeaders(string authUri, Metadata metadata)
            {
                var accessToken = GetAccessToken(authUri, CancellationToken.None);
                metadata.Add(CreateBearerTokenHeader(accessToken));
            }

            public static Metadata.Entry CreateBearerTokenHeader(string accessToken)
            {
                return new Metadata.Entry(AuthorizationHeader, Schema + " " + accessToken);
            }
        }
    }
}


text:
@implementation Event (CellHelpers)

- (NSAttributedString *)eventTitle{
    NSMutableAttributedString *eventTitle = [[NSMutableAttributedString alloc] initWithString:self.name attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:18]}];
    if ([self.name rangeOfString:@"N/A"].location == NSNotFound){
        [eventTitle appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" (%@)",self.categoryTitle] attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}]];
    }
    return eventTitle;
}

@end


text:
namespace g{
namespace Uno{
namespace Graphics{

// public enum PolygonWinding :234
uEnumType* PolygonWinding_typeof();

}}} // ::g::Uno::Graphics


text:
var path = require('path');
var webpack = require('webpack');
var node_modules = path.resolve(__dirname, '../node_modules');

var dir_client = path.resolve(__dirname, '../src/client/scripts');
var dir_dist = path.resolve(__dirname, '../dist');

module.exports = {
  entry: path.resolve(dir_client, 'client.js'),
  output: {
    path: dir_dist, // for standalone building
    publicPath: '/assets/', // for hot building
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {test: /src(\\|\/).+\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: {presets: ['es2015', 'react']}}
    ]
  },
  plugins: [
    // Avoid publishing files when compilation fails
    new webpack.NoErrorsPlugin()
  ],
  stats: {
    colors: true // Nice colored output
  },
  // Create Sourcemaps for the bundle
  devtool: 'source-map'
};


text:
using System.Drawing;
using NativeColor = System.Drawing.Color;

static class ColorConverter
{
	const Color DefaultColor = Color.Azul;

	public static string ToString(Color? color)
	{
		if (color == null)
			return null;

		switch (color.Value)
		{
			case Color.Blanco:
				return ToString(NativeColor.White);
			case Color.Rojo:
				return ToString(NativeColor.Red);
			case Color.Naranja:
				return ToString(NativeColor.Orange);
			case Color.Amarillo:
				return ToString(NativeColor.Yellow);
			case Color.Verde:
				return ToString(NativeColor.Green);
			case Color.Azul:
				return ToString(NativeColor.Blue);
			case Color.Indigo:
				return ToString(NativeColor.Indigo);
			case Color.Violeta:
				return ToString(NativeColor.Violet);
			case Color.Negro:
			default:
				return ToString(NativeColor.Black);
		}
	}

	static string ToString(NativeColor color) =>
		ColorTranslator.ToHtml(NativeColor.FromArgb(color.A, color.R, color.G, color.B));
}


text: curl -d topic=topic-04 -d message=blah-blah-blah http://localhost:8100/rest/api/1/messages


text:
@interface GDViewController ()

@end

@implementation GDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化tabBar
    [self setupTabBar];
    //初始化所有子控制器
    [self setupAllChildVc];

    UITabBarItem *item = [UITabBarItem appearance];
    // UITabBarItem文字的设置
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:10];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];

    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor orangeColor];
    [item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
}

// 初始化tabBar
- (void)setupTabBar
{
    GDTabBar *myTabBar = [[GDTabBar alloc] init];
    [self setValue:myTabBar forKey:@"tabBar"];
}

// 初始化所有子控制器
- (void)setupAllChildVc
{
    UIViewController *home = [[GDHomeViewController alloc] init];
    [self setupChildVc:home title:@"首页" imageName:@"tabbar_home_os7" selectedImageName:@"tabbar_home_selected_os7"];

    UIViewController *message = [[GDMessageViewController alloc] init];
    [self setupChildVc:message title:@"消息" imageName:@"tabbar_message_center_os7" selectedImageName:@"tabbar_message_center_selected_os7"];

    UIViewController *discover = [[GDDiscoverViewController alloc] init];
    [self setupChildVc:discover title:@"广场" imageName:@"tabbar_discover_os7" selectedImageName:@"tabbar_discover_selected_os7"];

    UIViewController *me = [[GDMeViewController alloc] init];
    [self setupChildVc:me title:@"我" imageName:@"tabbar_profile_os7" selectedImageName:@"tabbar_profile_selected_os7"];
}

- (void)setupChildVc:(UIViewController *)vc title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName
{
    vc.title = title;
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:selectedImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    vc.tabBarItem.image = [UIImage imageNamed:imageName];
    GDNavigationController *nav = [[GDNavigationController alloc] initWithRootViewController:vc];
    [self addChildViewController:nav];
}

@end


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace LogMagic
{
   /// <summary>
   /// Common interface for a log receiver
   /// </summary>
   public interface ILogWriter : IDisposable
   {
      /// <summary>
      /// Writes a sequence of log events to the target.
      /// </summary>
      void Write(IEnumerable<LogEvent> events);
   }
}


text:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

module ActiveSupport
  class TestCase
    fixtures :all
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>fakejar</groupId>
  <artifactId>fakejar</artifactId>
  <versioning>
    <release>0</release>
    <versions>
      <version>0</version>
    </versions>
    <lastUpdated>20170414082010</lastUpdated>
  </versioning>
</metadata>


text:
<?php

/**
 * DiaryImage form.
 *
 * @package    OpenPNE
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrinePluginFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class DiaryImageForm extends PluginDiaryImageForm
{
  public function configure()
  {
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/ib_upVote"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:src="@drawable/ic_action_good" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="This will be a comment. I wonder what it looks like as a multi-line comment." />

</LinearLayout>


text:
package meter_test

import (
	"reflect"
	"sort"
	"testing"

	meter "github.com/alxarch/go-meter/v2"
)

var _ sort.Interface = meter.DataPoints{}

// AssertEqual checks if values are equal
func AssertEqual(t *testing.T, a interface{}, b interface{}) {
	t.Helper()
	if !reflect.DeepEqual(a, b) {
		t.Errorf("a != b %v %v", a, b)
	}
}
func Assert(t *testing.T, ok bool, msg string, args ...interface{}) {
	t.Helper()
	if !ok {
		t.Errorf(msg, args...)
	}
}

func AssertNil(t *testing.T, a interface{}) {
	if a != nil {
		t.Errorf("a != nil %v", a)
	}
}


text:
"""Proxy dictionary for objects stored in a container"""

import weakref

class ProxyDict(dict):
    """A dictionary which uses a container object to store its values."""

    def __init__(self, container):
        self.containerRef = weakref.ref(container)
        """A weak reference to the container object."""

    def __getitem__(self, key):
        if key not in self:
            raise KeyError(key)

        # Values are not actually stored to avoid extra references.
        return self._getValueFromContainer(self._getContainer(), key)

    def __setitem__(self, key, value):
        # Values are not actually stored to avoid extra references.
        super(ProxyDict, self).__setitem__(key, None)

    def __repr__(self):
        return object.__repr__(self)

    def __str__(self):
        # C implementation does not use `self.__getitem__()`. :(
        itemFormat = '%r: %r'
        itemReprs = [itemFormat % item for item in self.iteritems()]
        return '{%s}' % ', '.join(itemReprs)

    def values(self):
        # C implementation does not use `self.__getitem__()`. :(
        valueList = []
        for key in self.iterkeys():
            valueList.append(self[key])
        return valueList

    def itervalues(self):
        # C implementation does not use `self.__getitem__()`. :(
        for key in self.iterkeys():
            yield self[key]
        raise StopIteration

    def items(self):
        # C implementation does not use `self.__getitem__()`. :(
        itemList = []
        for key in self.iterkeys():
            itemList.append((key, self[key]))
        return itemList

    def iteritems(self):
        # C implementation does not use `self.__getitem__()`. :(
        for key in self.iterkeys():
            yield (key, self[key])
        raise StopIteration

    def _getContainer(self):
        container = self.containerRef()
        if container is None:
            raise ValueError("the container object does no longer exist")
        return container