text:
azure.mgmt.eventgrid.models module
==================================

.. automodule:: azure.mgmt.eventgrid.models
    :members:
    :undoc-members:
    :show-inheritance:


text:
class JapaneseTranslator
    # My knowledge of counting Japanese is limited, so this may not
    # be entirely correct; in particular, I don't know what rules
    # to follow after 'hyaku man' (1,000,000).
    # I also combine a digit with its group, such as 'gohyaku' rather
    # than 'go hyaku'; I just like reading it better that way.

    DIGITS = %w(zero ichi ni san yon go roku nana hachi kyu)
    GROUPS = %w(nothingtoseeheremovealong ju hyaku sen)
    MAN = 10000

    def to_spoken(val)
        case val <=> 0
        when -1
            '- ' + to_spoken(-val)
        when 0
            DIGITS[0]
        else
            group(val, 0)
        end
    end

    private

    def group(val, level)
        if val >= MAN
            group(val / MAN, 0) + 'man ' + group(val % MAN, 0)
        else
            case val
            when 0
                ''
            when 1
                level == 0 ? DIGITS[val] : GROUPS[level]
            when 2...10
                DIGITS[val] + (GROUPS[level] if level > 0).to_s
            else
                group(val / 10, level+1) + ' ' + group(val % 10, level)
            end
        end
    end
end

class USEnglishTranslator
    # Formal, US English. Optional 'and'. Will not produce things
    # such as 'twelve hundred' but rather 'one thousand two hundred'.
    # The use of 'and' is incomplete; it is sometimes missed.

    DIGITS = %w(zero one two three four five six seven eight nine)
    TEENS  = %w(ten eleven twelve thirteen fourteen fifteen sixteen
                seventeen eighteen nineteen)
    TENS   = %w(hello world twenty thirty forty fifty sixty seventy
                eighty ninety)
    GROUPS = %w(thousand million billion trillion quadrillion
                quintillion sextillion septillion octillion nonillion
                decillion)
    K = 1000

    def initialize(conjunction = true)
        @conjunction = conjunction
    end

    def to_spoken(val)
        case val <=> 0
        when -1
            'negative ' + to_spoken(-val)
        when 0
            DIGITS[0]
        else
            group(val, 0).flatten.join(' ')
        end
    end

    private

    def group(val, level)
        x = group(val / K, level + 1) << GROUPS[level] if val >= K
        x.to_a << under_1000(val % K, level)
    end

    def under_1000(val, level)
        x = [DIGITS[val / 100]] << 'hundred' if val >= 100
        x.to_a << under_100(val % 100, (level == 0 and not x.nil?))
    end

    def under_100(val, junction)
        x = [('and' if @conjunction and junction)]    # wyf?
        case val
        when 0
            []
        when 1...10
            x << DIGITS[val]
        when 10...20
            x << TEENS[val - 10]
        else
            d = val % 10
            x << (TENS[val / 10] + ('-' + DIGITS[d] if d != 0).to_s)
        end
    end
end

class Integer
    def to_spoken(translator = USEnglishTranslator.new)
        translator.to_spoken(self).squeeze(' ').strip
    end
end

if $0 == __FILE__
    SAMPLES = [ 0, 1, 2, 5, 10, 11, 14, 18, 20, 21, 29, 33, 42, 50, 87, 99,
                100, 101, 110, 167, 199, 200, 201, 276, 300, 314, 500, 610,
                1000, 1039, 1347, 2309, 3098, 23501, 32767, 70000, 5480283,
                2435489238, 234100090000, -42, -2001 ]

    TRANSLATORS = { 'US English' => USEnglishTranslator.new,
                    'Japanese'   => JapaneseTranslator.new }

    # main
    TRANSLATORS.each do |lang, translator|
        puts
        puts lang
        puts '-' * lang.length
        SAMPLES.each do |val|
            puts "%12d => %s" % [val, val.to_spoken(translator)]
        end
    end
end

redpajama_set_name: RedPajamaGithub


text:
'use strict';

define([
  'angular',
  './DashboardController',
  './DashboardService'
], function(
  angular,
  DashboardController,
  DashboardService
) {
  var dashboardModule = angular.module('clientApp.dashboard', []);

  dashboardModule.config(['$stateProvider', 'prefixUrl',
  function($stateProvider, prefixUrl) {
    $stateProvider
      .state('dashboard', {
        url: prefixUrl('/dashboard'),
        templateUrl: '/modules/dashboard/dashboard.html',
        controller: DashboardController
      });
  }]);

  dashboardModule.factory('DashboardService', DashboardService);

  return dashboardModule;
});


text:
@protocol CRWWebViewProxy;
class FullscreenMediator;
class FullscreenModel;

// Helper object that observes the active WebState's CRWWebViewProxy.
@interface FullscreenWebViewProxyObserver : NSObject

// The proxy being observed.
@property(nonatomic, weak, nullable) id<CRWWebViewProxy> proxy;

// Designated initializer for an observer that uses `model` to update its proxy.
- (nullable instancetype)initWithModel:(nonnull FullscreenModel*)model
                              mediator:(nonnull FullscreenMediator*)mediator
    NS_DESIGNATED_INITIALIZER;
- (nullable instancetype)init NS_UNAVAILABLE;

@end

#endif  // IOS_CHROME_BROWSER_UI_FULLSCREEN_FULLSCREEN_WEB_VIEW_PROXY_OBSERVER_H_


text:
package ch.ninecode.net

;

import ch.ninecode.model.EquivalentInjection
import ch.ninecode.model.PowerTransformer
import ch.ninecode.model.PowerTransformerEnd
import ch.ninecode.model.Substation
import ch.ninecode.model.Terminal
import ch.ninecode.model.TopologicalNode

/**
 * Transformer data.
 *
 * Everything you need to know about a transformer.
 *
 * @param transformer  The PowerTransformer object.
 * @param ends         The associated PowerTransformerEnd objects ordered by endNumber (which by convention is descending by voltage).
 * @param terminals    The terminals ordered the same as the ends.
 * @param nodes        The nodes ordered the same as the ends.
 * @param voltages     The voltages ordered the same as the ends (V).
 * @param station      The Substation object where the transformer is located.
 * @param shortcircuit The EquivalentInjection object with the available short circuit power and impedance at the primary.
 */
case class TransformerData
(
    transformer: PowerTransformer,
    ends: Array[PowerTransformerEnd],
    terminals: Array[Terminal],
    nodes: Array[TopologicalNode],
    voltages: Array[(String, Double)],
    station: Option[Substation],
    shortcircuit: Option[EquivalentInjection]
)
{
    /** The (assumed) index of the primary PowerTransformerEnd */
    val primary: Int = 0

    /** The (assumed) index of the secondary PowerTransformerEnd */
    lazy val secondary: Int =
        if (ends.length < 3)
            1 // no choice, end #2
        else
        {
            val v = voltages.tail.map(_._2) // voltages excluding primary
            if (-1 != v.indexOf(400.0))
                v.indexOf(400.0) + 1 // use 400V end if there is one
            else
                v.indexOf(v.max) + 1 // use the highest voltage otherwise
        }

    /** @return the (assumed) primary (high voltage) PowerTransformerEnd */
    def end0: PowerTransformerEnd = ends(primary)

    /** @return the voltage for the transformer primary (high voltage) end (V) */
    def v0: Double = voltages(primary)._2

    /** @return the Terminal for the transformer primary (high voltage) end */
    def terminal0: Terminal = terminals(primary)

    /** @return the TopologicalNode for the transformer primary (high voltage) end */
    def node0: TopologicalNode = nodes(primary)

    /** @return the (assumed) secondary (low voltage) PowerTransformerEnd, for three or more winding transformers this may not be the one you want */
    def end1: PowerTransformerEnd = ends(secondary)

    /** @return the voltage for the transformer secondary (low voltage) end (V) */
    def v1: Double = voltages(secondary)._2

    /** @return the Terminal for the transformer secondary (low voltage) end */
    def terminal1: Terminal = terminals(secondary)

    /** @return the TopologicalNode for the transformer secondary (low voltage) end */
    def node1: TopologicalNode = nodes(secondary)

    /** @return a summary string for the transformer */
    def asString: String = s"${transformer.id} ${
        station match
        {
            case Some(s) => s.id
            case _ => ""
        }
    } ${(end0.ratedS / 1000.0).toInt.toString}kVA ${voltages.map(_._2.toInt).mkString(":")} ${nodes.map(_.id).mkString(":")}"
}


text:
Analysis Apps v. Alpha

Workspace-inspired, rough prototype of how apps could be done.

Version Alpha:

Just getting started

To do:

Plug-in AWE for tasks

Restyle site using newly designed theme

Decide how the mini WS browser should appear, if at all.

Add social aspects

Run end-2-end tests using protractor

            {{narrative.current_app.title}}

                        <form class="form-horizontal" role="form">

                            {{field.ui_name}}

                                <input ng-if="field.type == 'string'" ng-model="fields[field.ui_name]" type="text" class="form-control" placeholder="">

                              <button ng-click="runCell($index, narrative.current_app)" type="submit" class="btn btn-primary pull-right">Run</button>

                        </form>

                       {{narrative.current_app.description}}


text: SystemMisc systemMisc;


text:
namespace {

using gfx::Font;

class FontTest : public testing::Test {
 public:
  // Fulfills the memory management contract as outlined by the comment at
  // gfx::Font::GetNativeFont().
  void FreeIfNecessary(gfx::NativeFont font) {
#if defined(OS_LINUX)
    pango_font_description_free(font);
#endif
  }
};

#if defined(OS_WIN)
class ScopedMinimumFontSizeCallback {
 public:
  explicit ScopedMinimumFontSizeCallback(int minimum_size) {
    minimum_size_ = minimum_size;
    old_callback_ = gfx::PlatformFontWin::get_minimum_font_size_callback;
    gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
  }

  ~ScopedMinimumFontSizeCallback() {
    gfx::PlatformFontWin::get_minimum_font_size_callback = old_callback_;
  }

 private:
  static int GetMinimumFontSize() {
    return minimum_size_;
  }

  gfx::PlatformFontWin::GetMinimumFontSizeCallback old_callback_;
  static int minimum_size_;

  DISALLOW_COPY_AND_ASSIGN(ScopedMinimumFontSizeCallback);
};

int ScopedMinimumFontSizeCallback::minimum_size_ = 0;
#endif  // defined(OS_WIN)

TEST_F(FontTest, LoadArial) {
  Font cf(ASCIIToUTF16("Arial"), 16);
  gfx::NativeFont native = cf.GetNativeFont();
  ASSERT_TRUE(native);
  ASSERT_EQ(cf.GetStyle(), Font::NORMAL);
  ASSERT_EQ(cf.GetFontSize(), 16);
  ASSERT_EQ(cf.GetFontName(), ASCIIToUTF16("Arial"));
  FreeIfNecessary(native);
}

TEST_F(FontTest, LoadArialBold) {
  Font cf(ASCIIToUTF16("Arial"), 16);
  Font bold(cf.DeriveFont(0, Font::BOLD));
  gfx::NativeFont native = bold.GetNativeFont();
  ASSERT_TRUE(native);
  ASSERT_EQ(bold.GetStyle(), Font::BOLD);
  FreeIfNecessary(native);
}

TEST_F(FontTest, Ascent) {
  Font cf(ASCIIToUTF16("Arial"), 16);
  ASSERT_GT(cf.GetBaseline(), 2);
  ASSERT_LE(cf.GetBaseline(), 22);
}

TEST_F(FontTest, Height) {
  Font cf(ASCIIToUTF16("Arial"), 16);
  ASSERT_GE(cf.GetHeight(), 16);
  // TODO(akalin): Figure out why height is so large on Linux.
  ASSERT_LE(cf.GetHeight(), 26);
}

TEST_F(FontTest, AvgWidths) {
  Font cf(ASCIIToUTF16("Arial"), 16);
  ASSERT_EQ(cf.GetExpectedTextWidth(0), 0);
  ASSERT_GT(cf.GetExpectedTextWidth(1), cf.GetExpectedTextWidth(0));
  ASSERT_GT(cf.GetExpectedTextWidth(2), cf.GetExpectedTextWidth(1));
  ASSERT_GT(cf.GetExpectedTextWidth(3), cf.GetExpectedTextWidth(2));
}

TEST_F(FontTest, Widths) {
  Font cf(ASCIIToUTF16("Arial"), 16);
  ASSERT_EQ(cf.GetStringWidth(ASCIIToUTF16("")), 0);
  ASSERT_GT(cf.GetStringWidth(ASCIIToUTF16("a")),
            cf.GetStringWidth(ASCIIToUTF16("")));
  ASSERT_GT(cf.GetStringWidth(ASCIIToUTF16("ab")),
            cf.GetStringWidth(ASCIIToUTF16("a")));
  ASSERT_GT(cf.GetStringWidth(ASCIIToUTF16("abc")),
            cf.GetStringWidth(ASCIIToUTF16("ab")));
}

#if defined(OS_WIN)
TEST_F(FontTest, DeriveFontResizesIfSizeTooSmall) {
  // This creates font of height -8.
  Font cf(L"Arial", 6);
  // The minimum font size is set to 5 in browser_main.cc.
  ScopedMinimumFontSizeCallback minimum_size(5);

  Font derived_font = cf.DeriveFont(-4);
  LOGFONT font_info;
  GetObject(derived_font.GetNativeFont(), sizeof(LOGFONT), &font_info);
  EXPECT_EQ(-5, font_info.lfHeight);
}

TEST_F(FontTest, DeriveFontKeepsOriginalSizeIfHeightOk) {
  // This creates font of height -8.
  Font cf(L"Arial", 6);
  // The minimum font size is set to 5 in browser_main.cc.
  ScopedMinimumFontSizeCallback minimum_size(5);

  Font derived_font = cf.DeriveFont(-2);
  LOGFONT font_info;
  GetObject(derived_font.GetNativeFont(), sizeof(LOGFONT), &font_info);
  EXPECT_EQ(-6, font_info.lfHeight);
}
#endif  // defined(OS_WIN)

}  // namespace


text:
"""Azure Service Bus Message Queue transport module for kombu.

Note that the Shared Access Policy used to connect to Azure Service Bus
requires Manage, Send and Listen claims since the broker will create new
queues and delete old queues as required.

Note that if the SAS key for the Service Bus account contains a slash, it will
have to be regenerated before it can be used in the connection URL.

More information about Azure Service Bus:
https://azure.microsoft.com/en-us/services/service-bus/

Features
========
* Type: Virtual
* Supports Direct: *Unreviewed*
* Supports Topic: *Unreviewed*
* Supports Fanout: *Unreviewed*
* Supports Priority: *Unreviewed*
* Supports TTL: *Unreviewed*

Connection String
=================

Connection string has the following format:

.. code-block::

    azureservicebus://SAS_POLICY_NAME:SAS_KEY@SERVICE_BUSNAMESPACE

Transport Options
=================

* ``visibility_timeout``
* ``queue_name_prefix``
* ``wait_time_seconds``
* ``peek_lock``
"""

import string
from queue import Empty

from kombu.utils.encoding import bytes_to_str, safe_str
from kombu.utils.json import loads, dumps
from kombu.utils.objects import cached_property

from . import virtual

try:
    # azure-servicebus version <= 0.21.1
    from azure.servicebus import ServiceBusService, Message, Queue
except ImportError:
    try:
        # azure-servicebus version >= 0.50.0
        from azure.servicebus.control_client import \
            ServiceBusService, Message, Queue
    except ImportError:
        ServiceBusService = Message = Queue = None

# dots are replaced by dash, all other punctuation replaced by underscore.
CHARS_REPLACE_TABLE = {
    ord(c): 0x5f for c in string.punctuation if c not in '_'
}

class Channel(virtual.Channel):
    """Azure Service Bus channel."""

    default_visibility_timeout = 1800  # 30 minutes.
    default_wait_time_seconds = 5  # in seconds
    default_peek_lock = False
    domain_format = 'kombu%(vhost)s'
    _queue_service = None
    _queue_cache = {}

    def __init__(self, *args, **kwargs):
        if ServiceBusService is None:
            raise ImportError('Azure Service Bus transport requires the '
                              'azure-servicebus library')

        super().__init__(*args, **kwargs)

        for queue in self.queue_service.list_queues():
            self._queue_cache[queue] = queue

    def entity_name(self, name, table=CHARS_REPLACE_TABLE):
        """Format AMQP queue name into a valid ServiceBus queue name."""
        return str(safe_str(name)).translate(table)

    def _new_queue(self, queue, **kwargs):
        """Ensure a queue exists in ServiceBus."""
        queue = self.entity_name(self.queue_name_prefix + queue)
        try:
            return self._queue_cache[queue]
        except KeyError:
            self.queue_service.create_queue(queue, fail_on_exist=False)
            q = self._queue_cache[queue] = self.queue_service.get_queue(queue)
            return q

    def _delete(self, queue, *args, **kwargs):
        """Delete queue by name."""
        queue_name = self.entity_name(queue)
        self._queue_cache.pop(queue_name, None)
        self.queue_service.delete_queue(queue_name)
        super()._delete(queue_name)

    def _put(self, queue, message, **kwargs):
        """Put message onto queue."""
        msg = Message(dumps(message))
        self.queue_service.send_queue_message(self.entity_name(queue), msg)

    def _get(self, queue, timeout=None):
        """Try to retrieve a single message off ``queue``."""
        message = self.queue_service.receive_queue_message(
            self.entity_name(queue),
            timeout=timeout or self.wait_time_seconds,
            peek_lock=self.peek_lock
        )

        if message.body is None:
            raise Empty()

        return loads(bytes_to_str(message.body))

    def _size(self, queue):
        """Return the number of messages in a queue."""
        return self._new_queue(queue).message_count

    def _purge(self, queue):
        """Delete all current messages in a queue."""
        n = 0

        while True:
            message = self.queue_service.read_delete_queue_message(
                self.entity_name(queue), timeout=0.1)

            if not message.body:
                break
            else:
                n += 1

        return n

    @property
    def queue_service(self):
        if self._queue_service is None:
            self._queue_service = ServiceBusService(
                service_namespace=self.conninfo.hostname,
                shared_access_key_name=self.conninfo.userid,
                shared_access_key_value=self.conninfo.password)

        return self._queue_service

    @property
    def conninfo(self):
        return self.connection.client

    @property
    def transport_options(self):
        return self.connection.client.transport_options

    @cached_property
    def visibility_timeout(self):
        return (self.transport_options.get('visibility_timeout') or
                self.default_visibility_timeout)

    @cached_property
    def queue_name_prefix(self):
        return self.transport_options.get('queue_name_prefix', '')

    @cached_property
    def wait_time_seconds(self):
        return self.transport_options.get('wait_time_seconds',
                                          self.default_wait_time_seconds)

    @cached_property
    def peek_lock(self):
        return self.transport_options.get('peek_lock',
                                          self.default_peek_lock)

class Transport(virtual.Transport):
    """Azure Service Bus transport."""

    Channel = Channel

    polling_interval = 1
    default_port = None


text:
namespace mediapipe {

constexpr char kEncodedTag[] = "ENCODED";
constexpr char kFloatVectorTag[] = "FLOAT_VECTOR";

TEST(QuantizeFloatVectorCalculatorTest, WrongConfig) {
  CalculatorGraphConfig::Node node_config =
      ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb(
        calculator: "QuantizeFloatVectorCalculator"
        input_stream: "FLOAT_VECTOR:float_vector"
        output_stream: "ENCODED:encoded"
        options {
          [mediapipe.QuantizeFloatVectorCalculatorOptions.ext]: {
            min_quantized_value: 1
          }
        }
      )pb");
  CalculatorRunner runner(node_config);
  std::vector<float> empty_vector;
  runner.MutableInputs()
      ->Tag(kFloatVectorTag)
      .packets.push_back(
          MakePacket<std::vector<float>>(empty_vector).At(Timestamp(0)));
  auto status = runner.Run();
  EXPECT_FALSE(status.ok());
  EXPECT_THAT(
      status.message(),
      testing::HasSubstr(
          "Both max_quantized_value and min_quantized_value must be provided"));
}

TEST(QuantizeFloatVectorCalculatorTest, WrongConfig2) {
  CalculatorGraphConfig::Node node_config =
      ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb(
        calculator: "QuantizeFloatVectorCalculator"
        input_stream: "FLOAT_VECTOR:float_vector"
        output_stream: "ENCODED:encoded"
        options {
          [mediapipe.QuantizeFloatVectorCalculatorOptions.ext]: {
            max_quantized_value: -1
            min_quantized_value: 1
          }
        }
      )pb");
  CalculatorRunner runner(node_config);
  std::vector<float> empty_vector;
  runner.MutableInputs()
      ->Tag(kFloatVectorTag)
      .packets.push_back(
          MakePacket<std::vector<float>>(empty_vector).At(Timestamp(0)));
  auto status = runner.Run();
  EXPECT_FALSE(status.ok());
  EXPECT_THAT(
      status.message(),
      testing::HasSubstr(
          "max_quantized_value must be greater than min_quantized_value"));
}

TEST(QuantizeFloatVectorCalculatorTest, WrongConfig3) {
  CalculatorGraphConfig::Node node_config =
      ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb(
        calculator: "QuantizeFloatVectorCalculator"
        input_stream: "FLOAT_VECTOR:float_vector"
        output_stream: "ENCODED:encoded"
        options {
          [mediapipe.QuantizeFloatVectorCalculatorOptions.ext]: {
            max_quantized_value: 1
            min_quantized_value: 1
          }
        }
      )pb");
  CalculatorRunner runner(node_config);
  std::vector<float> empty_vector;
  runner.MutableInputs()
      ->Tag(kFloatVectorTag)
      .packets.push_back(
          MakePacket<std::vector<float>>(empty_vector).At(Timestamp(0)));
  auto status = runner.Run();
  EXPECT_FALSE(status.ok());
  EXPECT_THAT(
      status.message(),
      testing::HasSubstr(
          "max_quantized_value must be greater than min_quantized_value"));
}

TEST(QuantizeFloatVectorCalculatorTest, TestEmptyVector) {
  CalculatorGraphConfig::Node node_config =
      ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb(
        calculator: "QuantizeFloatVectorCalculator"
        input_stream: "FLOAT_VECTOR:float_vector"
        output_stream: "ENCODED:encoded"
        options {
          [mediapipe.QuantizeFloatVectorCalculatorOptions.ext]: {
            max_quantized_value: 1
            min_quantized_value: -1
          }
        }
      )pb");
  CalculatorRunner runner(node_config);
  std::vector<float> empty_vector;
  runner.MutableInputs()
      ->Tag(kFloatVectorTag)
      .packets.push_back(
          MakePacket<std::vector<float>>(empty_vector).At(Timestamp(0)));
  MP_ASSERT_OK(runner.Run());
  const std::vector<Packet>& outputs =
      runner.Outputs().Tag(kEncodedTag).packets;
  EXPECT_EQ(1, outputs.size());
  EXPECT_TRUE(outputs[0].Get<std::string>().empty());
  EXPECT_EQ(Timestamp(0), outputs[0].Timestamp());
}

TEST(QuantizeFloatVectorCalculatorTest, TestNonEmptyVector) {
  CalculatorGraphConfig::Node node_config =
      ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb(
        calculator: "QuantizeFloatVectorCalculator"
        input_stream: "FLOAT_VECTOR:float_vector"
        output_stream: "ENCODED:encoded"
        options {
          [mediapipe.QuantizeFloatVectorCalculatorOptions.ext]: {
            max_quantized_value: 64
            min_quantized_value: -64
          }
        }
      )pb");
  CalculatorRunner runner(node_config);
  std::vector<float> vector = {0.0f, -64.0f, 64.0f, -32.0f, 32.0f};
  runner.MutableInputs()
      ->Tag(kFloatVectorTag)
      .packets.push_back(
          MakePacket<std::vector<float>>(vector).At(Timestamp(0)));
  MP_ASSERT_OK(runner.Run());
  const std::vector<Packet>& outputs =
      runner.Outputs().Tag(kEncodedTag).packets;
  EXPECT_EQ(1, outputs.size());
  const std::string& result = outputs[0].Get<std::string>();
  ASSERT_FALSE(result.empty());
  EXPECT_EQ(5, result.size());
  // 127
  EXPECT_EQ('\x7F', result.c_str()[0]);
  // 0
  EXPECT_EQ('\0', result.c_str()[1]);
  // 255
  EXPECT_EQ('\xFF', result.c_str()[2]);
  // 63
  EXPECT_EQ('\x3F', result.c_str()[3]);
  // 191
  EXPECT_EQ('\xBF', result.c_str()[4]);
  EXPECT_EQ(Timestamp(0), outputs[0].Timestamp());
}

TEST(QuantizeFloatVectorCalculatorTest, TestSaturation) {
  CalculatorGraphConfig::Node node_config =
      ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb(
        calculator: "QuantizeFloatVectorCalculator"
        input_stream: "FLOAT_VECTOR:float_vector"
        output_stream: "ENCODED:encoded"
        options {
          [mediapipe.QuantizeFloatVectorCalculatorOptions.ext]: {
            max_quantized_value: 64
            min_quantized_value: -64
          }
        }
      )pb");
  CalculatorRunner runner(node_config);
  std::vector<float> vector = {-65.0f, 65.0f};
  runner.MutableInputs()
      ->Tag(kFloatVectorTag)
      .packets.push_back(
          MakePacket<std::vector<float>>(vector).At(Timestamp(0)));
  MP_ASSERT_OK(runner.Run());
  const std::vector<Packet>& outputs =
      runner.Outputs().Tag(kEncodedTag).packets;
  EXPECT_EQ(1, outputs.size());
  const std::string& result = outputs[0].Get<std::string>();
  ASSERT_FALSE(result.empty());
  EXPECT_EQ(2, result.size());
  // 0
  EXPECT_EQ('\0', result.c_str()[0]);
  // 255
  EXPECT_EQ('\xFF', result.c_str()[1]);
  EXPECT_EQ(Timestamp(0), outputs[0].Timestamp());
}

}  // namespace mediapipe


text:
<!DOCTYPE html>

Fund <?=$project->name?>

    <?php
    $data['project'] = $project;
    $this->load->view("Project/project_view", $data);?>
    <form action="<?= base_url()?>Funder/fund_Project/<?=$project->projectId?>" method="post">

                Amount
                    <input type="number" name="amount" min="0">

                <input type="submit" value="Submit" class="button primary large" />

    </form>


text:
====================
DevStack Integration
====================

This directory contains the files necessary to integrate magnum with devstack.

Refer the quickstart guide at
http://docs.openstack.org/developer/magnum/dev/quickstart.html
for more information on using devstack and magnum.

Running devstack with magnum for the first time may take a long time as it
needs to download the Fedora Atomic qcow2 image (see
http://www.projectatomic.io/download/).

To install magnum into devstack, add the following settings to enable the
magnum plugin::

     cat > /opt/stack/devstack/local.conf << END
     [[local|localrc]]
     enable_plugin heat https://github.com/openstack/heat master
     enable_plugin magnum https://github.com/openstack/magnum master
     END

Additionally, you might need additional Neutron configurations for
your environment.
Please refer to the devstack documentation [#devstack_neutron]_ for details.

Then run devstack normally::

    cd /opt/stack/devstack
    ./stack.sh

.. [#devstack_neutron] https://docs.openstack.org/developer/devstack/guides/neutron.html


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.oasp.java.dev</groupId>
  <artifactId>oasp4j</artifactId>
  <version>dev-SNAPSHOT</version> <!-- This POM will never be released -->
  <packaging>pom</packaging>
  <name>${project.artifactId}</name>
  <description>Open Application Standard Platform for Java (OASP4J).</description>
  <url>http://oasp.io/oasp4j/maven/oasp4j</url>
  <inceptionYear>2014</inceptionYear>

  <modules>
    <module>bom</module>
    <module>modules</module>
  </modules>

  <properties>
    <java.version>1.7</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <oasp4j.version>2.1.0</oasp4j.version>
    <port.range>81</port.range>
    <oasp.gpg.keyname>joerg.hohwiller@capgemini.com</oasp.gpg.keyname>
    <oasp.flatten.mode>oss</oasp.flatten.mode>
    <spring.boot.version>1.3.3.RELEASE</spring.boot.version>
    <js.client.dir>src/main/client</js.client.dir>
  </properties>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <configuration>
          <encoding>${project.build.sourceEncoding}</encoding>
          <includeEmptyDirs>true</includeEmptyDirs>
        </configuration>
      </plugin>

      <!-- configure java compiler -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
          <encoding>${project.build.sourceEncoding}</encoding>
          <source>${java.version}</source>
          <target>${java.version}</target>
        </configuration>
      </plugin>

      <!-- advanced manifests -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
              <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
            </manifest>
          </archive>
        </configuration>
      </plugin>

      <!-- also generate source JARs -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-source-plugin</artifactId>
        <executions>
          <execution>
            <id>attach-sources</id>
            <phase>package</phase>
            <goals>
              <goal>jar-no-fork</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- http://mojo.codehaus.org/flatten-maven-plugin/ -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>flatten-maven-plugin</artifactId>
        <configuration>
          <flattenMode>${oasp.flatten.mode}</flattenMode>
        </configuration>
        <executions>
          <execution>
            <id>flatten</id>
            <phase>process-test-resources</phase>
            <goals>
              <goal>flatten</goal>
            </goals>
          </execution>
          <execution>
            <id>flatten.clean</id>
            <phase>clean</phase>
            <goals>
              <goal>clean</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <!-- avoid version in local war files, exclude development properties from WARs -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
          <packagingExcludes>WEB-INF/classes/config/application.properties</packagingExcludes>
          <warName>${project.artifactId}</warName>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <!-- Surefire changed the default to the project.build.directory causing trouble with file paths to test resources -->
          <workingDirectory>${basedir}</workingDirectory>
        </configuration>
      </plugin>

      <!-- site generation settings -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
      </plugin>
    </plugins>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-resources-plugin</artifactId>
          <version>2.7</version>
        </plugin>
        <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>3.2</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-clean-plugin</artifactId>
          <version>2.6</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jar-plugin</artifactId>
          <version>2.5</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-source-plugin</artifactId>
          <version>2.4</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.4</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-checkstyle-plugin</artifactId>
          <version>2.9.1</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-antrun-plugin</artifactId>
          <version>1.8</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>2.7</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-jxr-plugin</artifactId>
          <version>2.4</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-javadoc-plugin</artifactId>
          <version>2.9.1</version>
          <configuration>
            <!-- http://jira.codehaus.org/browse/MJAVADOC-308 -->
            <!--<maxmemory>5048m</maxmemory>-->
            <notree>true</notree>
            <show>private</show>
            <encoding>${project.reporting.outputEncoding}</encoding>
            <charset>${project.build.sourceEncoding}</charset>
            <docfilessubdirs>true</docfilessubdirs>
            <!--<additionalparam>-Xdoclint:none</additionalparam>-->
            <links>
              <link>http://docs.oracle.com/javase/7/docs/api/</link>
              <link>http://m-m-m.sourceforge.net/apidocs/</link>
            </links>
            <doctitle>JavaDocs for ${project.name}</doctitle>
            <windowtitle>JavaDocs for ${project.name}</windowtitle>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.17</version>
          <configuration>
            <!-- force locale to en_EN or tests will fail in other locales -->
            <argLine>-Duser.language=en -Duser.region=EN</argLine>
            <!-- Surefire changed the default to the project.build.directory causing trouble with file paths to test resources -->
            <workingDirectory>${basedir}</workingDirectory>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-report-plugin</artifactId>
          <version>2.9</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-pmd-plugin</artifactId>
          <version>3.2</version>
          <configuration>
            <targetJdk>${java.version}</targetJdk>
          </configuration>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-war-plugin</artifactId>
          <version>2.5</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-gpg-plugin</artifactId>
          <version>1.5</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-help-plugin</artifactId>
          <version>2.2</version>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>cobertura-maven-plugin</artifactId>
          <version>2.6</version>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>sonar-maven-plugin</artifactId>
          <version>2.4</version>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>findbugs-maven-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>taglist-maven-plugin</artifactId>
          <version>2.4</version>
        </plugin>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>flatten-maven-plugin</artifactId>
          <version>1.0.0</version>
        </plugin>
        <plugin>
          <groupId>org.owasp</groupId>
          <artifactId>dependency-check-maven</artifactId>
          <version>1.3.6</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <configuration>
          <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jxr-plugin</artifactId>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-javadoc-plugin</artifactId>
        <configuration>
          <!--<notree>true</notree>-->
          <show>private</show>
          <encoding>${project.reporting.outputEncoding}</encoding>
          <charset>${project.build.sourceEncoding}</charset>
          <docfilessubdirs>true</docfilessubdirs>
          <stylesheetfile>${user.dir}/src/main/javadoc/stylesheet.css</stylesheetfile>
          <!--<additionalparam>-Xdoclint:none -source ${java.version}</additionalparam>-->
          <links>
            <link>http://docs.oracle.com/javase/7/docs/api/</link>
            <!--<link>http://oasp.github.io/oasp4j/maven/apidocs/</link>-->
          </links>
          <doctitle>JavaDocs for ${project.name}</doctitle>
          <windowtitle>JavaDocs for ${project.name}</windowtitle>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>taglist-maven-plugin</artifactId>
        <configuration>
          <tags>
            <tag>TODO</tag>
            <tag>@todo</tag>
            <tag>FIXME</tag>
            <tag>@deprecated</tag>
            <tag>REVIEW</tag>
          </tags>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.owasp</groupId>
        <artifactId>dependency-check-maven</artifactId>
        <reportSets>
          <reportSet>
            <reports>
              <!-- https://github.com/jeremylong/DependencyCheck/issues/386-->
              <!-- <report>aggregate</report> -->
              <report>check</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>
    </plugins>
  </reporting>

  <profiles>
    <profile>
      <id>all</id>
      <activation>
        <file>
          <exists>pom.xml</exists>
        </file>
      </activation>
      <modules>
        <module>samples</module>
      </modules>
    </profile>
    <profile>
      <id>security</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.owasp</groupId>
            <artifactId>dependency-check-maven</artifactId>
            <configuration>
              <failBuildOnCVSS>8</failBuildOnCVSS>
            </configuration>
            <executions>
              <execution>
                <goals>
                  <goal>check</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
    <profile>
      <id>deploy</id>
      <build>
        <plugins>
          <!-- also generate javadoc JARs -->
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <executions>
              <execution>
                <id>attach-javadocs</id>
                <goals>
                  <goal>jar</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
          <!-- Sign artifacts with PGP -->
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-gpg-plugin</artifactId>
            <configuration>
            	<keyname>${oasp.gpg.keyname}</keyname>
            </configuration>
            <executions>
              <execution>
                <id>sign-artifacts</id>
                <phase>verify</phase>
                <goals>
                  <goal>sign</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
      <distributionManagement>
        <snapshotRepository>
          <id>ossrh</id>
          <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
          <id>ossrh</id>
          <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
      </distributionManagement>
    </profile>
    <profile>
      <!-- separate eclipse build from command-line... -->
      <id>eclipse</id>
      <activation>
        <property>
          <name>eclipse.application</name>
        </property>
      </activation>
      <build>
        <directory>eclipse-target</directory>
      </build>
    </profile>
  </profiles>

  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/oasp/oasp4j/issues</url>
  </issueManagement>

  <scm>
    <url>https://github.com/oasp/oasp4j/tree/develop</url>
  </scm>

  <!--
    <mailingLists>
    <mailingList>
    <name>oasp-devel</name>
    <subscribe>TODO</subscribe>
    <unsubscribe>TODO</unsubscribe>
    <post>TODO</post>
    <archive>TODO</archive>
    </mailingList>
    </mailingLists>
  -->
  <organization>
    <name>OASP-Team</name>
    <url>http://oasp.io/oasp4j/maven/team-list.html</url>
  </organization>

  <developers>
    <developer>
      <id>hohwille</id>
      <name>Jörg Hohwiller</name>
      <email>hohwille@users.sourceforge.net</email>
      <organization></organization>
      <organizationUrl/>
      <roles>
        <role>admin</role>
        <role>designer</role>
        <role>developer</role>
      </roles>
      <timezone>+1</timezone>
      <properties/>
    </developer>
    <developer>
      <id>ksobkowiak</id>
      <name>Krzysztof Sobkowiak</name>
      <email>sobkowiak@onet.eu</email>
      <organization></organization>
      <organizationUrl/>
      <roles>
        <role>admin</role>
        <role>designer</role>
        <role>developer</role>
      </roles>
      <timezone>+1</timezone>
      <properties/>
    </developer>
  </developers>

  <licenses>
    <license>
      <name>Apache Software Licenese</name>
      <url>http://oasp.github.io/terms-of-use.html</url>
      <distribution>repo</distribution>
      <comments/>
    </license>
  </licenses>

  <distributionManagement>
    <repository>
      <id>oasp.releases</id>
      <name>OASP Releases</name>
      <url>http://oasp-ci.cloudapp.net/nexus/content/repositories/releases/</url>
    </repository>
    <snapshotRepository>
      <id>oasp.snapshots</id>
      <name>OASP Snapshots</name>
      <url>http://oasp-ci.cloudapp.net/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
    <site>
      <id>oasp-site</id>
      <url>file://${user.dir}/target/oasp4j/maven</url>
    </site>
  </distributionManagement>

</project>


text:
package example.com.powerinterview.model;

import android.os.Parcel;
import android.os.Parcelable;

import java.io.Serializable;

/**
 * Created by Игорь on 11.04.2017.
 */

public class Action implements Parcelable, Serializable {

    private static final long serialVersionUID = -5303257196515386261L;
    private String key;

    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object obj) {
        boolean equals = false;
        try {
            if(((Action)obj).getKey().equals(getKey()))
                equals = true;
        }
        finally {
            return equals;
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.key);
        dest.writeString(this.value);
    }

    public Action() {
    }

    protected Action(Parcel in) {
        this.key = in.readString();
        this.value = in.readString();
    }

    public static final Creator<Action> CREATOR = new Creator<Action>() {
        @Override
        public Action createFromParcel(Parcel source) {
            return new Action(source);
        }

        @Override
        public Action[] newArray(int size) {
            return new Action[size];
        }
    };

}


text:
@interface WSQuesiton : YHCoderObject

@property (copy, nonatomic) NSString *questionId;
@property (copy, nonatomic) NSString *content;
@property (copy, nonatomic) NSString *relatedExpertId;
@property (copy, nonatomic) NSString *userName;
@property (copy, nonatomic) NSString *userHeadPicUrl;
@property (copy, nonatomic) NSString *state;
@property (copy, nonatomic) NSString *cTime;

+ (instancetype)quesitonWithDict:(NSDictionary *)dict;

@end


text:
"""Binary for training Tensorflow models on the YouTube-8M dataset."""

import json
import os
import time

import eval_util
import losses
import frame_level_models
import video_level_models
import readers
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow import app
from tensorflow import flags
from tensorflow import gfile
from tensorflow import logging
from tensorflow.python.ops import variables as tf_variables
from mygradients import mygradients, mygradients_full
import utils

FLAGS = flags.FLAGS

if __name__ == "__main__":
    # Dataset flags.
    flags.DEFINE_string("train_dir", "/tmp/yt8m_model/",
                        "The directory to save the model files in.")
    flags.DEFINE_string(
        "train_data_pattern", "",
        "File glob for the training dataset. If the files refer to Frame Level "
        "features (i.e. tensorflow.SequenceExample), then set --reader_type "
        "format. The (Sequence)Examples are expected to have 'rgb' byte array "
        "sequence feature as well as a 'labels' int64 context feature.")
    flags.DEFINE_string("feature_names", "mean_rgb", "Name of the feature "
                                                     "to use for training.")
    flags.DEFINE_string("feature_sizes", "1024", "Length of the feature vectors.")

    # Model flags.
    flags.DEFINE_bool(
        "frame_features", False,
        "If set, then --train_data_pattern must be frame-level features. "
        "Otherwise, --train_data_pattern must be aggregated video-level "
        "features. The model must also be set appropriately (i.e. to read 3D "
        "batches VS 4D batches.")
    flags.DEFINE_bool(
        "frame_only", False,
        "If set, then --train_data_pattern must be frame-level features. "
        "Otherwise, --train_data_pattern must be aggregated video-level "
        "features. The model must also be set appropriately (i.e. to read 3D "
        "batches VS 4D batches.")
    flags.DEFINE_bool(
        "norm", True,
        "If set, then --input_data should be l2-normalized before follow-up processing. "
        "Otherwise, --input_data remain unchanged")
    flags.DEFINE_string(
        "model", "LogisticModel",
        "Which architecture to use for the model. Models are defined "
        "in models.py.")
    flags.DEFINE_bool(
        "start_new_model", False,
        "If set, this will not resume from a checkpoint and will instead create a"
        " new model instance.")

    # Training flags.
    flags.DEFINE_integer("batch_size", 1024,
                         "How many examples to process per batch for training.")
    flags.DEFINE_integer("stride_size", 3,
                         "How many frames to skip in frame level models, "
                         "only used in LstmFramesModel and LstmSoftmaxModel.")
    flags.DEFINE_string("label_loss", "CrossEntropyLoss",
                        "Which loss function to use for training the model.")
    flags.DEFINE_float(
        "regularization_penalty", 1,
        "How much weight to give to the regularization loss (the label loss has "
        "a weight of 1).")
    flags.DEFINE_float("base_learning_rate", 0.01,
                       "Which learning rate to start with.")
    flags.DEFINE_float("learning_rate_decay", 0.95,
                       "Learning rate decay factor to be applied every "
                       "learning_rate_decay_examples.")
    flags.DEFINE_float("learning_rate_decay_examples", 4000000,
                       "Multiply current learning rate by learning_rate_decay "
                       "every learning_rate_decay_examples.")
    flags.DEFINE_integer("num_epochs", 5,
                         "How many passes to make over the dataset before "
                         "halting training.")

    # Other flags.
    flags.DEFINE_integer("num_readers", 8,
                         "How many threads to use for reading input files.")
    flags.DEFINE_string("optimizer", "AdamOptimizer",
                        "What optimizer class to use.")
    flags.DEFINE_string("gradient", None,
                        "What optimizer class to use.")
    flags.DEFINE_float("clip_gradient_norm", 0.1, "Norm to clip gradients to.")
    flags.DEFINE_bool(
        "log_device_placement", False,
        "Whether to write the device on which every op will run into the "
        "logs on startup.")

def validate_class_name(flag_value, category, modules, expected_superclass):
    """Checks that the given string matches a class of the expected type.

    Args:
      flag_value: A string naming the class to instantiate.
      category: A string used further describe the class in error messages
                (e.g. 'model', 'reader', 'loss').
      modules: A list of modules to search for the given class.
      expected_superclass: A class that the given class should inherit from.

    Raises:
      FlagsError: If the given class could not be found or if the first class
      found with that name doesn't inherit from the expected superclass.

    Returns:
      True if a class was found that matches the given constraints.
    """
    candidates = [getattr(module, flag_value, None) for module in modules]
    for candidate in candidates:
        if not candidate:
            continue
        if not issubclass(candidate, expected_superclass):
            raise flags.FlagsError("%s '%s' doesn't inherit from %s." %
                                   (category, flag_value,
                                    expected_superclass.__name__))
        return True
    raise flags.FlagsError("Unable to find %s '%s'." % (category, flag_value))

def get_input_data_tensors(reader,
                           data_pattern,
                           batch_size=1000,
                           num_epochs=None,
                           num_readers=1):
    """Creates the section of the graph which reads the training data.

    Args:
      reader: A class which parses the training data.
      data_pattern: A 'glob' style path to the data files.
      batch_size: How many examples to process at a time.
      num_epochs: How many passes to make over the training data. Set to 'None'
                  to run indefinitely.
      num_readers: How many I/O threads to use.

    Returns:
      A tuple containing the features tensor, labels tensor, and optionally a
      tensor containing the number of frames per video. The exact dimensions
      depend on the reader being used.

    Raises:
      IOError: If no files matching the given pattern were found.
    """
    logging.info("Using batch size of " + str(batch_size) + " for training.")
    with tf.name_scope("train_input"):
        files = gfile.Glob(data_pattern)
        if not files:
            raise IOError("Unable to find training files. data_pattern='" +
                          data_pattern + "'.")
        logging.info("Number of training files: %s.", str(len(files)))
        filename_queue = tf.train.string_input_producer(
            files, num_epochs=num_epochs, shuffle=True)
        training_data = [
            reader.prepare_reader(filename_queue) for _ in range(num_readers)
            ]

        return tf.train.shuffle_batch_join(
            training_data,
            batch_size=batch_size,
            capacity=FLAGS.batch_size * 5,
            min_after_dequeue=FLAGS.batch_size,
            allow_smaller_final_batch=True,
            enqueue_many=True)

def find_class_by_name(name, modules):
    """Searches the provided modules for the named class and returns it."""
    modules = [getattr(module, name, None) for module in modules]
    return next(a for a in modules if a)

def build_graph(reader,
                model,
                train_data_pattern,
                label_loss_fn=losses.CrossEntropyLoss(),
                batch_size=1000,
                base_learning_rate=0.01,
                learning_rate_decay_examples=1000000,
                learning_rate_decay=0.95,
                optimizer_class=tf.train.AdamOptimizer,
                clip_gradient_norm=1.0,
                regularization_penalty=1,
                num_readers=1,
                num_epochs=None):
    """Creates the Tensorflow graph.

    This will only be called once in the life of
    a training model, because after the graph is created the model will be
    restored from a meta graph file rather than being recreated.

    Args:
      reader: The data file reader. It should inherit from BaseReader.
      model: The core model (e.g. logistic or neural net). It should inherit
             from BaseModel.
      train_data_pattern: glob path to the training data files.
      label_loss_fn: What kind of loss to apply to the model. It should inherit
                  from BaseLoss.
      batch_size: How many examples to process at a time.
      base_learning_rate: What learning rate to initialize the optimizer with.
      optimizer_class: Which optimization algorithm to use.
      clip_gradient_norm: Magnitude of the gradient to clip to.
      regularization_penalty: How much weight to give the regularization loss
                              compared to the label loss.
      num_readers: How many threads to use for I/O operations.
      num_epochs: How many passes to make over the data. 'None' means an
                  unlimited number of passes.
    """

    global_step = tf.Variable(0, trainable=False, name="global_step")

    learning_rate = tf.train.exponential_decay(
        base_learning_rate,
        global_step * batch_size,
        learning_rate_decay_examples,
        learning_rate_decay,
        staircase=True)
    tf.summary.scalar('learning_rate', learning_rate)

    unused_video_id, model_input_raw, labels_batch, num_frames = (
        get_input_data_tensors(
            reader,
            train_data_pattern,
            batch_size=batch_size,
            num_readers=num_readers,
            num_epochs=num_epochs))
    tf.summary.histogram("model/input_raw", model_input_raw)

    feature_dim = len(model_input_raw.get_shape()) - 1
    if FLAGS.norm:
        model_input = tf.nn.l2_normalize(model_input_raw, feature_dim)
    else:
        model_input = model_input_raw

    with tf.name_scope("model"):
        result = model.create_model(
            model_input,
            num_frames=num_frames,
            vocab_size=reader.num_classes,
            labels=labels_batch)

        for variable in slim.get_model_variables():
            tf.summary.histogram(variable.op.name, variable)

        predictions = result["predictions"]
        if "predictions_negative" in result.keys():
            predictions_negative = result["predictions_negative"]
        else:
            predictions_negative = 1-predictions
        if "predictions_positive" in result.keys():
            predictions_positive = result["predictions_positive"]
        else:
            predictions_positive = predictions
        if predictions.get_shape().ndims==3:
            predictions = tf.reshape(predictions,[-1,predictions.get_shape().as_list()[2]])
            labels_batch = tf.reshape(labels_batch,[-1,labels_batch.get_shape().as_list()[2]])
        if "bottleneck" in result.keys():
            bottle_neck = result["bottleneck"]
        else:
            bottle_neck = tf.constant(0.0)
        if "predictions_class" in result.keys():
            predictions_class = result["predictions_class"]
        else:
            predictions_class = predictions
        if "predictions_encoder" in result.keys():
            predictions_encoder = result["predictions_encoder"]
        else:
            predictions_encoder = predictions
        if "predictions_experts" in result.keys():
            predictions_experts = result["predictions_experts"]
        else:
            predictions_experts = predictions
        if "predictions_postprocess" in result.keys():
            predictions_postprocess = result["predictions_postprocess"]
        else:
            predictions_postprocess = predictions

        if "loss" in result.keys():
            append_loss = result["loss"]
        else:
            append_loss = tf.constant(0.0)
        if "predictions_encoder" in result.keys():
            label_loss, float_encoders = label_loss_fn.calculate_loss_mix2(predictions, predictions_class, predictions_encoder, labels_batch)
            tf.summary.histogram("model/float_encoders", float_encoders)
        elif "predictions_class" in result.keys():
            label_loss = label_loss_fn.calculate_loss_mix(predictions, predictions_class, labels_batch)
        elif "predictions_experts" in result.keys():
            label_loss = label_loss_fn.calculate_loss_max(predictions, predictions_experts, labels_batch)
        elif "predictions_postprocess" in result.keys():
            label_loss = label_loss_fn.calculate_loss_postprocess(predictions_postprocess, labels_batch)
        elif "predictions_negative" in result.keys():
            label_loss = label_loss_fn.calculate_loss_negative(predictions_positive, predictions_negative, labels_batch)
        else:
            label_loss = label_loss_fn.calculate_loss(predictions, labels_batch)

        if "prediction_frames" in result.keys():
            predictions_frames = result["prediction_frames"]
            labels_frames = tf.tile(tf.reshape(labels_batch,[-1,1,reader.num_classes]),[1,FLAGS.moe_num_extend,1])
            labels_frames = tf.cast(tf.reshape(labels_frames,[-1,reader.num_classes]),tf.float32)
            frame_loss = label_loss_fn.calculate_loss(predictions_frames, labels_frames)
            if "prediction_prepare_frames" in result.keys():
                prediction_prepare_frames = result["prediction_prepare_frames"]
                prediction_prepare_video = result["prediction_prepare_video"]
                max_frames = model_input.get_shape().as_list()[1]
                frames_sum = tf.reduce_sum(tf.abs(model_input),axis=2)
                frames_true = tf.ones(tf.shape(frames_sum))
                frames_false = tf.zeros(tf.shape(frames_sum))
                frames_bool = tf.where(tf.greater(frames_sum, frames_false), frames_true, frames_false)
                frames_bool = tf.reshape(frames_bool[:,0:max_frames:FLAGS.stride_size],[-1,1])
                labels_prepare_frames = tf.tile(tf.reshape(labels_batch,[-1,1,reader.num_classes]),[1,max_frames//FLAGS.stride_size,1])
                labels_prepare_frames = tf.cast(tf.reshape(labels_prepare_frames,[-1,reader.num_classes]),tf.float32)*frames_bool
                prediction_prepare_frames = prediction_prepare_frames*frames_bool
                label_loss = 0.1*label_loss_fn.calculate_loss(prediction_prepare_frames, labels_prepare_frames) + \
                             0.1*label_loss_fn.calculate_loss(prediction_prepare_video, labels_batch)
            else:
                label_loss = label_loss*0.0
        else:
            frame_loss = tf.constant(0.0)
        tf.summary.scalar("label_loss", label_loss)

        if "regularization_loss" in result.keys():
            reg_loss = result["regularization_loss"]
        else:
            reg_loss = tf.constant(0.0)

        reg_losses = tf.losses.get_regularization_losses()
        if reg_losses:
            reg_loss += tf.add_n(reg_losses)

        if regularization_penalty != 0:
            tf.summary.scalar("reg_loss", reg_loss)

        # Adds update_ops (e.g., moving average updates in batch normalization) as
        # a dependency to the train_op.
        update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
        if "update_ops" in result.keys():
            update_ops += result["update_ops"]
        if update_ops:
            with tf.control_dependencies(update_ops):
                barrier = tf.no_op(name="gradient_barrier")
                with tf.control_dependencies([barrier]):
                    label_loss = tf.identity(label_loss)

        # Incorporate the L2 weight penalties etc.
        final_loss = regularization_penalty * reg_loss + label_loss + frame_loss + append_loss
        if FLAGS.gradient=="my":
            opt = tf.train.AdamOptimizer(learning_rate=learning_rate)
            variables_to_train = tf_variables.trainable_variables()
            top_grads, top_vars = mygradients(final_loss, variables_to_train,  global_step=global_step, name="mygradients_net")
            grads_and_vars = list(zip(top_grads, top_vars))
            train_op = opt.apply_gradients(grads_and_vars, global_step=global_step)
        else:
            optimizer = optimizer_class(learning_rate)
            train_op = slim.learning.create_train_op(
                final_loss,
                optimizer,
                global_step=global_step,
                clip_gradient_norm=clip_gradient_norm)

        tf.add_to_collection("global_step", global_step)
        tf.add_to_collection("loss", final_loss)
        tf.add_to_collection("reg_loss", reg_loss)
        tf.add_to_collection("bottleneck", bottle_neck)
        tf.add_to_collection("predictions", predictions)
        tf.add_to_collection("input_batch_raw", model_input_raw)
        tf.add_to_collection("input_batch", model_input)
        tf.add_to_collection("num_frames", num_frames)
        tf.add_to_collection("labels", tf.cast(labels_batch, tf.float32))
        tf.add_to_collection("train_op", train_op)

class Trainer(object):
    """A Trainer to train a Tensorflow graph."""

    def __init__(self, cluster, task, train_dir, log_device_placement=True):
        """"Creates a Trainer.

        Args:
          cluster: A tf.train.ClusterSpec if the execution is distributed.
            None otherwise.
          task: A TaskSpec describing the job type and the task index.
        """

        self.cluster = cluster
        self.task = task
        self.is_master = (task.type == "master" and task.index == 0)
        self.train_dir = train_dir
        self.config = tf.ConfigProto(log_device_placement=log_device_placement)

        if self.is_master and self.task.index > 0:
            raise StandardError("%s: Only one replica of master expected",
                                task_as_string(self.task))

    def run(self, start_new_model=False):
        """Performs training on the currently defined Tensorflow graph.

        Returns:
          A tuple of the training Hit@1 and the training PERR.
        """
        if self.is_master and start_new_model:
            self.remove_training_directory(self.train_dir)

        target, device_fn = self.start_server_if_distributed()

        checkpoint = self.get_latest_checkpoint(start_new_model, self.train_dir)

        with tf.Graph().as_default() as graph:

            restorer, saver = self.build_model()

            global_step = tf.get_collection("global_step")[0]
            loss = tf.get_collection("loss")[0]
            reg_loss = tf.get_collection("reg_loss")[0]
            predictions = tf.get_collection("predictions")[0]
            labels = tf.get_collection("labels")[0]
            train_op = tf.get_collection("train_op")[0]
            init_op = tf.global_variables_initializer()

        sv = tf.train.Supervisor(
            graph,
            logdir=self.train_dir,
            init_op=init_op,
            is_chief=self.is_master,
            global_step=global_step,
            save_model_secs=15 * 60,
            save_summaries_secs=120,
            saver=saver)

        logging.info("%s: Starting managed session.", task_as_string(self.task))
        with sv.managed_session(target, config=self.config) as sess:
            if checkpoint is not None:
                restorer.restore(sess, checkpoint)
            try:
                logging.info("%s: Entering training loop.", task_as_string(self.task))
                while not sv.should_stop():

                    batch_start_time = time.time()
                    _, global_step_val, loss_val, reg_loss_val, predictions_val, labels_val = sess.run(
                        [train_op, global_step, loss, reg_loss, predictions, labels])
                    seconds_per_batch = time.time() - batch_start_time

                    if self.is_master:
                        examples_per_second = labels_val.shape[0] / seconds_per_batch
                        hit_at_one = eval_util.calculate_hit_at_one(predictions_val,
                                                                    labels_val)
                        perr = eval_util.calculate_precision_at_equal_recall_rate(
                            predictions_val, labels_val)
                        gap = eval_util.calculate_gap(predictions_val, labels_val)

                        logging.info(
                            "%s: training step " + str(global_step_val) + "| Hit@1: " +
                            ("%.2f" % hit_at_one) + " PERR: " + ("%.2f" % perr) + " GAP: " +
                            ("%.2f" % gap) + " Loss: " + str(loss_val) +
                            " RegLoss: " + str(reg_loss_val),
                            task_as_string(self.task))

                        sv.summary_writer.add_summary(
                            utils.MakeSummary("model/Training_Hit@1", hit_at_one),
                            global_step_val)
                        sv.summary_writer.add_summary(
                            utils.MakeSummary("model/Training_Perr", perr), global_step_val)
                        sv.summary_writer.add_summary(
                            utils.MakeSummary("model/Training_GAP", gap), global_step_val)
                        sv.summary_writer.add_summary(
                            utils.MakeSummary("global_step/Examples/Second",
                                              examples_per_second), global_step_val)
                        sv.summary_writer.flush()

            except tf.errors.OutOfRangeError:
                logging.info("%s: Done training -- epoch limit reached.",
                             task_as_string(self.task))

        logging.info("%s: Exited training loop.", task_as_string(self.task))
        sv.Stop()

    def start_server_if_distributed(self):
        """Starts a server if the execution is distributed."""

        if self.cluster:
            logging.info("%s: Starting trainer within cluster %s.",
                         task_as_string(self.task), self.cluster.as_dict())
            server = start_server(self.cluster, self.task)
            target = server.target
            device_fn = tf.train.replica_device_setter(
                ps_device="/job:ps",
                worker_device="/job:%s/task:%d" % (self.task.type, self.task.index),
                cluster=self.cluster)
        else:
            target = ""
            device_fn = ""
        return (target, device_fn)

    def remove_training_directory(self, train_dir):
        """Removes the training directory."""
        try:
            logging.info(
                "%s: Removing existing train directory.",
                task_as_string(self.task))
            gfile.DeleteRecursively(train_dir)
        except:
            logging.error(
                "%s: Failed to delete directory " + train_dir +
                " when starting a new model. Please delete it manually and" +
                " try again.", task_as_string(self.task))

    def get_meta_filename(self, start_new_model, train_dir):
        if start_new_model:
            logging.info("%s: Flag 'start_new_model' is set. Building a new model.",
                         task_as_string(self.task))
            return None

        latest_checkpoint = tf.train.latest_checkpoint(train_dir)
        if not latest_checkpoint:
            logging.info("%s: No checkpoint file found. Building a new model.",
                         task_as_string(self.task))
            return None

        meta_filename = latest_checkpoint + ".meta"
        if not gfile.Exists(meta_filename):
            logging.info("%s: No meta graph file found. Building a new model.",
                         task_as_string(self.task))
            return None
        else:
            return meta_filename

    def recover_model(self, meta_filename):
        logging.info("%s: Restoring from meta graph file %s",
                     task_as_string(self.task), meta_filename)
        return tf.train.import_meta_graph(meta_filename)

    def get_latest_checkpoint(self, start_new_model, train_dir):
        if start_new_model:
            logging.info("%s: Flag 'start_new_model' is set. Building a new model.",
                         task_as_string(self.task))
            return None

        latest_checkpoint = tf.train.latest_checkpoint(train_dir)
        if not latest_checkpoint:
            logging.info("%s: No checkpoint file found. Building a new model.",
                         task_as_string(self.task))
            return None

        return latest_checkpoint

    def build_model(self):
        """Find the model and build the graph."""

        # Convert feature_names and feature_sizes to lists of values.
        feature_names, feature_sizes = utils.GetListOfFeatureNamesAndSizes(
            FLAGS.feature_names, FLAGS.feature_sizes)

        if FLAGS.frame_features:
            if FLAGS.frame_only:
                reader = readers.YT8MFrameFeatureOnlyReader(
                    feature_names=feature_names, feature_sizes=feature_sizes)
            else:
                reader = readers.YT8MFrameFeatureReader(
                    feature_names=feature_names, feature_sizes=feature_sizes)
        else:
            reader = readers.YT8MAggregatedFeatureReader(
                feature_names=feature_names, feature_sizes=feature_sizes)

        # Find the model.
        model = find_class_by_name(FLAGS.model,
                                   [frame_level_models, video_level_models])()
        label_loss_fn = find_class_by_name(FLAGS.label_loss, [losses])()
        optimizer_class = find_class_by_name(FLAGS.optimizer, [tf.train])

        build_graph(reader=reader,
                    model=model,
                    optimizer_class=optimizer_class,
                    clip_gradient_norm=FLAGS.clip_gradient_norm,
                    train_data_pattern=FLAGS.train_data_pattern,
                    label_loss_fn=label_loss_fn,
                    base_learning_rate=FLAGS.base_learning_rate,
                    learning_rate_decay=FLAGS.learning_rate_decay,
                    learning_rate_decay_examples=FLAGS.learning_rate_decay_examples,
                    regularization_penalty=FLAGS.regularization_penalty,
                    num_readers=FLAGS.num_readers,
                    batch_size=FLAGS.batch_size,
                    num_epochs=FLAGS.num_epochs)

        logging.info("%s: Built graph.", task_as_string(self.task))

        all_vars = tf.trainable_variables()
        restore_list = [var for var in all_vars if 'notrestore' not in var.name]

        return tf.train.Saver(var_list=restore_list), tf.train.Saver(max_to_keep=2, keep_checkpoint_every_n_hours=1)

class ParameterServer(object):
    """A parameter server to serve variables in a distributed execution."""

    def __init__(self, cluster, task):
        """Creates a ParameterServer.

        Args:
          cluster: A tf.train.ClusterSpec if the execution is distributed.
            None otherwise.
          task: A TaskSpec describing the job type and the task index.
        """

        self.cluster = cluster
        self.task = task

    def run(self):
        """Starts the parameter server."""

        logging.info("%s: Starting parameter server within cluster %s.",
                     task_as_string(self.task), self.cluster.as_dict())
        server = start_server(self.cluster, self.task)
        server.join()

def start_server(cluster, task):
    """Creates a Server.

    Args:
      cluster: A tf.train.ClusterSpec if the execution is distributed.
        None otherwise.
      task: A TaskSpec describing the job type and the task index.
    """

    if not task.type:
        raise ValueError("%s: The task type must be specified." %
                         task_as_string(task))
    if task.index is None:
        raise ValueError("%s: The task index must be specified." %
                         task_as_string(task))

    # Create and start a server.
    return tf.train.Server(
        tf.train.ClusterSpec(cluster),
        protocol="grpc",
        job_name=task.type,
        task_index=task.index)

def task_as_string(task):
    return "/job:%s/task:%s" % (task.type, task.index)

def main(unused_argv):
    # Load the environment.
    env = json.loads(os.environ.get("TF_CONFIG", "{}"))

    # Load the cluster data from the environment.
    cluster_data = env.get("cluster", None)
    cluster = tf.train.ClusterSpec(cluster_data) if cluster_data else None

    # Load the task data from the environment.
    task_data = env.get("task", None) or {"type": "master", "index": 0}
    task = type("TaskSpec", (object,), task_data)

    # Logging the version.
    logging.set_verbosity(tf.logging.INFO)
    logging.info("%s: Tensorflow version: %s.",
                 task_as_string(task), tf.__version__)

    # Dispatch to a master, a worker, or a parameter server.
    if not cluster or task.type == "master" or task.type == "worker":
        Trainer(cluster, task, FLAGS.train_dir, FLAGS.log_device_placement).run(
            start_new_model=FLAGS.start_new_model)
    elif task.type == "ps":
        ParameterServer(cluster, task).run()
    else:
        raise ValueError("%s: Invalid task_type: %s." %
                         (task_as_string(task), task.type))

if __name__ == "__main__":
    app.run()


text:
import { Component } from 'react';
import PropTypes from 'prop-types';

export default class extends Component {
  static propTypes = {
    vizParams: PropTypes.shape({
      timeWindow: PropTypes.number.isRequired,
      code: PropTypes.string.isRequired
    }),
    onSvgStable: PropTypes.func.isRequired
  };

  constructor() {
    super();

    this.state = {
      error: null
    };
  }

  componentDidMount() {
    this.sandbox = `${location.origin}/sandbox`;

    window.addEventListener('message', this.handleMessageFromSandbox);
  }

  componentWillUnmount() {
    window.removeEventListener('message', this.handleMessageFromSandbox);
  }

  componentWillReceiveProps(nextProps) {
    const { vizParams } = nextProps;

    if (vizParams !== this.props.vizParams) {
      if (vizParams === null) {
        this.sendMessageToSandbox({
          type: 'clear'
        });
      } else {
        this.sendMessageToSandbox({
          type: 'visualize',
          vizParams
        });
      }
    }
  }

  renderError() {
    const { error } = this.state;

    return (

        {error}

    );
  }

  sendMessageToSandbox(data) {
    this.sandboxWindow.postMessage(data, this.sandbox);
  }

  handleMessageFromSandbox = ({ data }) => {
    switch (data.type) {
      case 'success':
        this.setState({
          error: null
        });
        break;

      case 'error':
        this.setState({
          error: data.error
        });
        break;

      case 'svg-ready':
        this.props.onSvgStable(data.svg);
        break;
    }
  };

  saveSandboxWindow = iframe => {
    if (iframe !== null) {
      this.sandboxWindow = iframe.contentWindow;
    }
  };

  render() {
    const { error } = this.state;

    return (

          {error ? this.renderError() : null}

    );
  }
}


text:
/*
 *
 *   DCSoft RTF DOM v1.0
 *   Author : Yuan yong fu.
 *   Email  : yyf9989@hotmail.com
 *   blog site:http://www.cnblogs.com/xdesigner.
 *
 */

using System;

namespace RtfDomParser
{
	/// <summary>
    /// RTF parser node, this source code evolution from other software.
	/// </summary>
	public class RTFNode
	{
		/// <summary>
		/// initialize instance
		/// </summary>
		public RTFNode()
		{
		}

		public RTFNode( RTFNodeType type , string Key )
		{
			intType = type ;
			this.strKeyword = Key ;
		}

        public RTFNode( RTFToken token )
		{
			this.strKeyword = token.Key ;
			this.bolHasParameter = token.HasParam ;
			this.intParameter = token.Param ;
			if( token.Type == RTFTokenType.Control )
				intType = RTFNodeType.Control ;
			else if( token.Type == RTFTokenType.Control )
				intType = RTFNodeType.Control ;
			else if( token.Type == RTFTokenType.Keyword  )
				intType = RTFNodeType.Keyword ;
			else if( token.Type == RTFTokenType.ExtKeyword )
				intType = RTFNodeType.ExtKeyword ;
			else if( token.Type == RTFTokenType.Text )
				intType = RTFNodeType.Text ;
			else
				intType = RTFNodeType.Text ;
		}

		protected RTFNodeGroup myParent = null;
		/// <summary>
		/// parent node
		/// </summary>
		public virtual RTFNodeGroup Parent
		{
			get{ return myParent ;}
			set{ myParent = value;}
		}

		protected RTFRawDocument myOwnerDocument = null ;
		/// <summary>
		/// raw document which owner this node
		/// </summary>
		public virtual RTFRawDocument OwnerDocument
		{
			get{ return myOwnerDocument ;}
			set
			{
				myOwnerDocument = value;
				if( this.Nodes != null )
				{
					foreach( RTFNode node in this.Nodes )
					{
						node.OwnerDocument = value ;
					}
				}
			}
		}

		/// <summary>
		/// key word
		/// </summary>
		protected string strKeyword = null;
		/// <summary>
		/// Keyword
		/// </summary>
		public virtual string Keyword
		{
			get
            {
                return strKeyword ;
            }
			set
            {
                strKeyword = value;
            }
		}

		/// <summary>
		/// Whether this node has parameter
		/// </summary>
		protected bool bolHasParameter = false;
		/// <summary>
        /// Whether this node has parameter
		/// </summary>
		public virtual bool HasParameter
		{
			get
            {
                return bolHasParameter ;
            }
			set
            {
                bolHasParameter = value;
            }
		}

		protected int intParameter = 0;
		/// <summary>
		/// paramter value
		/// </summary>
		public virtual int Parameter
		{
			get
            {
                return intParameter ;
            }
		}

		/// <summary>
		/// child nodes
		/// </summary>
		public virtual RTFNodeList Nodes
		{
			get{ return null; }
		}

		/// <summary>
		/// index
		/// </summary>
		public int Index
		{
			get
			{
				if( myParent == null )
					return 0 ;
				else
					return myParent.Nodes.IndexOf( this );
			}
		}

		protected RTFNodeType intType = RTFNodeType.None ;
		/// <summary>
		/// node type
		/// </summary>
		public RTFNodeType Type
		{
			get
            {
                return intType ;
            }
		}

		/// <summary>
		/// previous node in parent nodes list
		/// </summary>
		public RTFNode PreviousNode
		{
			get
			{
				if( myParent != null )
				{
					int index = myParent.Nodes.IndexOf( this );
					if( index > 0 )
					{
						return myParent.Nodes[ index - 1 ];
					}
				}
				return null;
			}
		}
		/// <summary>
		/// next node in parent nodes list
		/// </summary>
		public RTFNode NextNode
		{
			get
			{
				if( myParent != null )
				{
					int index = myParent.Nodes.IndexOf( this );
					if( index >= 0 && index < myParent.Nodes.Count - 1 )
						return myParent.Nodes[ index + 1 ] ;
				}
				return null;
			}
		}

		/// <summary>
		/// write to rtf document
		/// </summary>
		/// <param name="writer">RTF text writer</param>
		public virtual void Write( RTFWriter writer )
		{
			if( intType == RTFNodeType.Control
                || intType == RTFNodeType.Keyword
                || intType == RTFNodeType.ExtKeyword )
			{
                if (this.bolHasParameter)
                {
                    writer.WriteKeyword(
                        this.strKeyword + this.intParameter,
                        this.intType == RTFNodeType.ExtKeyword);
                }
                else
                {
                    writer.WriteKeyword(
                        this.strKeyword,
                        this.intType == RTFNodeType.ExtKeyword);
                }
			}
            else if (intType == RTFNodeType.Text)
            {
                writer.WriteText(this.strKeyword);
            }
		}
	}

}


text:
local _, Engine = ...
local Handler = Engine:GetHandler("UnitFrame")

local Update = function(self, event, ...)
	local unit = self.unit
end

local Enable = function(self, unit)
	local Happiness = self.Happiness
	if Happiness then
	end
end

local Disable = function(self, unit)
	local Happiness = self.Happiness
	if Happiness then
	end
end

Handler:RegisterElement("Happiness", Enable, Disable, Update)


text:
After registering an external image file as a private image on the cloud platform, you can use the image to create ECSs or reinstall or change the OSs of existing ECSs. This section describes how to create an ECS from an image.

## Procedure

You can create an ECS by referring to  [Creating an ECS from an Image](creating-an-ecs-from-an-image.md).

Note the following when setting the parameters:

-   **Region**: Select the region where the private image is located.
-   **Flavor**: Select a flavor based on the OS type of the image and the OS versions described in  [OSs Supported by Different Types of ECSs](oss-supported-by-different-types-of-ecss.md).
-   **Image**: Select  **Private image**  and then the created image from the drop-down list.


text:
<!doctype html>

    <title>Code coverage report for auth/user.constant.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../prettify.css" />
    <link rel="stylesheet" href="../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / auth/ user.constant.js

        100%
        Statements
        2/2

        100%
        Branches
        0/0

        100%
        Functions
        1/1

        100%
        Lines
        2/2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15	1×

1×

(function() {
    'use strict';

    angular
        .module('emu.user', [])
        .constant('currentUser', {
            loggedIn : false,
            token : '',
            name : '',
            email : '',
            id: '',
            lastSeen: {}
        });
})();

  Code coverage
  generated by istanbul at Mon Nov 16 2015 17:54:32 GMT+0100 (CET)


text:
<?php

include "common.php.inc";
$dbh = getDBHandle();

$query = 'SELECT username, total_files, flagged_files FROM submissions JOIN users ON (users.userid=submissions.userid) WHERE release=? AND total_files > 0 ORDER BY total_files DESC';
if (isset($_GET['limit'])) {
  if (is_numeric($_GET['limit'])) {
    $query .= ' LIMIT ?';
    $stmt = $dbh->prepare($query);
    $stmt->bindParam(1, $config['release'], PDO::PARAM_STR, 4);
    $stmt->bindParam(2, $_GET['limit'], PDO::PARAM_INT);
  }
} else {
  $stmt = $dbh->prepare($query);
  $stmt->bindParam(1, $config['release'], PDO::PARAM_STR, 4);
}
$stmt->execute();
check_or_abort($stmt);
$response = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode($response);
?>


text:
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp

BEGIN_MESSAGE_MAP(CQC_EyesApp, CWinApp)
	//{{AFX_MSG_MAP(CQC_EyesApp)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp construction

CQC_EyesApp::CQC_EyesApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CQC_EyesApp object

CQC_EyesApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp initialization

BOOL CQC_EyesApp::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#endif

	CQC_EyesDlg dlg;
	m_pMainWnd = &dlg;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}


text:
#ifndef __POWERPC_KVM_PARA_H__
#define __POWERPC_KVM_PARA_H__

#include <uapi/asm/kvm_para.h>

#ifdef CONFIG_KVM_GUEST

#include <linux/of.h>

static inline int kvm_para_available(void)
{
	struct device_node *hyper_node;

	hyper_node = of_find_node_by_path("/hypervisor");
	if (!hyper_node)
		return 0;

	if (!of_device_is_compatible(hyper_node, "linux,kvm"))
		return 0;

	return 1;
}

extern unsigned long kvm_hypercall(unsigned long *in,
				   unsigned long *out,
				   unsigned long nr);

#else

static inline int kvm_para_available(void)
{
	return 0;
}

static unsigned long kvm_hypercall(unsigned long *in,
				   unsigned long *out,
				   unsigned long nr)
{
	return EV_UNIMPLEMENTED;
}

#endif

static inline long kvm_hypercall0_1(unsigned int nr, unsigned long *r2)
{
	unsigned long in[8];
	unsigned long out[8];
	unsigned long r;

	r = kvm_hypercall(in, out, KVM_HCALL_TOKEN(nr));
	*r2 = out[0];

	return r;
}

static inline long kvm_hypercall0(unsigned int nr)
{
	unsigned long in[8];
	unsigned long out[8];

	return kvm_hypercall(in, out, KVM_HCALL_TOKEN(nr));
}

static inline long kvm_hypercall1(unsigned int nr, unsigned long p1)
{
	unsigned long in[8];
	unsigned long out[8];

	in[0] = p1;
	return kvm_hypercall(in, out, KVM_HCALL_TOKEN(nr));
}

static inline long kvm_hypercall2(unsigned int nr, unsigned long p1,
				  unsigned long p2)
{
	unsigned long in[8];
	unsigned long out[8];

	in[0] = p1;
	in[1] = p2;
	return kvm_hypercall(in, out, KVM_HCALL_TOKEN(nr));
}

static inline long kvm_hypercall3(unsigned int nr, unsigned long p1,
				  unsigned long p2, unsigned long p3)
{
	unsigned long in[8];
	unsigned long out[8];

	in[0] = p1;
	in[1] = p2;
	in[2] = p3;
	return kvm_hypercall(in, out, KVM_HCALL_TOKEN(nr));
}

static inline long kvm_hypercall4(unsigned int nr, unsigned long p1,
				  unsigned long p2, unsigned long p3,
				  unsigned long p4)
{
	unsigned long in[8];
	unsigned long out[8];

	in[0] = p1;
	in[1] = p2;
	in[2] = p3;
	in[3] = p4;
	return kvm_hypercall(in, out, KVM_HCALL_TOKEN(nr));
}

static inline unsigned int kvm_arch_para_features(void)
{
	unsigned long r;

	if (!kvm_para_available())
		return 0;

	if(kvm_hypercall0_1(KVM_HC_FEATURES, &r))
		return 0;

	return r;
}

static inline bool kvm_check_and_clear_guest_paused(void)
{
	return false;
}

#endif /* __POWERPC_KVM_PARA_H__ */


text:
using System;
using System.Threading.Tasks;
using DevOps.Portal.Domain.Teamcity;
using DevOps.Portal.Infrastructure.Teamcity;

namespace DevOps.Portal.Application.Teamcity.Queries.GetProjects
{
    public class GetProjectByIdQuery : IGetProjectByIdQuery
    {
        private readonly ITeamcityService _teamcityService;

        public GetProjectByIdQuery(ITeamcityService teamcityService)
        {
            _teamcityService = teamcityService;
        }

        public async Task<Project> Execute(string id)
        {
            return await _teamcityService.GetProject(id);
        }
    }
}


text:
package armcosmos_test

import (
	"context"
	"log"

	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cosmos/armcosmos/v2"
)

// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/cosmos-db/resource-manager/Microsoft.DocumentDB/preview/2022-08-15-preview/examples/CosmosDBPKeyRangeIdGetMetrics.json
func ExamplePartitionKeyRangeIDClient_NewListMetricsPager() {
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}
	ctx := context.Background()
	client, err := armcosmos.NewPartitionKeyRangeIDClient("subid", cred, nil)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	pager := client.NewListMetricsPager("rg1", "ddb1", "databaseRid", "collectionRid", "0", "$filter=(name.value eq 'Max RUs Per Second') and timeGrain eq duration'PT1M' and startTime eq '2017-11-19T23:53:55.2780000Z' and endTime eq '2017-11-20T23:58:55.2780000Z", nil)
	for pager.More() {
		nextResult, err := pager.NextPage(ctx)
		if err != nil {
			log.Fatalf("failed to advance page: %v", err)
		}
		for _, v := range nextResult.Value {
			// TODO: use page item
			_ = v
		}
	}
}


text:
<?php
namespace Wandu\Http\Support;

use Psr\Http\Message\ResponseInterface;
use Wandu\Http\Exception\NotFoundException;
use Wandu\Http\Factory\ServerRequestFactory;
use Wandu\Http\Sender\ResponseSender;

class HttpServer
{
    /** @var \Wandu\Http\Factory\ServerRequestFactory */
    protected $requestFactory;

    /** @var \Wandu\Http\Sender\ResponseSender */
    protected $responseSender;

    public function __construct(ServerRequestFactory $requestFactory, ResponseSender $responseSender)
    {
        $this->requestFactory = $requestFactory;
        $this->responseSender = $responseSender;
    }

    /**
     * @param string $host
     * @param int $port
     * @param callable $handler
     * @throws \Exception
     */
    public function listen($host, $port, callable $handler)
    {
        // create a socket
        $socket = socket_create(AF_INET, SOCK_STREAM, 0);

        // bind the socket
        if (!socket_bind($socket, $host, (int)$port)) {
            throw new \Exception(
                "Could not bind: {$host}:{$port} - " .
                socket_strerror(socket_last_error())
            );
        }

        while (1) {
            // listen for connections
            socket_listen($socket);

            // try to get the client socket resource
            // if false we got an error close the connection and continue
            if (!$client = socket_accept($socket)) {
                socket_close($client);
                continue;
            }

            // create new request instance with the clients header.
            // In the real world of course you cannot just fix the max size to 1024..
            $contents = socket_read($client, 1024);

            echo $contents;

            // execute the callback
            $response = call_user_func($handler, $this->requestFactory->fromSocketBody($contents));

            // check if we really recived an Response object
            // if not return a 404 response object
            if (!$response || !$response instanceof ResponseInterface) {
                $response = new NotFoundException();
            }

            // make a string out of our response
            $responseBody = $this->responseSender->parseToSocketBody($response);

            // write the response to the client socket
            socket_write($client, $responseBody, strlen($responseBody));

            // close the connetion so we can accept new ones
            socket_close($client);
        }
    }
}


text:
InFresh
=======

Integrated System of Distribution Chain Business


text:
function onRequest(context) {
    var devicemgtProps = require('/app/conf/devicemgt-props.js').config();

    var devices = context.unit.params.devices;
    var deviceType = context.uriParams.deviceType;
    var deviceId = request.getParameter('deviceId');

    if (devices) {
        return {
            'devices': stringify(devices),
            'backendApiUri': devicemgtProps['httpsURL'] + '/connectedcup/stats/',
            'dashboardserverURL': devicemgtProps['dashboardserverURL']
        };
    } else if (deviceType && deviceId) {
        var deviceModule = require('/app/modules/device.js').deviceModule;
        var device = deviceModule.viewDevice(deviceType, deviceId);
        if (device && device.status != 'error') {
            return {
                'device': device.content,
                'backendApiUri': devicemgtProps['httpsURL'] + '/connectedcup/stats/' + deviceId,
                'dashboardserverURL': devicemgtProps['dashboardserverURL']
            };
        } else {
            response.sendError(404, 'Device Id ' + deviceId + ' of type ' + deviceType + ' cannot be found!');
            exit();
        }
    }
}


text:
import { Component } from "@angular/core";

@Component({
    selector: "syntaxReference",
    templateUrl: "app/public/pages/syntaxReference/syntaxReference.component.html",
    styleUrls: ["app/public/app.component.css", "app/public/pages/syntaxReference/syntaxReference.component.css"]
})

export class SyntaxReferenceComponent {}