text:
"""Functional operations.

## Higher Order Operators

TensorFlow provides several higher order operators to simplify the common
map-reduce programming patterns.

@@map_fn
@@foldl
@@foldr
@@scan
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import constant_op
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variable_scope as vs
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.gen_functional_ops import *
# pylint: enable=wildcard-import
# pylint: disable=unused-import
from tensorflow.python.ops.gen_functional_ops import _symbolic_gradient
# pylint: enable=unused-import

# TODO(yuanbyu, mrry): Handle stride to support sliding windows.
def foldl(fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
          swap_memory=False, name=None):
  """foldl on the list of tensors unpacked from `elems` on dimension 0.

  This foldl operator repeatedly applies the callable `fn` to a sequence
  of elements from first to last. The elements are made of the tensors
  unpacked from `elems` on dimension 0. The callable fn takes two tensors as
  arguments. The first argument is the accumulated value computed from the
  preceding invocation of fn. If `initializer` is None, `elems` must contain
  at least one element, and its first element is used as the initializer.

  Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
  of the result tensor is fn(initializer, values[0]).shape`.

  Args:
    fn: The callable to be performed.
    elems: A tensor to be unpacked on dimension 0.
    initializer: (optional) The initial value for the accumulator.
    parallel_iterations: (optional) The number of iterations allowed to run
                         in parallel.
    back_prop: (optional) True enables back propagation.
    swap_memory: (optional) True enables GPU-CPU memory swapping.
    name: (optional) Name prefix for the returned tensors.

  Returns:
    A tensor resulting from applying `fn` consecutively to the list of tensors
    unpacked from `elems`, from first to last.

  Raises:
    TypeError: if `fn` is not callable.

  Example:
    ```python
    elems = [1, 2, 3, 4, 5, 6]
    sum = foldl(lambda a, x: a + x, elems)
    # sum == 21
    ```
  """
  if not callable(fn):
    raise TypeError("fn must be callable.")

  # TODO(ebrevdo): Change to using colocate_with here and in other methods.
  with vs.variable_op_scope([elems], name, "foldl") as varscope:
    # Any get_variable calls fn will cache the first call locally
    # and not issue repeated network I/O requests for each iteration.
    if varscope.caching_device is None:
      varscope.set_caching_device(lambda op: op.device)

    # Convert elems to tensor array.
    n = array_ops.shape(elems)[0]
    elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n,
                                            dynamic_size=False,
                                            infer_shape=True)
    elems_ta = elems_ta.unpack(elems)

    if initializer is None:
      a = elems_ta.read(0)
      i = constant_op.constant(1)
    else:
      a = ops.convert_to_tensor(initializer)
      i = constant_op.constant(0)

    def compute(i, a):
      a = fn(a, elems_ta.read(i))
      return [i + 1, a]
    _, r_a = control_flow_ops.while_loop(
        lambda i, a: i < n, compute, [i, a],
        parallel_iterations=parallel_iterations,
        back_prop=back_prop,
        swap_memory=swap_memory)
    return r_a

def foldr(fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
          swap_memory=False, name=None):
  """foldr on the list of tensors unpacked from `elems` on dimension 0.

  This foldr operator repeatedly applies the callable `fn` to a sequence
  of elements from last to first. The elements are made of the tensors
  unpacked from `elems`. The callable fn takes two tensors as arguments.
  The first argument is the accumulated value computed from the preceding
  invocation of fn. If `initializer` is None, `elems` must contain at least
  one element, and its first element is used as the initializer.

  Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
  of the result tensor is `fn(initializer, values[0]).shape`.

  Args:
    fn: The callable to be performed.
    elems: A tensor that is unpacked into a sequence of tensors to apply `fn`.
    initializer: (optional) The initial value for the accumulator.
    parallel_iterations: (optional) The number of iterations allowed to run
                         in parallel.
    back_prop: (optional) True enables back propagation.
    swap_memory: (optional) True enables GPU-CPU memory swapping.
    name: (optional) Name prefix for the returned tensors.

  Returns:
    A tensor resulting from applying `fn` consecutively to the list of tensors
    unpacked from `elems`, from last to first.

  Raises:
    TypeError: if `fn` is not callable.

  Example:
    ```python
    elems = [1, 2, 3, 4, 5, 6]
    sum = foldr(lambda a, x: a + x, elems)
    # sum == 21
    ```
  """
  if not callable(fn):
    raise TypeError("fn must be callable.")

  with vs.variable_op_scope([elems], name, "foldr") as varscope:
    # Any get_variable calls fn will cache the first call locally
    # and not issue repeated network I/O requests for each iteration.
    if varscope.caching_device is None:
      varscope.set_caching_device(lambda op: op.device)

    # Convert elems to tensor array.
    n = array_ops.shape(elems)[0]
    elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n,
                                            dynamic_size=False,
                                            infer_shape=True)
    elems_ta = elems_ta.unpack(elems)

    if initializer is None:
      i = n - 1
      a = elems_ta.read(i)
    else:
      i = n
      a = ops.convert_to_tensor(initializer)
    def compute(i, a):
      i -= 1
      a = fn(a, elems_ta.read(i))
      return [i, a]
    _, r_a = control_flow_ops.while_loop(
        lambda i, a: i > 0, compute, [i, a],
        parallel_iterations=parallel_iterations,
        back_prop=back_prop,
        swap_memory=swap_memory)
    return r_a

def map_fn(fn, elems, dtype=None, parallel_iterations=10, back_prop=True,
           swap_memory=False, name=None):
  """map on the list of tensors unpacked from `elems` on dimension 0.

  This map operator repeatedly applies the callable `fn` to a sequence of
  elements from first to last. The elements are made of the tensors unpacked
  from `elems`. `dtype` is the data type of the return value of `fn`. Users
  must provide `dtype` if it is different from the data type of `elems`.

  Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
  of the result tensor is `[len(values)] + fn(values[0]).shape`.

  Args:
    fn: The callable to be performed.
    elems: A tensor to be unpacked to apply `fn`.
    dtype: (optional) The output type of `fn`.
    parallel_iterations: (optional) The number of iterations allowed to run
                         in parallel.
    back_prop: (optional) True enables back propagation.
    swap_memory: (optional) True enables GPU-CPU memory swapping.
    name: (optional) Name prefix for the returned tensors.

  Returns:
    A tensor that packs the results of applying `fn` to the list of tensors
    unpacked from `elems`, from first to last.

  Raises:
    TypeError: if `fn` is not callable.

  Example:
    ```python
    elems = [1, 2, 3, 4, 5, 6]
    squares = map_fn(lambda x: x * x, elems)
    # squares == [1, 4, 9, 16, 25, 36]
    ```
  """
  if not callable(fn):
    raise TypeError("fn must be callable.")

  with vs.variable_op_scope([elems], name, "map") as varscope:
    # Any get_variable calls fn will cache the first call locally
    # and not issue repeated network I/O requests for each iteration.
    if varscope.caching_device is None:
      varscope.set_caching_device(lambda op: op.device)

    dtype = dtype if dtype else elems.dtype

    # Convert elems to tensor array.
    n = array_ops.shape(elems)[0]
    elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n,
                                            dynamic_size=False,
                                            infer_shape=True)
    elems_ta = elems_ta.unpack(elems)

    i = constant_op.constant(0)
    acc_ta = tensor_array_ops.TensorArray(dtype=dtype, size=n,
                                          dynamic_size=False,
                                          infer_shape=True)
    def compute(i, ta):
      ta = ta.write(i, fn(elems_ta.read(i)))
      return [i + 1, ta]
    _, r_a = control_flow_ops.while_loop(
        lambda i, a: i < n, compute, [i, acc_ta],
        parallel_iterations=parallel_iterations,
        back_prop=back_prop,
        swap_memory=swap_memory)
    result = r_a.pack()
    elems_dims = ops.convert_to_tensor(elems).get_shape().dims
    result_dims = result.get_shape().dims
    if elems_dims and result_dims:
      result.set_shape([elems_dims[0]] + result_dims[1:])
    return result

def scan(fn, elems, initializer=None, parallel_iterations=10, back_prop=True,
         swap_memory=False, name=None):
  """scan on the list of tensors unpacked from `elems` on dimension 0.

  This scan operator repeatedly applies the callable `fn` to a sequence
  of elements from first to last. The elements are made of the tensors
  unpacked from `elems` on dimension 0. The callable fn takes two tensors as
  arguments. The first argument is the accumulated value computed from the
  preceding invocation of fn. If `initializer` is None, `elems` must contain
  at least one element, and its first element is used as the initializer.

  Suppose that `elems` is unpacked into `values`, a list of tensors. The shape
  of the result tensor is `[len(values)] + fn(initializer, values[0]).shape`.

  Args:
    fn: The callable to be performed.
    elems: A tensor to be unpacked on dimension 0.
    initializer: (optional) The initial value for the accumulator.
    parallel_iterations: (optional) The number of iterations allowed to run
                         in parallel.
    back_prop: (optional) True enables back propagation.
    swap_memory: (optional) True enables GPU-CPU memory swapping.
    name: (optional) Name prefix for the returned tensors.

  Returns:
    A tensor that packs the results of applying `fn` to the list of tensors
    unpacked from `elems`, from first to last.

  Raises:
    TypeError: if `fn` is not callable.

  Example:
    ```python
    elems = [1, 2, 3, 4, 5, 6]
    sum = scan(lambda a, x: a + x, elems)
    # sum == [1, 3, 6, 10, 15, 21]
    ```
  """
  if not callable(fn):
    raise TypeError("fn must be callable.")

  with vs.variable_op_scope([elems], name, "scan") as varscope:
    # Any get_variable calls fn will cache the first call locally
    # and not issue repeated network I/O requests for each iteration.
    if varscope.caching_device is None:
      varscope.set_caching_device(lambda op: op.device)

    # Convert elems to tensor array.
    n = array_ops.shape(elems)[0]
    elems_ta = tensor_array_ops.TensorArray(dtype=elems.dtype, size=n,
                                            dynamic_size=False,
                                            infer_shape=True)
    elems_ta = elems_ta.unpack(elems)

    if initializer is None:
      a = elems_ta.read(0)
      i = constant_op.constant(1)
    else:
      a = ops.convert_to_tensor(initializer)
      i = constant_op.constant(0)

    # Create a tensor array to store the intermediate values.
    acc_ta = tensor_array_ops.TensorArray(dtype=a.dtype, size=n,
                                          dynamic_size=False,
                                          infer_shape=True)
    if initializer is None:
      acc_ta = acc_ta.write(0, a)

    def compute(i, a, ta):
      a = fn(a, elems_ta.read(i))
      ta = ta.write(i, a)
      return [i + 1, a, ta]
    _, _, r_a = control_flow_ops.while_loop(
        lambda i, a, ta: i < n, compute, [i, a, acc_ta],
        parallel_iterations=parallel_iterations,
        back_prop=back_prop, swap_memory=swap_memory)
    result = r_a.pack()
    elems_dims = ops.convert_to_tensor(elems).get_shape().dims
    result_dims = result.get_shape().dims
    if elems_dims and result_dims:
      result.set_shape([elems_dims[0]] + result_dims[1:])
    return result

@ops.RegisterShape("SymbolicGradient")
def _symbolic_gradient_shape(op):
  # Say, (u, v) = f(x, y, z), _symbolic_gradient(f) is a function of
  # (x, y, z, du, dv) -> (dx, dy, dz). Therefore, shapes of its
  # outputs (dx, dy, dz) are the same as (x, y, z).
  return [op.inputs[i].get_shape() for i in range(len(op.outputs))]


text:
class TMongoDriver;

class MongoCommand
{
public:
    MongoCommand(const QString &path);
    ~MongoCommand();

    bool open(const QString &env);
    void close();
    QStringList getCollectionNames() const;

private:
    TMongoDriver *driver;
    QString settingsPath;
    QString databaseName;

    T_DISABLE_COPY(MongoCommand)
    T_DISABLE_MOVE(MongoCommand)
};

#endif // MONGOCOMMAND_H

redpajama_set_name: RedPajamaGithub


text:
flv.js  [![npm](https://img.shields.io/npm/v/flv.js.svg?style=flat)](https://www.npmjs.com/package/flv.js)
======
An HTML5 Flash Video (FLV) Player written in pure JavaScript without Flash. LONG LIVE FLV!

This project relies on [Media Source Extensions][] to work.

**For FLV live stream playback, please consider [mpegts.js][] which is under active development.**

**This project will become rarely maintained.**

[mpegts.js]: https://github.com/xqq/mpegts.js
## Overview
flv.js works by transmuxing FLV file stream into ISO BMFF (Fragmented MP4) segments, followed by feeding mp4 segments into an HTML5 `<video>` element through [Media Source Extensions][] API.

[Media Source Extensions]: https://w3c.github.io/media-source/

## Demo
[http://bilibili.github.io/flv.js/demo/](http://bilibili.github.io/flv.js/demo/)

## Features
- FLV container with H.264 + AAC / MP3 codec playback
- Multipart segmented video playback
- HTTP FLV low latency live stream playback
- FLV over WebSocket live stream playback
- Compatible with Chrome, FireFox, Safari 10, IE11 and Edge
- Extremely low overhead, and hardware accelerated by your browser!

## Installation
```bash
npm install --save flv.js
```

## Build
```bash
npm ci                 # install dependencies / dev-dependences
npm run build:debug    # debug version flv.js will be emitted to /dist
npm run build          # minimized release version flv.min.js will be emitted to /dist
```

[cnpm](https://github.com/cnpm/cnpm) mirror is recommended if you are in Mainland China.

## CORS
If you use standalone video server for FLV stream, `Access-Control-Allow-Origin` header must be configured correctly on video server for cross-origin resource fetching.

See [cors.md](docs/cors.md) for more details.

## Getting Started
```html
<script src="flv.min.js"></script>
<video id="videoElement"></video>
<script>
    if (flvjs.isSupported()) {
        var videoElement = document.getElementById('videoElement');
        var flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: 'http://example.com/flv/video.flv'
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
    }
</script>
```

## Limitations
- MP3 audio codec is currently not working on IE11 / Edge
- HTTP FLV live stream is not currently working on all browsers, see [livestream.md](docs/livestream.md)

## Multipart playback
You only have to provide a playlist for `MediaDataSource`. See [multipart.md](docs/multipart.md)

## Livestream playback
See [livestream.md](docs/livestream.md)

## API and Configuration
See [api.md](docs/api.md)

## Debug
```bash
npm ci         # install dependencies / dev-dependences
npm run dev    # watch file changes and build debug version on the fly
```

## Design
See [design.md](docs/design.md)

## License
```
Copyright (C) 2016 Bilibili. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```


text:
        <?php $form = $this->beginWidget('CActiveForm', array('id' => 'banner-crop-image-form', 'enableAjaxValidation' => false)); ?>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

<?php echo Yii::t('UserModule.views_profile_cropBannerImage', 'Modify your title image'); ?>

<?php //echo Yii::t('UserModule.views_profile_cropBannerImage', 'Select the area of your image you want to save as user avatar and click Save.');     ?>

            <?php echo $form->errorSummary($model); ?>
            <?php echo $form->hiddenField($model, 'cropX'); ?>
            <?php echo $form->hiddenField($model, 'cropY'); ?>
            <?php echo $form->hiddenField($model, 'cropW'); ?>
            <?php echo $form->hiddenField($model, 'cropH'); ?>

                <?php
                $this->widget('ext.yii-jcrop.jCropWidget', array(
                    'imageUrl' => $profileImage->getUrl('_org') . "?nocache=" . time(),
                    'formElementX' => 'CropProfileImageForm_cropX',
                    'formElementY' => 'CropProfileImageForm_cropY',
                    'formElementWidth' => 'CropProfileImageForm_cropW',
                    'formElementHeight' => 'CropProfileImageForm_cropH',
                    'jCropOptions' => array(
                        'aspectRatio' => '2.8333',
                        'boxWidth' => 400,
                        'setSelect' => array(0, 0, 200, 75),
                    ),
                        )
                );
                ?>

            <?php
            echo HHtml::ajaxButton(Yii::t('UserModule.views_profile_cropBannerImage', 'Save'), array('//user/account/cropBannerImage'), array(
                'type' => 'POST',
                'beforeSend' => 'function(){ $("#invite-loader").removeClass("hidden"); }',
                'success' => 'function(html){ $("#globalModal").html(html); }',
                    ), array('class' => 'btn btn-primary'));
            ?>

            <?php //echo CHtml::submitButton(Yii::t('UserModule.views_profile_cropBannerImage', 'Save'), array('class' => 'btn btn-primary'));  ?>

            <button type="button" class="btn btn-primary"
                    data-dismiss="modal"><?php echo Yii::t('UserModule.views_profile_cropBannerImage', 'Close'); ?></button>

        <?php $this->endWidget(); ?>


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2019 Ryo Suzuki
//	Copyright (c) 2016-2019 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include <memory>
# include "Fwd.hpp"

namespace s3d
{
	class ManagedScript
	{
	private:

		class ManagedScriptDetail;

		std::shared_ptr<ManagedScriptDetail> pImpl;

	public:

		ManagedScript();

		explicit ManagedScript(const FilePath& path);

		~ManagedScript();

		[[nodiscard]] bool isEmpty() const;

		[[nodiscard]] explicit operator bool() const;

		[[nodiscard]] bool compiled() const;

		void run() const;
	};
}


text:
#include <aws/ssm/model/DocumentStatus.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace SSM
  {
    namespace Model
    {
      namespace DocumentStatusMapper
      {

        static const int Creating_HASH = HashingUtils::HashString("Creating");
        static const int Active_HASH = HashingUtils::HashString("Active");
        static const int Updating_HASH = HashingUtils::HashString("Updating");
        static const int Deleting_HASH = HashingUtils::HashString("Deleting");

        DocumentStatus GetDocumentStatusForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == Creating_HASH)
          {
            return DocumentStatus::Creating;
          }
          else if (hashCode == Active_HASH)
          {
            return DocumentStatus::Active;
          }
          else if (hashCode == Updating_HASH)
          {
            return DocumentStatus::Updating;
          }
          else if (hashCode == Deleting_HASH)
          {
            return DocumentStatus::Deleting;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<DocumentStatus>(hashCode);
          }

          return DocumentStatus::NOT_SET;
        }

        Aws::String GetNameForDocumentStatus(DocumentStatus enumValue)
        {
          switch(enumValue)
          {
          case DocumentStatus::Creating:
            return "Creating";
          case DocumentStatus::Active:
            return "Active";
          case DocumentStatus::Updating:
            return "Updating";
          case DocumentStatus::Deleting:
            return "Deleting";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace DocumentStatusMapper
    } // namespace Model
  } // namespace SSM
} // namespace Aws


text:
import React from 'react';

const SubMenu = (props) => {
  return (
    <ul className='vertical menu' data-drilldown children={props} />
  );
};

export default SubMenu;


text:
Alloy.Collections.Youtube = Alloy.createCollection('YoutubeB');
Alloy.Globals.Close = null;
// we need this Close global here since the Row controller needs a way to set Close button
Alloy.Globals.GlobalLoad = function() {
};

Alloy.Globals.CoverUpdate = function() {
};

Alloy.Globals.Load = false;
//


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2022 The Chromium Authors. All rights reserved.
     Use of this source code is governed by a BSD-style license that can be
     found in the LICENSE file. -->

<resources>
    <!-- Surface color elevations -->
    <dimen name="dialog_bg_color_elev">@dimen/default_elevation_3</dimen>
    <dimen name="menu_bg_color_elev">@dimen/default_elevation_5</dimen>
    <dimen name="sheet_bg_color_elev">@dimen/default_elevation_4</dimen>
    <dimen name="snackbar_background_color_elev">@dimen/default_elevation_4</dimen>
</resources>


text:
<ion-side-menus enable-menu-with-back-views="true">

  <ion-side-menu-content>
    <ion-nav-bar class="bar-assertive-900"
                 ng-class="{expanded: isExpanded, 'has-header-fab-left': hasHeaderFabLeft, 'has-header-fab-right': hasHeaderFabRight}"
                 align-title="left">

      <ion-nav-buttons side="right">
        <button class="button button-icon button-clear ion-navicon" menu-toggle="right">
        </button>
      </ion-nav-buttons>
    </ion-nav-bar>
    <ion-nav-view name="fabContent"></ion-nav-view>
    <ion-nav-view name="menuContent" ng-class="{expanded: isExpanded}"></ion-nav-view>
  </ion-side-menu-content>

  <ion-side-menu side="right">
    <ion-header-bar class="app-bg expanded">

eLink {{user.firstname}}

    </ion-header-bar>
    <ion-content class="stable-bg has-expanded-header">
      <ion-list>
        <ion-item nav-clear menu-close ng-show="!userAuthenticated" ui-sref="app.login">
          Login
        </ion-item>
        <ion-item nav-clear menu-close ng-show="userAuthenticated" ng-click="logout()">
          Logout
        </ion-item>
        <ion-item nav-clear menu-close ng-show="userAuthenticated" on-tap="loadTargetState('app.bibli-nonLu')">
          Non Lu{{countNonLu}}
        </ion-item>
        <ion-item nav-clear menu-close ng-show="userAuthenticated" on-tap="loadTargetState('app.bibli-lu')">
          Biblio{{countBiblio}}
        </ion-item>
        <ion-item nav-clear menu-close ng-show="userAuthenticated" on-tap="loadTargetState('app.cercle-view')">
          Mes cercles{{countCercle}}
        </ion-item>
        <ion-item nav-clear menu-close ng-show="userAuthenticated" on-tap="loadTargetState('app.icdc-view')">
          Top Ten
        </ion-item>
        <ion-item nav-clear menu-close ng-show="userAuthenticated" on-tap="loadTargetState('app.gestion-view')">
          Gérer mes cercles
        </ion-item>
      </ion-list>
    </ion-content>

  </ion-side-menu>
</ion-side-menus>


text:
package org.example.service;

/**
 * Constants.
 */
public class PurchasingServiceConstants {
    public static final String QPID_ICF = "org.wso2.andes.jndi.PropertiesFileInitialContextFactory";
    public static final String CF_NAME_PREFIX = "connectionfactory.";
    public static final String QUEUE_NAME_PREFIX = "queue.";
    public static final String CF_NAME = "qpidConnectionfactory";

    public static final String CARBON_CLIENT_ID = "carbon";
    public static final String CARBON_VIRTUAL_HOST_NAME = "carbon";
    public static final String CARBON_DEFAULT_HOSTNAME = "localhost";
    public static final String CARBON_DEFAULT_PORT = "5672";

    public static final String USERNAME = "admin";
    public static final String PASSWORD = "admin";

    public static String REORDER_REQUEST_QUEUE = "reorderRequestQueue";
    public static String REORDER_RESPONSE_QUEUE = "reorderResponseQueue";

    public static String getTCPConnectionURL(String username, String password) {
        // amqp://{username}:{password}@carbon/carbon?brokerlist='tcp://{hostname}:{port}'
        return "amqp://" + username + ":" + password + "@" + CARBON_CLIENT_ID + "/" + CARBON_VIRTUAL_HOST_NAME +
                "?brokerlist='tcp://" + CARBON_DEFAULT_HOSTNAME + ":" + CARBON_DEFAULT_PORT + "'";
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Monitor Project – Generated Reports</title>

    <link rel="stylesheet" href="./css/print.css" type="text/css" media="print" />
        <meta name="Date-Revision-yyyymmdd" content="20180816" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

                                 Last Published: 2018-08-16
               | Version: 4.0.2

Overview

                  Introduction

Project Documentation

                  Project Information

            Project Reports

                  JavaDocs

                  Surefire Report

                  Checkstyle

                  JDepend

                  Source Xref

                  Test Source Xref

                  Tag List

Generated Reports

This document provides an overview of the various reports that are automatically generated by Maven . Each report is briefly described below.

Overview

Document
Description

JavaDocs
JavaDoc API documentation.

Surefire Report
Report on the test results of the project.

Checkstyle
Report on coding style conventions.

JDepend
JDepend traverses Java class file directories and generates design quality metrics for each Java package. JDepend allows you to automatically measure the quality of a design in terms of its extensibility, reusability, and maintainability to manage package dependencies effectively.

Source Xref
HTML based, cross-reference version of Java source code.

Test Source Xref
HTML based, cross-reference version of Java test source code.

Tag List
Report on various tags found in the code.

        ©            2011-2018

                       - Privacy Policy.
        Apache Maven, Maven, Apache, the Apache feather logo, and the Apache Maven project logos are trademarks of The Apache Software Foundation.


text:
package org.apache.pinot.plugin.metrics.yammer;

import com.yammer.metrics.core.Metered;
import java.util.concurrent.TimeUnit;
import org.apache.pinot.spi.metrics.PinotMetered;

public abstract class YammerMetered implements PinotMetered {
  private final Metered _metered;

  public YammerMetered(Metered metered) {
    _metered = metered;
  }

  @Override
  public Object getMetered() {
    return _metered;
  }

  @Override
  public TimeUnit rateUnit() {
    return _metered.rateUnit();
  }

  @Override
  public String eventType() {
    return _metered.eventType();
  }

  @Override
  public long count() {
    return _metered.count();
  }

  @Override
  public double fifteenMinuteRate() {
    return _metered.fifteenMinuteRate();
  }

  @Override
  public double fiveMinuteRate() {
    return _metered.fiveMinuteRate();
  }

  @Override
  public double meanRate() {
    return _metered.meanRate();
  }

  @Override
  public double oneMinuteRate() {
    return _metered.oneMinuteRate();
  }

  @Override
  public Object getMetric() {
    return _metered;
  }
}


text:
/*
 * main.cpp
 *   (ここにファイルの簡易説明を記入)
 *
 *  Created on: 2015/05/24
 *      Author: wlamigo
 *		changed : oasi-adamay
 *
 *   (ここにファイルの説明を記入)
 */

#include <opencv2/opencv.hpp>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cmath>
#include "picojson.h"
#include "tclap/CmdLine.h"

#include "modelHandler.hpp"
#include "convertRoutine.hpp"

#include "glsCV.h"
//Lib
#pragma comment (lib, "opengl32.lib")
#pragma comment (lib, "glew32.lib")
#pragma comment (lib, "glfw3dll.lib")
#pragma comment (lib, "glsCV.lib")

//#ifdef _DEBUG
#if 1
#include "Timer.h"
#define _TMR_(...)  Timer tmr(__VA_ARGS__)
#else
#define _TMR_(...)
#endif

#define MODEL_BIN

int main(int argc, char** argv) {
	_TMR_("total time\t:");
	glsCvInit();

	// definition of command line arguments
	TCLAP::CmdLine cmd("waifu2x reimplementation using OpenCV", ' ', "1.0.0");

	TCLAP::ValueArg<std::string> cmdInputFile("i", "input_file",
		"path to input image file (you should input full path)", true, "",
		"string", cmd);

	TCLAP::ValueArg<std::string> cmdOutputFile("o", "output_file",
		"path to output image file (you should input full path)", false,
		"(auto)", "string", cmd);

	std::vector<std::string> cmdModeConstraintV;
	cmdModeConstraintV.push_back("noise");
	cmdModeConstraintV.push_back("scale");
	cmdModeConstraintV.push_back("noise_scale");
	TCLAP::ValuesConstraint<std::string> cmdModeConstraint(cmdModeConstraintV);
	TCLAP::ValueArg<std::string> cmdMode("m", "mode", "image processing mode",
		false, "noise_scale", &cmdModeConstraint, cmd);

	std::vector<int> cmdNRLConstraintV;
	cmdNRLConstraintV.push_back(1);
	cmdNRLConstraintV.push_back(2);
	TCLAP::ValuesConstraint<int> cmdNRLConstraint(cmdNRLConstraintV);
	TCLAP::ValueArg<int> cmdNRLevel("", "noise_level", "noise reduction level",
		false, 1, &cmdNRLConstraint, cmd);

	TCLAP::ValueArg<double> cmdScaleRatio("", "scale_ratio",
		"custom scale ratio", false, 2.0, "double", cmd);

	TCLAP::ValueArg<std::string> cmdModelPath("", "model_dir",
		"path to custom model directory (don't append last / )", false,
		"models", "string", cmd);

	TCLAP::ValueArg<int> cmdNumberOfJobs("j", "jobs",
		"number of threads launching at the same time", false, 1, "integer",
		cmd);

	// definition of command line argument : end

	// parse command line arguments
	try {
		cmd.parse(argc, argv);
	}
	catch (std::exception &e) {
		std::cerr << e.what() << std::endl;
		std::cerr << "Error : cmd.parse() threw exception" << std::endl;
		std::exit(-1);
	}

	// load image file
	std::cout << "Load image file:" << cmdInputFile.getValue() << std::endl;
	cv::Mat image = cv::imread(cmdInputFile.getValue(), cv::IMREAD_COLOR);
	if (image.empty()){
		std::cerr << "Error : cannot open image " << cmdInputFile.getValue() << std::endl;
		std::exit(-1);
	}

//	cv::Mat srcImg = image.clone();

	{
		_TMR_("Process Time\t:");

	image.convertTo(image, CV_32F, 1.0 / 255.0);
	cv::cvtColor(image, image, cv::COLOR_BGR2YUV);

	// set number of jobs for processing models
	w2xc::modelUtility::getInstance().setNumberOfJobs(cmdNumberOfJobs.getValue());

	string strModelExt;
#if !defined(MODEL_BIN)
	strModelExt = ".json";
#else
	strModelExt = ".bin";
#endif

	// ===== Noise Reduction Phase =====
	if (cmdMode.getValue() == "noise" || cmdMode.getValue() == "noise_scale") {
		_TMR_("Noise Reduction\t:");
		std::cout << "Noise Reduction Phase." << std::endl;

		std::string modelFileName(cmdModelPath.getValue());
		modelFileName = modelFileName + "/noise"
			+ std::to_string(cmdNRLevel.getValue()) + "_model" + strModelExt;
		std::vector<std::unique_ptr<w2xc::Model> > models;

		std::cout << "Load model file:" << modelFileName << std::endl;
#if !defined(MODEL_BIN)
		if (!w2xc::modelUtility::generateModelFromJSON(modelFileName, models))
#else
		if (!w2xc::modelUtility::generateModelFromBin(modelFileName, models))
#endif
			std::exit(-1);

		std::vector<cv::Mat> imageSplit;
		cv::Mat imageY;
		cv::split(image, imageSplit);
		imageSplit[0].copyTo(imageY);

		w2xc::convertWithModels(imageY, imageSplit[0], models);

		cv::merge(imageSplit, image);

	} // noise reduction phase : end

	// ===== scaling phase =====

	if (cmdMode.getValue() == "scale" || cmdMode.getValue() == "noise_scale") {
		_TMR_("scaling Phase\t\t:");
		std::cout << "scaling phase." << std::endl;

		// calculate iteration times of 2x scaling and shrink ratio which will use at last
		int iterTimesTwiceScaling = static_cast<int>(std::ceil(
			std::log2(cmdScaleRatio.getValue())));
		double shrinkRatio = 0.0;
		if (static_cast<int>(cmdScaleRatio.getValue())
			!= std::pow(2, iterTimesTwiceScaling)) {
			shrinkRatio = cmdScaleRatio.getValue()
				/ std::pow(2.0, static_cast<double>(iterTimesTwiceScaling));
		}

		std::string modelFileName(cmdModelPath.getValue());
		modelFileName = modelFileName + "/scale2.0x_model" + strModelExt;

		std::vector<std::unique_ptr<w2xc::Model> > models;

		std::cout << "Load model file:" << modelFileName << std::endl;
#if !defined(MODEL_BIN)
		if (!w2xc::modelUtility::generateModelFromJSON(modelFileName, models))
#else
		if (!w2xc::modelUtility::generateModelFromBin(modelFileName, models))
#endif
			std::exit(-1);

		std::cout << "start scaling" << std::endl;
		// 2x scaling
		for (int nIteration = 0; nIteration < iterTimesTwiceScaling;
			nIteration++) {

			std::cout << "#" << std::to_string(nIteration + 1)
				<< " 2x scaling..." << std::endl;

			cv::Size imageSize = image.size();
			imageSize.width *= 2;
			imageSize.height *= 2;
			cv::Mat image2xNearest;
			cv::resize(image, image2xNearest, imageSize, 0, 0, cv::INTER_NEAREST);
			std::vector<cv::Mat> imageSplit;
			cv::Mat imageY;
			cv::split(image2xNearest, imageSplit);
			imageSplit[0].copyTo(imageY);

			// generate bicubic scaled image and split
			imageSplit.clear();
			cv::Mat image2xBicubic;
			cv::resize(image, image2xBicubic, imageSize, 0, 0, cv::INTER_CUBIC);
			cv::split(image2xBicubic, imageSplit);

			if (!w2xc::convertWithModels(imageY, imageSplit[0], models)){
				std::cerr << "w2xc::convertWithModels : something error has occured.\n"
					"stop." << std::endl;
				std::exit(1);
			};

			cv::merge(imageSplit, image);
#if 0
			{
				_TMR_("delete models\t:");
				models.clear();
			}
#endif

		} // 2x scaling : end

		if (shrinkRatio != 0.0) {
			cv::Size lastImageSize = image.size();
			lastImageSize.width =
				static_cast<int>(static_cast<double>(lastImageSize.width
				* shrinkRatio));
			lastImageSize.height =
				static_cast<int>(static_cast<double>(lastImageSize.height
				* shrinkRatio));
			cv::resize(image, image, lastImageSize, 0, 0, cv::INTER_LINEAR);
		}

	}

	cv::cvtColor(image, image, cv::COLOR_YUV2BGR);
	image.convertTo(image, CV_8U, 255.0);
	}	//_TMR

	std::string outputFileName = cmdOutputFile.getValue();
	if (outputFileName == "(auto)") {
		outputFileName = cmdInputFile.getValue();
		int tailDot = (int)outputFileName.find_last_of('.');
		outputFileName.erase(tailDot, outputFileName.length());
		outputFileName = outputFileName + "(" + cmdMode.getValue() + ")";
		std::string &mode = cmdMode.getValue();
		if (mode.find("noise") != mode.npos){
			outputFileName = outputFileName + "(Level" + std::to_string(cmdNRLevel.getValue())
				+ ")";
		}
		if (mode.find("scale") != mode.npos){
			outputFileName = outputFileName + "(x" + std::to_string(cmdScaleRatio.getValue())
				+ ")";
		}
		outputFileName += ".png";
	}
	std::cout << "Save image file:" << outputFileName << std::endl;
	cv::imwrite(outputFileName, image);

	std::cout << "process successfully done!" << std::endl;

	//cv::Mat dstImg = image.clone();
	//cv::Mat cubicImg;
	//cv::resize(srcImg, cubicImg, Size(0, 0), 2.0, 2.0, cv::INTER_CUBIC);

	glsCvTerminate();

#if 0
	cv::imshow("src", srcImg);
	cv::imshow("dst", dstImg);
	cv::imshow("cubic", cubicImg);
#endif

//	std::cin.get();
	return 0;
}


text:
package org.arp.producers;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

@ApplicationScoped
public class EntityManagerProducer {

    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("categories-pu");

    @Produces
    @RequestScoped
    public EntityManager createEntityManager() {
    	return emf.createEntityManager();
    }

    public void closeEntityManager(@Disposes EntityManager em) {
    	if (em.isOpen()) {
            em.close();
        }
    }

}


text:
using System;

namespace Raksha.Tsp
{
	public class TspException
		: Exception
	{
		public TspException()
		{
		}

		public TspException(
			string message)
			: base(message)
		{
		}

		public TspException(
			string		message,
			Exception	e)
			: base(message, e)
		{
		}
	}
}


text:
> Example dashboard for apinf that uses aggregated data from API-Umbrella.

### Setup

1. Create `config.js` file in project root

  ```
  export default {
    host: '<api_umbrella_host>',
    key: '<api_key>',
    token: '<api_token>'
  }
  ```

2. Install dependencies

  ```
  $ npm install && npm start
  ```

### License

[MIT](https://github.com/frenchbread/apinf-dashboard-example/blob/master/LICENSE)


text:
libDTShape loads and animates 3d animated shapes. It's an offshoot of the code from the Torque3D engine, simplified and abstracted so it can more easily be incorporated into other projects.

libDTShape supports both classic "compiled" dts models, and also collada models.

## What amazing features does it support?

To summarize:

* Rigid animation
* Skinned animation (Software and Hardware Accelerated)
* Animation triggers
* Ground frames
* Multiple animation threads & blending
* Imposters
* Detail levels
* Collision meshes

## What platforms does it support?

* Windows (x86, amd64)
* OS X (x86, amd64)
* Linux (x86, amd64, arm)

While libDTShape is mainly optimized for x86/x64, it can support any generic platform provided the platform headers are setup correctly.

## How do I use it?

An example application is located in the example folder. Currently since the code assumes nothing about your rendering library, you'll need to create your own TSMeshRenderer, TSMeshInstanceRenderData, TSMaterial, TSMaterialInstance and TSMaterialManager classes.

If you want to do more advanced things such as collision detection, note that while interfaces are exposed to enumerate collision primitives and surfaces, as of yet there is no example of making use of this data.

## Why shoud I use it instead of "solution x"?

Good question. If you want a fully featured solution which you can insert into your indie game in 5 seconds, libdtshape might not be for you. On the other hand if you want something reasonably simple and non-assuming which can be built upon, maybe you should check out libdtshape.

*NOTE*: As libdtshape is currently in its early stages of development, the API is subject to change. Feel free to suggest ideas for improvement on the Issue Tracker.


text:
package com.dyz.gameserver.msg.response.draw;

import java.io.IOException;

import com.alibaba.fastjson.JSONObject;
import com.context.ConnectAPI;
import com.dyz.gameserver.commons.message.ServerResponse;

/**
 * 抽奖返回
 * @author luck
 *
 */
public class DrawResponse extends ServerResponse {

	public DrawResponse(int status, JSONObject json) {
		//type   0:获取奖品信息    1:获取随机获得奖品id    2:抽奖功能尚未开启
		super(status, ConnectAPI.DRAw_RESPONSE);
		  if(status > 0){
			  try {
	                output.writeUTF(json.toString());
	            } catch (IOException e) {
	                e.printStackTrace();
	            } finally {
	           	 output.close();
				}
	        }

	}

}


text:
Master/slave replication is a simple fault-tolerance configuration
that allows a slave to fully sync up and maintain sync'd up with a
master.

## Configuring the Master

No special configuration is required on the master, but here's an
example startup command that is known to work:

    MCDIR=/path/to/memcached/
    EPDIR=/path/to/ep-engine/
    DBDIR=/path/to/write/database
    $MCDIR/memcached -u nobody -v -E $EPDIR/.libs/ep.so -e dbname=$DBDIR/mem.db

## Configuring the slave

The slave configuration is almost identical to the master, but
includes a `-O` parameter pointing to the location of the master.  For
example:

    MASTER=w.x.y.z:11211
    $MCDIR/memcached -u nobody -v -O $MASTER \
        -E $EPDIR/.libs/ep.so -e dbname=$DBDIR/mem.db


text:
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.decorators import permission_required
from django.contrib import messages

from froide.foirequest.models import FoiMessage
from froide.helper.utils import render_403

from .utils import run_guidance

@require_POST
@permission_required('guide.can_run_guidance')
def rerun_rules(request, message_id):
    if not request.user.is_staff:
        return render_403(request)

    message = get_object_or_404(FoiMessage, id=message_id)
    notify = False

    if request.POST.get('notify'):
        notify = True

    run_guidance(message, active_only=False, notify=notify)

    messages.add_message(
        request, messages.SUCCESS,
        _('Guidance refreshed for message.')
    )

    return redirect(message)


text:
layout: post
title: "Battle of the Container OSes: CoreOS"
modified:
categories:
excerpt: "The poster child"
tags: []
comments: true
image:
  feature: coreos-wordmark-horiz-color-wide.png
  credit: CoreOS
  creditlink: http://coreos.com
date: 2015-03-30T10:07:24-04:00
---

This is an ongoing comparison series between different publicly available operating systems focused on running some form of containers, trying to be as objective as possible but I'll add my own commentary of course. I am not covering the different container technologies such as Docker, Rocket, LXC or others. There are no winners or losers, I leave it up as an exercise to the reader to decide if any of the compared OSes would be useful for them. Got an OS that's not covered? Leave a comment!

# Battle measurements
 - Ease of deployment
 - Ease of use
 - Documentation
 - Integrations
 - Functionality

So let's see what we can get out of this :)

# CoreOS

## Ease of deployment

**[CoreOS](http://coreos.com)** is sort of the poster child of container OSes currently, and they're really making it easy to try out. You can run it on public cloud platforms such as Azure, EC2, DigitalOcean, EC2 Container Service, GCE, RackSpace, or baremetal, or on Vagrant, OpenStack or VMware. There are even more community-supported deployments models if those listed doesn't satisfy what you're after, a [full list is available here](https://coreos.com/docs/#running-coreos). Lots of choices and they're all deployed using something called a cloud-config.

Cloud-configs is are special files that let's you set machine parameters, launch services at start, configure the underlying hardware and so on, and is supported on several modern distributions such as Ubuntu, CentOS, CoreOS, RancherOS and more. If you haven't started looking at cloud-config yet you should [go read this](https://www.digitalocean.com/community/tutorials/an-introduction-to-cloud-config-scripting).

# Ease of use

When you first deploy CoreOS, you'll quickly realize that it's actually made to not login to. Ever. This is pretty interesting and makes you look at deploying this in your infrastructure in a different light as most existing infrastructure management tools require a login or agent running on the hosts, but that's not possible or suitable here. More distributions are looking at this way of deployment and management, and you should start to get used to it.

To manage CoreOS, you use utilities such as **etcd** (a great key/value store for service discovery) and **fleet** (a tool to manage the scheduling of services).

[etcd](https://coreos.com/docs/distributed-configuration/getting-started-with-etcd/) is a key-value store used for shared configuration and service discovery, and is used already when you establish and build out the CoreOS cluster. It can then be used for all kinds of purposes for your applications, such as storing information on how applications are linked together and how they are configured. There's also a [free online version of etcd](https://coreos.com/docs/cluster-management/setup/cluster-discovery/) that you can use when trying out CoreOS on Vagrant for instance.

[fleet](https://coreos.com/docs/launching-containers/launching/launching-containers-fleet/) is then used to start/stop/schedule services, actually talking to [systemd](https://coreos.com/docs/launching-containers/launching/getting-started-with-systemd) to start containers as services. fleet is used to create more than just single containers though, it can also run something called "global units" which are run on all servers, suitable for monitoring agents or parts of an orchestration system such as Kubernetes or Mesos.

# Documentation

CoreOS has almost an entire book published under their [docs site](https://coreos.com/docs/), and it's full of really great examples, howtos and customizations. I don't think I couldn't ask for more from a documentation standpoint, they've done a tremendous job making it accessible, easy to read and interesting.

# Integrations

CoreOS has a lot of 3rd party integrations already, from [logging](https://logentries.com/logentries-and-coreos-announce-real-time-log-management-and-analytics-integration-for-highly-distributed-environments/), [management](https://coreos.com/blog/coreos-just-got-easier-to-try-with-panamax/), [monitoring](https://www.datadoghq.com/2014/08/monitor-coreos-scale-datadog/), resource abstraction and orchestration using Mesos and Marathon for instance and more. It seems like a lot of companies and projects wants to be a part of the CoreOS ecosystem.

# Functionality

CoreOS is what you could call a mature container OS. It's currently being used by a large community, and the company behind it is focused on large scale deployments. It has a lot of functionality built into it that then ties into the integrations mentioned above, it has auto-updating of entire clusters, automatic clustering during deployment thanks to cloud-config and etcd etc. Lots of good stuff.

# Conclusion

If you haven't tried out CoreOS yet, I highly recommend you to do so. I would recommend to try it out locally using Vagrant, or by using any of cloud providers listed above.

Good luck and have fun!


text:
//
//  LoginViewController.m
//  走起WeakDay
//
//  Created by scjy on 16/1/15.
//  Copyright © 2016年 刘海艳. All rights reserved.
//

#import "LoginViewController.h"
#import <BmobSDK/Bmob.h>
@interface LoginViewController ()

@end

@implementation LoginViewController

- (IBAction)addOneDate:(id)sender{
    //往GameScore表添加一条playerName为小明,分数为78的数据
    BmobObject *user = [BmobObject objectWithClassName:@"MenberUser"];

    [user setObject:@"yiral" forKey:@"user_Name"];
    [user setObject:@16 forKey:@"user_age"];
    [user setObject:@"女" forKey:@"user_Gander"];
    [user setObject:@"18860233231" forKey:@"user_Phone"];

    [user saveInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
        //进行操作
        YiralLog(@"注册成功");
    }];

}

- (IBAction)delegateOneData:(id)sender{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"MenberUser"];
    [bquery getObjectInBackgroundWithId:@"078d783dad" block:^(BmobObject *object, NSError *error){
        if (error) {
            //进行错误处理
        }
        else{
            if (object) {
                //异步删除object
                [object deleteInBackground];
            }
        }
    }];

}
- (IBAction)changeData:(id)sender {
    //查找GameScore表
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"MenberUser"];
    //查找GameScore表里面id为0c6db13c的数据
    [bquery getObjectInBackgroundWithId:@"078d783dad" block:^(BmobObject *object,NSError *error){
        //没有返回错误
        if (!error) {
            //对象存在
            if (object) {
                BmobObject *obj1 = [BmobObject objectWithoutDatatWithClassName:object.className objectId:object.objectId];
                //设置cheatMode为YES
                [obj1 setObject:@"yanzi" forKey:@"user_Name"];
                //异步更新数据
                [obj1 updateInBackground];
            }
        }else{
            //进行错误处理
        }
    }];
}

- (IBAction)insertData:(id)sender {

    //查找GameScore表
    BmobQuery   *bquery = [BmobQuery queryWithClassName:@"MenberUser"];
    //查找GameScore表里面id为0c6db13c的数据
    [bquery getObjectInBackgroundWithId:@"671d67acc3" block:^(BmobObject *object,NSError *error){
        if (error){
            //进行错误处理
        }else{
            //表里有id为0c6db13c的数据
            if (object) {
                //得到playerName和cheatMode
                NSString *playerName = [object objectForKey:@"user_Name"];
                NSString *cellPhione = [object objectForKey:@"user_Phone"];
                NSLog(@"%@----%@",playerName,cellPhione);
            }
        }
    }];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self showBackButton];
}
-(void)backButtonAction:(UIButton *)button{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

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

/*
#pragma mark - Navigation

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

@end


text:
<!DOCTYPE HTML>

    $
A

B
$

  $

A

B

$


text:
import sys
import os
import re
from PIL import Image, ImageDraw
import json

def get_cmap():
  # Get the file Mapping
  cmap_filename = 'cmap.json'
  cmap_file = open(cmap_filename, 'r')
  cmap = json.load(cmap_file)
  cmap_file.close()
  return cmap

def write_cmap(cmap):
  cmap_filename = 'cmap.json'
  cmap_file = open(cmap_filename, 'w')
  cmap_file.write(json.dumps(cmap))
  cmap_file.close()

GLOBAL_LABEL = 0
def get_label(cmap, character_name):
  global GLOBAL_LABEL
  if character_name not in cmap:
    cmap[character_name] = GLOBAL_LABEL
    GLOBAL_LABEL += 1
  return cmap[character_name]

def get_image(filename):
  f = open(filename, 'r')
  x = None
  y = None
  start = False
  img = Image.new( 'RGB', (4392,4868), "black") # create a new black image
  draw = ImageDraw.Draw(img)

  for line in f:
    if 'CHARACTER_NAME:' in line:
      character_name = line[len('CHARACTER_NAME:'):].replace(' ', '').rstrip()
    if 'PEN_DOWN' in line:
      start = True
      x = None
      y = None
    if 'PEN_UP' in line:
      start = False
      x = None
      y = None
    if not start:
      continue
    m = re.match(r'[0-9]+ +[0-9]+ +[0-9]+ +[0-9]+\.?', line)
    if m is not None:
      l = str(m.group()).split()
      if x is not None:
        draw.line((int(l[0]), int(l[1]), x, y), fill=255, width=80)
      x = int(l[0])
      y = int(l[1])
  #img.show()
  return character_name, img

cmap = get_cmap()
LISTFILES = open('LISTFILES.txt', 'w')
for folder in range(1, 46):
  dir = 'W' + str(folder)
  for file in os.listdir(dir):
    character_name, img = get_image(dir + '/' + file)
    label = get_label(cmap, character_name)
    output_filename = dir + '/' + character_name + '.jpg'
    LISTFILES.write(output_filename + ' ' + str(label) + '\n')
    print(dir + '/' + file + ': ' + character_name + ' - ' + str(label))
    img.save(output_filename, 'JPEG')
write_cmap(cmap)
LISTFILES.close()


text:
class Profile;

namespace content {
class WebContents;
}  // namespace content

namespace apps {

using IconContentCallback = base::OnceCallback<void(std::string)>;

// SvgIconTranscoder uses WebContents to transform an svg icon (as a file or
// as string data) into an SkBitmap and thence into png compressed data which
// can be written to a png file. In principal, this technique should work for
// any data:image/ mime-types supported by WebContents, but svg is all we need
// right now. File handling happens in the browser process.
// Some validation of svg data is performed prior to asking a WebContents
// renderer process (which could potentially die on bad data) to render the
// image. Since a renderer process can be destroyed for many valid reasons,
// SvgIconTranscoder always checks if its WebContents must be recreated.
class SvgIconTranscoder : public content::RenderProcessHostObserver {
 public:
  explicit SvgIconTranscoder(Profile* profile);

  SvgIconTranscoder(const SvgIconTranscoder&) = delete;
  SvgIconTranscoder& operator=(const SvgIconTranscoder&) = delete;
  ~SvgIconTranscoder() override;

  // Reads the svg data at svg_path and invokes the string Transcode method.
  // |callback| is invoked with and empty string on failure. Blocking call.
  void Transcode(const base::FilePath&& svg_path,
                 const base::FilePath&& png_path,
                 gfx::Size preferred_size,
                 IconContentCallback callback);

  // Validates and trims the svg_data before base64 encoding and dispatching to
  // |web_contents_| in a data: URI.  |callback| is invoked with and empty
  // string on failure. Blocking call.
  void Transcode(const std::string& svg_data,
                 const base::FilePath&& png_path,
                 gfx::Size preferred_size,
                 IconContentCallback callback);

  base::WeakPtr<SvgIconTranscoder> GetWeakPtr() {
    return weak_ptr_factory_.GetWeakPtr();
  }

 private:
  void MaybeCreateWebContents();

  bool PrepareWebContents();

  void RemoveObserver();

  // content::RenderProcessHostObserver:
  void RenderProcessReady(content::RenderProcessHost* host) override;
  // content::RenderProcessHostObserver:
  void RenderProcessExited(
      content::RenderProcessHost* host,
      const content::ChildProcessTerminationInfo& info) override;

  // Compresses the first received bitmap and  saves compressed data to
  // |png_path| if non-empty. If the file can't be saved, that's not considered
  // and error. Next time lucky.
  void OnDownloadImage(base::FilePath png_path,
                       IconContentCallback callback,
                       int id,
                       int http_status_code,
                       const GURL& image_url,
                       const std::vector<SkBitmap>& bitmaps,
                       const std::vector<gfx::Size>& sizes);

  const raw_ptr<Profile, DanglingUntriaged> profile_;
  std::unique_ptr<content::WebContents> web_contents_;
  bool web_contents_ready_{false};
  base::WeakPtrFactory<SvgIconTranscoder> weak_ptr_factory_{this};
};

}  // namespace apps

#endif  // CHROME_BROWSER_ICON_TRANSCODER_SVG_ICON_TRANSCODER_H_


text:
package com.amazonaws.services.autoscaling.model;

import java.io.Serializable;

/**
 *
 */
public class DescribeScalingProcessTypesResult implements Serializable,
        Cloneable {

    /**
     *

     * The names of the process types.
     *

     */
    private com.amazonaws.internal.SdkInternalList<ProcessType> processes;

    /**
     *

     * The names of the process types.
     *

     *
     * @return The names of the process types.
     */
    public java.util.List<ProcessType> getProcesses() {
        if (processes == null) {
            processes = new com.amazonaws.internal.SdkInternalList<ProcessType>();
        }
        return processes;
    }

    /**
     *

     * The names of the process types.
     *

     *
     * @param processes
     *        The names of the process types.
     */
    public void setProcesses(java.util.Collection<ProcessType> processes) {
        if (processes == null) {
            this.processes = null;
            return;
        }

        this.processes = new com.amazonaws.internal.SdkInternalList<ProcessType>(
                processes);
    }

    /**
     *

     * The names of the process types.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setProcesses(java.util.Collection)} or
     * {@link #withProcesses(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param processes
     *        The names of the process types.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeScalingProcessTypesResult withProcesses(
            ProcessType... processes) {
        if (this.processes == null) {
            setProcesses(new com.amazonaws.internal.SdkInternalList<ProcessType>(
                    processes.length));
        }
        for (ProcessType ele : processes) {
            this.processes.add(ele);
        }
        return this;
    }

    /**
     *

     * The names of the process types.
     *

     *
     * @param processes
     *        The names of the process types.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeScalingProcessTypesResult withProcesses(
            java.util.Collection<ProcessType> processes) {
        setProcesses(processes);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getProcesses() != null)
            sb.append("Processes: " + getProcesses());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeScalingProcessTypesResult == false)
            return false;
        DescribeScalingProcessTypesResult other = (DescribeScalingProcessTypesResult) obj;
        if (other.getProcesses() == null ^ this.getProcesses() == null)
            return false;
        if (other.getProcesses() != null
                && other.getProcesses().equals(this.getProcesses()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getProcesses() == null) ? 0 : getProcesses().hashCode());
        return hashCode;
    }

    @Override
    public DescribeScalingProcessTypesResult clone() {
        try {
            return (DescribeScalingProcessTypesResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
This 4-bit adder takes advantage of the full adder module by taking four full adders and linking them together to add 2 four bit inputs. In the 4-bit adder, the first carry bit is set to zero because there is no initial carry bit as an input.

## Waveforms

Simulation results from the Verilog representation of this Four-Bit Ripple Adder

![Project%202%20Waveform%20for%20Four-Sixteen%20Decoder](/Project%202%20–%20Combinational%20Logic/four_bit_ripple_adder/Simulation%20Waveforms/project2_four_bit_adder.png)

## Source Files
- **Four-Bit Ripple Adder Module** - four_bit_adder.v
- **Four-Bit Ripple Adder Test Bench** - four_bit_adder_test.v


text:
package com.badlogic.gdx.tests;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.tests.utils.GdxTest;

public class ScrollPaneWithDynamicScrolling extends GdxTest {
	private Stage stage;
	private Table container;
	Label dynamicLabel;
	ScrollPane scrollPane;
	int count;

	public void create () {
		stage = new Stage();
		Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));
		Gdx.input.setInputProcessor(stage);

		dynamicLabel = new Label("Chat box begin here", skin);

		float chatWidth = 200;
		float controlHeight = 300;

		scrollPane = new ScrollPane(dynamicLabel, skin);

		Table main = new Table();

		main.setFillParent(true);

		TextButton btAdd = new TextButton("Add text and scroll down", skin);

		main.add(btAdd).row();
		main.add(scrollPane).size(200, 100);

		stage.addActor(main);

		stage.setDebugAll(true);

		btAdd.addListener(new ChangeListener() {
			@Override
			public void changed (ChangeEvent event, Actor actor) {
				dynamicLabel.setText(dynamicLabel.getText() + "\nline " + count++);
				scrollPane.scrollTo(0, 0, 0, 0);
			}
		});

	}

	public void render () {
		Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		stage.act(Gdx.graphics.getDeltaTime());
		stage.draw();
	}

	public void resize (int width, int height) {
		stage.getViewport().update(width, height, true);
	}

	public void dispose () {
		stage.dispose();
	}

	public boolean needsGL20 () {
		return false;
	}
}


text:
#import "NSInputStream.h"

@interface NSInputStream (NSInputStream)
+ (id)inputStreamWithURL:(id)arg1;
+ (id)inputStreamWithFileAtPath:(id)arg1;
+ (id)inputStreamWithData:(id)arg1;
+ (id)allocWithZone:(struct _NSZone *)arg1;
- (unsigned long long)_cfTypeID;
- (_Bool)hasBytesAvailable;
- (_Bool)getBuffer:(char **)arg1 length:(unsigned long long *)arg2;
- (long long)read:(char *)arg1 maxLength:(unsigned long long)arg2;
@end


text:
package com.amazonaws.services.elasticbeanstalk.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.elasticbeanstalk.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * DescribeEnvironmentHealthRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeEnvironmentHealthRequestMarshaller implements Marshaller<Request<DescribeEnvironmentHealthRequest>, DescribeEnvironmentHealthRequest> {

    public Request<DescribeEnvironmentHealthRequest> marshall(DescribeEnvironmentHealthRequest describeEnvironmentHealthRequest) {

        if (describeEnvironmentHealthRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<DescribeEnvironmentHealthRequest> request = new DefaultRequest<DescribeEnvironmentHealthRequest>(describeEnvironmentHealthRequest,
                "AWSElasticBeanstalk");
        request.addParameter("Action", "DescribeEnvironmentHealth");
        request.addParameter("Version", "2010-12-01");
        request.setHttpMethod(HttpMethodName.POST);

        if (describeEnvironmentHealthRequest.getEnvironmentName() != null) {
            request.addParameter("EnvironmentName", StringUtils.fromString(describeEnvironmentHealthRequest.getEnvironmentName()));
        }

        if (describeEnvironmentHealthRequest.getEnvironmentId() != null) {
            request.addParameter("EnvironmentId", StringUtils.fromString(describeEnvironmentHealthRequest.getEnvironmentId()));
        }

        if (!describeEnvironmentHealthRequest.getAttributeNames().isEmpty()
                || !((com.amazonaws.internal.SdkInternalList<String>) describeEnvironmentHealthRequest.getAttributeNames()).isAutoConstruct()) {
            com.amazonaws.internal.SdkInternalList<String> attributeNamesList = (com.amazonaws.internal.SdkInternalList<String>) describeEnvironmentHealthRequest
                    .getAttributeNames();
            int attributeNamesListIndex = 1;

            for (String attributeNamesListValue : attributeNamesList) {
                if (attributeNamesListValue != null) {
                    request.addParameter("AttributeNames.member." + attributeNamesListIndex, StringUtils.fromString(attributeNamesListValue));
                }
                attributeNamesListIndex++;
            }
        }

        return request;
    }

}


text:
package com.flipkart.flux.client.intercept;

import static com.flipkart.flux.client.constant.ClientConstants.CLIENT;
import static com.flipkart.flux.client.constant.ClientConstants._VERSION;
import static com.flipkart.flux.client.utils.TestUtil.dummyInvocation;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.flipkart.flux.api.EventData;
import com.flipkart.flux.api.StateMachineDefinition;
import com.flipkart.flux.client.config.FluxClientConfiguration;
import com.flipkart.flux.client.intercept.SimpleWorkflowForTest.IntegerEvent;
import com.flipkart.flux.client.intercept.SimpleWorkflowForTest.StringEvent;
import com.flipkart.flux.client.intercept.SimpleWorkflowForTest.StringEventWithContext;
import com.flipkart.flux.client.model.Event;
import com.flipkart.flux.client.runtime.FluxRuntimeConnector;
import com.flipkart.flux.client.runtime.LocalContext;
import java.lang.reflect.Method;
import java.util.Collection;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class WorkflowInterceptorTest {

    SimpleWorkflowForTest simpleWorkflowForTest = new SimpleWorkflowForTest();
    SimpleWorkflowForReplayTest simpleWorkflowForReplayTest = new SimpleWorkflowForReplayTest();

    @Mock
    LocalContext localContext;

    @Mock
    FluxRuntimeConnector fluxRuntimeConnector;

    @Mock
    FluxClientConfiguration fluxClientConfiguration;

    WorkflowInterceptor workflowInterceptor;
    private ObjectMapper objectMapper;

    @Before
    public void setUp() throws Exception {
        objectMapper = new ObjectMapper();
        workflowInterceptor = new WorkflowInterceptor(localContext, () -> fluxRuntimeConnector,
                () -> objectMapper, () -> fluxClientConfiguration);
    }

    @Test
    public void shouldRegisterNewDefinitionWithLocalContext() throws Throwable {
        final Method invokedMethod = simpleWorkflowForTest.getClass().getDeclaredMethod("simpleDummyWorkflow", StringEvent.class, IntegerEvent.class);
        workflowInterceptor.invoke(dummyInvocation(invokedMethod));
        final String expectedWorkflowIdentifer = new MethodId(invokedMethod).toString() + _VERSION + "1";
        Mockito.verify(localContext, times(1)).registerNew(expectedWorkflowIdentifer, 1,
                "", null, null);
    }

    @Test
    public void shouldSubmitNewDefinitionAfterMethodIsInvoked() throws Throwable {
        workflowInterceptor.invoke(dummyInvocation(simpleWorkflowForTest.getClass().getDeclaredMethod("simpleDummyWorkflow", StringEvent.class, IntegerEvent.class)));
        Mockito.verify(fluxRuntimeConnector, times(1)).submitNewWorkflow(any(StateMachineDefinition.class)); // Not verifying the actual state machine here, that is taken care in the e2e test. Besides, localContext is a mock anyway
    }

    @Test
    public void shouldRefreshLocalContext() throws Throwable {
        try {
            workflowInterceptor.invoke(dummyInvocation(simpleWorkflowForTest.getClass().getDeclaredMethod("badWorkflow")));
        } catch (IllegalSignatureException e) {
            // Expected
        }
        verify(localContext, times(1)).reset();
    }

    @Test(expected = IllegalSignatureException.class)
    public void shouldNotAllowWorkflowMethodsThatReturnAnything() throws Throwable {
        workflowInterceptor.invoke(dummyInvocation(simpleWorkflowForTest.getClass().getDeclaredMethod("badWorkflow")));
    }

    @Test
    public void testWorkflowInterception_WithActualParameters() throws Throwable {
        /* setup */
        final MutableInt getEventNameCall = new MutableInt(0);
        doAnswer(invocation -> {
            Event argument = (Event) invocation.getArguments()[0];
            final int currentValue = getEventNameCall.intValue();
            getEventNameCall.increment();
            return argument.name() + currentValue;
        }).when(localContext).generateEventName(any(Event.class));

        final Method invokedMethod = simpleWorkflowForTest.getClass().getDeclaredMethod("simpleDummyWorkflow", StringEvent.class, IntegerEvent.class);
        final StringEvent testStringEvent = new StringEvent("someEvent");
        final IntegerEvent testIntegerEvent = new IntegerEvent(1);
        /* invoke method */
        workflowInterceptor.invoke(dummyInvocation(invokedMethod, new Object[]{testStringEvent, testIntegerEvent}));
        /* verifications */
        verify(localContext, times(1)).addEvents(
                new EventData(SimpleWorkflowForTest.STRING_EVENT_NAME + "0", StringEvent.class.getName(), objectMapper.writeValueAsString(testStringEvent), CLIENT),
                new EventData(SimpleWorkflowForTest.INTEGER_EVENT_NAME + "1", IntegerEvent.class.getName(), objectMapper.writeValueAsString(testIntegerEvent), CLIENT)
        );
    }

    @Test
    public void testWorkflowInterception_WithActualParameters_WithContextId() throws Throwable {
        when(localContext.generateEventName(any(Event.class))).thenReturn("someNewEvent");

        final Method invokedMethod = simpleWorkflowForTest.getClass().getDeclaredMethod("simpleDummyWorkflowWithCorrelationEvent", StringEventWithContext.class, IntegerEvent.class);
        final StringEventWithContext testStringEvent = new StringEventWithContext("someString", "aContextId");
        final IntegerEvent testIntegerEvent = new IntegerEvent(1);

        /* invoke method */
        workflowInterceptor.invoke(dummyInvocation(invokedMethod, new Object[]{testStringEvent, testIntegerEvent}));
        /* verifications */
        verify(localContext, times(1)).registerNew(
                new MethodId(invokedMethod).toString() + _VERSION + "1", 1, "",
                "aContextId", null);
    }

    @Test(expected = IllegalSignatureException.class)
    public void testSignatureCheck_shouldNotAllowParamsThatAreNotEvents() throws Throwable {
        workflowInterceptor.invoke(dummyInvocation(SimpleWorkflowForTest.class.getDeclaredMethod("badWorkflowWithNonEventParams", String.class)));
    }

    @Test(expected = IllegalSignatureException.class)
    public void testSignatureCheck_shouldNotAllowCollections() throws Throwable {
        //TODO This is temporary. We should ideally accept collections of events
        workflowInterceptor.invoke(dummyInvocation(SimpleWorkflowForTest.class.getDeclaredMethod("badWorkflowWithCollectionOfEvents", Collection.class)));
    }

    @Test
    public void testSignatureCheck_shouldAllowVarArgMethods() throws Throwable {
        when(localContext.generateEventName(any(Event.class))).thenReturn("someName");
        final StringEvent wfParam1 = new StringEvent("foobar");
        final StringEvent wfParam2 = new StringEvent("foobar2");
        final MethodInvocation invocation = dummyInvocation(SimpleWorkflowForTest.class.getDeclaredMethod("simpleDummyWorkflow", StringEvent[].class), new Object[]{new StringEvent[]{wfParam1, wfParam2}});
        workflowInterceptor.invoke(invocation);
        verify(localContext, times(1)).registerNew(
                new MethodId(invocation.getMethod()).toString() + _VERSION + "1", 1l, "",
                null, null);
        final EventData expectedData1 = new EventData("someName" /*cuz were using mock localContext */, "com.flipkart.flux.client.intercept.SimpleWorkflowForTest$StringEvent", objectMapper.writeValueAsString(wfParam1), CLIENT);
        final EventData expectedData2 = new EventData("someName", "com.flipkart.flux.client.intercept.SimpleWorkflowForTest$StringEvent", objectMapper.writeValueAsString(wfParam2), CLIENT);
        verify(localContext, times(1)).addEvents(expectedData1, expectedData2);
    }
}


text:
/** Event In Connector
 *
 * @author Cedric Stoquer
 */
function EventInConnector(module, id, connectorDescription) {
	Connector.call(this, module, id, connectorDescription);
}
inherit(EventInConnector, Connector);
EventInConnector.prototype.connectorClassName = 'eventIn';
EventInConnector.prototype.color = ROOT.COLOR.EVENT;

EventInConnector.prototype.connect = function (connector) {
	// TODO: check connector type.
	// there is a "Maximum call stack size exceeded" bug if we try to connect 2 EventIn Connectors
	connector.connect(this);
};


text:
#include "config.h"
#include "WebViewEfl.h"

#include "DownloadManagerEfl.h"
#include "EwkView.h"
#include "InputMethodContextEfl.h"
#include "WebContextMenuProxyEfl.h"
#include "WebPopupMenuListenerEfl.h"
#include "ewk_context_private.h"
#include <WebCore/CoordinatedGraphicsScene.h>
#include <WebCore/PlatformContextCairo.h>

#if ENABLE(FULLSCREEN_API)
#include "WebFullScreenManagerProxy.h"
#endif

#if ENABLE(TOUCH_EVENTS)
#include "EwkTouchEvent.h"
#endif

using namespace EwkViewCallbacks;
using namespace WebCore;

namespace WebKit {

PassRefPtr<WebView> WebView::create(WebContext* context, WebPageGroup* pageGroup)
{
    return adoptRef(new WebViewEfl(context, pageGroup));
}

WebViewEfl::WebViewEfl(WebContext* context, WebPageGroup* pageGroup)
    : WebView(context, pageGroup)
    , m_ewkView(0)
{
}

void WebViewEfl::setEwkView(EwkView* ewkView)
{
    m_ewkView = ewkView;

#if ENABLE(FULLSCREEN_API)
    m_page->fullScreenManager()->setWebView(ewkView->evasObject());
#endif
}

void WebViewEfl::paintToCairoSurface(cairo_surface_t* surface)
{
    CoordinatedGraphicsScene* scene = coordinatedGraphicsScene();
    if (!scene)
        return;

    PlatformContextCairo context(cairo_create(surface));

    const FloatPoint& position = contentPosition();
    double effectiveScale = m_page->deviceScaleFactor() * contentScaleFactor();

    cairo_matrix_t transform = { effectiveScale, 0, 0, effectiveScale, - position.x() * m_page->deviceScaleFactor(), - position.y() * m_page->deviceScaleFactor() };
    cairo_set_matrix(context.cr(), &transform);
    scene->paintToGraphicsContext(&context);
}

PassRefPtr<WebPopupMenuProxy> WebViewEfl::createPopupMenuProxy(WebPageProxy* page)
{
    return WebPopupMenuListenerEfl::create(page);
}

PassRefPtr<WebContextMenuProxy> WebViewEfl::createContextMenuProxy(WebPageProxy* page)
{
    return WebContextMenuProxyEfl::create(m_ewkView, page);
}

void WebViewEfl::setCursor(const Cursor& cursor)
{
    m_ewkView->setCursor(cursor);
}

void WebViewEfl::updateTextInputState()
{
    if (InputMethodContextEfl* inputMethodContext = m_ewkView->inputMethodContext())
        inputMethodContext->updateTextInputState();
}

void WebViewEfl::handleDownloadRequest(DownloadProxy* download)
{
    EwkContext* context = m_ewkView->ewkContext();
    context->downloadManager()->registerDownloadJob(toAPI(download), m_ewkView);
}

void WebViewEfl::setThemePath(const String& theme)
{
    m_page->setThemePath(theme);
}

#if ENABLE(TOUCH_EVENTS)
void WebViewEfl::sendTouchEvent(EwkTouchEvent* touchEvent)
{
    ASSERT(touchEvent);
    m_page->handleTouchEvent(NativeWebTouchEvent(touchEvent, transformFromScene()));
}
#endif

} // namespace WebKit


text:
'use strict';

var isitholiday = require('../lib/isitholiday.js');

exports['constructor'] = {
  setUp: function(done) {
    function nextDayDate(d) {
      return new Date(d.getTime() + 86400 * 1000);
    }
    this.NO_HOLIDAY = new Date('2011-11-11');
    this.KNOWN_HOLIDAY = nextDayDate(this.NO_HOLIDAY);
    var exampleCalendar = [{
      "summary": "Some event",
      "start": this.KNOWN_HOLIDAY,

      "end": nextDayDate(this.KNOWN_HOLIDAY)

    }];
    this.fixtures = {
      'sampleArray': exampleCalendar,
      'sampleJSONFile': '../test/data/1.json',
    };
    done();
  },
  'should require data source on the constructor': function(test) {
    test.throws(function() {
      isitholiday.initialize();
    }, Error, 'initialize should raise if args missing');

    test.done();
  },
  'variants': {
    setUp: function(done) {
      this.testInitializationAndLookup = function(test, testSource, testDate) {
        var tmpHolidayDb,
          sourceVariant = Object.prototype.toString.call(testSource);
        test.doesNotThrow(function() {
          tmpHolidayDb = isitholiday.initialize(testSource);
        }, Error, 'initialize with ' + sourceVariant);

        test.doesNotThrow(function() {
          tmpHolidayDb.lookup(testDate);
        }, Error, 'lookup should be available with ' + sourceVariant);
        return tmpHolidayDb;
      };
      this.assertFindsKnownHoliday = function(test, testSource, testDate) {
        var holidayDb = this.testInitializationAndLookup(test, testSource, testDate);
        var result = holidayDb.lookup(testDate);
        test.notEqual(result, false);
        test.ok(result.summary);
        test.ok(result.start);
        test.ok(result.end);
      };
      this.assertCanLookupAnythingElse = function(test, testSource) {
        var holidayDb = this.testInitializationAndLookup(test, testSource, new Date());
        test.equal(holidayDb.lookup(), false);
        test.equal(holidayDb.lookup(''), false);
        test.equal(holidayDb.lookup(42), false);
        test.equal(holidayDb.lookup(this.NO_HOLIDAY), false);
      };
      done();
    },

    'should support an array of event objects': {
      'return event data for known holiday': function(test) {
        this.assertFindsKnownHoliday(test, this.fixtures.sampleArray, this.KNOWN_HOLIDAY);
        test.done();
      },
      'return false for anything else': function(test) {
        this.assertCanLookupAnythingElse(test, this.fixtures.sampleArray);
        test.done();
      },
    },
    'should accept a local JSON file as data source': {
      'return event data for known holiday': function(test) {
        this.assertFindsKnownHoliday(test, this.fixtures.sampleJSONFile, this.KNOWN_HOLIDAY);
        test.done();
      },
    },

  },

};


text:
namespace Ui {
class Q3BoundaryFixedVelocity;
}

class Q3BoundaryFixedVelocity : public Q3BoundaryType
{
    Q_OBJECT

public:
    explicit Q3BoundaryFixedVelocity(QWidget *parent = 0);
    ~Q3BoundaryFixedVelocity();

    QVector2D velocity(Q3SceletonItem *item,
                       const QPointF &a, const QPointF &b, qreal time);
    void setVelocityText(const QString &vText);

private:
    Ui::Q3BoundaryFixedVelocity *ui;
};

#endif // Q3BOUNDARYFIXEDVELOCITY_H


text:
"""Functions that ease the use of Django."""
# pylint: disable=protected-access
from __future__ import absolute_import

from django.utils.safestring import mark_safe

def get_fields(model_object, ignore_fields=()):
    """Extract the fields of the model.

    Args:
        model_object (django.models.Model): model instance.
        ignore_fields (list): list of field names to ignore.

    Returns:
        dict. dictionary contain the models's fields.
    """
    fields = [(field.name, getattr(model_object, field.name))
              for field in model_object._meta.fields
              if field.name not in ignore_fields and
              not field.name.endswith("_ptr")]

    fields += [(field.name, list(getattr(model_object, field.name).all()))
               for field in model_object._meta.many_to_many
               if field.name not in ignore_fields]

    return dict(fields)

def get_sub_model(model_object):
    """Return the model inherited sub class instance.

    Used as a workaround for Django subclasses issues

    Args:
        model_object (django.models.Model): model instance.

    Returns:
        object: sub model instance. None if there is no sub model.
    """
    for sub_class in model_object.__class__.__subclasses__():
        possible_atter = sub_class.__name__.lower()

        if hasattr(model_object, possible_atter):
            sub_model = getattr(model_object, possible_atter)
            sub_sub_model = get_sub_model(sub_model)

            if sub_sub_model is not None:
                return sub_sub_model

            return sub_model

    return None

def linked_unicode(item):
    """Return a unicode string with a HTML link to given item's page.

    Args:
        item (django.db.models.Model): a link to this item will be returned

    Returns:
        str. the result unicode text
    """
    app = item._meta.app_label
    pagename = item.__class__.__name__.lower()
    return mark_safe("%s" %
                     (app, pagename, item.id, item))


text: Tests audits support in WebInspector Extensions API


text:
class CreateNewsItems < ActiveRecord::Migration
  def self.up
    create_table :news_items do |t|
      t.string :title
      t.text :contents
      t.integer :created_by_id
      t.integer :updated_by_id

      t.timestamps
    end
  end

  def self.down
    drop_table :news_items
  end
end


text:
module Sem4r

  module ReportDefinitionAccountExtension

    #
    # Query the list of field for a report type
    # @param [ReportDefinition::ReportTypes] a value of
    #
    def report_fields(report_type)
      soap_message = service.report_definition.report_fields(credentials, report_type)
      add_counters(soap_message.counters)
      els = soap_message.response.xpath("//getReportFieldsResponse/rval")
      els.map do |el|
        ReportField.from_element(el)
      end
    end

    #
    # Delete a report definition
    #
    # @param[ReportDefinition, Number]
    #
    def report_definition_delete(repdef_or_id)
      if repdef_or_id.class == ReportDefinition
        report_definition = repdef_or_id
      else
        report_definition = ReportDefinition.new(self)
        report_definition.instance_eval { @id = repdef_or_id }
      end

      op           = ReportDefinitionOperation.remove(report_definition)
      soap_message = service.report_definition.mutate(credentials, op.to_xml)
      add_counters(soap_message.counters)

      unless @report_definitions
        @report_definition.delete_if { |repdef| repdef == report_definition.id }
      end
      report_definition.instance_eval { @id = -1 } # repdef status invalid/deleted
      self
    end

    #
    # Delete all report definition
    #
    def report_definition_delete_all
      report_definitions.each do |repdef|
        repdef.delete
      end
    end

    #
    # Create a new report definition
    # @yield report definition DSL
    # @return [ReportDefinition] in unsaved state
    #
    # @example
    #   account.report_definition do
    #     name "MyReport"
    #     ...
    #   end
    #
    def report_definition(&block)
      ReportDefinition.new(self, &block)
    end

    #
    # Prints on stdout the list of report definition contained into account
    # @param [bool] true if the list must be refreshed
    # @return self
    #
    def p_report_definitions(refresh = false)
      report_definitions(refresh).each do |report_definition|
        puts report_definition.to_s
      end
      self
    end

    #
    # Returns an array of ReportDefinition
    # @param [bool] true if the list must be refreshed
    # @return [Array of ReportDefinition]
    #
    def report_definitions(refresh = false)
      _report_definitions unless @report_definitions and !refresh
      @report_definitions
    end

    private

    def _report_definitions
      soap_message = service.report_definition.get(credentials, ReportDefinitionSelector.new.to_xml)
      add_counters(soap_message.counters)
      els                 = soap_message.response.xpath("//entries")
      @report_definitions = els.map do |el|
        ReportDefinition.from_element(self, el)
      end
    end

  end

  class Account
    include ReportDefinitionAccountExtension
  end

end


text:
package com.gooddata.sdk.model.md;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.gooddata.sdk.common.util.GoodDataToStringBuilder;

import java.io.Serializable;

/**
 * Key (primary/foreign) of attribute
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Key implements Serializable {

    private static final long serialVersionUID = -2014349746875945306L;
    private final String data;
    private final String type;

    @JsonCreator
    public Key(@JsonProperty("data") String data, @JsonProperty("type") String type) {
        this.data = data;
        this.type = type;
    }

    public String getData() {
        return data;
    }

    public String getType() {
        return type;
    }

    @Override
    public String toString() {
        return GoodDataToStringBuilder.defaultToString(this);
    }
}


text:
<?php

namespace Knp\DoctrineBehaviors\ORM\Tree;

use Knp\DoctrineBehaviors\Reflection\ClassAnalyzer;

use Knp\DoctrineBehaviors\ORM\AbstractSubscriber;

use Doctrine\ORM\Event\LoadClassMetadataEventArgs,
    Doctrine\ORM\Events,
    Doctrine\ORM\Mapping\ClassMetadata;

/**
 * Tree subscriber.
 *
 * Adds mapping to the tree entities.
 */
class TreeSubscriber extends AbstractSubscriber
{
    private $nodeTrait;

    public function __construct(ClassAnalyzer $classAnalyzer, $isRecursive, $nodeTrait)
    {
        parent::__construct($classAnalyzer, $isRecursive);

        $this->nodeTrait = $nodeTrait;
    }

    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $classMetadata = $eventArgs->getClassMetadata();

        if (null === $classMetadata->reflClass) {
            return;
        }

        if ($this->isTreeNode($classMetadata)) {

            if (!$classMetadata->hasField('materializedPath')) {
                $classMetadata->mapField(array(
                    'fieldName' => 'materializedPath',
                    'type'      => 'string',
                    'length'    => 255
                ));
            }
        }
    }

    public function getSubscribedEvents()
    {
        return [Events::loadClassMetadata];
    }

    /**
     * Checks if entity is a tree
     *
     * @param ClassMetadata $classMetadata The metadata
     *
     * @return Boolean
     */
    private function isTreeNode(ClassMetadata $classMetadata)
    {
        return $this->getClassAnalyzer()->hasTrait(
            $classMetadata->reflClass,
            $this->nodeTrait,
            $this->isRecursive
        );
    }
}


text:
<?php

namespace spec\Sylius\Bundle\VariationBundle\Form\Type;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Symfony\Component\OptionsResolver\OptionsResolver;

class OptionValueChoiceTypeSpec extends ObjectBehavior
{
    public function let()
    {
        $this->beConstructedWith('varibale_name');
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\VariationBundle\Form\Type\OptionValueChoiceType');
    }

    public function it_is_a_form_type()
    {
        $this->shouldImplement('Symfony\Component\Form\FormTypeInterface');
    }

    public function it_has_options(OptionsResolver $resolver)
    {
        $resolver->setDefaults(Argument::withKey('choice_list'))->shouldBeCalled()->willReturn($resolver);

        $resolver->setRequired(array(
            'option',
        ))->shouldBeCalled()->willReturn($resolver);

        $resolver->addAllowedTypes(array(
            'option' => 'Sylius\Component\Variation\Model\OptionInterface',
        ))->shouldBeCalled()->willReturn($resolver);

        $this->setDefaultOptions($resolver);
    }

    public function it_has_a_parent()
    {
        $this->getParent()->shouldReturn('choice');
    }

    public function it_has_a_name()
    {
        $this->getName()->shouldReturn('sylius_varibale_name_option_value_choice');
    }
}


text:
/**
 * @overview
 * This file contains the address book class.
 */

/**
 * Creates an address book.
 * @constructor
 * @class
 * This class represents an address book.
 *
 * @author Parag Shah
 *
 * @param	{Hash}	params		a hash of parameters
 * @param {int}	params.id			a numeric ID
 * @param {String}	params.name		[string]	the name
 * @param {ZmOrganizer}	params.parent		the parent organizer
 * @param {ZmTree}	params.tree		a tree model that contains this organizer
 * @param {int}	params.color		the color of this address book
 * @param {String}	params.owner	the owner of the address book (if shared)
 * @param {String}	params.zid 		the the share ID of a shared address book
 * @param {String}	params.rid		the the remote folder id of a shared address book
 * @param {String}	params.restUrl	the REST URL of this organizer
 *
 * @extends		ZmFolder
 */
ZmAddrBook = function(params) {
	params.type = ZmOrganizer.ADDRBOOK;
	ZmFolder.call(this, params);
};

ZmAddrBook.prototype = new ZmFolder;
ZmAddrBook.prototype.constructor = ZmAddrBook;

// Consts

ZmAddrBook.ID_ADDRESSBOOK = ZmOrganizer.ID_ADDRBOOK; 							// XXX: may not be necessary

// Static methods

/**
 * Sorts the address books.
 *
 * @param	{ZmAddrBook}	addrBookA		the address book
 * @param	{ZmAddrBook}	addrBookB		the address book
 * @return	{int}	0 if the address books are the same; 1 if "a" is before "b"; -1 if "b" is before "a"
 */
ZmAddrBook.sortCompare =
function(addrBookA, addrBookB) {
	var check = ZmOrganizer.checkSortArgs(addrBookA, addrBookB);
	if (check != null) return check;

	// links appear after personal address books
	if (addrBookA.link != addrBookB.link) {
		return addrBookA.link ? 1 : -1;
	}

	// trash folder should always go last w/in personal addrbooks
	if (addrBookA.nId == ZmFolder.ID_TRASH) { return 1; }
	if (addrBookB.nId == ZmFolder.ID_TRASH) { return -1; }

	// sort by calendar name
	var addrBookAName = addrBookA.name.toLowerCase();
	var addrBookBName = addrBookB.name.toLowerCase();
	if (addrBookAName < addrBookBName) { return -1; }
	if (addrBookAName > addrBookBName) { return 1; }
	return 0;
};

// Public methods

/**
 * Returns a string representation of the object.
 *
 * @return		{String}		a string representation of the object
 */
ZmAddrBook.prototype.toString =
function() {
	return "ZmAddrBook";
};

ZmAddrBook.prototype.getIcon =
function() {
	if (this.nId == ZmFolder.ID_ROOT)			{ return null; }
	if (this.nId == ZmFolder.ID_TRASH)			{ return "Trash"; }
	if (this.link || this.isRemote())			{ return "SharedContactsFolder"; }
	if (this.nId == ZmFolder.ID_AUTO_ADDED)		{ return "EmailedContacts"; }
	return "ContactsFolder";
};

/**
 * Checks if the address book supports public access.
 *
 * @return	{Boolean}		always returns true
 */
ZmAddrBook.prototype.supportsPublicAccess =
function() {
	// AddrBook's can be accessed outside of ZCS (i.e. REST)
	return true;
};

/**
 * @private
 */
ZmAddrBook.prototype.mayContain =
function(what) {
	if (!what) return true;

	if (this.id == ZmOrganizer.ID_DLS) {
		return false;
	}

	if (what instanceof ZmAddrBook) {
		if (this.link) {
			return false; //can't move a folder to a shared folder, regardless of read-only status
		}
		if (!appCtxt.multiAccounts) {
			return true;
		}
		return this.mayContainFolderFromAccount(what.getAccount()); // cannot move folders across accounts, unless the target is local
	}

	if (this.nId == ZmOrganizer.ID_ROOT) {
		// cannot drag anything onto root folder
		return false;
	}
	if (this.link) {
		// cannot drop anything onto a read-only addrbook
		if (this.isReadOnly()) {
			return false;
		}
	}

	// An item or an array of items is being moved
	var items = (what instanceof Array) ? what : [what];
	var item = items[0];

	if (item.type != ZmItem.CONTACT && item.type != ZmItem.GROUP) {
		// only contacts are valid for addr books.
		return false;
	}

	// can't move items to folder they're already in; we're okay if
	// we have one item from another folder
	if (item.folderId) {
		var invalid = true;
		for (var i = 0; i < items.length; i++) {
			var tree = appCtxt.getById(items[i].folderId);
			if (tree != this) {
				invalid = false;
				break;
			}
		}

		return !invalid;
	}

	return true;
};


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
    internal static class ConversionExtensions
    {
        public static bool IsIdentityOrImplicitReference(this Conversion conversion)
        {
            return conversion.IsIdentity ||
                (conversion.IsImplicit && conversion.IsReference);
        }

        public static bool IsImplicitUserDefinedConversion(this Conversion conversion)
        {
            return conversion.IsUserDefined &&
                conversion.MethodSymbol != null &&
                conversion.MethodSymbol.MethodKind == MethodKind.Conversion &&
                conversion.MethodSymbol.Name == "op_Implicit";
        }
    }
}


text:
import("core.base.filter")
import("core.base.option")
import("core.base.global")
import("core.project.config")
import("core.project.project")
import("core.sandbox.sandbox")

-- get filter
function _filter()

    -- init filter
    if _g.filter == nil then
        _g.filter = filter.new()
        _g.filter:register("common", function (variable)

            -- attempt to get it directly from the configure
            local result = config.get(variable)
            if result == nil then

                -- init maps
                _g.common_maps = _g.common_maps or
                {
                    host        = os.host()
                ,   subhost     = os.subhost()
                ,   tmpdir      = function () return os.tmpdir() end
                ,   curdir      = function () return os.curdir() end
                ,   scriptdir   = function () return os.scriptdir() end
                ,   globaldir   = global.directory()
                ,   configdir   = config.directory()
                ,   projectdir  = project.directory()
                ,   programdir  = os.programdir()
                }

                -- map it
                result = _g.common_maps[variable]
            end

            -- is script? call it
            if type(result) == "function" then
                result = result()
            end

            -- ok?
            return result
        end)
    end

    -- ok
    return _g.filter
end

-- the package handler
function _handler(package, strval)

    -- @note cannot cache it, because the package instance will be changed
    return function (variable)

        -- init maps
        local maps =
        {
            version = function ()
                if strval then
                    -- set_urls("https://sqlite.org/2018/sqlite-autoconf-$(version)000.tar.gz",
                    --          {version = function (version) return version:gsub("%.", "") end})
                    local version_filter = package:url_version(strval)
                    if version_filter then
                        return version_filter(package:version_str())
                    end
                end
                return package:version_str()
            end
        }

        -- get value
        local result = maps[variable]
        if type(result) == "function" then
            result = result()
        end

        -- ok?
        return result
    end
end

-- attach filter to the given script and call it
function call(script, package)

    -- get sandbox filter and handlers of the given script
    local sandbox_filter   = sandbox.filter(script)
    local sandbox_handlers = sandbox_filter:handlers()

    -- switch to the handlers of the current filter
    sandbox_filter:set_handlers(_filter():handlers())

    -- register package handler
    sandbox_filter:register("package", _handler(package))

    -- call it
    script(package)

    -- restore handlers
    sandbox_filter:set_handlers(sandbox_handlers)
end

-- handle the string value of package
function handle(strval, package)

    -- register filter handler
    _filter():register("package", _handler(package, strval))

    -- handle string value
    strval = _filter():handle(strval)

    -- register filter handler
    _filter():register("package", nil)

    -- ok
    return strval
end