text:
const linebot = require('../index.js');

const bot = linebot({
	channelId: process.env.CHANNEL_ID,
	channelSecret: process.env.CHANNEL_SECRET,
	channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
	verify: true // default=true
});

bot.on('message', function (event) {
	switch (event.message.type) {
		case 'text':
			switch (event.message.text) {
				case 'Me':
					event.source.profile().then(function (profile) {
						return event.reply('Hello ' + profile.displayName + ' ' + profile.userId);
					});
					break;
				case 'Picture':
					event.reply({
						type: 'image',
						originalContentUrl: 'https://d.line-scdn.net/stf/line-lp/family/en-US/190X190_line_me.png',
						previewImageUrl: 'https://d.line-scdn.net/stf/line-lp/family/en-US/190X190_line_me.png'
					});
					break;
				case 'Location':
					event.reply({
						type: 'location',
						title: 'LINE Plus Corporation',
						address: '1 Empire tower, Sathorn, Bangkok 10120, Thailand',
						latitude: 13.7202068,
						longitude: 100.5298698
					});
					break;
				case 'Push':
					bot.push('U6350b7606935db981705282747c82ee1', ['Hey!', 'สวัสดี ' + String.fromCharCode(0xD83D, 0xDE01)]);
					break;
				case 'Push2':
					bot.push(['U6350b7606935db981705282747c82ee1', 'U6350b7606935db981705282747c82ee1'], ['Hey!', 'สวัสดี ' + String.fromCharCode(0xD83D, 0xDE01)]);
					break;
				case 'Multicast':
					bot.push(['U6350b7606935db981705282747c82ee1', 'U6350b7606935db981705282747c82ee1'], 'Multicast!');
					break;
				case 'Confirm':
					event.reply({
						type: 'template',
						altText: 'this is a confirm template',
						template: {
							type: 'confirm',
							text: 'Are you sure?',
							actions: [{
								type: 'message',
								label: 'Yes',
								text: 'yes'
							}, {
								type: 'message',
								label: 'No',
								text: 'no'
							}]
						}
					});
					break;
				case 'Multiple':
					return event.reply(['Line 1', 'Line 2', 'Line 3', 'Line 4', 'Line 5']);
					break;
				case 'Version':
					event.reply('linebot@' + require('../package.json').version);
					break;
				default:
					event.reply(event.message.text).then(function (data) {
						console.log('Success', data);
					}).catch(function (error) {
						console.log('Error', error);
					});
					break;
			}
			break;
		case 'image':
			event.message.content().then(function (data) {
				const s = data.toString('base64').substring(0, 30);
				return event.reply('Nice picture! ' + s);
			}).catch(function (err) {
				return event.reply(err.toString());
			});
			break;
		case 'video':
			event.reply('Nice movie!');
			break;
		case 'audio':
			event.reply('Nice song!');
			break;
		case 'location':
			event.reply(['That\'s a good location!', 'Lat:' + event.message.latitude, 'Long:' + event.message.longitude]);
			break;
		case 'sticker':
			event.reply({
				type: 'sticker',
				packageId: 1,
				stickerId: 1
			});
			break;
		default:
			event.reply('Unknow message: ' + JSON.stringify(event));
			break;
	}
});

bot.on('follow', function (event) {
	event.reply('follow: ' + event.source.userId);
});

bot.on('unfollow', function (event) {
	event.reply('unfollow: ' + event.source.userId);
});

bot.on('join', function (event) {
	event.reply('join: ' + event.source.groupId);
});

bot.on('leave', function (event) {
	event.reply('leave: ' + event.source.groupId);
});

bot.on('postback', function (event) {
	event.reply('postback: ' + event.postback.data);
});

bot.on('beacon', function (event) {
	event.reply('beacon: ' + event.beacon.hwid);
});

bot.listen('/linewebhook', process.env.PORT || 80, function () {
	console.log('LineBot is running.');
});


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="wiggle">
        <note>
            Frames file for 'wiggle' based on sentences in wsj.  No Verbnet entry.
        </note>

        <roleset id="wiggle.01" name="mode of motion" vncls="-">
            <roles>
                <role descr="entity in motion" n="0"/>
                <role descr="path" n="1"/>
            </roles>

            <example name="not the flat-headed borer!">
                <inflection aspect="ns" form="full" person="ns" tense="present" voice="active"/>
                <text>
                    Some 500 insects and 150 diseases wiggle, chew and romp through
                    growers' nightmares, including maggots, mites, mildew, thrips,
                    black rot and the flat-headed borer.
                </text>
                <arg n="0">Some 500 insects and 150 diseases</arg>
                <rel>wiggle</rel>
                <arg n="1">through growers' nightmares</arg>
                <arg n="M" f="ADV">[0] including maggots, mites, mildew, thrips, black rot
                    and the flat-headed borer
                </arg>
            </example>

            <note>
            </note>

        </roleset>

        <roleset id="wiggle.02" name="cause to wiggle" vncls="-">
            <roles>
                <role descr="causer" n="0"/>
                <role descr="thing wiggling" n="1"/>
            </roles>

            <example name="wiggling fanny">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    ``She just wiggled her fanny and all the French fell in love with
                    her,'' sniffed the literary world's Maria Jolas, not entirely
                    inaccurately.
                </text>
                <arg n="0">She</arg>
                <arg f="DIS" n="M">just</arg>
                <rel>wiggled</rel>
                <arg n="1">her fanny</arg>
            </example>

            <note>
                Rolesets could be merged?
            </note>

        </roleset>
    </predicate>
</frameset>

redpajama_set_name: RedPajamaGithub


text:
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.CMS.Sites.Models;
using Kooboo.CMS.Sites.Persistence;
using Kooboo.Extensions;
using Kooboo.CMS.Common.Persistence.Non_Relational;

namespace Kooboo.CMS.Sites.Services
{
    [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(UserManager))]
    public class UserManager : ManagerBase<User, IUserProvider>
    {
        #region .ctor
        Kooboo.CMS.Account.Services.UserManager _accountUserManager;
        Kooboo.CMS.Account.Services.RoleManager _accountRoleManager;
        public UserManager(IUserProvider provider, Kooboo.CMS.Account.Services.UserManager accountUserManager, Kooboo.CMS.Account.Services.RoleManager roleManager)
            : base(provider)
        {
            this._accountUserManager = accountUserManager;
            this._accountRoleManager = roleManager;
        }

        #endregion

        #region All/Get/Update
        public override IEnumerable<User> All(Site site, string filterName)
        {
            var result = Provider.All(site).Select(it => it.AsActual());
            if (!string.IsNullOrEmpty(filterName))
            {
                result = result.Where(it => it.UserName.Contains(filterName, StringComparison.CurrentCultureIgnoreCase));
            }
            return result;
        }

        public override User Get(Site site, string name)
        {
            return Provider.Get(new User() { Site = site, UserName = name });
        }

        public override void Update(Site site, User @new, User old)
        {
            @new.Site = site;
            @old.Site = site;
            Provider.Update(@new, @old);
        }
        #endregion

        #region IsInRole
        public virtual bool IsInRole(Site site, string userName, string role)
        {
            if (IsAdministrator(userName))
            {
                return true;
            }
            var siteUser = this.Get(site, userName);

            if (siteUser != null && siteUser.Roles != null)
            {
                return siteUser.Roles.Any(it => it.EqualsOrNullEmpty(role, StringComparison.OrdinalIgnoreCase));
            }
            return false;
        }
        #endregion

        #region Authorize
        public virtual bool Authorize(Site site, string userName, Kooboo.CMS.Account.Models.Permission permission)
        {
            string contextKey = "Permission:" + permission.ToString();
            var allow = CallContext.Current.GetObject<bool?>(contextKey);
            if (!allow.HasValue)
            {
                allow = false;

                if (IsAdministrator(userName))
                {
                    allow = true;
                }
                else
                {
                    var roles = GetRoles(site, userName);
                    allow = roles.Any(it => it.HasPermission(permission));
                }
                CallContext.Current.RegisterObject(contextKey, allow);
            }
            return allow.Value;
        }

        public virtual bool IsAdministrator(string userName)
        {
            var accountUser = _accountUserManager.Get(userName);
            if (accountUser == null)
            {
                return false;
            }
            return accountUser.IsAdministrator;
        }

        public virtual bool AllowCreatingSite(string userName)
        {
            return IsAdministrator(userName);
        }

        protected virtual IEnumerable<Kooboo.CMS.Account.Models.Role> GetRoles(Site site, string userName)
        {
            if (site != null)
            {
                var siteUser = this.Get(site, userName);

                if (siteUser != null && siteUser.Roles != null)
                {
                    return siteUser.Roles.Select(it => _accountRoleManager.Get(it)).Where(it => it != null);
                }
            }

            var accountUser = _accountUserManager.Get(userName);
            if (accountUser != null && !string.IsNullOrEmpty(accountUser.GlobalRoles))
            {
                return accountUser.GlobalRoles.Split(",".ToArray(), StringSplitOptions.RemoveEmptyEntries).Select(it => _accountRoleManager.Get(it)).Where(it => it != null);
            }

            return new Kooboo.CMS.Account.Models.Role[0];
        }
        public virtual bool Authorize(Site site, string userName)
        {
            if (IsAdministrator(userName))
            {
                return true;
            }
            return GetRoles(site, userName).Count() > 0;
        }
        #endregion

    }
}


text:
#pragma once

#include <cl2hpp.hpp>
#include <kernel/KParam.hpp>

namespace opencl {

struct Param {
    cl::Buffer* data;
    KParam info;
    Param& operator=(const Param& other) = default;
    Param(const Param& other)            = default;
    Param(Param&& other)                 = default;

    // AF_DEPRECATED("Use Array<T>")
    Param();
    // AF_DEPRECATED("Use Array<T>")
    Param(cl::Buffer* data_, KParam info_);
    ~Param() = default;
};

// AF_DEPRECATED("Use Array<T>")
Param makeParam(cl::Buffer& mem, int off, const int dims[4],
                const int strides[4]);
}  // namespace opencl


text:
package com.intellij.refactoring.actions;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.replaceConstructorWithBuilder.ReplaceConstructorWithBuilderHandler;
import org.jetbrains.annotations.NotNull;

public class ReplaceConstructorWithBuilderAction extends BaseRefactoringAction{
  @Override
  protected boolean isAvailableInEditorOnly() {
    return true;
  }

  @Override
  protected boolean isAvailableOnElementInEditorAndFile(@NotNull PsiElement element, @NotNull Editor editor, @NotNull PsiFile file, @NotNull DataContext context) {
    final int offset = editor.getCaretModel().getOffset();
    final PsiElement elementAt = file.findElementAt(offset);
    final PsiClass psiClass = ReplaceConstructorWithBuilderHandler.getParentNamedClass(elementAt);
    return psiClass != null && psiClass.getConstructors().length > 0 && !psiClass.isEnum();
  }

  @Override
  protected boolean isEnabledOnElements(@NotNull final PsiElement[] elements) {
    return false;
  }

  @Override
  protected RefactoringActionHandler getHandler(@NotNull final DataContext dataContext) {
    return new ReplaceConstructorWithBuilderHandler();
  }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\AdminBundle\Event;

use Knp\Menu\FactoryInterface;
use Knp\Menu\ItemInterface;
use SM\StateMachine\StateMachineInterface;
use Sylius\Bundle\UiBundle\Menu\Event\MenuBuilderEvent;
use Sylius\Component\Core\Model\OrderInterface;

class OrderShowMenuBuilderEvent extends MenuBuilderEvent
{
    public function __construct(
        FactoryInterface $factory,
        ItemInterface $menu,
        private OrderInterface $order,
        private StateMachineInterface $stateMachine
    ) {
        parent::__construct($factory, $menu);
    }

    public function getOrder(): OrderInterface
    {
        return $this->order;
    }

    public function getStateMachine(): StateMachineInterface
    {
        return $this->stateMachine;
    }
}


text:
'use strict';

function getIPAddress() {
    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
                return alias.address;
        }
    }
    return '0.0.0.0';
}

module.exports = {
    env: 'development',
    host: 'localhost', //getIPAddress(),
    port: 9000,
    secret: 'base_secret',
    mongo: {
        uri: 'mongodb://localhost/',
        db: 'base',
        username: '',
        password: ''
    }

};


text:
A Swift Wrapper for NSTimer that uses a closure instead of a selector for the firing action, for a more modern timer API.

## Usage

Use SwiftTimer for the most part like you would use NSTimer. The notable exception is that it takes a closure instead of a selector for the firing action, providing a more modern API, and freeing it to be used in otherwise "Pure Swift" code. All the other rules for NSTimer apply. Be sure to invalidate it when you're done with it to avoid memory leaks and retain cycles.

Create a timer:

``` swift
self.timer = SwiftTimer(timeInterval: 0.01, userInfo: nil, repeats: true) {   [unowned self] timer in
 // Do your stuff here
// Access the timer instance and the userInfo dictionary
if let dictionary = timer.userInfo {....}
}
 ```
Fire off the timer:

`self.timer?.fire()`

Invalidate The Timer:

`self.timer?.invalidate()`
`self.timer = nil`

Check to see if your timer is currently running:

`if self.timer?.running {...}`

## License:
SwiftTimer is free to use under the MIT License.


text:
//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.pda.struts.actions;

import com.openbravo.pos.pda.bo.RestaurantManager;
import com.openbravo.pos.ticket.CategoryInfo;
import com.openbravo.pos.ticket.ProductInfo;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.DynaActionForm;

/**
 *
 * @author jaroslawwozniak
 */
public class ProductAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        DynaActionForm inputFormPlace = (DynaActionForm) form;
        RestaurantManager manager = new RestaurantManager();
        List<CategoryInfo> categories = new ArrayList<CategoryInfo>();
        categories = manager.findAllCategories();
        List products = new ArrayList<ProductInfo>();
        products = manager.findProductsByCategory(categories.get(0).getId());
        List taxRates = new ArrayList<String>();
        taxRates = manager.findAllTaxRatesByCategory(products);
        List subcategories = new ArrayList<CategoryInfo>();
        subcategories = manager.findAllSubcategories(categories.get(0).getId());

        request.setAttribute("products", products);
        request.setAttribute("rates", taxRates);
        request.getSession().setAttribute("place", (String) inputFormPlace.get("place"));
        request.setAttribute("placeName", manager.findPlaceNameById((String) inputFormPlace.get("place")));
        request.setAttribute("categories", categories);
        request.setAttribute("subcategories", subcategories);
        request.getSession().setAttribute("floorId", (String) inputFormPlace.get("floorId"));

        return mapping.findForward(SUCCESS);
    }
}


text:
package io.warp10.script.ext.inmemory;

import io.warp10.continuum.Configuration;
import io.warp10.continuum.store.Constants;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptStack;
import io.warp10.script.WarpScriptStackFunction;
import io.warp10.script.WarpScriptException;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;

public class IMINFO extends NamedWarpScriptFunction implements WarpScriptStackFunction {

    //private static final Logger LOG = LoggerFactory.getLogger(IMINFO.class);
    private final Map<String,Object> infos;
    private final long startTime;

    public IMINFO(String name, Properties warpConfigProperties) {
        super(name);
        //System.out.println("NEW IMINFO");

        this.infos = new HashMap<String, Object>();
        this.startTime = System.currentTimeMillis();

        if (warpConfigProperties.containsKey(Configuration.IN_MEMORY_CHUNKED)) {
            String chunkedStr = warpConfigProperties.getProperty(Configuration.IN_MEMORY_CHUNKED);
            infos.put("isChunked", "true".equals(chunkedStr));
        }
        if (warpConfigProperties.containsKey(Configuration.IN_MEMORY_CHUNK_COUNT)) {
            String chunkCountStr = warpConfigProperties.getProperty(Configuration.IN_MEMORY_CHUNK_COUNT);
            infos.put("chunkCount", Integer.parseInt(chunkCountStr));
        }
        if (warpConfigProperties.containsKey(Configuration.IN_MEMORY_CHUNK_LENGTH)) {
            String chunkDurationStr = warpConfigProperties.getProperty(Configuration.IN_MEMORY_CHUNK_LENGTH);
            infos.put("chunkDuration", Long.parseLong(chunkDurationStr));
        }
    }

    @Override
    public Object apply(WarpScriptStack stack) throws WarpScriptException {

        long uptime = System.currentTimeMillis() - this.startTime;
        this.infos.put("uptime", uptime * Constants.TIME_UNITS_PER_MS);

        stack.push(this.infos);
        return stack;
    }
}


text: Image sharing service written using Flask.


text:
@interface UILabel (JMCVerticalAlign)

- (void)jmc_alignTop;
- (void)jmc_alignBottom;

@end


text:
'use strict';

exports.assign = function (tokenizer) {
    //NOTE: obtain Tokenizer proto this way to avoid module circular references
    var tokenizerProto = Object.getPrototypeOf(tokenizer);

    tokenizer.tokenStartLoc = -1;

    //NOTE: add location info builder method
    tokenizer._attachLocationInfo = function (token) {
        token.location = {
            start: this.tokenStartLoc,
            end: -1
        };
    };

    //NOTE: patch token creation methods and attach location objects
    tokenizer._createStartTagToken = function (tagNameFirstCh) {
        tokenizerProto._createStartTagToken.call(this, tagNameFirstCh);
        this._attachLocationInfo(this.currentToken);
    };

    tokenizer._createEndTagToken = function (tagNameFirstCh) {
        tokenizerProto._createEndTagToken.call(this, tagNameFirstCh);
        this._attachLocationInfo(this.currentToken);
    };

    tokenizer._createCommentToken = function () {
        tokenizerProto._createCommentToken.call(this);
        this._attachLocationInfo(this.currentToken);
    };

    tokenizer._createDoctypeToken = function (doctypeNameFirstCh) {
        tokenizerProto._createDoctypeToken.call(this, doctypeNameFirstCh);
        this._attachLocationInfo(this.currentToken);
    };

    tokenizer._createCharacterToken = function (type, ch) {
        tokenizerProto._createCharacterToken.call(this, type, ch);
        this._attachLocationInfo(this.currentCharacterToken);
    };

    //NOTE: patch token emission methods to determine end location
    tokenizer._emitCurrentToken = function () {
        //NOTE: if we have pending character tokenmake it's end location equal to the
        //current token's start location.
        if (this.currentCharacterToken)
            this.currentCharacterToken.location.end = this.currentToken.location.start;

        this.currentToken.location.end = this.preprocessor.pos + 1;
        tokenizerProto._emitCurrentToken.call(this);
    };

    tokenizer._emitCurrentCharacterToken = function () {
        //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(),
        //then set it's location at the current preprocessor position
        if (this.currentCharacterToken && this.currentCharacterToken.location.end === -1) {
            //NOTE: we don't need to increment preprocessor position here, since character token
            //emission here is always forced by the start of the next token character token.
            //So, we already have advanced position here.
            this.currentCharacterToken.location.end = this.preprocessor.pos;
        }

        tokenizerProto._emitCurrentCharacterToken.call(this);
    };

    //NOTE: patch initial states for each mode to obtain token start position
    Object.keys(tokenizerProto.MODE)

        .map(function (modeName) {
            return tokenizerProto.MODE[modeName];
        })

        .forEach(function (state) {
            tokenizer[state] = function (cp) {
                this.tokenStartLoc = this.preprocessor.pos;
                tokenizerProto[state].call(this, cp);
            };
        });
};


text:
@implementation CustomScrollView
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self == nil) {
        return nil;
    }
    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanGesture:)];
    [self addGestureRecognizer:gestureRecognizer];
    return self;
}

-(void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer{
    CGPoint translation = [gestureRecognizer translationInView:self];
    CGRect bounds = self.bounds;

    CGFloat newBoundsOriginX = bounds.origin.x - translation.x;
    CGFloat minBoundsOriginX = 0.0;
    CGFloat maxBoundsOriginX = self.contentSize.width - bounds.size.width;
    bounds.origin.x = fmax(minBoundsOriginX, fmin(newBoundsOriginX, maxBoundsOriginX));

    CGFloat newBoundsOriginY = bounds.origin.y - translation.y;
    CGFloat minBoundsOriginY = 0.0;
    CGFloat maxBoundsOriginY = self.contentSize.height - bounds.size.height;
    bounds.origin.y = fmax(minBoundsOriginY, fmin(newBoundsOriginY, maxBoundsOriginY));

    self.bounds = bounds;
    [gestureRecognizer setTranslation:CGPointZero inView:self];
}
@end


text:
'''
 Unit tests for oc service
'''

import os
import six
import sys
import unittest
import mock

# Removing invalid variable names for tests so that I can
# keep them brief
# pylint: disable=invalid-name,no-name-in-module
# Disable import-error b/c our libraries aren't loaded in jenkins
# pylint: disable=import-error
# place class in our python path
module_path = os.path.join('/'.join(os.path.realpath(__file__).split('/')[:-4]), 'library')  # noqa: E501
sys.path.insert(0, module_path)
from oc_service import OCService, locate_oc_binary  # noqa: E402

# pylint: disable=too-many-public-methods
class OCServiceTest(unittest.TestCase):
    '''
     Test class for OCService
    '''

    @mock.patch('oc_service.Utils.create_tmpfile_copy')
    @mock.patch('oc_service.OCService._run')
    def test_state_list(self, mock_cmd, mock_tmpfile_copy):
        ''' Testing a get '''
        params = {'name': 'router',
                  'namespace': 'default',
                  'ports': None,
                  'state': 'list',
                  'labels': None,
                  'clusterip': None,
                  'portalip': None,
                  'selector': None,
                  'session_affinity': None,
                  'service_type': None,
                  'external_ips': None,
                  'kubeconfig': '/etc/origin/master/admin.kubeconfig',
                  'debug': False}

        service = '''{
            "kind": "Service",
            "apiVersion": "v1",
            "metadata": {
                "name": "router",
                "namespace": "default",
                "selfLink": "/api/v1/namespaces/default/services/router",
                "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa",
                "resourceVersion": "3206",
                "creationTimestamp": "2017-01-26T15:06:14Z",
                "labels": {
                    "router": "router"
                }
            },
            "spec": {
                "ports": [
                    {
                        "name": "80-tcp",
                        "protocol": "TCP",
                        "port": 80,
                        "targetPort": 80
                    },
                    {
                        "name": "443-tcp",
                        "protocol": "TCP",
                        "port": 443,
                        "targetPort": 443
                    },
                    {
                        "name": "1936-tcp",
                        "protocol": "TCP",
                        "port": 1936,
                        "targetPort": 1936
                    },
                    {
                        "name": "5000-tcp",
                        "protocol": "TCP",
                        "port": 5000,
                        "targetPort": 5000
                    }
                ],
                "selector": {
                    "router": "router"
                },
                "clusterIP": "172.30.129.161",
                "type": "ClusterIP",
                "sessionAffinity": "None"
            },
            "status": {
                "loadBalancer": {}
            }
        }'''
        mock_cmd.side_effect = [
            (0, service, '')
        ]

        mock_tmpfile_copy.side_effect = [
            '/tmp/mocked_kubeconfig',
        ]

        results = OCService.run_ansible(params, False)

        self.assertFalse(results['changed'])
        self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router')

    @mock.patch('oc_service.Utils.create_tmpfile_copy')
    @mock.patch('oc_service.OCService._run')
    def test_create(self, mock_cmd, mock_tmpfile_copy):
        ''' Testing a create service '''
        params = {'name': 'router',
                  'namespace': 'default',
                  'ports': {'name': '9000-tcp',
                            'port': 9000,
                            'protocol': 'TCP',
                            'targetPOrt': 9000},
                  'state': 'present',
                  'labels': None,
                  'clusterip': None,
                  'portalip': None,
                  'selector': {'router': 'router'},
                  'session_affinity': 'ClientIP',
                  'service_type': 'ClusterIP',
                  'external_ips': None,
                  'kubeconfig': '/etc/origin/master/admin.kubeconfig',
                  'debug': False}

        service = '''{
            "kind": "Service",
            "apiVersion": "v1",
            "metadata": {
                "name": "router",
                "namespace": "default",
                "selfLink": "/api/v1/namespaces/default/services/router",
                "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa",
                "resourceVersion": "3206",
                "creationTimestamp": "2017-01-26T15:06:14Z",
                "labels": {
                    "router": "router"
                }
            },
            "spec": {
                "ports": [
                    {
                        "name": "80-tcp",
                        "protocol": "TCP",
                        "port": 80,
                        "targetPort": 80
                    },
                    {
                        "name": "443-tcp",
                        "protocol": "TCP",
                        "port": 443,
                        "targetPort": 443
                    },
                    {
                        "name": "1936-tcp",
                        "protocol": "TCP",
                        "port": 1936,
                        "targetPort": 1936
                    },
                    {
                        "name": "5000-tcp",
                        "protocol": "TCP",
                        "port": 5000,
                        "targetPort": 5000
                    }
                ],
                "selector": {
                    "router": "router"
                },
                "clusterIP": "172.30.129.161",
                "type": "ClusterIP",
                "sessionAffinity": "None"
            },
            "status": {
                "loadBalancer": {}
            }
        }'''
        mock_cmd.side_effect = [
            (1, '', 'Error from server: services "router" not found'),
            (1, '', 'Error from server: services "router" not found'),
            (0, service, ''),
            (0, service, '')
        ]

        mock_tmpfile_copy.side_effect = [
            '/tmp/mocked_kubeconfig',
        ]

        results = OCService.run_ansible(params, False)

        self.assertTrue(results['changed'])
        self.assertTrue(results['results']['returncode'] == 0)
        self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router')

    @unittest.skipIf(six.PY3, 'py2 test only')
    @mock.patch('os.path.exists')
    @mock.patch('os.environ.get')
    def test_binary_lookup_fallback(self, mock_env_get, mock_path_exists):
        ''' Testing binary lookup fallback '''

        mock_env_get.side_effect = lambda _v, _d: ''

        mock_path_exists.side_effect = lambda _: False

        self.assertEqual(locate_oc_binary(), 'oc')

    @unittest.skipIf(six.PY3, 'py2 test only')
    @mock.patch('os.path.exists')
    @mock.patch('os.environ.get')
    def test_binary_lookup_in_path(self, mock_env_get, mock_path_exists):
        ''' Testing binary lookup in path '''

        oc_bin = '/usr/bin/oc'

        mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin'

        mock_path_exists.side_effect = lambda f: f == oc_bin

        self.assertEqual(locate_oc_binary(), oc_bin)

    @unittest.skipIf(six.PY3, 'py2 test only')
    @mock.patch('os.path.exists')
    @mock.patch('os.environ.get')
    def test_binary_lookup_in_usr_local(self, mock_env_get, mock_path_exists):
        ''' Testing binary lookup in /usr/local/bin '''

        oc_bin = '/usr/local/bin/oc'

        mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin'

        mock_path_exists.side_effect = lambda f: f == oc_bin

        self.assertEqual(locate_oc_binary(), oc_bin)

    @unittest.skipIf(six.PY3, 'py2 test only')
    @mock.patch('os.path.exists')
    @mock.patch('os.environ.get')
    def test_binary_lookup_in_home(self, mock_env_get, mock_path_exists):
        ''' Testing binary lookup in ~/bin '''

        oc_bin = os.path.expanduser('~/bin/oc')

        mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin'

        mock_path_exists.side_effect = lambda f: f == oc_bin

        self.assertEqual(locate_oc_binary(), oc_bin)

    @unittest.skipIf(six.PY2, 'py3 test only')
    @mock.patch('shutil.which')
    @mock.patch('os.environ.get')
    def test_binary_lookup_fallback_py3(self, mock_env_get, mock_shutil_which):
        ''' Testing binary lookup fallback '''

        mock_env_get.side_effect = lambda _v, _d: ''

        mock_shutil_which.side_effect = lambda _f, path=None: None

        self.assertEqual(locate_oc_binary(), 'oc')

    @unittest.skipIf(six.PY2, 'py3 test only')
    @mock.patch('shutil.which')
    @mock.patch('os.environ.get')
    def test_binary_lookup_in_path_py3(self, mock_env_get, mock_shutil_which):
        ''' Testing binary lookup in path '''

        oc_bin = '/usr/bin/oc'

        mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin'

        mock_shutil_which.side_effect = lambda _f, path=None: oc_bin

        self.assertEqual(locate_oc_binary(), oc_bin)

    @unittest.skipIf(six.PY2, 'py3 test only')
    @mock.patch('shutil.which')
    @mock.patch('os.environ.get')
    def test_binary_lookup_in_usr_local_py3(self, mock_env_get, mock_shutil_which):
        ''' Testing binary lookup in /usr/local/bin '''

        oc_bin = '/usr/local/bin/oc'

        mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin'

        mock_shutil_which.side_effect = lambda _f, path=None: oc_bin

        self.assertEqual(locate_oc_binary(), oc_bin)

    @unittest.skipIf(six.PY2, 'py3 test only')
    @mock.patch('shutil.which')
    @mock.patch('os.environ.get')
    def test_binary_lookup_in_home_py3(self, mock_env_get, mock_shutil_which):
        ''' Testing binary lookup in ~/bin '''

        oc_bin = os.path.expanduser('~/bin/oc')

        mock_env_get.side_effect = lambda _v, _d: '/bin:/usr/bin'

        mock_shutil_which.side_effect = lambda _f, path=None: oc_bin

        self.assertEqual(locate_oc_binary(), oc_bin)

    @mock.patch('oc_service.Utils.create_tmpfile_copy')
    @mock.patch('oc_service.OCService._run')
    def test_create_with_labels(self, mock_cmd, mock_tmpfile_copy):
        ''' Testing a create service '''
        params = {'name': 'router',
                  'namespace': 'default',
                  'ports': {'name': '9000-tcp',
                            'port': 9000,
                            'protocol': 'TCP',
                            'targetPOrt': 9000},
                  'state': 'present',
                  'labels': {'component': 'some_component', 'infra': 'true'},
                  'clusterip': None,
                  'portalip': None,
                  'selector': {'router': 'router'},
                  'session_affinity': 'ClientIP',
                  'service_type': 'ClusterIP',
                  'external_ips': None,
                  'kubeconfig': '/etc/origin/master/admin.kubeconfig',
                  'debug': False}

        service = '''{
            "kind": "Service",
            "apiVersion": "v1",
            "metadata": {
                "name": "router",
                "namespace": "default",
                "selfLink": "/api/v1/namespaces/default/services/router",
                "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa",
                "resourceVersion": "3206",
                "creationTimestamp": "2017-01-26T15:06:14Z",
                "labels": {"component": "some_component", "infra": "true"}
            },
            "spec": {
                "ports": [
                    {
                        "name": "80-tcp",
                        "protocol": "TCP",
                        "port": 80,
                        "targetPort": 80
                    },
                    {
                        "name": "443-tcp",
                        "protocol": "TCP",
                        "port": 443,
                        "targetPort": 443
                    },
                    {
                        "name": "1936-tcp",
                        "protocol": "TCP",
                        "port": 1936,
                        "targetPort": 1936
                    },
                    {
                        "name": "5000-tcp",
                        "protocol": "TCP",
                        "port": 5000,
                        "targetPort": 5000
                    }
                ],
                "selector": {
                    "router": "router"
                },
                "clusterIP": "172.30.129.161",
                "type": "ClusterIP",
                "sessionAffinity": "None"
            },
            "status": {
                "loadBalancer": {}
            }
        }'''
        mock_cmd.side_effect = [
            (1, '', 'Error from server: services "router" not found'),
            (1, '', 'Error from server: services "router" not found'),
            (0, service, ''),
            (0, service, '')
        ]

        mock_tmpfile_copy.side_effect = [
            '/tmp/mocked_kubeconfig',
        ]

        results = OCService.run_ansible(params, False)

        self.assertTrue(results['changed'])
        self.assertTrue(results['results']['returncode'] == 0)
        self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router')
        self.assertEqual(results['results']['results'][0]['metadata']['labels'], {"component": "some_component", "infra": "true"})

    @mock.patch('oc_service.Utils.create_tmpfile_copy')
    @mock.patch('oc_service.OCService._run')
    def test_create_with_external_ips(self, mock_cmd, mock_tmpfile_copy):
        ''' Testing a create service '''
        params = {'name': 'router',
                  'namespace': 'default',
                  'ports': {'name': '9000-tcp',
                            'port': 9000,
                            'protocol': 'TCP',
                            'targetPOrt': 9000},
                  'state': 'present',
                  'labels': {'component': 'some_component', 'infra': 'true'},
                  'clusterip': None,
                  'portalip': None,
                  'selector': {'router': 'router'},
                  'session_affinity': 'ClientIP',
                  'service_type': 'ClusterIP',
                  'external_ips': ['1.2.3.4', '5.6.7.8'],
                  'kubeconfig': '/etc/origin/master/admin.kubeconfig',
                  'debug': False}

        service = '''{
            "kind": "Service",
            "apiVersion": "v1",
            "metadata": {
                "name": "router",
                "namespace": "default",
                "selfLink": "/api/v1/namespaces/default/services/router",
                "uid": "fabd2440-e3d8-11e6-951c-0e3dd518cefa",
                "resourceVersion": "3206",
                "creationTimestamp": "2017-01-26T15:06:14Z",
                "labels": {"component": "some_component", "infra": "true"}
            },
            "spec": {
                "ports": [
                    {
                        "name": "80-tcp",
                        "protocol": "TCP",
                        "port": 80,
                        "targetPort": 80
                    },
                    {
                        "name": "443-tcp",
                        "protocol": "TCP",
                        "port": 443,
                        "targetPort": 443
                    },
                    {
                        "name": "1936-tcp",
                        "protocol": "TCP",
                        "port": 1936,
                        "targetPort": 1936
                    },
                    {
                        "name": "5000-tcp",
                        "protocol": "TCP",
                        "port": 5000,
                        "targetPort": 5000
                    }
                ],
                "selector": {
                    "router": "router"
                },
                "clusterIP": "172.30.129.161",
                "externalIPs": ["1.2.3.4", "5.6.7.8"],
                "type": "ClusterIP",
                "sessionAffinity": "None"
            },
            "status": {
                "loadBalancer": {}
            }
        }'''
        mock_cmd.side_effect = [
            (1, '', 'Error from server: services "router" not found'),
            (1, '', 'Error from server: services "router" not found'),
            (0, service, ''),
            (0, service, '')
        ]

        mock_tmpfile_copy.side_effect = [
            '/tmp/mocked_kubeconfig',
        ]

        results = OCService.run_ansible(params, False)

        self.assertTrue(results['changed'])
        self.assertTrue(results['results']['returncode'] == 0)
        self.assertEqual(results['results']['results'][0]['metadata']['name'], 'router')
        self.assertEqual(results['results']['results'][0]['metadata']['labels'], {"component": "some_component", "infra": "true"})
        self.assertEqual(results['results']['results'][0]['spec']['externalIPs'], ["1.2.3.4", "5.6.7.8"])


text:
using VocaDb.Model.Domain.Versioning;

namespace VocaDb.Model.DataContracts.Versioning {

	public class ArchivedObjectVersionWithFieldsContract<TFields, TReason>
		: ArchivedObjectVersionContract {

		public ArchivedObjectVersionWithFieldsContract() { }

		public ArchivedObjectVersionWithFieldsContract(ArchivedObjectVersion archivedVersion,
			TFields fields, TReason reason)
			: base(archivedVersion) {

			ChangedFields = fields;
			Reason = reason;

		}

		public TFields ChangedFields { get; set; }

		public TReason Reason { get; set; }

	}

	public static class ArchivedObjectVersionWithFieldsContract {

		public static ArchivedObjectVersionWithFieldsContract<TFields, TReason> Create<TFields, TReason>(
			ArchivedObjectVersion archivedVersion,
			TFields fields, TReason reason) {
			return new ArchivedObjectVersionWithFieldsContract<TFields, TReason>(archivedVersion, fields, reason);
		}

	}

}


text:
export * from './newSound';
export * from './sounds';


text:
@interface SobotTest6 : NSObject

- (void)sayHello:(NSString *)str;
@end


text:
package com.google.gwt.sample.guestbook.client;

import com.google.gwt.canvas.dom.client.CssColor;
import com.google.gwt.sample.guestbook.client.Orbital.Mass;
import com.google.gwt.sample.guestbook.client.Orbital.OrbitalObserver;

public class CanvasOrbital extends CanvasCustom implements OrbitalObserver
{
    public enum PaintEffect{
        PARTICULAR,
        STROBE,
        STREAM,
    }

    private static final CssColor backgoundColour = CssColor.make( 255, 255, 255 );
    private PaintEffect effect = PaintEffect.PARTICULAR;
    private Orbital orbital;
    private Mass[] bodies;
    private double[] coord = new double[2];

    public void setOrbital( Orbital orbital )
    {
    	if( orbital != null ){
//        	orbital.removeObserver();
        	//TODO Clear existing.
        }
    	this.orbital = orbital;
        bodies = orbital.getBodies();
        orbital.addObserver( this );
        init();
    }

    @Override
    public void init()
    {
        context.closePath();
        context.beginPath();
        context.clearRect( 0, 0, WIDTH, HEIGHT );

        for( Mass body : bodies = orbital.getBodies() ){
            context.setFillStyle( CssColor.make( "red" ) );
            context.fillRect( body.x, body.y, 3, 3 );
            context.stroke();
        }

        orbital.getOrbiterLocation( coord );
        context.moveTo( x = (int)coord[0], y = (int)coord[1] );
//        context.closePath();
    }

    public void setPaintEffect( PaintEffect newEffect )
    {
    	if( effect == PaintEffect.PARTICULAR  &&  newEffect != PaintEffect.PARTICULAR ){
    		//Clear the particle pixels before the next effect is painted otherwise the next effect will not correctly erase it.
            context.beginPath();
            context.setFillStyle( backgoundColour );
            context.fillRect( x, y, 3, 3 );
            context.stroke();
            context.closePath();
    	}
        effect = newEffect;
    }

    public void getControlPanel()
    {

    }

//    /* (non-Javadoc)
//     * @see com.google.gwt.sample.guestbook.client.CanvasExt#updateCanvas()
//     */
    @Override
    public void updateCanvas()
    {
//        randomIncrementColour();
//
//        orbital.iterate();
//        orbital.getOrbiterCoord( coord );
//
//        switch( effect ){
//        case PARTICULAR:
//            context.setFillStyle( backgoundColour );
//            context.fillRect( x, y, 3, 3 );
//            context.stroke();
//            context.setFillStyle( colour );
//            context.fillRect( x = coord[0], y = coord[1], 3, 3 );
//            context.stroke();
//            break;
//        case STROBE:
//            context.setFillStyle( colour );
//            context.fillRect( x = coord[0], y = coord[1], 2, 2 );
//            context.stroke();
//            break;
//        case STREAM:
//            context.beginPath();
//            context.setStrokeStyle( colour );
//            context.moveTo( x, y );
//            context.lineTo( x = coord[0], y = coord[1] );
//            context.stroke();
//            context.closePath();
//            break;
//        }
    }

    /* (non-Javadoc)
     * @see com.google.gwt.sample.guestbook.client.Orbital.OrbitalObserver#orbiterMovedTo(double, double)
     */
    @Override
    public void orbiterMovedTo( double newX, double newY )
    {
        randomIncrementColour();

        switch( effect ){
        case PARTICULAR:
            context.beginPath();
            context.setFillStyle( backgoundColour );
            context.fillRect( x, y, 3, 3 );
            context.stroke();
            context.setFillStyle( colour );
            context.fillRect( x = (int)newX, y = (int)newY, 3, 3 );
            context.stroke();
            context.closePath();
            break;
        case STROBE:
            context.beginPath();
            context.setFillStyle( colour );
            context.fillRect( x = (int)newX, y = (int)newY, 2, 2 );
            context.stroke();
            context.closePath();
            break;
        case STREAM:
            context.beginPath();
            context.moveTo( x, y );
            context.setStrokeStyle( colour );
            context.lineTo( x = (int)newX, y = (int)newY );
            context.stroke();
            context.closePath();
            break;
        }
    }

    /* (non-Javadoc)
     * @see com.google.gwt.sample.guestbook.client.Orbital.OrbitalObserver#numberOfBodiesChanged(com.google.gwt.sample.guestbook.client.Orbital.Mass[])
     */
    @Override
    public void numberOfBodiesChanged( Mass[] bodies )
    {
        for( Mass body : this.bodies ){
            context.setFillStyle( backgoundColour );
            context.fillRect( body.x, body.y, 3, 3 );
            context.stroke();
        }
        for( Mass body : this.bodies = bodies ){
            context.setFillStyle( CssColor.make( "red" ) );
            context.fillRect( body.x, body.y, 3, 3 );
            context.stroke();
        }
    }
}


text:
using DragonSpark.Model.Selection.Conditions;
using DragonSpark.Model.Sequences;
using System.Reflection;

namespace DragonSpark.Reflection;

public interface IMetadata<T> : IConditional<ICustomAttributeProvider, Array<T>> {}


text:
[![npm](https://img.shields.io/npm/v/gtran-kml.svg)](https://www.npmjs.com/package/gtran-kml) [![Build Status](https://travis-ci.org/haoliangyu/gtran-kml.svg?branch=master)](https://travis-ci.org/haoliangyu/gtran-kml)

Convert geojson to kml file and backwards.

This is a sub-project of [gtran](https://github.com/haoliangyu/gtran).

## Installation

```javascript
npm install gtran-kml
```

## Functions

- **fromGeoJson(geojson, fileName, options)**

  Save the geojson into the given file name.

  Since **1.1.11**, it also supports Mapbox's [simplestyle-spec](https://github.com/mapbox/simplestyle-spec).

  options:

  - documentName - Specify the name of the full document. The Default value is **'My KML'**.

  - documentDescription - Specify the description of the full document. The Default value is **'Converted from GeoJson by gtran-kml'**.

  - name - Specify the feature name using a geojson property. The Default value is **'name'**.

  - featureStyleKey - Specify the xml style key in the xml feature properties.

  - symbol - Specify feature Symbol. It accepts an symbol object or a function to return the symbol per feature.

    Supported styles:

    - Point

      - color - HTML color code or array of RGB values, indicating feature color.

      - alpha - An integer value (0-255), indicating the color opacity

      - scale - Feature size, a float number.

      - icon - Link of feature icons. Some generally used icons can be found [here](http://kml4earth.appspot.com/icons.html).

    - LineString

      - color - HTML color code or array of RGB values, indicating feature color.

      - alpha - An integer value (0-255), indicating the color opacity

      - width - A float value, indicating line width.

    - Polygon

      - color - HTML color code or array of RGB values, indicating feature color.

      - alpha - An integer value (0-255), indicating the color opacity

      - fill - A boolean value, indicating whether to fill the polygon.

      - outline - A boolean value, indicating whether to outline the polygon.

  See the detail explaination at [KML format reference](https://developers.google.com/kml/documentation/kmlreference).

  - pretty - Pretty print the output KML. The default value is **false**.

- **toGeoJson(fileName)**

  Read the given file into geojson.

## Use Example

```javascript
const kml = require('gtran-kml');

// Specify promise library if necessary
kml.setPromiseLib(require('bluebird'));

// Read KML file
kml
  .toGeoJson('source.kml')
  .then((object) {
    const geojson = object;
  });

const geojson = {
  'type': 'FeatureCollection',
  'features': [{
    'type': 'Feature',
    'geometry': {"type":"Point","coordinates":[-70.2532459795475,43.6399758607149]},
    'properties': {
      'id': 1,
      'Name': 'test'
    }
  }]
};

// Define a symbol for all features in the layer
const pointSymbol = {
  color: '#2dcd86',
  alpha: 255,
  scale: 1,
  icon: 'http://maps.google.com/mapfiles/kml/shapes/square.png'
};

// Save geojson into KML file
kml.fromGeoJson(geojson, 'point.kml', {
  symbol: pointSymbol,
  name: 'Name'
})

// Define a symbol for each individual feature
kml.fromGeoJson(geojson, 'point.kml', {
  symbol: (feature) => {
    return {
      color: '#2dcd86',
      alpha: 255 * Math.random(),
      scale: 1,
      icon: 'http://maps.google.com/mapfiles/kml/shapes/square.png'
    }
  },
  name: 'Name'
})
```


text:
package com.example.android.unsplash;

import android.content.Intent;
import com.example.android.unsplash.R;

/**
 * Holding intent extra names and utility methods for intent handling.
 */
public class IntentUtil {
    public static final String FONT_SIZE = "fontSize";
    public static final String PADDING = "padding";
    public static final String PHOTO = "photo";
    public static final String TEXT_COLOR = "color";
    public static final String RELEVANT_PHOTOS = "relevant";
    public static final String SELECTED_ITEM_POSITION = "selected";
    public static final String BUNDLE_PHOTOS = "photos";
    public static final int REQUEST_CODE = R.id.requestCode;

    /**
     * Checks if all extras are present in an intent.
     *
     * @param intent The intent to check.
     * @param extras The extras to check for.
     * @return true if all extras are present, else false.
     */
    public static boolean hasAll(Intent intent, String... extras) {
        for (String extra : extras) {
            if (!intent.hasExtra(extra)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Checks if any extra is present in an intent.
     *
     * @param intent The intent to check.
     * @param extras The extras to check for.
     * @return true if any checked extra is present, else false.
     */
    public static boolean hasAny(Intent intent, String... extras) {
        for (String extra : extras) {
            if (intent.hasExtra(extra)) {
                return true;
            }
        }
        return false;
    }
}


text:
layout: page
title: About
permalink: /about/
---

Thermal printing


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using TankArena.Utils;

namespace TankArena.UI
{
	public class InputBoxController : MonoBehaviour {

		public delegate void ProcessName(string name);

		public Button cancelButton;
		public Button enterButton;
		public InputField inputField;
		public string inputName;
		public ProcessName externalAction;

		private GameObject[] slotGOs;

		// Use this for initialization
		void Start ()
		{
			DBG.Log("Starting input dialogue!");
			if (inputField != null)
			{
				inputField.onEndEdit.RemoveAllListeners();
				inputField.onEndEdit.AddListener(UpdateName);
				inputField.onValueChanged.RemoveAllListeners();
				inputField.onValueChanged.AddListener(UpdateName);
			}
			slotGOs = new GameObject[3];
			//disable save slots to ensure correct click
			foreach(int slotNum in new int[] {1, 2, 3})
			{
				slotGOs[slotNum - 1] = GameObject.Find("SaveSlot" + slotNum);
			}
			ToggleSaveSlotButtons(false);

		}

		private void ToggleSaveSlotButtons(bool enable)
		{
			foreach(GameObject slotGO in slotGOs)
			{
				var button = slotGO.GetComponent<Button>();
				if (button != null)
				{
					button.enabled = enable;
				}
			}
		}

		public void EnterClicked()
		{
			gameObject.SetActive(false);
			ToggleSaveSlotButtons(true);
			if (externalAction != null)
			{
				externalAction(inputName);
			}
		}

		public void OKClicked()
		{
			gameObject.SetActive(false);
			ToggleSaveSlotButtons(true);
			if (externalAction != null)
			{
				externalAction("true");
			}
		}

		public void CancelClicked()
		{
			gameObject.SetActive(false);
			ToggleSaveSlotButtons(true);
			if (externalAction != null)
			{
				externalAction(null);
			}
		}

		public void UpdateName(string name)
		{
			inputName = name;
		}

		// Update is called once per frame
		void Update ()
		{

		}
	}
}


text:
"""Test script to check required Python version.

Execute this code at the command line by typing:

  python swc-installation-test-1.py

How to get a command line:

- On OSX run this with the Terminal application.

- On Windows, go to the Start menu, select 'Run' and type 'cmd'
(without the quotes) to run the 'cmd.exe' Windows Command Prompt.

- On Linux, either use your login shell directly, or run one of a
  number of graphical terminals (e.g. 'xterm', 'gnome-terminal', ...).

For some screen shots, see:

  http://software-carpentry.org/setup/terminal.html

Run the script and follow the instructions it prints at the end.  If
you see an error saying that the 'python' command was not found, than
you may not have any version of Python installed.  See:

  http://www.python.org/download/releases/2.7.3/#download

for installation instructions.

This test is separate to avoid Python syntax errors parsing the more
elaborate `swc-installation-test-2.py`.
"""

import sys as _sys

__version__ = '0.1'

def check():
    if _sys.version_info < (2, 6):
        print('check for Python version (python):')
        print('outdated version of Python: ' + _sys.version)
        return False
    return True

if __name__ == '__main__':
    if check():
        print('Passed')
    else:
        print('Failed')
        print('Install a current version of Python!')
        print('http://www.python.org/download/releases/2.7.3/#download')
        _sys.exit(1)


text:
package com.b2international.snowowl.snomed.reasoner.domain;

import java.io.Serializable;

import com.b2international.snowowl.core.terminology.ComponentCategory;
import com.b2international.snowowl.snomed.cis.SnomedIdentifiers;
import com.b2international.snowowl.snomed.core.domain.SnomedConcept;
import com.b2international.snowowl.snomed.core.domain.SnomedCoreComponent;
import com.b2international.snowowl.snomed.core.domain.SnomedDescription;
import com.b2international.snowowl.snomed.core.domain.SnomedRelationship;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @since 6.11
 */
public final class ReasonerConcreteDomainMember implements Serializable {

	private String originMemberId;

	/*
	 * Note that the rest of the values below can be completely different (or even
	 * absent) when compared to the "origin" concrete domain member, especially if
	 * the change is a new inference!
	 */
	private Boolean released;
	private SnomedCoreComponent referencedComponent;
	private String referenceSetId;
	private Integer group;
	private String typeId;
	private String serializedValue;
	private String characteristicTypeId;

	// Default constructor is used in JSON de-serialization
	public ReasonerConcreteDomainMember() { }

	public ReasonerConcreteDomainMember(final String originMemberId) {
		setOriginMemberId(originMemberId);
	}

	public String getOriginMemberId() {
		return originMemberId;
	}

	private void setOriginMemberId(final String originMemberId) {
		this.originMemberId = originMemberId;
	}

	public Boolean isReleased() {
		return released;
	}

	public void setReleased(final Boolean released) {
		this.released = released;
	}

	public SnomedCoreComponent getReferencedComponent() {
		return referencedComponent;
	}

	public void setReferencedComponent(final SnomedCoreComponent referencedComponent) {
		this.referencedComponent = referencedComponent;
	}

	@JsonProperty
	public String getReferencedComponentId() {
		return getReferencedComponent() == null ? null : getReferencedComponent().getId();
	}

	@JsonIgnore
	public void setReferencedComponentId(final String referencedComponentId) {
		final ComponentCategory referencedComponentCategory = SnomedIdentifiers.getComponentCategory(referencedComponentId);

		switch (referencedComponentCategory) {
			case CONCEPT:
				setReferencedComponent(new SnomedConcept(referencedComponentId));
				break;
			case DESCRIPTION:
				setReferencedComponent(new SnomedDescription(referencedComponentId));
				break;
			case RELATIONSHIP:
				setReferencedComponent(new SnomedRelationship(referencedComponentId));
				break;
			default:
				throw new IllegalStateException(String.format("Unexpected referenced component category '%s' for SCTID '%s'.",
						referencedComponentCategory,
						referencedComponentId));
		}
	}

	public String getReferenceSetId() {
		return referenceSetId;
	}

	public void setReferenceSetId(final String referenceSetId) {
		this.referenceSetId = referenceSetId;
	}

	public Integer getGroup() {
		return group;
	}

	public void setGroup(final Integer group) {
		this.group = group;
	}

	public String getTypeId() {
		return typeId;
	}

	public void setTypeId(final String typeId) {
		this.typeId = typeId;
	}

	public String getSerializedValue() {
		return serializedValue;
	}

	public void setSerializedValue(final String serializedValue) {
		this.serializedValue = serializedValue;
	}

	public String getCharacteristicTypeId() {
		return characteristicTypeId;
	}

	public void setCharacteristicTypeId(final String characteristicTypeId) {
		this.characteristicTypeId = characteristicTypeId;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("ReasonerConcreteDomainMember [originMemberId=");
		builder.append(originMemberId);
		builder.append(", released=");
		builder.append(released);
		builder.append(", referencedComponent=");
		builder.append(referencedComponent);
		builder.append(", referenceSetId=");
		builder.append(referenceSetId);
		builder.append(", group=");
		builder.append(group);
		builder.append(", typeId=");
		builder.append(typeId);
		builder.append(", serializedValue=");
		builder.append(serializedValue);
		builder.append(", characteristicTypeId=");
		builder.append(characteristicTypeId);
		builder.append("]");
		return builder.toString();
	}
}


text:
//**************************************************************************/
// Copyright (c) 1998-2005 Autodesk, Inc.
// All rights reserved.
//
// These coded instructions, statements, and computer programs contain
// unpublished proprietary information written by Autodesk, Inc., and are
// protected by Federal copyright law. They may not be disclosed to third
// parties or copied or duplicated in any form, in whole or in part, without
// the prior written consent of Autodesk, Inc.
//**************************************************************************/
// DESCRIPTION: Defines a class for monitoring a ReferenceTarget by holding a weak reference to it
// (IsRealDependency returns false) and passing NotifyRefChanged messages to the owner of the
// class instance.
// AUTHOR: Larry.Minton - created May.14.2004
//***************************************************************************/

#pragma once
#include "maxheap.h"
#include "ref.h"

//! Id for IRefTargMonitor interface
#define IID_REFTARG_MONITOR 0x3070552c

//! \brief This notification is sent to a IRefTargetMonitor's owner when it sets it's target
/*! Without this message, it's possible for the IRefTargetMontitor target to change with the owner not knowing about it.
\see IRefTargMonitor
*/
#define REFMSG_REFTARGMONITOR_TARGET_SET    REFMSG_USER + 0x3070552c

class RefTargMonitorRefMaker;

//! \brief The interface for an owner of a RefTargMonitorRefMaker class.
/*! The owner of a RefTargMonitorRefMaker instance must implement this interface. Messages from
the RefTargMonitorRefMaker instance are passed to the owner through this interface.
\see RefTargMonitorRefMaker, IIndirectReferenceMaker
*/
class IRefTargMonitor: public MaxHeapOperators {
public:
	//! \brief Calls to the RefTargMonitorRefMaker instance's NotifyRefChanged method are passed to its owner through this method.
	/*! The RefTargMonitorRefMaker owner is responsible for ensuring that an infinite recursion of message passing does not occur.
	Typically the owner would set a flag while propogating a message, and not propogate a new message if that flag
	is set.

	Since the owner doesn't hold a reference to the RefTargMonitorRefMaker's watched object, the watched object may not be
	saved or loaded when the owner is saved or loaded. The owner must handle this case. Typically, the owner would also derive from
	IIndirectReferenceMaker, which will result in the watched object being saved and loaded. For an example, see the NodeTransformMonitor
	class in maxsdk\\samples\\controllers\\nodetransformmonitor.cpp.

	The arguments to this method, other than fromMonitoredTarget, correspond to the arguments of ReferenceMaker::NotifyRefChanged.
	\param changeInt - This is the interval of time over which the message is active.
	\param hTarget - This is the handle of the reference target the message was sent by.
	\param partID - This contains information specific to the message passed in.
	\param message - The message which needs to be handled.
	\param fromMonitoredTarget - true if message originated from RefTargMonitorRefMaker's monitored target.
	\param propagate - If called through ReferenceMaker::NotifyDependents(), the value of 'propagate' passed
	to it. Used if calling NotifyDependents() from within NotifyRefChanged().
	\param caller - The RefTargMonitorRefMaker instance making this call. May be needed if multiple instances reference the monitored target.
	\returns Typically REF_SUCCEED indicating the message was processed.
	*/
	virtual RefResult ProcessRefTargMonitorMsg(
						const Interval& changeInt,
						RefTargetHandle hTarget,
						PartID& partID,
						RefMessage message,
						bool fromMonitoredTarget,
						bool propagate,
						RefTargMonitorRefMaker* caller) = 0;

#pragma warning( push )
#pragma warning( disable : 4481 )
private:
	// We want the IRefTargMonitor::ProcessRefTargMonitorMsg method with the following signature to be sealed to force derived classes
	// that implement this method with this signature to modify their implementation to the new signature.
	//! \deprecated Deprecated method in terms of implementation as of 3ds Max 2015 - re-implement with new method signature
	virtual RefResult ProcessRefTargMonitorMsg(
		Interval changeInt,
		RefTargetHandle hTarget,
		PartID& partID,
		RefMessage message,
		bool fromMonitoredTarget)MAX_SEALED
	{
		UNUSED_PARAM(changeInt); UNUSED_PARAM(hTarget);
		UNUSED_PARAM(partID); UNUSED_PARAM(message); UNUSED_PARAM(fromMonitoredTarget);
		assert(false);
		return REF_FAIL;
	}
public:
#pragma warning( pop )

	//! \brief Calls to the RefTargMonitorRefMaker instance's DoEnumDependents method are passed to its owner through this method.
	/*! The RefTargMonitorRefMaker owner is responsible for ensuring that an infinite recursion  does not occur.
	Typically the owner would set a flag while enumerating dependents, and not start a new enumeration if that flag
	is set.
	\param dep - the DependentEnumProc.
	\returns 1 to stop the enumeration and 0 to continue.
	*/
	virtual int ProcessEnumDependents(DependentEnumProc* dep) = 0;
};

//! \brief Defines a class for monitoring a ReferenceTarget
/*! Defines a class for monitoring a ReferenceTarget by holding a weak reference to it
(IsRealDependency returns false) and passing NotifyRefChanged messages to the owner of the
class instance. The owner would create an instance of this class passing itself as the
owner and the ReferenceTarget to watch as the target. The owner must derive from IRefTargMonitor,
and would typically derive from IIndirectReferenceMaker. If the owner derives from IIndirectReferenceMaker,
during scene load IIndirectReferenceMaker::SetIndirectReference is called to set the indirect reference. Thus,
you wouldn't normally call this class's Save or Load methods from the owner if it derives from
IRefTargMonitor.
\see IRefTargMonitor, IIndirectReferenceMaker
*/
class RefTargMonitorRefMaker: public ReferenceMaker, public PostPatchProc {
private:
	IRefTargMonitor &mOwner;	// the owner of this instance
	RefTargetHandle mpTarget;	// the object being monitored
	volatile unsigned int mInDelete;	// instance is in the process of being deleted. Helps protect against double delete
										// attempts due to DeleteAllRefsFromMe() in dtor.

	//! \brief Private destructor for class instances. Instances should be deleted via DeleteThis()
	~RefTargMonitorRefMaker();

public:
	CoreExport Class_ID ClassID();

	//! \brief Constructor for class instances.
	/*! \param myOwner - The owner of the instance. The owner is responsible for deleting this instance. The owner must
	implement the IRefTargMonitor interface.
	\param theTarget - The object instance to be watched.
	*/
	CoreExport RefTargMonitorRefMaker(IRefTargMonitor &myOwner, RefTargetHandle theTarget = NULL);

	//! \brief Set the object being watched.
	/*! \param theTarget - The object instance to be watched.
	*/
	CoreExport void SetRef(RefTargetHandle theTarget);

	//! \brief Get the object being watched.
	/*! \returns The object instance being watched.
	*/
	CoreExport RefTargetHandle GetRef();

	//! \brief Save a pointer to the object being watched.
	/*! The owner can call this method from its Save method it it wants to persistently watch the object
	across of load/save. As noted above, if the owner derives from IIndirectReferenceMaker, the owner typically
	would not call this method.
	\param isave - The ISave pointer passed to the owner's Save method.
	\returns One of the following values:
	IO_OK - The result was acceptable - no errors.
	IO_ERROR - This is returned if an error occurred.
	*/
	IOResult Save(ISave *isave);

	//! \brief Load a pointer to the object being watched.
	/*! The owner can call this method from its Load method it it wants to persistently watch the object
	across of load/save. The owner would create a new RefTargMonitorRefMaker setting itself as an owner, and
	then call this method using that instance. As noted above, if the owner derives from IIndirectReferenceMaker,
	the owner typically would not call this method.
	\param iload - The ILoad pointer passed to the owner's Load method.
	\returns One of the following values:
	IO_OK - The result was acceptable - no errors.
	IO_ERROR - This is returned if an error occurred.
	*/
	IOResult Load(ILoad *iload);

	//! \brief The PostPatchProc used when cloning.
	/*! The PostPatchProc is used when cloning since the watched object may or may not have also been cloned.
	When the owner is cloned, it would typically create a new RefTargMonitorRefMaker pointing at the cloned
	watched object. At the time the owner is cloned, the watched object may not have been cloned yet, or it
	may not be cloned at all. The owner should check to see if the watched object has been cloned already, and
	set the new RefTargMonitorRefMaker to watch it if so. If not, the new RefTargMonitorRefMaker should be set
	to watch the original watch object, and register this proc via remap.AddPostPatchProc. This proc will check
	after the cloning is complete whether the watch object was cloned, and if so set the clone as the watched
	object. If it was not cloned, the original object will be watched by the new RefTargMonitorRefMaker.
	\param remap - The RemapDir passed to the owner's Clone method.
	\returns TRUE in all cases
	*/
	int Proc(RemapDir& remap);

	// ReferenceMaker Methods
	//! \brief This method will notify the RefTargMonitorRefMaker of changes to the watched object.
	/*! Implemented by the system.
	Changes to the watched object cause messages to be passed to this method, and the implementation of this
	method passes those messages to the owner via the owner's ProcessRefTargMonitorMsg callback
	\returns The value returned from the owner's ProcessRefTargMonitorMsg callback
	*/
	RefResult NotifyRefChanged( const Interval& changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate );

	//! \brief Get the number of references instance makes.
	/*! Implemented by the system.
	RefTargMonitorRefMaker makes 1 reference - the watched object.
	\returns The number of references instance makes.
	*/
	int NumRefs();

	//! \brief Get the indexed reference.
	/*! Implemented by the system.
	The watched object should be accessed via GetRef and SetRef. This method is used by the system.
	\returns The watched object.
	*/
	RefTargetHandle GetReference(int i);

	//! \brief Set the indexed reference.
	/*! Implemented by the system.
	Sets the watched object.
	The watched object should be accessed via GetRef and SetRef. This method is used by the system.
	*/
protected:
	virtual void SetReference(int i, RefTargetHandle rtarg);
public:

	//! \brief Specifies that this reference to the watched object should not prevent the watched object from being deleted
	/*! Implemented by the system.
	\returns FALSE in all cases
	*/
	BOOL IsRealDependency(ReferenceTarget *rtarg);

	//! \brief Allows a reference target to enumerate all references to it.
	/*! Implemented by the system.
	This method allows a reference target to enumerate all references to it. The implementation of this method passes the
	DependentEnumProc to the owner via the owner's ProcessEnumDependents callback.
	\returns 1 to stop the enumeration and 0 to continue
	*/
	int DoEnumDependentsImpl(DependentEnumProc* dep);

	//! \brief Delete this instance.
	void DeleteThis();

	//! \brief Retrieves the name of the plugin class
	/*! \param s Reference to a string filled in with the name of the plugin class
	*/
	virtual void GetClassName(MSTR& s) { s = _M("RefTargMonitorRefMaker"); } // from Animatable

};


text:
exports.pool = require('any-db').createPool(process.env.DATABASE_URL,
  {min: 5, max: 15});


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>CreateSemaphore</title>

CreateSemaphore()

语法

Semaphore = CreateSemaphore([InitialCount])

概要

Creates a new semaphore object.

A semaphore is a thread synchronization object that keeps an internal count. It has two kinds of operations:
signal and wait. A wait operation decreases the count
of the semaphore by one. If the count would drop below 0, the wait operation will block until a signal call is made.
A signal operation increases the count one, releasing a blocking thread if there is one. A semaphore allows
to enforce minimum or maximum counts across threads for example to prevent a queue from running out or getting
too many items.

Unlike a mutex, a semaphore object is not "owned" by a particular thread, which means that
signal/wait calls do not need to be done from the same thread as it is the case with LockMutex() and
UnlockMutex(). In fact a common use for a semaphore objects is for one thread to do the
SignalSemaphore() calls and for another one to do all WaitSemaphore() calls to implement
a producer/consumer pattern.

参数

InitialCount (optional)

It has be a positive value that specifies the initial count of the semaphore.
If it is not specified, the initial count is zero.

返回值

The new semaphore, or zero if the semaphore creation has failed.

示例

This example shows a "producer" thread populating a queue with elements and the main thread reading them.
The semaphore is used to make sure the queue never runs out of elements. Note that this could also be
achieved with only a mutex and waiting/polling for queue elements with a Delay() in between,
but the semaphore commands do a more efficient wait (returning immediately at the SignalSemaphore() call
and not just on the next time a polling loop would check the queue).

Global Semaphore = CreateSemaphore()
Global Mutex     = CreateMutex()
Global NewList Queue()

Procedure Producer(Total)

  For i = 1 To Total
    Delay(Random(750) + 250)

    ; The queue access still needs a normal mutex lock to be thread-safe
    LockMutex(Mutex)
      LastElement(Queue())
      AddElement(Queue())
      Queue() = i
    UnlockMutex(Mutex)

    ; Signal that there is a new queue element
    SignalSemaphore(Semaphore)
  Next i

EndProcedure

If CreateThread(@Producer(), 30)

  For i = 1 To 30
    ; wait for one element to be available
    WaitSemaphore(Semaphore)

    ; display the queue state
    LockMutex(Mutex)
      Queue$ = "Queue:"
      ForEach Queue()
        Queue$ + " " + Str(Queue())
      Next Queue()
      Debug Queue$

      ; remove head element from the queue
      FirstElement(Queue())
      DeleteElement(Queue())
    UnlockMutex(Mutex)

  Next i

EndIf

参阅

FreeSemaphore()

已支持操作系统
所有

<- CreateMutex() - Thread Index - CreateThread() ->


text:
.class Lo/oh;
.super Lo/nB$If;

# annotations
.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic ˊ:Lcom/google/android/gms/fitness/request/af;

.field final synthetic ˋ:Lo/of;

# direct methods
.method constructor <init>(Lo/of;Lo/ᓖ;Lcom/google/android/gms/fitness/request/af;)V
    .locals 0

    iput-object p1, p0, Lo/oh;->ˋ:Lo/of;

    iput-object p3, p0, Lo/oh;->ˊ:Lcom/google/android/gms/fitness/request/af;

    invoke-direct {p0, p2}, Lo/nB$If;-><init>(Lo/ᓖ;)V

    return-void
.end method

# virtual methods
.method protected ˊ(Lo/nB;)V
    .locals 4

    new-instance v2, Lo/nB$ˊ;

    invoke-direct {v2, p0}, Lo/nB$ˊ;-><init>(Lo/ᒯ$ˋ;)V

    invoke-interface {p1}, Lo/nB;->ᵢ()Landroid/content/Context;

    move-result-object v0

    invoke-virtual {v0}, Landroid/content/Context;->getPackageName()Ljava/lang/String;

    move-result-object v3

    invoke-interface {p1}, Lo/nB;->ʻ()Lo/nG;

    move-result-object v0

    iget-object v1, p0, Lo/oh;->ˊ:Lcom/google/android/gms/fitness/request/af;

    invoke-interface {v0, v1, v2, v3}, Lo/nG;->ˊ(Lcom/google/android/gms/fitness/request/af;Lo/nL;Ljava/lang/String;)V

    return-void
.end method

.method protected bridge synthetic ˊ(Lo/ᒮ$ˊ;)V
    .locals 1

    move-object v0, p1

    check-cast v0, Lo/nB;

    invoke-virtual {p0, v0}, Lo/oh;->ˊ(Lo/nB;)V

    return-void
.end method


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

<TITLE>
ZooDefs.Ids (ZooKeeper 3.3.1 API)
</TITLE>

<META NAME="date" CONTENT="2010-05-07">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.zookeeper

Interface ZooDefs.Ids

Enclosing class:
ZooDefs

public static interface ZooDefs.Ids

Field Summary

static Id
ANYONE_ID_UNSAFE

          This Id represents anyone.

static Id
AUTH_IDS

          This Id is only usable to set ACLs.

static ArrayList<ACL>
CREATOR_ALL_ACL

          This ACL gives the creators authentication id's all permissions.

static ArrayList<ACL>
OPEN_ACL_UNSAFE

          This is a completely open ACL .

static ArrayList<ACL>
READ_ACL_UNSAFE

          This ACL gives the world the ability to read.

Field Detail

ANYONE_ID_UNSAFE

static final Id ANYONE_ID_UNSAFE

This Id represents anyone.

AUTH_IDS

static final Id AUTH_IDS

This Id is only usable to set ACLs. It will get substituted with the
 Id's the client authenticated with.

OPEN_ACL_UNSAFE

static final ArrayList<ACL> OPEN_ACL_UNSAFE

This is a completely open ACL .

CREATOR_ALL_ACL

static final ArrayList<ACL> CREATOR_ALL_ACL

This ACL gives the creators authentication id's all permissions.

READ_ACL_UNSAFE

static final ArrayList<ACL> READ_ACL_UNSAFE

This ACL gives the world the ability to read.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2010 The Apache Software Foundation


text:
class Error(Exception):
    """Base validation exception."""

class SchemaError(Error):
    """An error was encountered in the schema."""

class Invalid(Error):
    """The data was invalid.

    :attr msg: The error message.
    :attr path: The path to the error, as a list of keys in the source data.
    :attr error_message: The actual error message that was raised, as a
        string.

    """

    def __init__(self, message, path=None, error_message=None, error_type=None):
        Error.__init__(self, message)
        self.path = path or []
        self.error_message = error_message or message
        self.error_type = error_type

    @property
    def msg(self):
        return self.args[0]

    def __str__(self):
        path = ' @ data[%s]' % ']['.join(map(repr, self.path)) \
            if self.path else ''
        output = Exception.__str__(self)
        if self.error_type:
            output += ' for ' + self.error_type
        return output + path

    def prepend(self, path):
        self.path = path + self.path

class MultipleInvalid(Invalid):
    def __init__(self, errors=None):
        self.errors = errors[:] if errors else []

    def __repr__(self):
        return 'MultipleInvalid(%r)' % self.errors

    @property
    def msg(self):
        return self.errors[0].msg

    @property
    def path(self):
        return self.errors[0].path

    @property
    def error_message(self):
        return self.errors[0].error_message

    def add(self, error):
        self.errors.append(error)

    def __str__(self):
        return str(self.errors[0])

    def prepend(self, path):
        for error in self.errors:
            error.prepend(path)

class RequiredFieldInvalid(Invalid):
    """Required field was missing."""

class ObjectInvalid(Invalid):
    """The value we found was not an object."""

class DictInvalid(Invalid):
    """The value found was not a dict."""

class ExclusiveInvalid(Invalid):
    """More than one value found in exclusion group."""

class InclusiveInvalid(Invalid):
    """Not all values found in inclusion group."""

class SequenceTypeInvalid(Invalid):
    """The type found is not a sequence type."""

class TypeInvalid(Invalid):
    """The value was not of required type."""

class ValueInvalid(Invalid):
    """The value was found invalid by evaluation function."""

class ContainsInvalid(Invalid):
    """List does not contain item"""

class ScalarInvalid(Invalid):
    """Scalars did not match."""

class CoerceInvalid(Invalid):
    """Impossible to coerce value to type."""

class AnyInvalid(Invalid):
    """The value did not pass any validator."""

class AllInvalid(Invalid):
    """The value did not pass all validators."""

class MatchInvalid(Invalid):
    """The value does not match the given regular expression."""

class RangeInvalid(Invalid):
    """The value is not in given range."""

class TrueInvalid(Invalid):
    """The value is not True."""

class FalseInvalid(Invalid):
    """The value is not False."""

class BooleanInvalid(Invalid):
    """The value is not a boolean."""

class UrlInvalid(Invalid):
    """The value is not a URL."""

class EmailInvalid(Invalid):
    """The value is not an email address."""

class FileInvalid(Invalid):
    """The value is not a file."""

class DirInvalid(Invalid):
    """The value is not a directory."""

class PathInvalid(Invalid):
    """The value is not a path."""

class LiteralInvalid(Invalid):
    """The literal values do not match."""

class LengthInvalid(Invalid):
    pass

class DatetimeInvalid(Invalid):
    """The value is not a formatted datetime string."""

class DateInvalid(Invalid):
    """The value is not a formatted date string."""

class InInvalid(Invalid):
    pass

class NotInInvalid(Invalid):
    pass

class ExactSequenceInvalid(Invalid):
    pass

class NotEnoughValid(Invalid):
    """The value did not pass enough validations."""
    pass

class TooManyValid(Invalid):
    """The value passed more than expected validations."""
    pass


text:
import { BorderLayout } from "../layout/borderLayout";
import { LoggerFactory } from "../logger";
import { ColumnChangeEvent } from "../columnChangeEvent";
export declare class GridPanel {
    private masterSlaveService;
    private gridOptionsWrapper;
    private columnController;
    private rowRenderer;
    private floatingRowModel;
    private eventService;
    private rowModel;
    private rangeController;
    private dragService;
    private selectionController;
    private clipboardService;
    private csvCreator;
    private mouseEventService;
    private layout;
    private logger;
    private forPrint;
    private scrollWidth;
    private scrollLagCounter;
    private eBodyViewport;
    private eRoot;
    private eBody;
    private eBodyContainer;
    private ePinnedLeftColsContainer;
    private ePinnedRightColsContainer;
    private eHeaderContainer;
    private eHeaderOverlay;
    private ePinnedLeftHeader;
    private ePinnedRightHeader;
    private eHeader;
    private eBodyViewportWrapper;
    private ePinnedLeftColsViewport;
    private ePinnedRightColsViewport;
    private eHeaderViewport;
    private eFloatingTop;
    private ePinnedLeftFloatingTop;
    private ePinnedRightFloatingTop;
    private eFloatingTopContainer;
    private eFloatingTopViewport;
    private eFloatingBottom;
    private ePinnedLeftFloatingBottom;
    private ePinnedRightFloatingBottom;
    private eFloatingBottomContainer;
    private eFloatingBottomViewport;
    private eAllCellContainers;
    private lastLeftPosition;
    private lastTopPosition;
    private animationThreadCount;
    agWire(loggerFactory: LoggerFactory): void;
    private onRowDataChanged();
    getLayout(): BorderLayout;
    private init();
    private disableBrowserDragging();
    private addEventListeners();
    private addDragListeners();
    private addCellListeners();
    private processMouseEvent(eventName, mouseEvent, eventSource);
    private addShortcutKeyListeners();
    private onCtrlAndA(event);
    private onCtrlAndC(event);
    private onCtrlAndV(event);
    private onCtrlAndD(event);
    getPinnedLeftFloatingTop(): HTMLElement;
    getPinnedRightFloatingTop(): HTMLElement;
    getFloatingTopContainer(): HTMLElement;
    getPinnedLeftFloatingBottom(): HTMLElement;
    getPinnedRightFloatingBottom(): HTMLElement;
    getFloatingBottomContainer(): HTMLElement;
    private createOverlayTemplate(name, defaultTemplate, userProvidedTemplate);
    private createLoadingOverlayTemplate();
    private createNoRowsOverlayTemplate();
    ensureIndexVisible(index: any): void;
    getCenterWidth(): number;
    isHorizontalScrollShowing(): boolean;
    isVerticalScrollShowing(): boolean;
    periodicallyCheck(): void;
    ensureColumnVisible(key: any): void;
    showLoadingOverlay(): void;
    showNoRowsOverlay(): void;
    hideOverlay(): void;
    private getWidthForSizeColsToFit();
    sizeColumnsToFit(nextTimeout?: number): void;
    getBodyContainer(): HTMLElement;
    getDropTargetBodyContainers(): HTMLElement[];
    getBodyViewport(): HTMLElement;
    getPinnedLeftColsContainer(): HTMLElement;
    getDropTargetLeftContainers(): HTMLElement[];
    getPinnedRightColsContainer(): HTMLElement;
    getDropTargetPinnedRightContainers(): HTMLElement[];
    getHeaderContainer(): HTMLElement;
    getHeaderOverlay(): HTMLElement;
    getRoot(): HTMLElement;
    getPinnedLeftHeader(): HTMLElement;
    getPinnedRightHeader(): HTMLElement;
    private queryHtmlElement(selector);
    private findElements();
    getHeaderViewport(): HTMLElement;
    private centerMouseWheelListener(event);
    private pinnedLeftMouseWheelListener(event);
    private generalMouseWheelListener(event, targetPanel);
    onColumnsChanged(event: ColumnChangeEvent): void;
    private setWidthsOfContainers();
    private showPinnedColContainersIfNeeded();
    private sizeHeaderAndBody();
    setHorizontalScrollPosition(hScrollPosition: number): void;
    scrollHorizontally(pixels: number): number;
    getHorizontalScrollPosition(): number;
    turnOnAnimationForABit(): void;
    private addScrollListener();
    private requestDrawVirtualRows();
    horizontallyScrollHeaderCenterAndFloatingCenter(): void;
    private verticallyScrollLeftPinned(bodyTopPosition);
    private verticallyScrollBody(position);
    getVerticalScrollPosition(): number;
    getBodyViewportClientRect(): ClientRect;
    getFloatingTopClientRect(): ClientRect;
    getFloatingBottomClientRect(): ClientRect;
    getPinnedLeftColsViewportClientRect(): ClientRect;
    getPinnedRightColsViewportClientRect(): ClientRect;
    addScrollEventListener(listener: () => void): void;
    removeScrollEventListener(listener: () => void): void;
}


text:
property :system_managed, [true, false]
property :automatic_managed, [true, false], default: false
property :initial_size, Integer
property :maximum_size, Integer

include Chef::Mixin::ShellOut
include Windows::Helper

action :set do
  pagefile = new_resource.name
  initial_size = new_resource.initial_size
  maximum_size = new_resource.maximum_size
  system_managed = new_resource.system_managed
  automatic_managed = new_resource.automatic_managed

  if automatic_managed
    set_automatic_managed unless automatic_managed?
  else
    unset_automatic_managed if automatic_managed?

    # Check that the resource is not just trying to unset automatic managed, if it is do nothing more
    if (initial_size && maximum_size) || system_managed
      validate_name
      create(pagefile) unless exists?(pagefile)

      if system_managed
        set_system_managed(pagefile) unless max_and_min_set?(pagefile, 0, 0)
      else
        unless max_and_min_set?(pagefile, initial_size, maximum_size)
          set_custom_size(pagefile, initial_size, maximum_size)
        end
      end
    end
  end
end

action :delete do
  validate_name
  pagefile = new_resource.name
  delete(pagefile) if exists?(pagefile)
end

action_class do
  def validate_name
    return if /^.:.*.sys/ =~ new_resource.name
    raise "#{new_resource.name} does not match the format DRIVE:\\path\\file.sys for pagefiles. Example: C:\\pagefile.sys"
  end

  def exists?(pagefile)
    @exists ||= begin
      Chef::Log.debug("Checking if #{pagefile} exists by runing: #{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" list /format:list")
      cmd = shell_out("#{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" list /format:list", returns: [0])
      cmd.stderr.empty? && (cmd.stdout =~ /SettingID=#{get_setting_id(pagefile)}/i)
    end
  end

  def max_and_min_set?(pagefile, min, max)
    @max_and_min_set ||= begin
      Chef::Log.debug("Checking if #{pagefile} min: #{min} and max #{max} are set")
      cmd = shell_out("#{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" list /format:list", returns: [0])
      cmd.stderr.empty? && (cmd.stdout =~ /InitialSize=#{min}/i) && (cmd.stdout =~ /MaximumSize=#{max}/i)
    end
  end

  def create(pagefile)
    converge_by("create pagefile #{pagefile}") do
      Chef::Log.debug("Running #{wmic} pagefileset create name=\"#{win_friendly_path(pagefile)}\"")
      cmd = shell_out("#{wmic} pagefileset create name=\"#{win_friendly_path(pagefile)}\"")
      check_for_errors(cmd.stderr)
    end
  end

  def delete(pagefile)
    converge_by("remove pagefile #{pagefile}") do
      Chef::Log.debug("Running #{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" delete")
      cmd = shell_out("#{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" delete")
      check_for_errors(cmd.stderr)
    end
  end

  def automatic_managed?
    @automatic_managed ||= begin
      Chef::Log.debug('Checking if pagefiles are automatically managed')
      cmd = shell_out("#{wmic} computersystem where name=\"%computername%\" get AutomaticManagedPagefile /format:list")
      cmd.stderr.empty? && (cmd.stdout =~ /AutomaticManagedPagefile=TRUE/i)
    end
  end

  def set_automatic_managed
    converge_by('set pagefile to Automatic Managed') do
      Chef::Log.debug("Running #{wmic} computersystem where name=\"%computername%\" set AutomaticManagedPagefile=True")
      cmd = shell_out("#{wmic} computersystem where name=\"%computername%\" set AutomaticManagedPagefile=True")
      check_for_errors(cmd.stderr)
    end
  end

  def unset_automatic_managed
    converge_by('set pagefile to User Managed') do
      Chef::Log.debug("Running #{wmic} computersystem where name=\"%computername%\" set AutomaticManagedPagefile=False")
      cmd = shell_out("#{wmic} computersystem where name=\"%computername%\" set AutomaticManagedPagefile=False")
      check_for_errors(cmd.stderr)
    end
  end

  def set_custom_size(pagefile, min, max)
    converge_by("set #{pagefile} to InitialSize=#{min} & MaximumSize=#{max}") do
      Chef::Log.debug("Running #{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" set InitialSize=#{min},MaximumSize=#{max}")
      cmd = shell_out("#{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" set InitialSize=#{min},MaximumSize=#{max}", returns: [0])
      check_for_errors(cmd.stderr)
    end
  end

  def set_system_managed(pagefile) # rubocop: disable Style/AccessorMethodName
    converge_by("set #{pagefile} to System Managed") do
      Chef::Log.debug("Running #{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" set InitialSize=0,MaximumSize=0")
      cmd = shell_out("#{wmic} pagefileset where SettingID=\"#{get_setting_id(pagefile)}\" set InitialSize=0,MaximumSize=0", returns: [0])
      check_for_errors(cmd.stderr)
    end
  end

  def get_setting_id(pagefile)
    pagefile = win_friendly_path(pagefile)
    pagefile = pagefile.split('\\')
    "#{pagefile[1]} @ #{pagefile[0]}"
  end

  def check_for_errors(stderr)
    raise stderr.chomp unless stderr.empty?
  end

  def wmic
    @wmic ||= locate_sysnative_cmd('wmic.exe')
  end
end


text:
package parallelwork

import (
	"container/list"
	"context"
	"sync"
	"time"

	"golang.org/x/sync/errgroup"

	"github.com/kopia/kopia/internal/clock"
)

// Queue represents a work queue with multiple parallel workers.
type Queue struct {
	monitor *sync.Cond

	queueItems        *list.List
	enqueuedWork      int64
	activeWorkerCount int64
	completedWork     int64

	nextReportTime time.Time

	ProgressCallback func(ctx context.Context, enqueued, active, completed int64)
}

// CallbackFunc is a callback function.
type CallbackFunc func() error

// EnqueueFront adds the work to the front of the queue.
func (v *Queue) EnqueueFront(ctx context.Context, callback CallbackFunc) {
	v.enqueue(ctx, true, callback)
}

// EnqueueBack adds the work to the back of the queue.
func (v *Queue) EnqueueBack(ctx context.Context, callback CallbackFunc) {
	v.enqueue(ctx, false, callback)
}

func (v *Queue) enqueue(ctx context.Context, front bool, callback CallbackFunc) {
	v.monitor.L.Lock()
	defer v.monitor.L.Unlock()

	v.enqueuedWork++

	// add to the queue and signal one reader
	if front {
		v.queueItems.PushFront(callback)
	} else {
		v.queueItems.PushBack(callback)
	}

	v.maybeReportProgress(ctx)
	v.monitor.Signal()
}

// Process starts N workers, which will be processing elements in the queue until the queue
// is empty and all workers are idle or until any of the workers returns an error.
func (v *Queue) Process(ctx context.Context, workers int) error {
	defer v.reportProgress(ctx)

	eg, ctx := errgroup.WithContext(ctx)

	for i := 0; i < workers; i++ {
		eg.Go(func() error {
			for {
				select {
				case <-ctx.Done():
					// context canceled - some other worker returned an error.
					//nolint:wrapcheck
					return ctx.Err()

				default:
					callback := v.dequeue(ctx)
					if callback == nil {
						// no more work, shut down.
						return nil
					}

					err := callback()
					v.completed(ctx)
					if err != nil {
						return err
					}
				}
			}
		})
	}

	//nolint:wrapcheck
	return eg.Wait()
}

func (v *Queue) dequeue(ctx context.Context) CallbackFunc {
	v.monitor.L.Lock()
	defer v.monitor.L.Unlock()

	for v.queueItems.Len() == 0 && v.activeWorkerCount > 0 {
		// no items in queue, but some workers are active, they may add more.
		v.monitor.Wait()
	}

	// no items in queue, no workers are active, no more work.
	if v.queueItems.Len() == 0 {
		return nil
	}

	v.activeWorkerCount++
	v.maybeReportProgress(ctx)

	front := v.queueItems.Front()
	v.queueItems.Remove(front)

	return front.Value.(CallbackFunc) //nolint:forcetypeassert
}

func (v *Queue) completed(ctx context.Context) {
	v.monitor.L.Lock()
	defer v.monitor.L.Unlock()

	v.activeWorkerCount--
	v.completedWork++
	v.maybeReportProgress(ctx)

	v.monitor.Broadcast()
}

func (v *Queue) reportProgress(ctx context.Context) {
	cb := v.ProgressCallback
	if cb != nil {
		cb(ctx, v.enqueuedWork, v.activeWorkerCount, v.completedWork)
	}
}

func (v *Queue) maybeReportProgress(ctx context.Context) {
	if clock.Now().Before(v.nextReportTime) {
		return
	}

	v.nextReportTime = clock.Now().Add(1 * time.Second)

	v.reportProgress(ctx)
}

// OnNthCompletion invokes the provided callback once the returned callback function has been invoked exactly n times.
func OnNthCompletion(n int, callback CallbackFunc) CallbackFunc {
	var mu sync.Mutex

	return func() error {
		mu.Lock()
		n--
		call := n == 0
		mu.Unlock()

		if call {
			return callback()
		}

		return nil
	}
}

// NewQueue returns new parallel work queue.
func NewQueue() *Queue {
	return &Queue{
		queueItems: list.New(),
		monitor:    sync.NewCond(&sync.Mutex{}),
	}
}


text:
{-|
Module      : ChainFlyer
Copyright   : (c) Tatsuya Hirose, 2015
License     : BSD3
Maintainer  : tatsuya.hirose.0804@gmail.com
-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}

module Servant.ChainFlyer.Types.Address
( Address(..)
) where

import Data.Aeson
import GHC.Generics

-- | Address.
data Address = Address
    { address            :: String
    , unconfirmed_balance :: Integer
    , confirmed_balance   :: Integer
    } deriving (Show, Generic)

instance FromJSON Address
instance ToJSON Address


text:
namespace RNUIExamples
{
    using System;
    using System.Linq;
    using RAGENativeUI;
    using RAGENativeUI.Elements;

    internal static class Util
    {
        /// <summary>
        /// Create new list menu item containing all the <see cref="HudColor"/>s which can be selected by the user.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        public static UIMenuListScrollerItem<HudColor> NewColorsItem(string text, string description)
            => new UIMenuListScrollerItem<HudColor>(text, description, (HudColor[])Enum.GetValues(typeof(HudColor)))
            {
                // custom formatter that adds whitespace between words (i.e. "RedDark" -> "Red Dark")
                Formatter = v => v.ToString().Aggregate("", (acc, c) => acc + (acc.Length > 0 && char.IsUpper(c) ? " " : "") + c)
            };

        public static UIMenuCheckboxItem NewTriStateCheckbox(string name, string description)
        {
            var cb = new UIMenuCheckboxItem(name, false, description);

            cb.Activated += (s, i) =>
            {
                if (cb.Checked)
                {
                    if (cb.Style == UIMenuCheckboxStyle.Tick)
                    {
                        cb.Style = UIMenuCheckboxStyle.Cross;
                        cb.Checked = !cb.Checked; // make the item checked
                    }
                    else
                    {
                        cb.Style = UIMenuCheckboxStyle.Tick;
                    }
                }
            };

            return cb;
        }
    }
}