text:
package org.gradle.execution;

import com.google.common.collect.ImmutableSet;
import org.gradle.internal.deprecation.DeprecationLogger;
import org.gradle.internal.execution.UnitOfWork;
import org.gradle.internal.execution.steps.ValidateStep;
import org.gradle.internal.reflect.validation.TypeValidationProblem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static org.gradle.internal.reflect.validation.TypeValidationProblemRenderer.convertToSingleLine;
import static org.gradle.internal.reflect.validation.TypeValidationProblemRenderer.renderMinimalInformationAbout;

public class DefaultWorkValidationWarningRecorder implements ValidateStep.ValidationWarningRecorder, WorkValidationWarningReporter {
    private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWorkValidationWarningRecorder.class);

    private final AtomicInteger workWithFailuresCount = new AtomicInteger();

    @Override
    public void recordValidationWarnings(UnitOfWork work, Collection<TypeValidationProblem> warnings) {
        workWithFailuresCount.incrementAndGet();

        ImmutableSet<String> uniqueWarnings = warnings.stream().map(warning -> convertToSingleLine(renderMinimalInformationAbout(warning, true, false))).collect(ImmutableSet.toImmutableSet());
        LOGGER.warn("Execution optimizations have been disabled for {} to ensure correctness due to the following reasons:{}",
            work.getDisplayName(),
            uniqueWarnings.stream()
                .map(warning -> "\n  - " + warning)
                .collect(Collectors.joining()));
        warnings.forEach(warning -> DeprecationLogger.deprecateBehaviour(convertToSingleLine(renderMinimalInformationAbout(warning, false, false)))
            .withContext("Execution optimizations are disabled to ensure correctness.")
            .willBeRemovedInGradle9()
            .withUserManual(warning.getUserManualReference().getId(), warning.getUserManualReference().getSection())
            .nagUser()
        );
    }

    @Override
    public void reportWorkValidationWarningsAtEndOfBuild() {
        int workWithFailures = workWithFailuresCount.getAndSet(0);
        if (workWithFailures > 0) {
            LOGGER.warn(
                "\nExecution optimizations have been disabled for {} invalid unit(s) of work during this build to ensure correctness." +
                "\nPlease consult deprecation warnings for more details.",
                workWithFailures
            );
        }
    }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataMock = void 0;
var itemcollection_mock_1 = require("../collection/itemcollection/itemcollection.mock");
var DataMock = /** @class */ (function () {
    function DataMock(entity, process) {
        this.attributes = new itemcollection_mock_1.ItemCollectionMock();
        this.entity = entity;
        this.process = process;
        this.loadEventHandlers = [];
    }
    DataMock.prototype.refresh = function (save) {
        throw new Error(("refresh not implemented"));
    };
    DataMock.prototype.save = function (saveOptions) {
        throw new Error(("save not implemented"));
    };
    DataMock.prototype.isValid = function () {
        throw new Error(("isValid not implemented"));
    };
    DataMock.prototype.getIsDirty = function () {
        throw new Error(("getIsDirty not implemented"));
    };
    DataMock.prototype.addOnLoad = function (handler) {
        this.loadEventHandlers.push(handler);
    };
    DataMock.prototype.removeOnLoad = function (handler) {
        var index = this.loadEventHandlers.indexOf(handler);
        this.loadEventHandlers.splice(index);
    };
    return DataMock;
}());
exports.DataMock = DataMock;
//# sourceMappingURL=data.mock.js.map

redpajama_set_name: RedPajamaGithub


text:
"""Tests for arithmetic transforms."""

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

import numpy as np
import tensorflow as tf

from tensorflow.contrib.learn.python.learn.dataframe import tensorflow_dataframe as df

# pylint: disable=g-import-not-at-top
try:
  import pandas as pd
  HAS_PANDAS = True
except ImportError:
  HAS_PANDAS = False

class SumTestCase(tf.test.TestCase):
  """Test class for `Sum` transform."""

  def testSum(self):
    if not HAS_PANDAS:
      return
    num_rows = 100

    pandas_df = pd.DataFrame({"a": np.arange(num_rows),
                              "b": np.arange(num_rows, 2 * num_rows)})

    frame = df.TensorFlowDataFrame.from_pandas(
        pandas_df, shuffle=False, batch_size=num_rows)

    frame["a+b"] = frame["a"] + frame["b"]

    expected_sum = pandas_df["a"] + pandas_df["b"]
    actual_sum = frame.run_once()["a+b"]
    np.testing.assert_array_equal(expected_sum, actual_sum)

if __name__ == "__main__":
  tf.test.main()


text:
namespace SW
{
	RNDefineMeta(PickupEntity, RN::Entity)

	PickupEntity::PickupEntity(const std::string filename, ITEM_TYPE type)
	: _type(type)
	{
		RN::Model *model = RN::Model::WithFile(filename);
		SetModel(model);

		Initialize();
	}

	PickupEntity::PickupEntity(RN::Deserializer *deserializer)
	: RN::Entity(deserializer)
	{

		Initialize();
	}

	void PickupEntity::Initialize()
	{

	}

	void PickupEntity::Serialize(RN::Serializer *serializer)
	{
		Entity::Serialize(serializer);
	}

	void PickupEntity::Update(float delta)
	{
		if(GetWorldPosition().GetDistance(Player::GetSharedInstance()->GetWorldPosition()) < 1.0f)
		{
			// Pick up
			RemoveFromWorld();
			Player::GetSharedInstance()->PickUpItem(_type);
		}
	}
}


text:
#ifndef SPINE_ATTACHMENT_H_
#define SPINE_ATTACHMENT_H_

#ifdef __cplusplus
namespace spine {
extern "C" {
#endif

struct Slot;

typedef enum {
	ATTACHMENT_REGION, ATTACHMENT_REGION_SEQUENCE
} AttachmentType;

typedef struct Attachment Attachment;
struct Attachment {
	const char* const name;
	AttachmentType type;

	const void* const vtable;
};

void Attachment_dispose (Attachment* self);

#ifdef __cplusplus
}
}
#endif

#endif /* SPINE_ATTACHMENT_H_ */


text:
<bill session="110" type="s" number="54" updated="2009-01-09T11:14:17-05:00">
	<status><introduced date="1167886800" datetime="2007-01-04"/></status>

	<introduced date="1167886800" datetime="2007-01-04"/>
	<titles>
		<title type="short" as="introduced">Nursing School Clinics Act of 2007</title>
		<title type="official" as="introduced">A bill to amend title XIX of the Social Security Act to provide for coverage of services provided by nursing school clinics under State medicaid programs.</title>
	</titles>
	<sponsor id="300056"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1167886800" datetime="2007-01-04"><text>Sponsor introductory remarks on measure. (CR S73)</text></action>
		<action date="1167886800" datetime="2007-01-04"><text>Read twice and referred to the Committee on Finance.</text><reference label="text of measure as introduced" ref="CR S73"/></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	1/4/2007--Introduced.<br/>Nursing School Clinics Act of 2007 - Amends title XIX (Medicaid) of the Social Security Act to provide for coverage of nursing school clinic services.
	</summary>
</bill>


text:
<!DOCTYPE html>
<body>
<script src="../resources/js-test.js"></script>
<script>
    description("Basic test for 'gamepadconnected' and 'gamepaddisconnected' events.");

    jsTestIsAsync = true;

    if (window.gamepadController)
    {
        function onConnected(event) {
            debug("Gamepad connected");
            shouldBe("event.__proto__", "GamepadEvent.prototype");
            shouldBe("event.__proto__.__proto__", "Event.prototype");
            shouldBeEqualToString("event.gamepad.id", "MockStick 3000");
            shouldBe("event.gamepad.buttons.length", "3");
            shouldBe("event.gamepad.axes.length", "3");
            shouldBe("event.gamepad.buttons[0].value", "1.0");
            shouldBeTrue("event.gamepad.buttons[0].pressed");
            shouldBe("event.gamepad.buttons[1].value", "0.0");
            shouldBeFalse("event.gamepad.buttons[1].pressed");
            shouldBe("event.gamepad.axes.length", "3");
            shouldBe("event.gamepad.buttons[2].value", "0.333333");
            shouldBeTrue("event.gamepad.buttons[2].pressed");
            shouldBe("event.gamepad.axes[0]", "0.5");
            shouldBe("event.gamepad.axes[1]", "-1.0");
            shouldBe("event.gamepad.axes[2]", "0.333333");
            gamepadController.disconnect(0);
        }

        function onDisconnected(event) {
            debug("Gamepad disconnected");
            shouldBe("event.__proto__", "GamepadEvent.prototype");
            shouldBe("event.__proto__.__proto__", "Event.prototype");
            shouldBeEqualToString("event.gamepad.id", "MockStick 3000");
            shouldBe("event.gamepad.buttons.length", "3");
            shouldBe("event.gamepad.axes.length", "3");
            finishJSTest();
        }

        window.addEventListener('gamepadconnected', onConnected);
        window.addEventListener('gamepaddisconnected', onDisconnected);

        gamepadController.connect(0);
        gamepadController.setId(0, "MockStick 3000");
        gamepadController.setButtonCount(0, 3);
        gamepadController.setAxisCount(0, 3);
        gamepadController.setButtonData(0, 0, 1);
        gamepadController.setButtonData(0, 1, 0);
        gamepadController.setButtonData(0, 2, 0.333333);
        gamepadController.setAxisData(0, 0, .5);
        gamepadController.setAxisData(0, 1, -1.0);
        gamepadController.setAxisData(0, 2, 0.333333);
        gamepadController.dispatchConnected(0);
    }
    else
    {
        testFailed("no gamepadController available.");
    }
</script>
</body>


text:
.. PyRadmon documentation master file, created by
   sphinx-quickstart on Wed Jun 18 10:24:49 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

PyRadmon Documentation
====================================

.. module:: pyradmon

.. warning::

   This documentation is currently under construction. Significant
   changes to the documentation are possible!

**PyRadmon** is a radiance monitoring tool written completely in
**Python**.

Quick Start
-----------
Want to get a head start on using **PyRadmon**? Get going!

:doc:`userdocs/getting-started`

Contents
--------
.. toctree::
   :maxdepth: 2

   userdocs/introduction
   userdocs/getting-pyradmon
   userdocs/getting-started
   modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2021 Jiang Yin. All rights reserved.
// Homepage: https://gameframework.cn/
// Feedback: mailto:ellan@gameframework.cn
//------------------------------------------------------------

namespace GameFramework.Entity
{
    /// <summary>
    /// 显示实体成功事件。
    /// </summary>
    public sealed class ShowEntitySuccessEventArgs : GameFrameworkEventArgs
    {
        /// <summary>
        /// 初始化显示实体成功事件的新实例。
        /// </summary>
        public ShowEntitySuccessEventArgs()
        {
            Entity = null;
            Duration = 0f;
            UserData = null;
        }

        /// <summary>
        /// 获取显示成功的实体。
        /// </summary>
        public IEntity Entity
        {
            get;
            private set;
        }

        /// <summary>
        /// 获取加载持续时间。
        /// </summary>
        public float Duration
        {
            get;
            private set;
        }

        /// <summary>
        /// 获取用户自定义数据。
        /// </summary>
        public object UserData
        {
            get;
            private set;
        }

        /// <summary>
        /// 创建显示实体成功事件。
        /// </summary>
        /// <param name="entity">加载成功的实体。</param>
        /// <param name="duration">加载持续时间。</param>
        /// <param name="userData">用户自定义数据。</param>
        /// <returns>创建的显示实体成功事件。</returns>
        public static ShowEntitySuccessEventArgs Create(IEntity entity, float duration, object userData)
        {
            ShowEntitySuccessEventArgs showEntitySuccessEventArgs = ReferencePool.Acquire<ShowEntitySuccessEventArgs>();
            showEntitySuccessEventArgs.Entity = entity;
            showEntitySuccessEventArgs.Duration = duration;
            showEntitySuccessEventArgs.UserData = userData;
            return showEntitySuccessEventArgs;
        }

        /// <summary>
        /// 清理显示实体成功事件。
        /// </summary>
        public override void Clear()
        {
            Entity = null;
            Duration = 0f;
            UserData = null;
        }
    }
}


text:
from os.path import dirname

from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill
from mycroft.util.log import getLogger

__author__ = 'chrisl8'
# Based on helloworld by eward

LOGGER = getLogger(__name__)

class SmallTalkSkill(MycroftSkill):

    def __init__(self):
        super(SmallTalkSkill, self).__init__(name="SmallTalkSkill")

    def initialize(self):
        self.load_data_files(dirname(__file__))

        # thank_you_intent = IntentBuilder("ThankYouIntent").\
        #     require("ThankYouKeyword").build()
        # self.register_intent(thank_you_intent, self.handle_thank_you_intent)
        #
        # how_are_you_intent = IntentBuilder("HowAreYouIntent").\
        #     require("HowAreYouKeyword").build()
        # self.register_intent(how_are_you_intent,
        #                      self.handle_how_are_you_intent)

        hi_intent = IntentBuilder("HiIntent").\
            require("HiKeyword").build()
        self.register_intent(hi_intent,
                             self.handle_hi_intent)

        good_morning_intent = IntentBuilder("GoodMorningIntent"). \
            require("GoodMorningKeyword").build()
        self.register_intent(good_morning_intent,
                             self.handle_good_morning_intent)

    # def handle_thank_you_intent(self, message):
    #     self.speak_dialog("welcome")
    #
    # def handle_how_are_you_intent(self, message):
    #     self.speak_dialog("how.are.you")

    def handle_hi_intent(self, message):
        self.speak_dialog("hi")

    def handle_good_morning_intent(self, message):
        self.speak_dialog("good.morning")

    def stop(self):
        pass

def create_skill():
    return SmallTalkSkill()


text:
A Clojure client library for the
[Redis](http://code.google.com/p/redis) key value storage system.

## Dependencies

To use redis-clojure, you'll need:

* The [Clojure](http://clojure.org) programming language
* The [Clojure-Contrib](http://code.google.com/p/clojure-contrib) library (for running the tests)

## Building

To build redis-clojure:

    ant -Dclojure.jar=/path/to/clojure.jar

This will build `redis-clojure.jar`.

## Running tests

To run tests:

    ant -Dclojure.jar=/path/to/clojure.jar -Dclojure-contrib.jar=/path/to/clojure-contrib.jar test

*Note* you need to have `redis-server` running first.

## Using

To use redis-clojure in your application, simply make sure either
`redis-clojure.jar` or the contents of the `src/` directory is on your
classpath.

This can be accomplished like so:

    (add-classpath "file:///path/to/redis-clojure.jar")

## Examples

Check the `examples/` directory.

*Note* you need to have `redis-server` running first.

## Todo

* Work on performance
* Maybe implement pipelining


text:
const jwt = require("jsonwebtoken");
const User = require("../../../models/user");
const getReturnUrl = require("../../../lib/getReturnUrl");
const mongoose = require("mongoose");

const express = require("express");
const router = express.Router();

const passport = require("passport");
const Strategy = require("passport-google-oauth20").Strategy;

passport.use(
  new Strategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: `/v1/sign-in/google/callback`
    },
    (token, refreshToken, profile, cb) => {
      process.nextTick(() => {
        User.findOrCreate(profile)
          .then(user => {
            return cb(null, user);
          })
          .catch(err => {
            return cb(null, err);
          });
      });
    }
  )
);

router.get(
  "/google/callback",
  passport.authenticate("google", {
    failureRedirect: "/google",
    session: false
  }),
  (req, res) => {
    let jti = mongoose.Types.ObjectId();
    let token = jwt.sign(
      { jti: jti, sub: req.user._id },
      process.env.SECRET_KEY,
      { expiresIn: "30d" }
    );
    return res.redirect(
      `${req.session.returnUrl}/sign-in/callback?access_token=${token}`
    );
  }
);
router.get(
  "/:id/google",
  getReturnUrl,
  passport.authenticate("google", {
    scope: ["profile", "email"],
    session: false
  })
);

module.exports = router;


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

<title>com.snakybo.torch.queue (Torch Engine 1.0 API)</title>
<meta name="date" content="2016-08-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

com.snakybo.torch.queue

Interfaces

IQueueProcessor

Classes

QueueProcessor

Enums

QueueOperation


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
    <meta name="description" content="Construct polygons from a set of points, an rectangle, or a nested hierarchy and apply materials to them.">
    <meta name="cesium-sandcastle-labels" content="Development">
    <title>Cesium Demo</title>

Loading...


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.

/*++

Module Name:

    filecrt.cpp

Abstract:

    Implementation of the file functions in the C runtime library that
    are Windows specific.

--*/

#include "pal/thread.hpp"
#include "pal/file.hpp"

#include "pal/palinternal.h"
#include "pal/dbgmsg.h"
#include "pal/file.h"
#include "pal/cruntime.h"

#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>

#ifdef __APPLE__
#include <sys/syscall.h>
#endif // __APPLE__

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(CRT);

/*++
Function:
  _open_osfhandle

See MSDN doc.
--*/
int
__cdecl
_open_osfhandle( INT_PTR osfhandle, int flags )
{
    PAL_ERROR palError = NO_ERROR;
    CPalThread *pthrCurrent = NULL;
    IPalObject *pobjFile = NULL;
    CFileProcessLocalData *pLocalData = NULL;
    IDataLock *pDataLock = NULL;
    INT nRetVal = -1;
    INT openFlags = 0;

    PERF_ENTRY(_open_osfhandle);
    ENTRY( "_open_osfhandle (osfhandle=%#x, flags=%#x)\n", osfhandle, flags );

    pthrCurrent = InternalGetCurrentThread();

    if (flags != _O_RDONLY)
    {
        ASSERT("flag(%#x) not supported\n", flags);
        goto EXIT;
    }

    openFlags |= O_RDONLY;

    palError = g_pObjectManager->ReferenceObjectByHandle(
        pthrCurrent,
        reinterpret_cast<HANDLE>(osfhandle),
        &aotFile,
        0,
        &pobjFile
        );

    if (NO_ERROR != palError)
    {
        ERROR("Error dereferencing file handle\n");
        goto EXIT;
    }

    palError = pobjFile->GetProcessLocalData(
        pthrCurrent,
        ReadLock,
        &pDataLock,
        reinterpret_cast<void **>(&pLocalData)
        );

    if (NO_ERROR == palError)
    {
        if (NULL != pLocalData->unix_filename)
        {
            nRetVal = InternalOpen(pLocalData->unix_filename, openFlags);
        }
        else /* the only file object with no unix_filename is a pipe */
        {
            /* check if the file pipe descrptor is for read or write */
            if (pLocalData->open_flags == O_WRONLY)
            {
                ERROR( "Couldn't open a write pipe on read mode\n");
                goto EXIT;
            }

            nRetVal = pLocalData->unix_fd;
        }

        if ( nRetVal == -1 )
        {
            ERROR( "Error: %s.\n", strerror( errno ) );
        }
    }
    else
    {
        ASSERT("Unable to access file data");
    }

EXIT:

    if (NULL != pDataLock)
    {
        pDataLock->ReleaseLock(pthrCurrent, FALSE);
    }

    if (NULL != pobjFile)
    {
        pobjFile->ReleaseReference(pthrCurrent);
    }

    LOGEXIT( "_open_osfhandle return nRetVal:%d\n", nRetVal);
    PERF_EXIT(_open_osfhandle);
    return nRetVal;
}

/*++
Function:
    PAL_fflush

See MSDN for more details.
--*/
int
_cdecl
PAL_fflush( PAL_FILE *stream )
{
    int nRetVal = 0;

    PERF_ENTRY(fflush);
    ENTRY( "fflush( %p )\n", stream );

    nRetVal = fflush(stream ? stream->bsdFilePtr : NULL);

    LOGEXIT( "fflush returning %d\n", nRetVal );
    PERF_EXIT(fflush);
    return nRetVal;
}

/*++
PAL__getcwd

Wrapper function for getcwd.

Input parameters:

szBuf = a copy of the absolute pathname of the current working directory
is copied into szBuf.
nSize = size, in bytes, of the array referenced by szBuf.

Return value:
    A pointer to the pathname if successful, otherwise NULL is returned
--*/
char *
__cdecl
PAL__getcwd(
    char *szBuf,
    size_t nSize
    )
{
    return (char *)getcwd(szBuf, nSize);
}

/*++
PAL_mkstemp

Wrapper function for InternalMkstemp.

Input parameters:

szNameTemplate = template to follow when naming the created file

Return value:
    Open file descriptor on success, -1 if file could not be created
--*/
int
__cdecl
PAL_mkstemp(char *szNameTemplate)
{
    return InternalMkstemp(szNameTemplate);
}

/*++
InternalMkstemp

Wrapper for mkstemp.

Input parameters:

szNameTemplate = template to follow when naming the created file

Return value:
    Open file descriptor on success, -1 if file could not be created
--*/
int
CorUnix::InternalMkstemp(
    char *szNameTemplate
    )
{
    int nRet = -1;
#if MKSTEMP64_IS_USED_INSTEAD_OF_MKSTEMP
    nRet = mkstemp64(szNameTemplate);
#else
    nRet = mkstemp(szNameTemplate);
#endif
    return nRet;
}

/*++
PAL__open

Wrapper function for InternalOpen.

Input parameters:

szPath = pointer to a pathname of a file to be opened
nFlags = arguments that control how the file should be accessed
mode = file permission settings that are used only when a file is created

Return value:
    File descriptor on success, -1 on failure
--*/
int
__cdecl
PAL__open(
    const char *szPath,
    int nFlags,
    ...
    )
{
    int nRet = -1;
    int mode = 0;
    va_list ap;

    // If nFlags does not contain O_CREAT, the mode parameter will be ignored.
    if (nFlags & O_CREAT)
    {
        va_start(ap, nFlags);
        mode = va_arg(ap, int);
        va_end(ap);
    }

    nRet = InternalOpen(szPath, nFlags, mode);
    return nRet;
}

/*++
InternalOpen

Wrapper for open.

Input parameters:

szPath = pointer to a pathname of a file to be opened
nFlags = arguments that control how the file should be accessed
mode = file permission settings that are used only when a file is created

Return value:
    File descriptor on success, -1 on failure
--*/
int
CorUnix::InternalOpen(
    const char *szPath,
    int nFlags,
    ...
    )
{
    int nRet = -1;
    int mode = 0;
    va_list ap;

    // If nFlags does not contain O_CREAT, the mode parameter will be ignored.
    if (nFlags & O_CREAT)
    {
        va_start(ap, nFlags);
        mode = va_arg(ap, int);
        va_end(ap);
    }

#if OPEN64_IS_USED_INSTEAD_OF_OPEN
        nRet = open64(szPath, nFlags, mode);
#else
        nRet = open(szPath, nFlags, mode);
#endif
    return nRet;
}

/*++
PAL_rename

Wrapper function for rename.

Input parameters:

szOldName = pointer to the pathname of the file to be renamed
szNewName = pointer to the new pathname of the file

Return value:
    Returns 0 on success and -1 on failure
--*/
int
__cdecl
PAL_rename(
    const char *szOldName,
    const char *szNewName
    )
{
    return rename(szOldName, szNewName);
}

/*++
PAL_fgets

Wrapper function for InternalFgets.

Input parameters:

sz = stores characters read from the given file stream
nSize = number of characters to be read
pf = stream to read characters from

Return value:
    Returns a pointer to the string storing the characters on success
    and NULL on failure.
--*/
char *
__cdecl
PAL_fgets(
    char *sz,
    int nSize,
    PAL_FILE *pf
    )
{
    char * szBuf;

    PERF_ENTRY(fgets);
    ENTRY( "fgets(sz=%p (%s) nSize=%d pf=%p)\n", sz, sz, nSize, pf);

    if (pf != NULL)
    {
        szBuf = InternalFgets(sz, nSize, pf->bsdFilePtr, pf->bTextMode);
    }
    else
    {
        szBuf = NULL;
    }

    LOGEXIT("fgets() returns %p\n", szBuf);
    PERF_EXIT(fgets);

    return szBuf;
}

/*++
InternalFgets

Wrapper for fgets.

Input parameters:

sz = stores characters read from the given file stream
nSize = number of characters to be read
f = stream to read characters from
fTextMode = flag that indicates if file contents are text or binary

Return value:
    Returns a pointer to the string storing the characters on success
    and NULL on failure.

Notes:
In Unix systems, fgets() can return an error if it gets interrupted by a
signal before reading anything, and errno is set to EINTR. When this
happens, it is SOP to call fgets again.
--*/
char *
CorUnix::InternalFgets(
    char *sz,
    int nSize,
    FILE *f,
    bool fTextMode
    )
{
    char *retval = NULL;

    _ASSERTE(sz != NULL);
    _ASSERTE(f != NULL);

#if FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL
    clearerr(f);
#endif

    do
    {
        retval =  fgets(sz, nSize, f);
        if (NULL==retval)
        {
            if (feof(f))
            {
                TRACE("Reached EOF\n");
                break;
            }
            /* The man page suggests using ferror and feof to distinguish
               between error and EOF, but feof and errno is sufficient.
               Not all cases that set errno also flag ferror, so just
               checking errno is the best solution. */
            if (EINTR != errno)
            {
                WARN("got error; errno is %d (%s)\n",errno, strerror(errno));
                break;
            }
            /* we ignored a EINTR error, reset the stream's error state */
            clearerr(f);
            TRACE("call got interrupted (EINTR), trying again\n");
        }
        if (fTextMode)
        {
            int len = strlen(sz);
            if ((len>=2) && (sz[len-1]=='\n') && (sz[len-2]=='\r'))
            {
                sz[len-2]='\n';
                sz[len-1]='\0';
            }
        }
    } while(NULL == retval);

    return retval;
}

/*++
PAL_fwrite

Wrapper function for InternalFwrite.

Input parameters:

pvBuffer = array of objects to write to the given file stream
nSize = size of a object in bytes
nCount = number of objects to write
pf = stream to write characters to

Return value:
    Returns the number of objects written.
--*/
size_t
__cdecl
PAL_fwrite(
    const void *pvBuffer,
    size_t nSize,
    size_t nCount,
    PAL_FILE *pf
    )
{
    size_t nWrittenBytes = 0;

    PERF_ENTRY(fwrite);
    ENTRY( "fwrite( pvBuffer=%p, nSize=%d, nCount=%d, pf=%p )\n",
           pvBuffer, nSize, nCount, pf);
    _ASSERTE(pf != NULL);

    nWrittenBytes = InternalFwrite(pvBuffer, nSize, nCount, pf->bsdFilePtr, &pf->PALferrorCode);

    LOGEXIT( "fwrite returning size_t %d\n", nWrittenBytes );
    PERF_EXIT(fwrite);
    return nWrittenBytes;
}

/*++
InternalFwrite

Wrapper for fwrite.

Input parameters:

pvBuffer = array of objects to write to the given file stream
nSize = size of a object in bytes
nCount = number of objects to write
f = stream to write characters to
pnErrorCode = reference to a PAL_FILE's fwrite error code field

Return value:
    Returns the number of objects written.
--*/
size_t
CorUnix::InternalFwrite(
    const void *pvBuffer,
    size_t nSize,
    size_t nCount,
    FILE *f,
    INT *pnErrorCode
    )
{
    size_t nWrittenBytes = 0;
    _ASSERTE(f != NULL);

#if FILE_OPS_CHECK_FERROR_OF_PREVIOUS_CALL
    clearerr(f);
#endif

    nWrittenBytes = fwrite(pvBuffer, nSize, nCount, f);

    // Make sure no error ocurred.
    if ( nWrittenBytes < nCount )
    {
        // Set the FILE* error code
        *pnErrorCode = PAL_FILE_ERROR;
    }

    return nWrittenBytes;
}

/*++
PAL_fseek

Wrapper function for fseek.

Input parameters:

pf = a given file stream
lOffset = distance from position to set file-position indicator
nWhence = method used to determine the file_position indicator location relative to lOffset

Return value:
    0 on success, -1 on failure.
--*/
int
_cdecl
PAL_fseek(
    PAL_FILE * pf,
    LONG lOffset,
    int nWhence
    )
{
    int nRet = 0;

    PERF_ENTRY(fseek);
    ENTRY( "fseek( %p, %ld, %d )\n", pf, lOffset, nWhence );

    nRet = fseek(pf ? pf->bsdFilePtr : NULL, lOffset, nWhence);

    LOGEXIT("fseek returning %d\n", nRet);
    PERF_EXIT(fseek);
    return nRet;
}


text:
//
//  RKURL.h
//  RestKit
//
//  Created by Jeff Arena on 10/18/10.
//  Copyright 2010 Two Toasters
//
//  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.
//

/**
 RKURL extends the Cocoa NSURL base class to provide support for the concepts
 of base URL and resource path that are used extensively throughout the RestKit
 framework. Instances of RKURL are aware of the baseURL they were constructed against
 (if any) and the resource path that was appended to that baseURL as well as any
 query parameters present in the URL. RKURL is immutable, but provides numerous
 methods for constructing new RKURL instances where the received becomes the baseURL
 of the RKURL instance.
 */
@interface RKURL : NSURL

/**
 Returns the base URL of the receiver.

 @return The base URL of the receiver.
 */
@property (nonatomic, copy, readonly) NSURL *baseURL;

/**
 Returns the resource path of the receiver.

 The resource path is the path portion of the complete
 URL beyond that contained in the baseURL.

 @return The base URL of the receiver.
 */
@property (nonatomic, copy, readonly) NSString *resourcePath;

/**
 Returns the query of a URL conforming to RFC 1808 as a dictionary.

 @see [NSURL query]
 @return The query of the URL as a dictionary.
 */
@property (nonatomic, readonly) NSDictionary *queryParameters;

/**
 Creates and returns an RKURL object intialized with a provided base URL.

 @param baseURL The URL object with which to initialize the RKURL object.
 @return An RKURL object initialized with baseURL.
 */
+ (id)URLWithBaseURL:(NSURL *)baseURL;

/**
 Creates and returns an RKURL object intialized with a provided base URL and
 resource path.

 @param baseURL The URL object with which to initialize the RKURL object.
 @param resourcePath The resource path for the RKURL object.
 @return An RKURL object initialized with baseURL and resourcePath.
 */
+ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath;

/**
 Creates and returns an RKURL object intialized with a provided base URL,
 resource path, and a dictionary of query parameters.

 @param baseURL The URL object with which to initialize the RKURL object.
 @param resourcePath The resource path for the RKURL object.
 @param queryParameters The query parameters for the RKURL object.
 @return An RKURL object initialized with baseURL, resourcePath, and queryParameters.
 */
+ (id)URLWithBaseURL:(NSURL *)baseURL resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters;

/**
 Creates and returns an RKURL object intialized with a base URL constructed from the specified
 base URL string.

 @param baseURLString The string with which to initialize the RKURL object.
 @return An RKURL object initialized with baseURLString.
 */
+ (id)URLWithBaseURLString:(NSString *)baseURLString;

/**
 Creates and returns an RKURL object intialized with a base URL constructed from the specified
 base URL string and resource path.

 @param baseURLString The string with which to initialize the RKURL object.
 @param resourcePath The resource path for the RKURL object.
 @return An RKURL object initialized with baseURLString and resourcePath.
 */
+ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath;

/**
 Creates and returns an RKURL object intialized with a base URL constructed from the specified
 base URL string, resource path and a dictionary of query parameters.

 @param baseURLString The string with which to initialize the RKURL object.
 @param resourcePath The resource path for the RKURL object.
 @param queryParameters The query parameters for the RKURL object.
 @return An RKURL object initialized with baseURLString, resourcePath and queryParameters.
 */
+ (id)URLWithBaseURLString:(NSString *)baseURLString resourcePath:(NSString *)resourcePath queryParameters:(NSDictionary *)queryParameters;

/**
 Initializes an RKURL object with a base URL, a resource path string, and a dictionary of query
 parameters.

 @param baseURL The NSURL with which to initialize the RKURL object.
 @param resourcePath The resource path for the RKURL object.
 @param queryParameters The query parameters for the RKURL object.
 @return An RKURL object initialized with baseURL, resourcePath and queryParameters.
 */
- (id)initWithBaseURL:(NSURL *)theBaseURL resourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters; // Designated initializer

/**
 Returns a new RKURL object with a new resource path appended to its path.

 @param theResourcePath The resource path to append to the receiver's path.
 @return A new RKURL that refers to a new resource at theResourcePath.
 */
- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath;

/**
 Returns a new RKURL object with a new resource path appended to its path and a dictionary
 of query parameters merged with the existing query.

 @param theResourcePath The resource path to append to the receiver's path.
 @param theQueryParameters A dictionary of query parameters to merge with any existing query/
 @return A new RKURL that refers to a new resource at theResourcePath with a new query
    including the values from theQueryParameters.
 */
- (RKURL *)URLByAppendingResourcePath:(NSString *)theResourcePath queryParameters:(NSDictionary *)theQueryParameters;

/**
 Returns a new RKURL object with a dictionary of query parameters merged with the existing query.

 @param theQueryParameters A dictionary of query parameters to merge with any existing query/
 @return A new RKURL that refers to the same resource as the receiver with a new query
    including the values from theQueryParameters.
 */
- (RKURL *)URLByAppendingQueryParameters:(NSDictionary *)theQueryParameters;

/**
 Returns a new RKURL object with the baseURL of the receiver and a new resourcePath.

 @param newResourcePath The resource path to replace the value of resourcePath in the new RKURL object.
 @return An RKURL object with newResourcePath appended to the receiver's baseURL.
 */
- (RKURL *)URLByReplacingResourcePath:(NSString *)newResourcePath;

/**
 Returns a new RKURL object with its resource path processed as a pattern and evaluated
 against the specified object.

 Resource paths may contain pattern strings prefixed by colons (":") that refer to key-value
 coding accessible properties on the provided object. For example, given an RKURL initialized
 as:

    RKURL *URL = [RKURL URLWithBaseURLString:@"http://restkit.org"
                                resourcePath:@"/paginate?per_page=:perPage&page=:page"];

 And a dictionary containing values:

    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"25", @"perPage",
                                                                          @"5", @"page", nil];

 A new RKURL can be constructed by interpolating dictionary against the original URL:

    RKURL *interpolatedURL = [URL URLByInterpolatingResourcePathWithObject:dictionary];

 The absoluteString of this new URL would be: http://restkit.org/paginate?per_page=25&page=5

 @see SOCKIT
 @return A new RKURL object with its resource path evaluated as a pattern and interpolated with
    properties of object.
 */
- (RKURL *)URLByInterpolatingResourcePathWithObject:(id)object;

@end


text:
package com.dci.intellij.dbn.generator;

import com.dci.intellij.dbn.object.DBDataset;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class DatasetJoinBundle {
    private List<DatasetJoin> joins = new ArrayList<DatasetJoin>();

    public DatasetJoinBundle(Set<DBDataset> datasets, boolean lenient) {
        for (DBDataset dataset1 : datasets) {
            for (DBDataset dataset2 : datasets) {
                if (!dataset1.equals(dataset2)) {
                    createJoin(dataset1, dataset2, lenient);
                }
            }
        }
    }

    private void createJoin(DBDataset dataset1, DBDataset dataset2, boolean lenient) {
        if (!contains(dataset1, dataset2)) {
            DatasetJoin datasetJoin = new DatasetJoin(dataset1, dataset2, lenient);
            if (!datasetJoin.isEmpty()) {
                joins.add(datasetJoin);
            }
        }
    }

    protected boolean contains(DBDataset... datasets) {
        for (DatasetJoin datasetJoin : joins) {
            if (datasetJoin.contains(datasets)) return true;
        }
        return false;
    }

    public List<DatasetJoin> getJoins() {
        return joins;
    }

    public boolean isEmpty() {
        for (DatasetJoin join : joins) {
            if (!join.isEmpty()) {
                return false;
            }
        }
        return true;
    }
}


text:
package handlers

import (
	"fmt"
	"gocodelab/gopherfacedb/common/utility"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

type UploadVideoForm struct {
	FieldNames []string
	Fields     map[string]string
	Errors     map[string]string
}

func DisplayUploadVideoForm(w http.ResponseWriter, r *http.Request, u *UploadVideoForm) {
	RenderTemplate(w, "./templates/uploadvideoform.html", u)
}

func ProcessUploadVideo(w http.ResponseWriter, r *http.Request, u *UploadVideoForm) {

	file, fileheader, err := r.FormFile("videofile")

	if err != nil {
		log.Println("Encountered error when attempting to read uploaded file: ", err)
	}

	randomFileName := utility.GenerateUUID()

	if fileheader != nil {

		extension := filepath.Ext(fileheader.Filename)
		r.ParseMultipartForm(32 << 20)

		defer file.Close()

		videoFilePathWithoutExtension := "./static/uploads/videos/" + randomFileName
		f, err := os.OpenFile(videoFilePathWithoutExtension+extension, os.O_WRONLY|os.O_CREATE, 0666)

		if err != nil {
			log.Println(err)
			return
		}

		defer f.Close()
		io.Copy(f, file)

		thumbImageFilePath := videoFilePathWithoutExtension + "_thumb.png"
		command := "ffmpeg -y  -i " + videoFilePathWithoutExtension + extension + " -s 430x372 -f mjpeg -vframes 1 -ss 3 " + thumbImageFilePath
		commandOutput, err := exec.Command("sh", "-c", command).Output()
		fmt.Println("video thumbnail generation command output: ", commandOutput)

		if err != nil {
			log.Println(err)
			return
		}

		m := make(map[string]string)
		m["thumbnailPath"] = strings.TrimPrefix(videoFilePathWithoutExtension, ".") + "_thumb.png"
		m["videoPath"] = strings.TrimPrefix(videoFilePathWithoutExtension, ".") + ".mp4"

		RenderTemplate(w, "./templates/videopreview.html", m)

	} else {
		w.Write([]byte("Failed to process uploaded file!"))
	}
}

func ValidateUploadVideoForm(w http.ResponseWriter, r *http.Request, u *UploadVideoForm) {

	ProcessUploadVideo(w, r, u)

}

func UploadVideoHandler(w http.ResponseWriter, r *http.Request) {

	u := UploadVideoForm{}
	u.Fields = make(map[string]string)
	u.Errors = make(map[string]string)

	switch r.Method {

	case "GET":
		DisplayUploadVideoForm(w, r, &u)
	case "POST":
		ValidateUploadVideoForm(w, r, &u)
	default:
		DisplayUploadVideoForm(w, r, &u)
	}

}


text: [Pure CSS ripple effect (no JavaScript)](https://github.com/mladenplavsic/css-ripple-effect)


text:
require 'test_helper'

require 'outpost/scouts'

describe "using only report data integration test" do
  class RetrieveServerData < Outpost::Application
    using Outpost::Scouts::Http => 'master http server' do
      options :host => 'localhost', :port => 9595, :path => '/'
    end

    using Outpost::Scouts::Ping => :load_balancer do
      options :host => 'localhost'
      report :up, :response_time => {:less_than => 500}
    end
  end

  before(:each) do
    @server = Server.new
    @server.boot(TestApp)
    @server.wait_until_booted

    @outpost = RetrieveServerData.new
    @outpost.run
  end

  it "should build report for each scout" do
    assert_equal 2, @outpost.reports.size
  end

  it "should build reports with data" do
    http_report = @outpost.reports['master http server']
    ping_report = @outpost.reports[:load_balancer]

    report_data = http_report.data

    assert report_data.delete(:response_time) < 500
    assert_equal({:response_code => 200,
                  :response_body => 'Up and running!'}, http_report.data)
  end
end


text:
package com.weather.material;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Toast;

import com.weather.material.fragments.AboutFragment;
import com.weather.material.fragments.NewsFragment;
import com.weather.material.fragments.PicFramgent;
import com.weather.material.fragments.WeaFragment;
import com.weather.material.fragments.wea_area_item.AreaFragment;
import com.weather.material.utils.ActivityCollector;
import com.weather.material.utils.BaseActivity;
import com.weather.material.utils.MyApplication;

public class MainActivity extends BaseActivity
{

    private DrawerLayout drawer_layout;
    private NavigationView nav_view;
    private Toolbar toolbar;
    private NewsFragment newsFragment;
    private AppBarLayout appbar;
    private AppBarLayout.LayoutParams params;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        //drawerlayout
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_Layout);

        //toolbar
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null)
        {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
        }
        WeaFragment fragmentById = (WeaFragment) getSupportFragmentManager().findFragmentById(R.id.WeaFragment);
        //侧边栏
        nav_view = (NavigationView) findViewById(R.id.nav_view);
        nav_view.setCheckedItem(R.id.news);
        //appbar 特定界面 appbar不进行滚动隐藏
        appbar = (AppBarLayout)findViewById(R.id.appbar_mainActivity);
        params = (AppBarLayout.LayoutParams) appbar.getChildAt(0).getLayoutParams();

        //初始跳入新闻
        SwitchToNews();
        nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener()
        {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item)
            {
                switch (item.getItemId())
                {
                    case R.id.news:
                        SwitchToNews();
                        drawer_layout.closeDrawers();
                        break;
                    case R.id.pic:
                        SwitchToPic();
                        drawer_layout.closeDrawers();
                        break;
                    case R.id.weather:
                        SwitchToWeather();
                        drawer_layout.closeDrawers();
                        break;
                    case R.id.about:
                        SwitchToAbout();
                        drawer_layout.closeDrawers();
                        break;
                    case R.id.exit:
                        ActivityCollector.finishAllActivity();
                        break;
                }
                return true;
            }
        });
    }

    //跳转到关于界面fragment
    private void SwitchToAbout()
    {
        /*FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.remove(newsFragment).commit();*/
        FragmentTransaction replace = getSupportFragmentManager().beginTransaction().replace(R.id.fl_inner_mainActivity, new AboutFragment());
        replace.commit();
        toolbar.setTitle("关于");
    }

    //跳转新闻Fragment
    public void SwitchToNews()
    {
        //代码设置appbar的滚动隐藏功能 app:layout_scrollFlags="scroll|enterAlways|snap"
        params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS|AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL);
        newsFragment = new NewsFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fl_inner_mainActivity, newsFragment).commit();
        toolbar.setTitle("新闻");
    }

    //跳转图片Fragment
    private void SwitchToPic()
    {
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_inner_mainActivity, new PicFramgent()).commit();
        toolbar.setTitle("图片");
    }

    //跳转天气Fragment
    public void SwitchToWeather()
    {
        //不许appbar进行滚动隐藏
        params.setScrollFlags(0);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_inner_mainActivity, new WeaFragment()).commit();
        toolbar.setTitle("天气");
    }

    public void SwitchAreaFragToWeaFrag(String urlWeather)
    {
        toolbar.setTitle("天气");
        params.setScrollFlags(0);
        //通过bundle传递数据-从AreaFragment传递数据到MainActivity
        WeaFragment weaFragment = new WeaFragment();
        Bundle bundle = new Bundle();
        bundle.putString("Data", urlWeather);
        weaFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_inner_mainActivity,weaFragment).commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    //右边的设置按钮
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case android.R.id.home:
                drawer_layout.openDrawer(GravityCompat.START);
                break;
            case R.id.exit:
                Toast.makeText(MyApplication.getContext(), "退出", Toast.LENGTH_SHORT).show();
                ActivityCollector.finishAllActivity();
                break;
            case R.id.about:
                SwitchToAbout();
                break;
        }
        return true;
    }

}


text:
var Flume = require('../')
var LevelLog = require('flumelog-level')

require('./memlog')(Flume(LevelLog('/tmp/test_flumedb-levellog' + Date.now())))

// XXX there is a bug in flumelog-level!
// something to do with inconsistent support for stream options, seqs, values ?
// require('./memlog-map')
//  (LevelLog('/tmp/test_flumedb-levellog-map'+Date.now()))


text:
import test from 'ava';
import { isMutable, modify } from '@collectable/core';
import { SortedSetStructure, add, has, size } from '../../src';
import { fromStringArray } from '../test-utils';

let set0: SortedSetStructure<string>, set1: SortedSetStructure<string>;
test.before(() => {
  set0 = modify(fromStringArray(['A', 'B', 'D']));
  set1 = add('C', set0);
});

test('the input set is returned', t => {
  t.is(set0, set1);
});

test('the input set is still mutable', t => {
  t.true(isMutable(set1));
});

test('the set size is incremented', t => {
  t.is(size(set1), 4);
});

test('the added item can be retrieved from the set', t => {
  t.true(has('C', set1));
});

test('all expected members exist in the set in the correct order', t => {
  t.deepEqual(Array.from(set1), ['A', 'B', 'C', 'D']);
});


text:
@import ORSSerial;

static const NSTimeInterval kTimeoutDuration = 0.5;

typedef NS_ENUM(NSInteger, ORSSerialBoardRequestType) {
	ORSSerialBoardRequestTypeReadTemperature = 1,
	ORSSerialBoardRequestTypeReadLED,
	ORSSerialBoardRequestTypeSetLED,
};

@interface ORSSerialBoardController () <ORSSerialPortDelegate>

@property (nonatomic, readwrite) NSInteger temperature; // In degrees C

@property (nonatomic, strong) NSTimer *pollingTimer;

@end

@implementation ORSSerialBoardController

#pragma mark - Private

- (void)pollingTimerFired:(NSTimer *)timer
{
	[self readTemperature];
	[self readLEDState];
}

#pragma mark Sending Commands

- (void)readTemperature
{
	NSData *command = [@"$TEMP?;" dataUsingEncoding:NSASCIIStringEncoding];
	ORSSerialPacketDescriptor *responseDescriptor =
	[[ORSSerialPacketDescriptor alloc] initWithMaximumPacketLength:10
														  userInfo:nil
												 responseEvaluator:^BOOL(NSData *inputData) {
													 return [self temperatureFromResponsePacket:inputData] != nil;
												 }];
	ORSSerialRequest *request = [ORSSerialRequest requestWithDataToSend:command
															   userInfo:@(ORSSerialBoardRequestTypeReadTemperature)
														timeoutInterval:kTimeoutDuration
													 responseDescriptor:responseDescriptor];
	[self.serialPort sendRequest:request];
}

- (void)readLEDState
{
	NSData *command = [@"$LED?;" dataUsingEncoding:NSASCIIStringEncoding];
	ORSSerialPacketDescriptor *responseDescriptor =
	[[ORSSerialPacketDescriptor alloc] initWithMaximumPacketLength:10
														  userInfo:nil
												 responseEvaluator:^BOOL(NSData *inputData) {
													 return [self LEDStateFromResponsePacket:inputData] != nil;
												 }];
	ORSSerialRequest *request = [ORSSerialRequest requestWithDataToSend:command
															   userInfo:@(ORSSerialBoardRequestTypeReadLED)
														timeoutInterval:kTimeoutDuration
													 responseDescriptor:responseDescriptor];
	[self.serialPort sendRequest:request];
}

- (void)sendCommandToSetLEDToState:(BOOL)LEDState
{
	NSString *commandString = [NSString stringWithFormat:@"$LED%@;", (LEDState ? @"1" : @"0")];
	NSData *command = [commandString dataUsingEncoding:NSASCIIStringEncoding];
	ORSSerialPacketDescriptor *responseDescriptor =
	[[ORSSerialPacketDescriptor alloc] initWithMaximumPacketLength:10
														  userInfo:nil
												 responseEvaluator:^BOOL(NSData *inputData) {
													 return [self LEDStateFromResponsePacket:inputData] != nil;
												 }];
	ORSSerialRequest *request = [ORSSerialRequest requestWithDataToSend:command
															   userInfo:@(ORSSerialBoardRequestTypeSetLED)
														timeoutInterval:kTimeoutDuration
													 responseDescriptor:responseDescriptor];
	[self.serialPort sendRequest:request];
}

#pragma mark Parsing Responses

- (NSNumber *)temperatureFromResponsePacket:(NSData *)data
{
	if (![data length]) return nil;
	NSString *dataAsString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	if (![dataAsString hasPrefix:@"!TEMP"]) return nil;
	if (![dataAsString hasSuffix:@";"]) return nil;
	if ([dataAsString length] < 6) return nil;

	NSString *temperatureString = [dataAsString substringWithRange:NSMakeRange(5, [dataAsString length]-6)];
	return @([temperatureString integerValue]);
}

- (NSNumber *)LEDStateFromResponsePacket:(NSData *)data
{
	if (![data length]) return nil;
	NSString *dataAsString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
	if (![dataAsString hasPrefix:@"!LED"]) return nil;
	if (![dataAsString hasSuffix:@";"]) return nil;
	if ([dataAsString length] < 6) return nil;

	NSString *LEDStateString = [dataAsString substringWithRange:NSMakeRange(4, [dataAsString length]-5)];
	return @([LEDStateString integerValue]);
}

#pragma mark - ORSSerialPortDelegate

- (void)serialPortWasRemovedFromSystem:(ORSSerialPort *)serialPort
{
	self.serialPort = nil;
}

- (void)serialPort:(ORSSerialPort *)serialPort didEncounterError:(NSError *)error
{
	NSLog(@"Serial port %@ encountered an error: %@", self.serialPort, error);
}

- (void)serialPort:(ORSSerialPort *)serialPort didReceiveResponse:(NSData *)responseData toRequest:(ORSSerialRequest *)request
{
	ORSSerialBoardRequestType requestType = [request.userInfo integerValue];
	switch (requestType) {
		case ORSSerialBoardRequestTypeReadTemperature:
			self.temperature = [[self temperatureFromResponsePacket:responseData] integerValue];
			break;

		case ORSSerialBoardRequestTypeReadLED:
		case ORSSerialBoardRequestTypeSetLED:
			// Don't call the setter to avoid continuing to send set commands indefinitely
			[self willChangeValueForKey:@"LEDOn"];
			_LEDOn = [[self LEDStateFromResponsePacket:responseData] boolValue];
			[self didChangeValueForKey:@"LEDOn"];
			break;

		default:
			break;
	}
}

- (void)serialPortWasOpened:(ORSSerialPort *)serialPort
{
	// Start polling
	self.pollingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(pollingTimerFired:) userInfo:nil repeats:YES];
	[self.pollingTimer fire]; // Do first read
}

- (void)serialPortWasClosed:(ORSSerialPort *)serialPort
{
	// Stop polling
	self.pollingTimer = nil;
}

#pragma mark - Properties

- (void)setSerialPort:(ORSSerialPort *)serialPort
{
	if (serialPort != _serialPort) {
		[_serialPort close];
		_serialPort.delegate = nil;

		_serialPort = serialPort;

		_serialPort.baudRate = @57600;
		_serialPort.delegate = self;
		[_serialPort open];
	}
}

- (void)setLEDOn:(BOOL)LEDOn
{
	_LEDOn = LEDOn;
	[self sendCommandToSetLEDToState:_LEDOn];
}

- (void)setPollingTimer:(NSTimer *)pollingTimer
{
	if (pollingTimer != _pollingTimer) {
		[_pollingTimer invalidate];
		_pollingTimer = pollingTimer;
	}
}

@end


text:
import logging
from pyvisdk.exceptions import InvalidArgumentError

########################################
# Automatically generated, do not edit.
########################################

log = logging.getLogger(__name__)

def LongOption(vim, *args, **kwargs):
    '''The LongOption data object type is used to define the minimum, maximum, and
    default values for a 64-bit long option.'''

    obj = vim.client.factory.create('ns0:LongOption')

    # do some validation checking...
    if (len(args) + len(kwargs)) < 3:
        raise IndexError('Expected at least 4 arguments got: %d' % len(args))

    required = [ 'defaultValue', 'max', 'min' ]
    optional = [ 'valueIsReadonly', 'dynamicProperty', 'dynamicType' ]

    for name, arg in zip(required+optional, args):
        setattr(obj, name, arg)

    for name, value in kwargs.items():
        if name in required + optional:
            setattr(obj, name, value)
        else:
            raise InvalidArgumentError("Invalid argument: %s.  Expected one of %s" % (name, ", ".join(required + optional)))

    return obj


text:
module Math.Util where

import Control.Applicative
import Data.List
import GHC.Float       (double2Int)

-- Fast variant of floor
floorD :: Double -> Int
floorD x | x < 0     = double2Int x - 1
         | otherwise = double2Int x
{-# INLINE floorD #-}

floorD' :: Double -> Double -> Double
floorD' grain x = fromIntegral (floorD (x / grain)) * grain
{-# INLINE floorD' #-}

roundD :: Double -> Double -> Double
roundD grain x = if frac > 0.5 then whole + grain else whole
    where
      whole = floorD' grain x
      frac = (x - floorD' grain x) / grain

median :: (Ord a, Fractional a) =>  [a] -> a
median xs =
    if odd len
    then xs' !! mid
    else evenMedian
  where
    xs' = sort xs
    len = length xs
    mid = len `div` 2
    evenMedian = (xs' !! mid + xs' !! (mid+1)) / 2

absdev :: (Ord a, Fractional a) =>  [a] -> a
absdev xs = sum $ abs <$> ((-) <$> xs <*> pure (median xs))


text: <!DOCTYPE html>


text:
package org.eurekaj.manager.plugin;

import org.eurekaj.api.service.EurekaJApplicationServices;
import org.eurekaj.manager.util.ClassPathUtil;

public class EurekaJManagerApplicationServices implements EurekaJApplicationServices {
	private static EurekaJManagerApplicationServices applicationServices;

	public static EurekaJApplicationServices getInstance() {
        ClassPathUtil.addPluginDirectory();
		if (applicationServices == null) {
			applicationServices = new EurekaJManagerApplicationServices();
		}

		return applicationServices;
	}

	public String getLoggedInUsername() {
		return null;//SecurityManager.getAuthenticatedUsername();
	}
}


text:
var GSVPANO = GSVPANO || {};
GSVPANO.PanoLoader = function (parameters) {

	'use strict';

	var _parameters = parameters || {},
		_location,
        _nextLocation,
		_zoom,
		_panoId,
		_panoClient = new google.maps.StreetViewService(),
		_count = 0,
		_total = 0,
		_canvas = document.createElement('canvas'),
		_ctx = _canvas.getContext('2d'),
		rotation = 0,
		pitch = 0,
		copyright = '',
		onSizeChange = null,
		onPanoramaLoad = null;

	this.setProgress = function (p) {

		if (this.onProgress) {
			this.onProgress(p);
		}

	};

	this.setNextLocation = function (loc) {
	    this._nextLocation = loc;
	};

	this.throwError = function (message) {

		if (this.onError) {
			this.onError(message);
		} else {
			console.error(message);
		}

	};

	this.adaptTextureToZoom = function () {

		var w = 416 * Math.pow(2, _zoom),
			h = (416 * Math.pow(2, _zoom - 1));
		_canvas.width = w;
		_canvas.height = h;
		_ctx.translate( _canvas.width, 0);
		_ctx.scale(-1, 1);
	};

	this.composeFromTile = function (x, y, texture) {

		_ctx.drawImage(texture, x * 512, y * 512);
		_count++;

		var p = Math.round(_count * 100 / _total);
		this.setProgress(p);

		if (_count === _total) {
			this.canvas = _canvas;
			if (this.onPanoramaLoad) {
				this.onPanoramaLoad();
			}
		}

	};

	this.composePanorama = function (panoId) {

		this.setProgress(0);
		console.log('Loading panorama for zoom ' + _zoom + '...');

		var w = (_zoom==3) ? 7 : Math.pow(2, _zoom),
			h = Math.pow(2, _zoom - 1),
			self = this,
			url,
			x,
			y;

		_count = 0;
		_total = w * h;

		for( y = 0; y < h; y++) {
			for( x = 0; x < w; x++) {
				url = 'http://maps.google.com/cbk?output=tile&panoid=' + panoId + '&zoom=' + _zoom + '&x=' + x + '&y=' + y + '&' + Date.now();
			    (function (x, y) {

					var img = new Image();
					img.addEventListener('load', function () {
						self.composeFromTile(x, y, this);
					});
					img.addEventListener('error', function () {
					    self.composeFromTile(x, y, new Image());
					});
					img.crossOrigin = '';
					img.src = url;
				})(x, y);
			}
		}

	};

	this.load = function (location, nextLocation, callback) {

		console.log('Load for', location);
		var self = this;

		_panoClient.getPanoramaByLocation(location, 20, function (result, status) {
			if (status === google.maps.StreetViewStatus.OK) {

			    var heading = google.maps.geometry.spherical.computeHeading(result.location.latLng, nextLocation);

				if( self.onPanoramaData ) self.onPanoramaData( result );
				rotation = result.tiles.centerHeading * Math.PI / 180.0;
				pitch = result.tiles.originPitch;
				copyright = result.copyright;
				self.copyright = result.copyright;
				_panoId = result.location.pano;
				self.location = location;
				self.rotation = rotation;
				self.pitch = pitch;
				self.image_date = result.imageDate;
				self.id = _panoId;
				callback();
			} else {
				if( self.onNoPanoramaData ) self.onNoPanoramaData( status );
				self.throwError('Could not retrieve panorama for the following reason: ' + status);
				callback();
			}
		});

	};

	this.setZoom = function( z ) {
		_zoom = z;
		this.adaptTextureToZoom();
	};

	this.setZoom( _parameters.zoom || 1 );

};


text:
import subprocess
import os
import json

class Client(object):
    def __init__(self, user, pipe):
        self.user = user
        self.events = {}

        rfd, wfd = pipe

        self.reader = os.fdopen(rfd,"r")
        self.writer = os.fdopen(wfd,"w")

    def add(self, repository, branch, command):
        self.events[repository + "/" + branch] = command

    def execute(self, repository, branch, sha):
        command = self.events[repository + "/" + branch]

        subprocess.call(command + [repository, branch, sha])

    def notify(self, repository, branch, sha):
        print("notifying with uid =", os.getuid())

        self.writer.write(json.dumps({
            "repository": repository,
            "branch": branch,
            "sha": sha
        }) + "\n")
        self.writer.flush()

    def run(self):
        print("running client uid({0})".format(os.getuid()))

        while True:
            payload = json.loads(self.reader.readline())

            print("notified with uid({0}): {1}".format(os.getuid(), payload))
            self.execute(
                    payload["repository"],
                    payload["branch"],
                    payload["sha"])


text:
package org.pentaho.di.engine.configuration.impl;

import org.pentaho.di.engine.configuration.api.RunConfiguration;
import org.pentaho.di.engine.configuration.api.RunConfigurationExecutor;
import org.pentaho.di.engine.configuration.api.RunConfigurationProvider;
import org.pentaho.di.engine.configuration.api.RunConfigurationService;
import org.pentaho.di.engine.configuration.impl.pentaho.DefaultRunConfigurationProvider;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by bmorrise on 3/14/17.
 */
public class RunConfigurationManager implements RunConfigurationService {

  private RunConfigurationProvider defaultRunConfigurationProvider;
  private List<RunConfigurationProvider> runConfigurationProviders;

  public RunConfigurationManager( List<RunConfigurationProvider> runConfigurationProviders ) {
    this.runConfigurationProviders = runConfigurationProviders;
  }

  @Override public List<RunConfiguration> load() {
    List<RunConfiguration> runConfigurations = new ArrayList<>();
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      runConfigurations.addAll( runConfigurationProvider.load() );
    }
    Collections.sort( runConfigurations, ( o1, o2 ) -> {
      if ( o2.getName().equals( DefaultRunConfigurationProvider.DEFAULT_CONFIG_NAME ) ) {
        return 1;
      }
      return o1.getName().compareToIgnoreCase( o2.getName() );
    } );
    return runConfigurations;
  }

  @Override public RunConfiguration load( String name ) {
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      RunConfiguration runConfiguration = runConfigurationProvider.load( name );
      if ( runConfiguration != null ) {
        return runConfiguration;
      }
    }
    return null;
  }

  @Override public boolean save( RunConfiguration runConfiguration ) {
    RunConfigurationProvider runConfigurationProvider = getProvider( runConfiguration.getType() );
    return runConfigurationProvider != null && runConfigurationProvider.save( runConfiguration );
  }

  @Override
  public boolean delete( String name ) {
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      if ( runConfigurationProvider.load( name ) != null && runConfigurationProvider.delete( name ) ) {
        return true;
      }
    }
    return false;
  }

  @Override public void deleteAll() {
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      runConfigurationProvider.deleteAll();
    }
  }

  public String[] getTypes() {
    List<String> types = new ArrayList<>();
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      types.add( runConfigurationProvider.getType() );
    }
    return types.toArray( new String[ 0 ] );
  }

  public List<String> getNames() {
    List<String> names = new ArrayList<>();
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      names.addAll( runConfigurationProvider.getNames() );
    }
    Collections.sort( names, ( o1, o2 ) -> {
      if ( o2.equals( DefaultRunConfigurationProvider.DEFAULT_CONFIG_NAME ) ) {
        return 1;
      }
      return o1.compareToIgnoreCase( o2 );
    } );
    return names;
  }

  public List<String> getNames( String type ) {
    List<String> names = new ArrayList<>();
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders( type ) ) {
      names.addAll( runConfigurationProvider.getNames() );
    }
    Collections.sort( names, ( o1, o2 ) -> {
      if ( o2.equals( DefaultRunConfigurationProvider.DEFAULT_CONFIG_NAME ) ) {
        return 1;
      }
      return o1.compareToIgnoreCase( o2 );
    } );
    return names;
  }

  public RunConfiguration getRunConfigurationByType( String type ) {
    RunConfigurationProvider runConfigurationProvider = getProvider( type );
    if ( runConfigurationProvider != null ) {
      return runConfigurationProvider.getConfiguration();
    }
    return null;
  }

  public RunConfigurationExecutor getExecutor( String type ) {
    RunConfigurationProvider runConfigurationProvider = getProvider( type );
    if ( runConfigurationProvider != null ) {
      return runConfigurationProvider.getExecutor();
    }
    return null;
  }

  private RunConfigurationProvider getProvider( String type ) {
    for ( RunConfigurationProvider runConfigurationProvider : getRunConfigurationProviders() ) {
      if ( runConfigurationProvider.getType().equals( type ) ) {
        return runConfigurationProvider;
      }
    }
    return null;
  }

  public List<RunConfigurationProvider> getRunConfigurationProviders( String type ) {
    List<RunConfigurationProvider> runConfigurationProviders = new ArrayList<>();
    if ( defaultRunConfigurationProvider != null ) {
      runConfigurationProviders.add( defaultRunConfigurationProvider );
    }
    for ( RunConfigurationProvider runConfigurationProvider : this.runConfigurationProviders ) {
      if ( runConfigurationProvider.isSupported( type ) ) {
        runConfigurationProviders.add( runConfigurationProvider );
      }
    }
    return runConfigurationProviders;
  }

  public List<RunConfigurationProvider> getRunConfigurationProviders() {
    List<RunConfigurationProvider> runConfigurationProviders = new ArrayList<>();
    if ( defaultRunConfigurationProvider != null ) {
      runConfigurationProviders.add( defaultRunConfigurationProvider );
    }
    runConfigurationProviders.addAll( this.runConfigurationProviders );
    return runConfigurationProviders;
  }

  public RunConfigurationProvider getDefaultRunConfigurationProvider() {
    return defaultRunConfigurationProvider;
  }

  public void setDefaultRunConfigurationProvider(
    RunConfigurationProvider defaultRunConfigurationProvider ) {
    this.defaultRunConfigurationProvider = defaultRunConfigurationProvider;
  }
}


text:
"""Button handle operation which take a lot of time to another thread.
Then waiting reault"""
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import time
import sys

class WorkThread(QThread):
    trigger = pyqtSignal(str)
    def __init__(self):
        super(WorkThread, self).__init__()

    def run(self):
        print("run\n")
        time.sleep(1)
        self.trigger.emit("HellowSignal")

class MyWindow(QWidget):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.button1 = QPushButton("One")
        self.button2 = QPushButton("StartThread")
        self.label1 = QLabel()
        self.layout = QGridLayout()
        self.layout.addWidget(self.button1)
        self.layout.addWidget(self.button2)
        self.layout.addWidget(self.label1)
        self.setLayout(self.layout)
        self.resize(200,200)
        self.button1.clicked.connect(self.ButtonCallBack)
        self.button2.clicked.connect(self.StartWorkInAThread)
        self.w = WorkThread()
        self.w.trigger.connect(self.Stop)

    def ButtonCallBack(self, e):
        print(e)
        print(type(self))
        print(self.sender().text())

    def StartWorkInAThread(self, e):
        self.w.start()
        print("start work\n")

    def Stop(self, text):
        print("stop\n")
        print(text)
        print(self.sender().isFinished())
        self.label1.setText(text)

if __name__== '__main__':
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())


text:
using System.Collections.Generic;
using System.Web.Mvc;
using KendoGridDemo.Models;
using Newtonsoft.Json;

namespace KendoGridDemo.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult Index(string Comments)
        {

            var cmntData = JsonConvert.DeserializeObject<List<ResponseComments>>(Comments);
            return View();
        }
        //public ActionResult About()
        //{
        //    ViewBag.Message = "Your app description page.";

        //    return View();
        //}

        //public ActionResult Contact()
        //{
        //    ViewBag.Message = "Your contact page.";

        //    return View();
        //}
    }
}


text:
package org.immutables.fixture.couse.sub;

import com.google.common.base.Optional;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import java.util.Map;
import org.immutables.fixture.couse.A;
import org.immutables.fixture.couse.B;
import org.immutables.value.Value;

@Target(ElementType.TYPE_USE)
@interface Strange {}

@Value.Immutable
interface AbstractC {

  @Strange
  int i();

  @Strange
  String s();

  A a();

  Optional<A> aO();

  Map<A, List<B>> abM();

  Map<RetentionPolicy, C> raM();

  @SuppressWarnings("CheckReturnValue")
  default void use() {
    C c = C.builder()
        .a(A.builder().build())
        .aO(Optional.absent())
        .build();

    c.toString();
  }
}


text:
Keep an eye on [Github](https://github.com/reactiveui/ReactiveUI/pull/1387)

[Samsung forum](https://developer.samsung.com/forum/en)


text:
<?php

namespace Cetera\Iterator;

/**
 * Итератор объектов, на которые ссылается поле
 *
 * @package FastsiteCMS
 **/
class Linkset extends DynamicObject {

    /**
     * Конструктор
     *
     * @param Object $object
     * @return void
     */
    public function __construct($object, $field)
    {

		if ($field['type'] != FIELD_LINKSET && $field['type'] != FIELD_MATSET)
			throw new \Cetera\Exception\CMS('Illegal type of field '.$field['name'].' - '.$field['type']);

		/*
        if ($field['type'] == FIELD_LINKSET) {

			if ($field['len'] == CATALOG_VIRTUAL_USERS) {
			    $od = \Cetera\User::getObjectDefinition();
			} elseif ($field['pseudo_type'] == PSEUDO_FIELD_CATOLOGS) {
			    $od = \Cetera\Catalog::getObjectDefinition();
			} elseif (!$field['len']) {
				$od = $object->objectDefinition;
			} else {
			    $c = \Cetera\Catalog::getById($field['len']);
			    if (!$c) throw new \CeteraException\CMS('Catalog '.$field['len'].' is not found.');
			    $od = $c->materialsObjectDefinition;
			}

        }
		else {
            $od = \Cetera\ObjectDefinition::findById($field['len']);
        }
*/

		parent::__construct( $field->getObjectDefinition() );

		//$linktable = $object->table.'_'.$od->table.'_'.$field['name'];

		$this->query->innerJoin('main', $field->getLinkTable(), 'b', 'main.id = b.dest and b.id='.(int)$object->id);

    }

    /**
     * Добавляет произвольный материал в итератор
     *
     * @param \Cetera\DynamicFieldsObject $material
     * @return void
     */
	public function add($material, $check = true) {
		if ($material->objectDefinition->id != $this->objectDefinition->id) {
			throw new \Exception('Illegal type of material '.$material->objectDefinition->id.'. Must be '.$this->objectDefinition->id);
		}
		$this->fetchElements();
		return parent::add($material, $check);
	}

    /**
     * Удаляет материал из итератора
     *
     * @param \Cetera\DynamicFieldsObject $material
     * @return void
     */
	public function remove(\Cetera\DynamicFieldsObject $material) {
		if ($material->objectDefinition->id != $this->objectDefinition->id) {
			throw new \Exception('Illegal type of material '.$material->objectDefinition->id.'. Must be '.$this->objectDefinition->id);
		}
		$this->fetchElements();
		foreach ($this->elements as $key => $value) {
			if ($value->id == $material->id) {
				unset($this->elements[$key]);
				$this->elements = array_values($this->elements);
				break;
			}
		}
		return $this;
	}

}


text:
<?php

namespace skeeks\cms\components\storage;

use skeeks\cms\helpers\StringHelper;
use skeeks\cms\models\StorageFile;
use Yii;
use yii\base\Exception;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\httpclient\Client;
use yii\web\UploadedFile;
use yii\helpers\BaseUrl;

use \skeeks\sx\File;
use \skeeks\sx\Dir;

/*interface Storage
{
    public function add($file);
    public function update($storageFileSrc, $file);
    public function delete($storageFileSrc);

}*/

/**
 *
 * @property Cluster[] $clusters
 *
 * Class Storage
 * @package common\components\Storage
 */
class Storage extends Component
{
    public $components = [];

    /**
     *
     * Загрузить файл в хранилище, добавить в базу, вернуть модель StorageFile
     *
     * @param UploadedFile|string|File $file объект UploadedFile или File или rootPath до файла локально или http:// путь к файлу (TODO:: доделать)
     * @param array                    $data данные для сохранения в базу
     * @param null                     $clusterId идентификатор кластера по умолчанию будет выбран первый из конфигурации
     * @return StorageFile
     * @throws Exception
     */
    public function upload($file, $data = [], $clusterId = null)
    {
        //Для начала всегда загружаем файл во временную диррикторию
        $tmpdir = Dir::runtimeTmp();
        $tmpfile = $tmpdir->newFile();

        $original_file_name = '';

        if ($file instanceof UploadedFile) {
            $extension = File::object($file->name)->getExtension();
            $tmpfile->setExtension($extension);
            $original_file_name = $file->getBaseName();

            if (!$file->saveAs($tmpfile->getPath())) {
                throw new Exception("Файл не загружен во временную диррикторию");
            }
        } else {

            if ($file instanceof File || (is_string($file) && BaseUrl::isRelative($file))) {
                /*print_r($file);die;*/
                $file = File::object($file);
                $original_file_name = $file->getBaseName();

                $tmpfile->setExtension($file->getExtension());
                $tmpfile = $file->move($tmpfile);
            } else {
                if (is_string($file) && !BaseUrl::isRelative($file)) {

                    $client = new Client();
                    $response = $client
                        ->createRequest()
                        ->setUrl($file)
                        ->setOptions([
                            //'timeout' => 10,
                            'followLocation' => true,
                        ])
                        ->send();

                    if ($response->isOk) {
                        $file_content = $response->content;
                    } else {
                        throw new Exception("Не удалось скачать файл: {$file} " . $response->statusCode);
                    }

                    /*$curl_session = curl_init($file);

                    if (!$curl_session) {
                        throw new Exception("Неверная ссылка");
                    }

                    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($curl_session, CURLOPT_BINARYTRANSFER, true);
                    curl_setopt($curl_session, CURLOPT_FOLLOWLOCATION, true);

                    $file_content = curl_exec($curl_session);

                    curl_close($curl_session);*/

                    if (!$file_content) {
                        throw new Exception("Скачанный файл пустой: {$file}");
                    }

                    $extension = pathinfo($file, PATHINFO_EXTENSION);

                    $fileNameData = $file;

                    $fileNameData = str_replace(".", "_", $fileNameData);
                    $fileNameData = str_replace("?", "_", $fileNameData);
                    $fileNameData = str_replace("&", "_", $fileNameData);
                    $fileNameData = str_replace("?", "_", $fileNameData);

                    $original_file_name = pathinfo($fileNameData, PATHINFO_BASENAME);

                    $pos = strpos($extension, "?");

                    if ($pos === false) {

                    } else {
                        $extension = substr($extension, 0, $pos);
                    }

                    if ($extension) {
                        $tmpfile->setExtension($extension);
                    }

                    $is_file_saved = file_put_contents($tmpfile, $file_content);

                    if (!$is_file_saved) {
                        throw new Exception("Не удалось сохранить файл");
                    }

                    //Если в ссылке нет расширения
                    //if (!$extension) {
                        $tmpfile = new File($tmpfile->getPath());

                        try {
                            $mimeType = FileHelper::getMimeType($tmpfile->getPath(), null, false);
                        } catch (InvalidConfigException $e) {
                            throw new Exception("Не удалось пределить расширение файла: ".$e->getMessage());
                        }

                        if (!$mimeType) {
                            throw new Exception("Не удалось пределить расширение файла");
                        }

                        $extensions = FileHelper::getExtensionsByMimeType($mimeType);
                        if ($extensions) {
                            if (in_array("jpg", $extensions)) {
                                $extension = 'jpg';
                            } elseif(in_array("png", $extensions)) {
                                $extension = 'png';
                            } elseif(in_array("gif", $extensions)) {
                                $extension = 'gif';
                            } else {
                                if (!$extension) {
                                    $extension = $extensions[0];
                                }
                            }

                            $newFile = new File($tmpfile->getPath());
                            $newFile->setExtension($extension);

                            if ($tmpfile->getExtension() != $newFile->getExtension()) {
                                $tmpfile = $tmpfile->copy($newFile);
                            }
                        }
                    //}

                    if (!strpos($original_file_name, ".")) {
                        $original_file_name = $original_file_name . "." . $extension;
                    }

                } else {
                    throw new Exception("Файл должен быть определен как \yii\web\UploadedFile или \skeeks\sx\File или string");
                }
            }
        }

        $newData = [];

        //$data["type"]       = $tmpfile->getType();
        $newData["mime_type"] = $tmpfile->getMimeType();
        $newData["size"] = $tmpfile->size()->getBytes();
        $newData["extension"] = $tmpfile->getExtension();
        $newData["original_name"] = $original_file_name;

        //Елси это изображение
        if ($tmpfile->getType() == 'image') {
            if (extension_loaded('gd')) {
                list($width, $height, $type, $attr) = getimagesize($tmpfile->toString());
                $newData["image_height"] = $height;
                $newData["image_width"] = $width;
            }

        }

        if ($cluster = $this->getCluster($clusterId)) {
            if ($newFileSrc = $cluster->upload($tmpfile)) {
                $newData = array_merge($newData, [
                    "cluster_id"   => $cluster->id,
                    "cluster_file" => $newFileSrc,
                ]);
            }
        }

        $data = array_merge((array) $newData, (array) $data);
        $file = new StorageFile($data);
        if (!$file->save()) {
            throw new Exception("Файл не сохранен: " . print_r($file->errors, true));
        }

        return $file;
    }

    protected $_clusters = null;

    /**
     * @return Cluster[]
     */
    public function getClusters()
    {
        if ($this->_clusters === null) {
            ArrayHelper::multisort($this->components, 'priority');

            foreach ($this->components as $id => $data) {
                if (!is_int($id)) {
                    $data['id'] = $id;
                }

                $cluster = \Yii::createObject($data);
                $this->_clusters[$cluster->id] = $cluster;
            }
        }

        return $this->_clusters;
    }

    /**
     * @param null $id
     * @return Cluster
     */
    public function getCluster($id = null)
    {
        if ($id == null) {
            foreach ($this->clusters as $clusterId => $cluster) {
                return $cluster;
            }
        } else {
            return ArrayHelper::getValue($this->clusters, $id);
        }
    }
}


text:
<!--

Thanks for contributing! 🍄 Do not ignore this template, plz.

1. Does this PR close/fix an existing issue? Write something like `Closes #10`

Help us test and visualize this PR:

2. What pages does this PR affect? Include some REAL URLs where you tested the code
3. If applicable, add demonstrative screenshots or gifs

Lastly:

4. Open the PR as draft and review it yourself first. Fix what you find and explain weird code, if necessary.

-->

## Test URLs

## Screenshot


text:
<?hh // strict

namespace Dust\Helper;

use Dust\Evaluate;

class DefaultHelper
{
	/**
	 * @param \Dust\Evaluate\Chunk $chunk
	 * @param \Dust\Evaluate\Context $context
	 * @param \Dust\Evaluate\Bodies $bodies
	 * @return \Dust\Evaluate\Chunk
	 */
	public function __invoke(Evaluate\Chunk $chunk, Evaluate\Context $context, Evaluate\Bodies $bodies): Evaluate\Chunk {
		$selectInfo = $context->get("__selectInfo");
		if ($selectInfo == NULL)
			$chunk->setError("Default must be inside select");

		//check
		if (!$selectInfo->selectComparisonSatisfied)
			return $chunk->render($bodies->block, $context);
		else
			return $chunk;
	}
}