text:
using System;
using System.Threading.Tasks;
using Abp;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Threading;
using Abp.Zero;
using Microsoft.AspNet.Identity;
using YoYoCms.AbpProjectTemplate.Authorization.Roles;
using YoYoCms.AbpProjectTemplate.Identity;

namespace YoYoCms.AbpProjectTemplate.UserManagement.Users
{
    /// <summary>
    /// User manager.
    /// Used to implement domain logic for users.
    /// Extends <see cref="AbpUserManager{TRole,TUser}"/>.
    /// </summary>
    public class UserManager : AbpUserManager<Role, User>
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public UserManager(
            UserStore userStore,
            RoleManager roleManager,
            IPermissionManager permissionManager,
            IUnitOfWorkManager unitOfWorkManager,
            ICacheManager cacheManager,
            IRepository<OrganizationUnit, long> organizationUnitRepository,
            IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository,
            IOrganizationUnitSettings organizationUnitSettings,
            IdentityEmailMessageService emailService,
            ILocalizationManager localizationManager,
            ISettingManager settingManager,
            IdentitySmsMessageService smsService,
            IUserTokenProviderAccessor userTokenProviderAccessor)
            : base(
                  userStore,
                  roleManager,
                  permissionManager,
                  unitOfWorkManager,
                  cacheManager,
                  organizationUnitRepository,
                  userOrganizationUnitRepository,
                  organizationUnitSettings,
                  localizationManager,
                  emailService,
                  settingManager,
                  userTokenProviderAccessor)
        {
            _unitOfWorkManager = unitOfWorkManager;

            SmsService = smsService;
        }

        #region 覆盖原AbpZero方法
        /// <summary>
        /// 多语言处理
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private string L(string name)
        {
            return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
        }
        /// <summary>
        /// 检查是否有重复的邮箱或者用户名。
        /// </summary>
        /// <param name="expectedUserId"></param>
        /// <param name="userName"></param>
        /// <param name="emailAddress"></param>
        /// <returns></returns>
        public override async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
        {
            var user = (await FindByNameAsync(userName));
            if (user != null && user.Id != expectedUserId)
            {

                return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName));
            }

            if (!string.IsNullOrEmpty(emailAddress))
            {
                user = (await FindByEmailAsync(emailAddress));
                if (user != null && user.Id != expectedUserId)
                {
                    return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
                }
            }

            return IdentityResult.Success;
        }
        /// <summary>
        /// 新的创建User方法,不判断Email的问题
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public override async Task<IdentityResult> CreateAsync(User user)
        {
            var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
            if (!result.Succeeded)
            {
                return result;
            }

          //  user.EmailAddress = string.Empty;

            var tenantId = GetCurrentTenantId();
            if (tenantId.HasValue && !user.TenantId.HasValue)
            {
                user.TenantId = tenantId.Value;
            }

            try
            {
                return await base.CreateAsync(user);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

        }
        /// <summary>
        /// 获取当前租户Id
        /// </summary>
        /// <returns></returns>
        private int? GetCurrentTenantId()
        {
            if (_unitOfWorkManager.Current != null)
            {
                return _unitOfWorkManager.Current.GetTenantId();
            }

            return AbpSession.TenantId;
        }
        #endregion

        public async Task<User> GetUserOrNullAsync(UserIdentifier userIdentifier)
        {
            using (_unitOfWorkManager.Begin())
            {
                using (_unitOfWorkManager.Current.SetTenantId(userIdentifier.TenantId))
                {
                    return await FindByIdAsync(userIdentifier.UserId);
                }
            }
        }

        public User GetUserOrNull(UserIdentifier userIdentifier)
        {
            return AsyncHelper.RunSync(() => GetUserOrNullAsync(userIdentifier));
        }

        public async Task<User> GetUserAsync(UserIdentifier userIdentifier)
        {
            var user = await GetUserOrNullAsync(userIdentifier);
            if (user == null)
            {
                throw new ApplicationException("There is no user: " + userIdentifier);
            }

            return user;
        }

        public User GetUser(UserIdentifier userIdentifier)
        {
            return AsyncHelper.RunSync(() => GetUserAsync(userIdentifier));
        }
    }
}


text:
alias cb="cargo build"
alias cbr="cargo build --release"
alias ct="cargo test"
alias cr="cargo run"

# Add Cargo's global binaries to PATH
export PATH=$PATH:~/.cargo/bin

# Needed by [racer](https://github.com/phildawes/racer)
# test with, racer complete std::io::B (should show some completions)
export RUST_SRC_PATH=/usr/local/var/rust/src/src

# aliases for rustc
function rce() {
    if [[ -z $@ ]]; then
        echo "Usage: $0:t <Error-Message-Code>"
        echo "Example: rce E0425"
        return 1
    else
        rustc --explain "$@" | less
    fi
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef __WINE_LOADPERF_H
#define __WINE_LOADPERF_H

#ifdef __cplusplus
extern "C" {
#endif

DWORD WINAPI InstallPerfDllA(LPCSTR, LPCSTR, ULONG_PTR);
DWORD WINAPI InstallPerfDllW(LPCWSTR, LPCWSTR, ULONG_PTR);
#define      InstallPerfDll WINELIB_NAME_AW(InstallPerfDll);

DWORD WINAPI LoadPerfCounterTextStringsA(LPCSTR, BOOL);
DWORD WINAPI LoadPerfCounterTextStringsW(LPCWSTR, BOOL);
#define      LoadPerfCounterTextStrings WINELIB_NAME_AW(LoadPerfCounterTextStrings)

DWORD WINAPI UnloadPerfCounterTextStringsA(LPCSTR, BOOL);
DWORD WINAPI UnloadPerfCounterTextStringsW(LPCWSTR, BOOL);
#define      UnloadPerfCounterTextStrings WINELIB_NAME_AW(UnloadPerfCounterTextStrings)

#ifdef __cplusplus
}
#endif

#endif /* __WINE_LOADPERF_H */


text:
function Add-EventHandler {
    <#
    .Synopsis
        Adds an event handler to an object
    .Description
        Adds an event handler to an object.  If the object has a
        resource dictionary, it will add an eventhandlers
        hashtable to that object and it will store the event handler,
        so it can be removed later.
    .Example
        $window = New-Window
        $window | Add-EventHandler Loaded { $this.Top = 100 }
    .Parameter Object
        The Object to add an event handler to
    .Parameter EventName
        The name of the event (i.e. Loaded)
    .Parameter Handler
        The script block that will handle the event
    .Parameter SourceType
        For RoutedEvents, the type that originates the event
    .Parameter PassThru
        If this is set, the delegate that is added to the object will
        be returned from the function.
    #>
    param(
    [Parameter(ValueFromPipeline=$true, Mandatory=$true, Position = 0, ParameterSetName="SimpleEvents")]
    [ValidateNotNull()]
    [Alias("Object")]
    $InputObject,

    [Parameter(Mandatory=$true, Position=1)]
    [String]
    $EventName,

    [Parameter(Mandatory=$true, Position=2)]
    [ScriptBlock]
    $Handler,

    [Parameter(Mandatory=$false)]
    [String]
    $SourceType,

    [Switch]
    $PassThru
    )

    process {
        if($SourceType) {
            $Type = $SourceType -as [Type]
            if(!$Type) {
                $Type = (Get-Command $SourceType).OutputType[0].Type
            }
            if(!$Type) {
                Write-Error "Can't determine type from '$SourceType', you should pass either a Type or the name of a ShowUI command that outputs a UI Element. We will try the InputObject(s)"
                $Type = $InputObject.GetType()
            }
        } else {
            $Type = $InputObject.GetType()
        }

        if ($eventName.StartsWith("On_")) {
            $eventName = $eventName.Substring(3)
        }

        $Event = $Type.GetEvent($EventName, [Reflection.BindingFlags]"IgnoreCase, Public, Instance")
        if (-not $Event) {
            Write-Error "Handler $EventName does not exist on $InputObject"
            return
        }

        $realHandler = ([ScriptBlock]::Create(@"
`$eventName = 'On_$eventName';
. Initialize-EventHandler
`$ErrorActionPreference = 'stop'

$Handler

trap {
    . Write-WPFError `$_
    continue
}
"@)) -as $event.EventHandlerType

        if($realHandler -is [System.Windows.RoutedEventHandler] -and $Type::"${EventName}Event" ) {
            $InputObject.AddHandler( $Type::"${EventName}Event", $realHandler )
        } else {

            if ($InputObject.Resources) {

                if (-not $InputObject.Resources.EventHandlers) {
                    $InputObject.Resources.EventHandlers = @{}
                }
                $InputObject.Resources.EventHandlers."On_$EventName" = $realHandler
            }
            $event.AddEventHandler($InputObject, $realHandler)
        }
        if ($passThru) {
            $RealHandler
        }
    }
}


text:
using CodeCracker.Properties;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
using System.Threading.Tasks;

namespace CodeCracker.CSharp.Style
{
    public sealed class StringFormatFixAllProvider : FixAllProvider
    {
        private static readonly SyntaxAnnotation stringFormatAnnotation = new SyntaxAnnotation(nameof(StringFormatFixAllProvider));
        private StringFormatFixAllProvider() { }
        public static readonly StringFormatFixAllProvider Instance = new StringFormatFixAllProvider();
        public override Task<CodeAction> GetFixAsync(FixAllContext fixAllContext)
        {
            switch (fixAllContext.Scope)
            {
                case FixAllScope.Document:
                    return Task.FromResult(CodeAction.Create(Resources.StringFormatCodeFixProvider_Title,
                        async ct => fixAllContext.Document.WithSyntaxRoot(await GetFixedDocumentAsync(fixAllContext, fixAllContext.Document).ConfigureAwait(false))));
                case FixAllScope.Project:
                    return Task.FromResult(CodeAction.Create(Resources.StringFormatCodeFixProvider_Title,
                        ct => GetFixedProjectAsync(fixAllContext, fixAllContext.Project)));
                case FixAllScope.Solution:
                    return Task.FromResult(CodeAction.Create(Resources.StringFormatCodeFixProvider_Title,
                        ct => GetFixedSolutionAsync(fixAllContext)));
                default:
                    return null;
            }
        }

        private async static Task<Solution> GetFixedSolutionAsync(FixAllContext fixAllContext)
        {
            var newSolution = fixAllContext.Solution;
            foreach (var projectId in newSolution.ProjectIds)
                newSolution = await GetFixedProjectAsync(fixAllContext, newSolution.GetProject(projectId)).ConfigureAwait(false);
            return newSolution;
        }

        private async static Task<Solution> GetFixedProjectAsync(FixAllContext fixAllContext, Project project)
        {
            var solution = project.Solution;
            var newDocuments = project.Documents.ToDictionary(d => d.Id, d => GetFixedDocumentAsync(fixAllContext, d));
            await Task.WhenAll(newDocuments.Values).ConfigureAwait(false);
            foreach (var newDoc in newDocuments)
                solution = solution.WithDocumentSyntaxRoot(newDoc.Key, newDoc.Value.Result);
            return solution;
        }

        private async static Task<SyntaxNode> GetFixedDocumentAsync(FixAllContext fixAllContext, Document document)
        {
            var diagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false);
            var root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false);
            var nodes = diagnostics.Select(d => root.FindNode(d.Location.SourceSpan, getInnermostNodeForTie: true).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()).Where(n => !n.IsMissing).ToList();
            var newRoot = root.ReplaceNodes(nodes, (original, rewritten) => rewritten.WithAdditionalAnnotations(stringFormatAnnotation));
            while (true)
            {
                var annotatedNodes = newRoot.GetAnnotatedNodes(stringFormatAnnotation);
                var node = annotatedNodes.FirstOrDefault();
                if (node == null) break;
                newRoot = StringFormatCodeFixProvider.CreateNewStringInterpolation(newRoot, (InvocationExpressionSyntax)node);
            }
            return newRoot;
        }
    }
}


text:
<?php
class ServiceOutput_jsonp extends BaseServiceOutputFormatter
{
	function Format($Data,$Request)
	{
		$Result=json_encode($Data);
		if (!isset($Request['jsonp']))
		{
			//JSONP callback not set error
			$JSONP="callback";
			return "alert('jFramework Service Error: JSONP call without JSONP callback parameter set.')";
		}
		else
			$JSONP=$Request['jsonp'];
			$Result=$JSONP." ( ".$Result." );";
		$this->Headers=array("content-type"=>"text/javascript");
		return $Result;
	}

	//This automatically shows on help request for this service
	function HelpNotice()
	{
		return "پارامتر jsonp باید برای اینگونه خروجی تنظیم گردد، در غیر اینصورت یک پیغام خطا نمایش داده می شود.";
	}
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                        http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <interactiveMode/>

    <mirrors>
        <!-- @formatter:off -->
        <!-- @formatter:on -->
    </mirrors>

    <offline/>

    <pluginGroups>
        <pluginGroup>com.amashchenko.maven.plugin</pluginGroup>
        <pluginGroup>com.github.ferstl</pluginGroup>
        <pluginGroup>com.github.spotbugs</pluginGroup>
        <pluginGroup>io.quarkus</pluginGroup>
        <pluginGroup>io.takari</pluginGroup>
        <pluginGroup>org.apache.maven.plugins</pluginGroup>
        <pluginGroup>org.apache.tomcat.maven</pluginGroup>
        <pluginGroup>org.codehaus.mojo</pluginGroup>
        <pluginGroup>org.owasp</pluginGroup>
        <pluginGroup>org.reficio</pluginGroup>
        <pluginGroup>org.sonarsource.scanner.maven</pluginGroup>
        <pluginGroup>org.springframework.boot</pluginGroup>
    </pluginGroups>

    <!-- @formatter:off -->
    <profiles>
        <profile>
            <id>gpg-keyname</id>
            <activation><activeByDefault>true</activeByDefault></activation>
            <properties><gpg.keyname>${env.CI_OPT_GPG_KEYNAME}</gpg.keyname></properties>
        </profile>
    </profiles>
    <!-- @formatter:on -->

    <proxies>
    </proxies>

    <servers>
        <!-- @formatter:off -->
        <server><id>gpg.passphrase</id><passphrase>${env.CI_OPT_GPG_PASSPHRASE}</passphrase></server>
        <server><id>ossrh-nexus2-snapshots</id><username>${env.CI_OPT_OSSRH_NEXUS2_USER}</username><password>${env.CI_OPT_OSSRH_NEXUS2_PASS}</password></server>
        <server><id>ossrh-nexus2-staging</id><username>${env.CI_OPT_OSSRH_NEXUS2_USER}</username><password>${env.CI_OPT_OSSRH_NEXUS2_PASS}</password></server>
        <!-- @formatter:on -->
    </servers>

    <usePluginRegistry/>
</settings>


text:
package com.netflix.spinnaker.clouddriver.alicloud.common;

import static com.netflix.spinnaker.clouddriver.core.provider.agent.Namespace.HEALTH;

import com.netflix.spinnaker.cats.cache.Cache;
import com.netflix.spinnaker.cats.cache.CacheData;
import com.netflix.spinnaker.clouddriver.alicloud.AliCloudProvider;
import com.netflix.spinnaker.clouddriver.model.HealthState;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

public class HealthHelper {

  private static boolean healthyStateMatcher(String key, String loadBalancerId, String instanceId) {
    String regex;
    if (StringUtils.isNotBlank(loadBalancerId)) {
      regex = AliCloudProvider.ID + ":.*:" + loadBalancerId + ":" + instanceId + ":.*";
      return Pattern.matches(regex, key);
    } else {
      regex = AliCloudProvider.ID + ":.*:" + instanceId + ":.*";
    }
    return Pattern.matches(regex, key);
  }

  public static HealthState judgeInstanceHealthyState(
      Collection<String> allHealthyKeys,
      List<String> loadBalancerIds,
      String instanceId,
      Cache cacheView) {
    Set<String> healthyKeys = new HashSet<>();
    if (loadBalancerIds != null) {
      for (String loadBalancerId : loadBalancerIds) {
        List<String> collect =
            allHealthyKeys.stream()
                .filter(tab -> HealthHelper.healthyStateMatcher(tab, loadBalancerId, instanceId))
                .collect(Collectors.toList());
        Collection<CacheData> healthData = cacheView.getAll(HEALTH.ns, collect, null);
        if (CollectionUtils.isEmpty(healthData)) {
          return HealthState.Unknown;
        }
        healthyKeys.addAll(collect);
      }
    } else {
      List<String> collect =
          allHealthyKeys.stream()
              .filter(tab -> HealthHelper.healthyStateMatcher(tab, null, instanceId))
              .collect(Collectors.toList());
      healthyKeys.addAll(collect);
    }
    Collection<CacheData> healthData = cacheView.getAll(HEALTH.ns, healthyKeys, null);
    Map<String, Integer> healthMap = new HashMap<>(16);
    for (CacheData cacheData : healthData) {
      String serverHealthStatus = cacheData.getAttributes().get("serverHealthStatus").toString();
      healthMap.put(serverHealthStatus, healthMap.getOrDefault(serverHealthStatus, 0) + 1);
    }
    Integer normal = healthMap.get("normal");
    Integer abnormal = healthMap.get("abnormal");
    if (normal != null && normal > 0 && abnormal == null) {
      return HealthState.Up;
    } else if (abnormal != null && abnormal > 0 && normal == null) {
      return HealthState.Down;
    } else if (abnormal == null && normal == null) {
      return HealthState.Down;
    } else {
      return HealthState.Unknown;
    }
  }
}


text:
A [Handlebars][] ternary helper.

[![npm Version][npm-badge]][npm]
[![Build Status][build-badge]][build-status]
[![Test Coverage][coverage-badge]][coverage-result]
[![Dependency Status][dep-badge]][dep-status]

## Installation

Install using npm:

    $ npm install handlebars-helper-ternary

## Usage

**helpers.js**

Example helpers file that requires in Handlebars and registers the ternary
helper under the name "ternary".

```js
var Handlebars = require('handlebars');

Handlebars.registerHelper('ternary', require('handlebars-helper-ternary'));
```

**templates/example.handlebars**

Example template file that makes use of the ternary helper.  This helper
accepts three arguments: a `test` argument to evaluate for truthiness, a `yes`
argument to return in the case that `test` is truthy, and a `no` argument to
return in the case that `test` is falsy.

```
<button type="button">{{ternary isNew "Add" "Save"}}</button>
```

## Changelog

### 1.0.0 - 2015-07-17
- Initial release

## License

MIT

[Handlebars]: http://handlebarsjs.com/
[build-badge]: https://img.shields.io/travis/jimf/handlebars-helper-ternary/master.svg
[build-status]: https://travis-ci.org/jimf/handlebars-helper-ternary
[npm-badge]: https://img.shields.io/npm/v/handlebars-helper-ternary.svg
[npm]: https://www.npmjs.org/package/handlebars-helper-ternary
[coverage-badge]: https://img.shields.io/coveralls/jimf/handlebars-helper-ternary.svg
[coverage-result]: https://coveralls.io/r/jimf/handlebars-helper-ternary
[dep-badge]: https://img.shields.io/david/jimf/handlebars-helper-ternary.svg
[dep-status]: https://david-dm.org/jimf/handlebars-helper-ternary


text:
This is a very simple sample jekyll app that serves a static website.

It can be staged by using [stager-jekyll](https://github.com/apcera/continuum-sample-apps/tree/master/stager-jekyll).

For more information on how to stage `example-jekyll`, check out the `README.md` at the above link.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.aries.subsystem.core.internal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;

import org.apache.aries.subsystem.core.archive.DeploymentManifest;
import org.apache.aries.subsystem.core.archive.SubsystemContentHeader;
import org.osgi.framework.BundleException;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Resource;
import org.osgi.service.subsystem.Subsystem.State;
import org.osgi.service.subsystem.SubsystemConstants;
import org.osgi.service.subsystem.SubsystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StopAction extends AbstractAction {
	private static final Logger logger = LoggerFactory.getLogger(StopAction.class);

	public StopAction(BasicSubsystem requestor, BasicSubsystem target, boolean disableRootCheck) {
		super(requestor, target, disableRootCheck);
	}

	@Override
	public Object run() {
		checkRoot();
		State state = target.getState();
		if (EnumSet.of(State.INSTALLED, State.RESOLVED).contains(state))
			return null;
		else if (EnumSet.of(State.INSTALL_FAILED, State.UNINSTALLING, State.UNINSTALLED).contains(state))
			throw new IllegalStateException("Cannot stop from state " + state);
		else if (EnumSet.of(State.INSTALLING, State.RESOLVING, State.STARTING, State.STOPPING).contains(state)) {
			waitForStateChange(state);
			return new StopAction(requestor, target, disableRootCheck).run();
		}
		target.setState(State.STOPPING);
		List<Resource> resources = new ArrayList<Resource>(Activator.getInstance().getSubsystems().getResourcesReferencedBy(target));
		SubsystemContentHeader header = target.getSubsystemManifest().getSubsystemContentHeader();
		if (header != null) {
			Collections.sort(resources, new StartResourceComparator(target.getSubsystemManifest().getSubsystemContentHeader()));
			Collections.reverse(resources);
		}
		for (Resource resource : resources) {
			// Don't stop the region context bundle.
			if (Utils.isRegionContextBundle(resource))
				continue;
			try {
				stopResource(resource);
			}
			catch (Exception e) {
				logger.error("An error occurred while stopping resource " + resource + " of subsystem " + target, e);
			}
		}
		// TODO Can we automatically assume it actually is resolved?
		target.setState(State.RESOLVED);
		try {
			synchronized (target) {
				target.setDeploymentManifest(new DeploymentManifest(
						target.getDeploymentManifest(),
						null,
						target.isAutostart(),
						target.getSubsystemId(),
						SubsystemIdentifier.getLastId(),
						target.getLocation(),
						false,
						false));
			}
		}
		catch (Exception e) {
			throw new SubsystemException(e);
		}
		return null;
	}

	private void stopBundleResource(Resource resource) throws BundleException {
		if (target.isRoot())
			return;
		((BundleRevision)resource).getBundle().stop();
	}

	private void stopResource(Resource resource) throws BundleException, IOException {
		if (Utils.getActiveUseCount(resource) > 0)
			return;
		String type = ResourceHelper.getTypeAttribute(resource);
		if (SubsystemConstants.SUBSYSTEM_TYPE_APPLICATION.equals(type)
				|| SubsystemConstants.SUBSYSTEM_TYPE_COMPOSITE.equals(type)
				|| SubsystemConstants.SUBSYSTEM_TYPE_FEATURE.equals(type))
			stopSubsystemResource(resource);
		else if (IdentityNamespace.TYPE_BUNDLE.equals(type))
			stopBundleResource(resource);
		else if (IdentityNamespace.TYPE_FRAGMENT.equals(type))
			return;
		else
			throw new SubsystemException("Unsupported resource type: " + type);
	}

	private void stopSubsystemResource(Resource resource) throws IOException {
		new StopAction(target, (BasicSubsystem)resource, !((BasicSubsystem)resource).isRoot()).run();
	}
}


text:
package cram

import (
        "encoding/json"
        "net/http"
        "fmt"
        )

type Final struct {
  Title string
  Ratings map[string]map[string]string
}

func init() {
  http.HandleFunc("/", GetRatings)
}

func GetRatings(w http.ResponseWriter, r *http.Request) {
  Output := Final{
    Title: "",
    Ratings: map[string]map[string]string{
      "user": make(map[string]string),
      "critic": make(map[string]string),
    },
  }

  name := r.URL.Path[1:]

  imdb_id := tmdb(name, &Output)

  imdb(imdb_id, &Output)
  metacritic(&Output)

  w.Header().Set("Application-Type", "Application/json")
  res, err := json.Marshal(Output)
  fmt.Println(res)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  fmt.Fprint(w, string(res))
}


text:
<link href="./tooltip.css" rel="stylesheet">

    Small Help
    I'm a div

    Small Help
    I'm a wider div

Small HelpI'm

    Small Help
    Top variant

    Small Help
    <input aria-describedby="input-tooltip"/>
    Label

    Small Help
    Xmas Tree


text:
#ifndef GCC_COMMON_TARGHOOKS_H
#define GCC_COMMON_TARGHOOKS_H

extern enum unwind_info_type default_except_unwind_info (struct gcc_options *);
extern enum unwind_info_type dwarf2_except_unwind_info (struct gcc_options *);
extern enum unwind_info_type sjlj_except_unwind_info (struct gcc_options *);

extern bool default_target_handle_option (struct gcc_options *,
					  struct gcc_options *,
					  const struct cl_decoded_option *,
					  location_t);

extern const struct default_options empty_optimization_table[];

#endif


text:
package com.vsct.dt.strowgr.admin.gui.mapping.json;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.vsct.dt.strowgr.admin.core.configuration.EntryPointBackendServer;

import java.util.Map;

/**
 * Json mapping of {@code EntryPointBackendServer}.
 *
 * Created by william_montaz on 09/02/2016.
 */
public class EntryPointBackendServerMappingJson extends EntryPointBackendServer {

    @JsonCreator
    public EntryPointBackendServerMappingJson(@JsonProperty("id") String id,
                                              @JsonProperty("hostname") String hostname,
                                              @JsonProperty("ip") String ip,
                                              @JsonProperty("port") String port,
                                              @JsonProperty("context") Map<String, String> context,
                                              @JsonProperty("contextOverride") Map<String, String> contextOverride) {
        //TODO remove hostname attribute
        super(id, ip, port, context, contextOverride);
    }

    public EntryPointBackendServerMappingJson(EntryPointBackendServer s) {
        this(s.getId(), s.getHostname(), s.getIp(), s.getPort(), s.getContext(), s.getContextOverride());
    }
}


text:
var spawn = require('child_process').spawn;

/**
 * Connect middleware providing gzip compression on the fly. By default, it
 * compresses requests with mime types that match the expression
 * /text|javascript|json/.
 *
 * Options:
 *
 *  - `matchType`   Regular expression matching mime types to be compressed
 *  - `flags`       String of flags passed to the binary. Nothing by default
 *  - `bin`         Binary executable defaulting to "gzip"
 *
 * @param {Object} options
 * @api public
 */

exports = module.exports = function gzip(options) {
  var options = options || {},
      matchType = options.matchType || /text|javascript|json/,
      bin = options.bin || 'gzip',
      flags = options.flags || '';

  if (!matchType.test) throw new Error('option matchType must be a regular expression');

  flags = (flags) ? '-c ' + flags : '-c';
  flags = flags.split(' ');

  return function gzip(req, res, next) {
    var writeHead = res.writeHead,
        defaults = {};

    ['write', 'end'].forEach(function(name) {
      defaults[name] = res[name];
      res[name] = function() {
        // Make sure headers are setup if they haven't been called yet
        if (res.writeHead !== writeHead) {
          res.writeHead(res.statusCode);
        }
        res[name].apply(this, arguments);
      };
    });

    res.writeHead = function(code) {
      var args = Array.prototype.slice.call(arguments, 0),
          write = defaults.write,
          end = defaults.end,
          headers, key, accept, type, encoding, gzip, ua;
      if (args.length > 1) {
        headers = args.pop();
        for (key in headers) {
          res.setHeader(key, headers[key]);
        }
      }

      ua = req.headers['user-agent'] || '';
      accept = req.headers['accept-encoding'] || '';
      type = res.getHeader('content-type') || '';
      encoding = res.getHeader('content-encoding');

      if (req.method === 'HEAD' || code !== 200 || !~accept.indexOf('gzip') ||
          !matchType.test(type) || encoding ||
          (~ua.indexOf('MSIE 6') && !~ua.indexOf('SV1'))) {
        res.write = write;
        res.end = end;
        return finish();
      }

      res.setHeader('Content-Encoding', 'gzip');
      res.setHeader('Vary', 'Accept-Encoding');
      res.removeHeader('Content-Length');

      gzip = require('zlib').createGzip()

      res.write = function(chunk, encoding) {
        gzip.write(chunk, encoding);
      };

      res.end = function(chunk, encoding) {
        if (chunk) {
          res.write(chunk, encoding);
        }
        gzip.end();
      };

      gzip.addListener('data', function(chunk) {
        write.call(res, chunk);
      });

      gzip.addListener('end', function(code) {
        res.write = write;
        res.end = end;
        res.end();
      });

      finish();

      function finish() {
        res.writeHead = writeHead;
        res.writeHead.apply(res, args);
      }
    };

    next();
  };
};


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE component SYSTEM "dtds/component.dtd">

<component name="Course">

	<entity>
		<property name="year" type="int" size="4" key="true"/>
		<property name="number" type="int" key="true" size="5" hidden="true">
			<default-value-calculator on-create="true"
				class="org.openxava.test.calculators.CourseNumberCalculator"/>
		</property>
		<property name="description" type="String" required="true"/>
		<!-- dtype is to be compatible at db level with de JPA version -->
		<property name="dtype" type="String" hidden="true">
			<default-value-calculator on-create="true"
				class="org.openxava.calculators.StringCalculator">
				<set property="string" value="Course"/>
		</default-value-calculator>
		</property>
	</entity>

	<entity-mapping table="XAVATEST@separator@COURSE">
		<property-mapping property="year" column="YEAR"/>
		<property-mapping property="number" column="NUMBER"/>
		<property-mapping property="description" column="DESCRIPTION"/>
		<property-mapping property="dtype" column="DTYPE"/>
	</entity-mapping>

</component>


text:
using Bmz.Framework.Auditing;
using Shouldly;
using Xunit;

namespace Bmz.Framework.Tests.Auditing
{
    public class AuditingHelper_Tests
    {
        [Fact]
        public void Ignored_Properties_Should_Not_Be_Serialized()
        {
            var json = AuditingHelper.Serialize(new AuditingHelperTestPersonDto
            {
                FullName = "John Doe",
                Age = 18,
                School = new AuditingHelperTestSchoolDto
                {
                    Name = "Crosswell Secondary",
                    Address = "Broadway Ave, West Bend"
                }
            });

            json.ShouldBe("{\"fullName\":\"John Doe\",\"school\":{\"name\":\"Crosswell Secondary\"}}");
        }

        public class AuditingHelperTestPersonDto
        {
            public string FullName { get; set; }

            [DisableAuditing]
            public int Age { get; set; }

            public AuditingHelperTestSchoolDto School { get; set; }
        }

        public class AuditingHelperTestSchoolDto
        {
            public string Name { get; set; }

            [DisableAuditing]
            public string Address { get; set; }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>rasterizeHTML.js example</title>

    <canvas id="canvas" width="600" height="150"></canvas>

        Hover selector:
        <input type="text" id="hoverSelector" value=".link">

        Active selector:
        <input type="text" id="activeSelector">

        Focus selector:
        <input type="text" id="focusSelector">

        Target selector:
        <input type="text" id="targetSelector">

    <textarea id="input" cols="80" rows="10" style="width: 600px; height: 350px"></textarea>


text:
export default (dispatch, components, params) => {
    const needs = components.reduce((done, current) => {
        return current ? (current.needs || []).concat(done) : done;
    }, []);

    const promises = needs.map(need => dispatch(need(params)));

    return Promise.all(promises);
}


text:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import App from '../components/';
import * as Actions from '../actions/index';

class AppContainer extends Component {

    static defaultProps = {
        state: ''
    };

    static propTypes = {
        state: PropTypes.string
    }

    transitionToFoo = () => {
        this.props.transitionByName('FooContainer');
    }

    transitionToBar = () => {
        this.props.transitionByName('BarContainer', [ 1, 1 ]);
    }

    transitionTo = () => {
        this.props.transitionTo('/bar/2/1/');
    }

    render() {
        return (
            <div>
                <App
                    transitionToFoo={this.transitionToFoo}
                    transitionToBar={this.transitionToBar}
                    transitionTo={this.transitionTo}
                />
            </div>
        );
    }
}

function mapStateToProps(state) {
    return { state: state.state};
}

function mapDispatchToProps(dispatch) {
    return { };
}

export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudasset.v1p7beta1.model;

/**
 * Model definition for CreateExportSettingRequest.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Asset API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CreateExportSettingRequest extends com.google.api.client.json.GenericJson {

  /**
   * Required. The export setting details. The field `name` must be empty and it will be generated
   * in the format of:
   * projects/{PROJECT_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * folders/{FOLDER_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * organizations/{ORGANIZATION_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ExportSetting exportSetting;

  /**
   * Required. This is the client-assigned export setting identifier encoded in UTF-8 and it needs
   * to be unique under a specific [InventorySettings].
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String exportSettingId;

  /**
   * Required. The export setting details. The field `name` must be empty and it will be generated
   * in the format of:
   * projects/{PROJECT_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * folders/{FOLDER_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * organizations/{ORGANIZATION_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * @return value or {@code null} for none
   */
  public ExportSetting getExportSetting() {
    return exportSetting;
  }

  /**
   * Required. The export setting details. The field `name` must be empty and it will be generated
   * in the format of:
   * projects/{PROJECT_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * folders/{FOLDER_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * organizations/{ORGANIZATION_NUMBER}/inventorySettings/exportSettings/{EXPORT_SETTING_ID}
   * @param exportSetting exportSetting or {@code null} for none
   */
  public CreateExportSettingRequest setExportSetting(ExportSetting exportSetting) {
    this.exportSetting = exportSetting;
    return this;
  }

  /**
   * Required. This is the client-assigned export setting identifier encoded in UTF-8 and it needs
   * to be unique under a specific [InventorySettings].
   * @return value or {@code null} for none
   */
  public java.lang.String getExportSettingId() {
    return exportSettingId;
  }

  /**
   * Required. This is the client-assigned export setting identifier encoded in UTF-8 and it needs
   * to be unique under a specific [InventorySettings].
   * @param exportSettingId exportSettingId or {@code null} for none
   */
  public CreateExportSettingRequest setExportSettingId(java.lang.String exportSettingId) {
    this.exportSettingId = exportSettingId;
    return this;
  }

  @Override
  public CreateExportSettingRequest set(String fieldName, Object value) {
    return (CreateExportSettingRequest) super.set(fieldName, value);
  }

  @Override
  public CreateExportSettingRequest clone() {
    return (CreateExportSettingRequest) super.clone();
  }

}


text:
- [#2324](https://github.com/redux-saga/redux-saga/pull/2324) [`2466c79`](https://github.com/redux-saga/redux-saga/commit/2466c798a5f56a5015e61c8fdf0ef8f2a6a852a4) Thanks [@neurosnap](https://github.com/neurosnap)! - Add LICENSE file

- Updated dependencies [[`2466c79`](https://github.com/redux-saga/redux-saga/commit/2466c798a5f56a5015e61c8fdf0ef8f2a6a852a4)]:
  - @redux-saga/symbols@1.1.3

## 1.2.0

### Minor Changes

- [#2308](https://github.com/redux-saga/redux-saga/pull/2308) [`8207e33`](https://github.com/redux-saga/redux-saga/commit/8207e33) Thanks [@Andarist](https://github.com/Andarist), [@neurosnap](https://github.com/neurosnap)! - `exports` field has been added to the `package.json` manifest. It limits what files can be imported from a package but we've tried our best to allow importing all the files that were considered to be a part of the public API.

  This should fix the compatibility with Node.js ESM support.

### Patch Changes

- [#2293](https://github.com/redux-saga/redux-saga/pull/2293) [`2d2214e`](https://github.com/redux-saga/redux-saga/commit/2d2214e9ca8949892c0a7a23ceef39fa32d13939) Thanks [@neurosnap](https://github.com/neurosnap)! - Fixed an issue with arguments that exceed the maximum value for the internally-used `setTimeout`. Previously it could overflow based on the input that was too big and thus a timeout could resolve immediately.


text:
class FollowingTag < ActiveRecord::Base
  belongs_to :user
  belongs_to :tag
end


text:
import * as React from 'react';
import { compose } from 'recompose';
import styled from 'styled-components';

const enhance = compose(

);

const WhitePianoKeyOuter = styled.div`
  z-index: 10;
  color: black;

  &:last-child {
    border-right: 1px solid black;
  }

  .PianoKey--pressed {
    background: #fc354c;
  }

  &.PianoKey--justPressed {
    background: #fc354c;
    transition: background ease-in 10ms;
  }
`;
const WhitePianoKeyInner = styled.div`
  width: 24px;
  height: 98px;
  box-sizing: border-box;
  border-top: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  transition: background ease-in 100ms;
  background: white;
  display: flex;
  justify-content: center;
  align-items: flex-end;
`;
const MiddleC = styled.div`
  margin-bottom: 3px;
  font-size: 10px;
`;

const WhitePianoKey = ({ note, rootClassNames }) => (
  <WhitePianoKeyOuter>
    <WhitePianoKeyInner className={rootClassNames}>
      {note === 'C/4' ? <MiddleC>C</MiddleC> : null}
    </WhitePianoKeyInner>
  </WhitePianoKeyOuter>
);

export default compose(WhitePianoKey);


text:
$(window).scroll(function() {
    var scrollBottom = $(window).scrollTop() + $(window).height();

    if ($(window).scrollTop() > 100) {
        $('body').addClass('nav-hidden');
    }

    else {
        $('body').removeClass('nav-hidden');
    }
});

$(".full img").click(function() {
  $(".full img").toggleClass('zoom');
});


text: .. automodule:: tenable.ad


text:
package com.sanluan.cms.views.directive.cms;

// Generated 2015-5-10 17:54:56 by SourceMaker

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sanluan.cms.entities.cms.CmsCategoryAttribute;
import com.sanluan.cms.logic.service.cms.CmsCategoryAttributeService;
import com.sanluan.common.base.BaseDirective;
import com.sanluan.common.handler.DirectiveHandler;

import freemarker.template.TemplateException;

@Component
public class CmsCategoryAttributeDirective extends BaseDirective {

	@Override
	public void execute(DirectiveHandler handler) throws TemplateException, IOException {
		Integer id = handler.getInteger("id");
		if (null != id) {
			CmsCategoryAttribute bean = service.getEntity(id);
			handler.put("bean", bean).renderIfNotNull(bean);
		} else {
			Integer[] ids = handler.getIntegerArray("ids");
			if (null != ids && 0 < ids.length) {
				List<CmsCategoryAttribute> beanList = service.getEntitys(ids, "categoryId");
				Map<String, CmsCategoryAttribute> map = new HashMap<String, CmsCategoryAttribute>();
				for (CmsCategoryAttribute bean : beanList) {
					map.put(String.valueOf(bean.getCategoryId()), bean);
				}
				handler.put("map", map).renderIfNotNull(map);
			}
		}
	}

	@Autowired
	private CmsCategoryAttributeService service;

}


text:
namespace google {
namespace cloud {
namespace serviceusage_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/// Define the gRPC status code semantics for retrying requests.
struct ServiceUsageRetryTraits {
  static inline bool IsPermanentFailure(google::cloud::Status const& status) {
    return status.code() != StatusCode::kOk &&
           status.code() != StatusCode::kUnavailable;
  }
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace serviceusage_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SERVICEUSAGE_INTERNAL_SERVICE_USAGE_RETRY_TRAITS_H


text:
var myCalc = {
    input: "0",
    clearInputFlag: false,
    operandOne: null,
    operandTwo: null,
    operator: null,
    inputDigit: function (digit) {
        // First, check to see if we need to clear the input before adding a new entry
        if (this.clearInputFlag === true) {
            this.clearInput();
            this.clearInputFlag = false;
        }
        // If we're inputting a decimal point, only add it if one doesn't already exist
        // in the input
        if (digit === "." && this.input.includes(".")) {
            return;
        }
        // Limit input to 15 characters
        if (this.input.length >= 20) {
            return;
        }
        this.input = "" + this.input + digit;
        // Clear leading zero unless the 2nd character is a decimal point
        if (this.input.length > 1 && this.input[0] === "0" && this.input[1] !== ".") {
            this.input = this.input.substring(1);
        }
    },
    inputOperator: function (operator) {
        // Move what is currently in input to operand one/two.
        // This will also set the clear input flag
        // so that the next entry will be a new input
        this.moveInputToCalculator();
        // Perform the previous calculation
        this.calculate();
        // set the operator variable so that we can use it in the next calculate() call
        this.operator = operator;
    },
    calculate: function () {
        if (this.operandOne === null || this.operandTwo === null) {
            return;
        }
        var result;
        switch (this.operator) {
            case "add":
                result = this.operandOne + this.operandTwo;
                break;
            case "subtract":
                result = this.operandOne - this.operandTwo;
                break;
            case "multiply":
                result = this.operandOne * this.operandTwo;
                break;
            case "divide":
                result = this.operandOne / this.operandTwo;
                break;
            case "equal":
                break;
            default:
                result = null;
        }
        // round the result
        // result = Math.round(result);
        this.input = "" + result;
        this.operandOne = result;
    },
    performCalculation: function () {
        // We only call this function when somebody hits the equals sign
        this.moveInputToCalculator();
        this.calculate();
        this.clearInputFlag = true;
        this.operandOne = null;
        this.operandTwo = null;
        this.operator = null;
    },
    moveInputToCalculator: function () {
        if (this.operandOne === null) {
            this.operandOne = parseFloat(this.input);
        }
        else {
            this.operandTwo = parseFloat(this.input);
        }
        this.clearInputFlag = true;
    },
    clearInput: function () {
        this.input = "0";
    },
    clearAll: function () {
        this.clearInput();
        this.operandOne = null;
        this.operandTwo = null;
        this.operator = null;
    },
    delete: function () {
        this.input = this.input.split('');
        this.input.splice(this.input.length - 1, 1);
        this.input = this.input.join('');
        if (this.input.length === 0) {
            this.input = "0";
        }
    },
    reverseSign: function () {
        this.input = this.input.split('');
        if (this.input[0] === '-') {
            console.log("negative");
            this.input.shift();
        }
        else {
            console.log("positive");
            this.input.unshift('-');
        }
        this.input = this.input.join('');
    }
};
$(document).ready(function () {
    $('#calculator #buttons button').on('click', function () {
        var buttonName = $(this).attr('name');
        var operation = $(this).attr('operation');
        if (operation !== undefined) {
            myCalc.inputOperator(operation);
        }
        else if (myCalc.hasOwnProperty(buttonName)) {
            myCalc[buttonName]();
        }
        else {
            myCalc.inputDigit($(this).html());
        }
        // Update the input displayed
        $('#input').html(myCalc.input);
    });
});


text:
'use strict';

import * as assert from 'assert';
import * as vscode from 'vscode';
import * as path from 'path';
import { parseMarkup, cssUri } from '../../markupParser';
import * as fs from 'fs';

const HTML_FORMATTER = require('html-formatter');

const FILE_ENCODING = 'utf8';

const CONFLUENCE_FILENAME_EXTENSION = 'confluence';
const HTML_FILENAME_EXTENSION = 'html';

const PROJECT_ROOT_DIR = path.join(__dirname, '../../..');
const TEST_EXTENSION_PATH_PLACEHOLDER = '_TEST_EXTENSION_PATH_PLACEHOLDER_';
const TEST_FILES_ROOT = path.join(PROJECT_ROOT_DIR, "/src/test/suite/fixtures/testfiles");
const FIXTURES_ROOT = path.join(PROJECT_ROOT_DIR, "/src/test/suite/fixtures/expected");

function walkdirSync(dir: string): string[] {
    return fs.readdirSync(dir).reduce(function (result: string[], file) {
        const name = path.join(dir, file);
        const isDir = fs.statSync(name).isDirectory();
        return result.concat(isDir ? walkdirSync(name) : [name]);
    }, []);
}

function isConfluence(element: string): boolean {
    return (element.endsWith(`.${CONFLUENCE_FILENAME_EXTENSION}`));
}

// Defines a Mocha test suite to group tests of similar kind together
suite("MarkupParser Tests", function () {

    // Defines a Mocha unit test
    test("Test CSS Uri", function () {
        // const expected = vscode.Uri.file(path.join(__dirname, "../../../media/css/dummy.css"));
        const expected = vscode.Uri.file(path.join(PROJECT_ROOT_DIR, "/media/css/dummy.css"));
        // console.log(expected.fsPath)
        const css = cssUri("dummy.css");
        assert.notStrictEqual(css, undefined);
        if (css) {
            assert.strictEqual(css.fsPath, expected.fsPath);
            assert.strictEqual(css.scheme, expected.scheme);
        }
    });

    walkdirSync(TEST_FILES_ROOT).filter(isConfluence).forEach(fullFilePath => {
        const fileName = path.basename(fullFilePath);
        const dirName = path.dirname(fullFilePath);

        let typeDir = path.basename(dirName);
        let scopedDir = ''
        if (dirName.endsWith('scoped')) {
            scopedDir = path.basename(dirName);
            typeDir = path.basename(path.dirname(dirName));
        }

        const testName = "Render testfile: " + path.join(typeDir, scopedDir, fileName)
        test(testName, function () {
            const fixtureFile = path.join(FIXTURES_ROOT, scopedDir, fileName.replace(CONFLUENCE_FILENAME_EXTENSION, HTML_FILENAME_EXTENSION));

            let project_root_dir = PROJECT_ROOT_DIR;

            if (process.platform === 'win32') {
                project_root_dir = `/${project_root_dir.split(path.sep).join(path.posix.sep).replace(':', '%3A')}`;
            }

            const fixtureContent = HTML_FORMATTER.render(
                fs.readFileSync(fixtureFile, FILE_ENCODING).replace(new RegExp(TEST_EXTENSION_PATH_PLACEHOLDER, 'g'), project_root_dir)
            );

            const testFileUri = vscode.Uri.file(fullFilePath);
            const confluenceContent = fs.readFileSync(testFileUri.fsPath, FILE_ENCODING);

            const parsedMarkup = HTML_FORMATTER.render(
                parseMarkup(testFileUri, confluenceContent)
            );
            assert.strictEqual(parsedMarkup, fixtureContent);
        });
    });
});


text:
module Cairo

  class Widget
    attr_reader :pos

    def initialize(opts={}, *a)
      create(opts, *a)
      set_pos(*opts.values_at(:x, :y).map{|i| i || 0 }) unless @pos
      @width, @height = 100, 100 unless @width && @height
      klass = case Cairo.render_type
              when :x11; Cairo::DataSurface
              when :gl;  Cairo::OpenGL_Surface
              else raise "no Cairo.render_type found!"
              end
      @surface = klass.new(@width, @height)
      @surface.callback = method(:callback)
    end

    def create(opts, *a); end
    def set_pos(x,y); @pos = [x, y]; end
    def callback(cairo, width, height, cairo_helper); end

    def render; @surface.render; end
    def draw(*a); @surface.draw(*a); end
    def redraw(*a); @surface.surface && @surface.redraw(*a); end
    def destroy; @surface.destroy; end
  end

  class Widgets
    attr_reader :widgets
    def initialize; @widgets, @timers = {}, {}; end
    def add(name, widget); @widgets[name] = widget; end
    def draw(cairo_context=nil)
      @widgets.each{|name,widget|
        case Cairo.render_type
        when :x11
          widget.redraw(cairo_context, *widget.pos)

        when :gl
          GL.glPushMatrix
            widget.redraw(cairo_context, *widget.pos)
          GL.glPopMatrix

        else raise "no Cairo.render_type found!"
        end
      }
    end
    def render_all; @widgets.each{|name,widget| widget.render }; end
    def [](name); @widgets[name]; end
    def render(name); @widgets[name].render; end

    def fire_timers!
      now, run_now = Time.now.to_f, []
      @timers.each{|name,timers|
        timers.each{|state|
          if state[:next_tick] <= now
            run_now << [name, state[:method]] # queue run
            state[:next_tick] = now + state[:interval] # enqueue next tick
          end
        }
      }
      run_now.each{|name,method| @widgets[name].send(method) }
    end

    def add_timer(name, interval, method)
      @timers[name] ||= []
      @timers[name] << { method: method, interval: interval, next_tick: Time.now.to_f + interval }
    end
  end

  class << self
    attr_accessor :render_type

    def create_window(name, w=600, h=480, x=0, y=0)
      p [:create_window, name, Cairo.render_type, w, h]
      klass = case Cairo.render_type
              when :gl;   Cairo::GL::X11::Window
              when :x11;  Cairo::X11::Window
              else raise "no Cairo.render_type found!"
              end
      klass.new(name, nil, nil, :normal, w, h, x, y)
    end
  end

end


text:
package org.springframework.social.config;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionSignUp;

public class FakeConnectionSignUp implements ConnectionSignUp {

	public String execute(Connection<?> connection) {
		return "fakeuser";
	}

}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include <winpr/crt.h>
#include <winpr/windows.h>
#include <freerdp/log.h>

#ifndef _WIN32
#include <netdb.h>
#include <unistd.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#endif

#include "listener.h"

#define TAG FREERDP_TAG("core.listener")

#ifdef _WIN32
#if _WIN32_WINNT < 0x0600
static const char* inet_ntop(int af, const void* src, char* dst, size_t cnt)
{
	if (af == AF_INET)
	{
		struct sockaddr_in in;

		memset(&in, 0, sizeof(in));
		in.sin_family = AF_INET;
		memcpy(&in.sin_addr, src, sizeof(struct in_addr));
		getnameinfo((struct sockaddr *)&in, sizeof(struct sockaddr_in), dst, cnt, NULL, 0, NI_NUMERICHOST);
		return dst;
	}
	else if (af == AF_INET6)
	{
		struct sockaddr_in6 in;

		memset(&in, 0, sizeof(in));
		in.sin6_family = AF_INET6;
		memcpy(&in.sin6_addr, src, sizeof(struct in_addr6));
		getnameinfo((struct sockaddr*) &in, sizeof(struct sockaddr_in6), dst, cnt, NULL, 0, NI_NUMERICHOST);
		return dst;
	}

	return NULL;
}
#endif
#endif

static BOOL freerdp_listener_open(freerdp_listener* instance, const char* bind_address, UINT16 port)
{
	int status;
	int sockfd;
	char addr[64];
	void* sin_addr;
	int option_value;
	char servname[16];
	struct addrinfo* ai;
	struct addrinfo* res;
	struct addrinfo hints = { 0 };
	rdpListener* listener = (rdpListener*) instance->listener;
#ifdef _WIN32
	u_long arg;
#endif

	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;

	if (!bind_address)
		hints.ai_flags = AI_PASSIVE;

	sprintf_s(servname, sizeof(servname), "%d", port);
	status = getaddrinfo(bind_address, servname, &hints, &res);

	if (status != 0)
	{
#ifdef _WIN32
		WLog_ERR("getaddrinfo error: %s", gai_strerrorA(status));
#else
		WLog_ERR(TAG, "getaddrinfo");
#endif
		return FALSE;
	}

	for (ai = res; ai && (listener->num_sockfds < 5); ai = ai->ai_next)
	{
		if ((ai->ai_family != AF_INET) && (ai->ai_family != AF_INET6))
			continue;

		if (listener->num_sockfds == MAX_LISTENER_HANDLES)
		{
			WLog_ERR(TAG, "too many listening sockets");
			continue;
		}

		sockfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);

		if (sockfd == -1)
		{
			WLog_ERR(TAG, "socket");
			continue;
		}

		if (ai->ai_family == AF_INET)
			sin_addr = &(((struct sockaddr_in*) ai->ai_addr)->sin_addr);
		else
			sin_addr = &(((struct sockaddr_in6*) ai->ai_addr)->sin6_addr);

		inet_ntop(ai->ai_family, sin_addr, addr, sizeof(addr));

		option_value = 1;

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void*) &option_value, sizeof(option_value)) == -1)
			WLog_ERR(TAG, "setsockopt");

#ifndef _WIN32
		fcntl(sockfd, F_SETFL, O_NONBLOCK);
#else
		arg = 1;
		ioctlsocket(sockfd, FIONBIO, &arg);
#endif

		status = _bind((SOCKET) sockfd, ai->ai_addr, ai->ai_addrlen);

		if (status != 0)
		{
			closesocket((SOCKET) sockfd);
			continue;
		}

		status = _listen((SOCKET) sockfd, 10);

		if (status != 0)
		{
			WLog_ERR(TAG, "listen");
			closesocket((SOCKET) sockfd);
			continue;
		}

		/* FIXME: these file descriptors do not work on Windows */

		listener->sockfds[listener->num_sockfds] = sockfd;
		listener->events[listener->num_sockfds] =
			CreateFileDescriptorEvent(NULL, FALSE, FALSE, sockfd, FD_READ);
		listener->num_sockfds++;

		WLog_INFO(TAG, "Listening on %s:%s", addr, servname);
	}

	freeaddrinfo(res);

	return (listener->num_sockfds > 0 ? TRUE : FALSE);
}

static BOOL freerdp_listener_open_local(freerdp_listener* instance, const char* path)
{
#ifndef _WIN32
	int status;
	int sockfd;
	struct sockaddr_un addr;
	rdpListener* listener = (rdpListener*) instance->listener;
	HANDLE hevent;

	if (listener->num_sockfds == MAX_LISTENER_HANDLES)
	{
		WLog_ERR(TAG, "too many listening sockets");
		return FALSE;
	}

	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

	if (sockfd == -1)
	{
		WLog_ERR(TAG, "socket");
		return FALSE;
	}

	fcntl(sockfd, F_SETFL, O_NONBLOCK);

	addr.sun_family = AF_UNIX;
	strncpy(addr.sun_path, path, sizeof(addr.sun_path));
	unlink(path);

	status = _bind(sockfd, (struct sockaddr*) &addr, sizeof(addr));

	if (status != 0)
	{
		WLog_ERR(TAG, "bind");
		closesocket((SOCKET) sockfd);
		return FALSE;
	}

	status = _listen(sockfd, 10);

	if (status != 0)
	{
		WLog_ERR(TAG, "listen");
		closesocket((SOCKET) sockfd);
		return FALSE;
	}

	hevent = CreateFileDescriptorEvent(NULL, FALSE, FALSE, sockfd, FD_READ);
	if (!hevent)
	{
		WLog_ERR(TAG, "failed to create sockfd event");
		closesocket((SOCKET) sockfd);
		return FALSE;
	}

	listener->sockfds[listener->num_sockfds] = sockfd;
	listener->events[listener->num_sockfds] = hevent;
	listener->num_sockfds++;
	WLog_INFO(TAG, "Listening on socket %s.", addr.sun_path);
	return TRUE;
#else
	return TRUE;
#endif
}

static BOOL freerdp_listener_open_from_socket(freerdp_listener* instance, int fd)
{
#ifndef _WIN32
	rdpListener* listener = (rdpListener*) instance->listener;

	if (listener->num_sockfds == MAX_LISTENER_HANDLES)
	{
		WLog_ERR(TAG, "too many listening sockets");
		return FALSE;
	}

	if (fcntl(fd, F_SETFL, O_NONBLOCK) < 0)
		return FALSE;

	listener->sockfds[listener->num_sockfds] = fd;
	listener->events[listener->num_sockfds] =
		CreateFileDescriptorEvent(NULL, FALSE, FALSE, fd, FD_READ);
	if (!listener->events[listener->num_sockfds])
		return FALSE;

	listener->num_sockfds++;

	WLog_INFO(TAG, "Listening on socket %d.", fd);
	return TRUE;
#else
	return FALSE;
#endif

}

static void freerdp_listener_close(freerdp_listener* instance)
{
	int i;

	rdpListener* listener = (rdpListener*) instance->listener;

	for (i = 0; i < listener->num_sockfds; i++)
	{
		closesocket((SOCKET) listener->sockfds[i]);
		CloseHandle(listener->events[i]);
	}

	listener->num_sockfds = 0;
}

static BOOL freerdp_listener_get_fds(freerdp_listener* instance, void** rfds, int* rcount)
{
	int index;
	rdpListener* listener = (rdpListener*) instance->listener;

	if (listener->num_sockfds < 1)
		return FALSE;

	for (index = 0; index < listener->num_sockfds; index++)
	{
		rfds[*rcount] = (void*)(long)(listener->sockfds[index]);
		(*rcount)++;
	}

	return TRUE;
}

DWORD freerdp_listener_get_event_handles(freerdp_listener* instance, HANDLE* events, DWORD nCount)
{
	int index;
	rdpListener* listener = (rdpListener*) instance->listener;

	if (listener->num_sockfds < 1)
		return 0;

	if (listener->num_sockfds > nCount)
		return 0;

	for (index = 0; index < listener->num_sockfds; index++)
	{
		events[index] = listener->events[index];
	}

	return listener->num_sockfds;
}

static BOOL freerdp_listener_check_fds(freerdp_listener* instance)
{
	int i;
	void* sin_addr;
	int peer_sockfd;
	freerdp_peer* client = NULL;
	socklen_t peer_addr_size;
	struct sockaddr_storage peer_addr;
	rdpListener* listener = (rdpListener*) instance->listener;
	static const BYTE localhost6_bytes[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
	BOOL peer_accepted;

	if (listener->num_sockfds < 1)
		return FALSE;

	for (i = 0; i < listener->num_sockfds; i++)
	{
		peer_addr_size = sizeof(peer_addr);
		peer_sockfd = accept(listener->sockfds[i], (struct sockaddr*) &peer_addr, &peer_addr_size);
		peer_accepted = FALSE;

		if (peer_sockfd == -1)
		{
#ifdef _WIN32
			int wsa_error = WSAGetLastError();

			/* No data available */
			if (wsa_error == WSAEWOULDBLOCK)
				continue;
#else
			if (errno == EAGAIN || errno == EWOULDBLOCK)
				continue;
#endif
			WLog_DBG(TAG, "accept");

			free(client);
			return FALSE;
		}

		client = freerdp_peer_new(peer_sockfd);
		if (!client)
		{
			closesocket((SOCKET) peer_sockfd);
			return FALSE;
		}

		sin_addr = NULL;
		if (peer_addr.ss_family == AF_INET)
		{
			sin_addr = &(((struct sockaddr_in*) &peer_addr)->sin_addr);
			if ((*(UINT32*) sin_addr) == 0x0100007f)
				client->local = TRUE;
		}
		else if (peer_addr.ss_family == AF_INET6)
		{
			sin_addr = &(((struct sockaddr_in6*) &peer_addr)->sin6_addr);
			if (memcmp(sin_addr, localhost6_bytes, 16) == 0)
				client->local = TRUE;
		}
#ifndef _WIN32
		else if (peer_addr.ss_family == AF_UNIX)
			client->local = TRUE;
#endif

		if (sin_addr)
			inet_ntop(peer_addr.ss_family, sin_addr, client->hostname, sizeof(client->hostname));

		IFCALLRET(instance->PeerAccepted, peer_accepted, instance, client);

		if (!peer_accepted)
		{
			WLog_ERR(TAG, "PeerAccepted callback failed");
			closesocket((SOCKET) peer_sockfd);
			freerdp_peer_free(client);
		}
	}

	return TRUE;
}

freerdp_listener* freerdp_listener_new(void)
{
	freerdp_listener* instance;
	rdpListener* listener;

	instance = (freerdp_listener*) calloc(1, sizeof(freerdp_listener));

	if (!instance)
		return NULL;

	instance->Open = freerdp_listener_open;
	instance->OpenLocal = freerdp_listener_open_local;
	instance->OpenFromSocket = freerdp_listener_open_from_socket;
	instance->GetFileDescriptor = freerdp_listener_get_fds;
	instance->GetEventHandles = freerdp_listener_get_event_handles;
	instance->CheckFileDescriptor = freerdp_listener_check_fds;
	instance->Close = freerdp_listener_close;

	listener = (rdpListener*) calloc(1, sizeof(rdpListener));

	if (!listener)
	{
		free (instance);
		return NULL;
	}

	listener->instance = instance;

	instance->listener = (void*) listener;

	return instance;
}

void freerdp_listener_free(freerdp_listener* instance)
{
	rdpListener* listener;

	listener = (rdpListener*) instance->listener;
	free(listener);

	free(instance);
}


text:
namespace pdb {
namespace mutators {

namespace {

using testing::_;
using testing::Invoke;
using testing::Ref;
using testing::Return;
using testing::StrictMock;

class MockAddNamedStreamMutator
    : public AddNamedStreamMutatorImpl<MockAddNamedStreamMutator> {
 public:
  static const char kMutatorName[];

  MOCK_METHOD1(AddNamedStreams, bool(const PdbFile& pdb_file));

  bool AddFooStream(const PdbFile& pdb_file) {
    scoped_refptr<PdbByteStream> stream(new PdbByteStream());
    EXPECT_TRUE(stream->Init(reinterpret_cast<const uint8_t*>(kMutatorName),
                             ::strlen(kMutatorName)));
    added_stream_ = stream;
    EXPECT_TRUE(SetNamedStream("foo", stream.get()));
    return true;
  }

  bool GetAndReplaceFooStream(const PdbFile& pdb_file) {
    scoped_refptr<PdbStream> foo = GetNamedStream("foo");
    EXPECT_TRUE(foo.get() != NULL);

    scoped_refptr<PdbByteStream> stream(new PdbByteStream());
    EXPECT_TRUE(stream->Init(foo.get()));

    added_stream_ = stream;
    EXPECT_FALSE(SetNamedStream("foo", stream.get()));
    return true;
  }

  scoped_refptr<PdbStream> added_stream_;
};

const char MockAddNamedStreamMutator::kMutatorName[] =
    "MockAddNamedStreamMutator";

class AddNamedStreamMutatorTest : public testing::Test {
 public:
  virtual void SetUp() override { testing::Test::SetUp(); }

  void ReadActualPdb() {
    base::FilePath pdb_path =
        testing::GetSrcRelativePath(testing::kTestPdbFilePath);
    PdbReader pdb_reader;
    EXPECT_TRUE(pdb_reader.Read(pdb_path, &pdb_file_));
  }

  void CheckFooStreamAdded() {
    // Read the named stream map and ensure the stream was properly added.
    PdbInfoHeader70 header = {};
    NameStreamMap name_stream_map;
    ASSERT_TRUE(pdb::ReadHeaderInfoStream(pdb_file_, &header,
                                          &name_stream_map));
    ASSERT_TRUE(name_stream_map.count("foo"));
    size_t stream_id = name_stream_map["foo"];
    ASSERT_GT(pdb_file_.StreamCount(), stream_id);
    scoped_refptr<PdbStream> stream(pdb_file_.GetStream(stream_id));
    ASSERT_EQ(mutator_.added_stream_.get(), stream.get());
  }

  StrictMock<MockAddNamedStreamMutator> mutator_;
  PdbFile pdb_file_;
};

}  // namespace

TEST_F(AddNamedStreamMutatorTest, FailsWithNoHeaderInfoStream) {
  EXPECT_FALSE(mutator_.MutatePdb(&pdb_file_));
}

TEST_F(AddNamedStreamMutatorTest, FailsIfAddNamedStreamsFails) {
  ASSERT_NO_FATAL_FAILURE(testing::InitMockPdbFile(&pdb_file_));
  EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1).
      WillOnce(Return(false));
  EXPECT_FALSE(mutator_.MutatePdb(&pdb_file_));
}

TEST_F(AddNamedStreamMutatorTest, SucceedsWithNoInsertion) {
  ASSERT_NO_FATAL_FAILURE(testing::InitMockPdbFile(&pdb_file_));
  EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1).
      WillOnce(Return(true));
  EXPECT_TRUE(mutator_.MutatePdb(&pdb_file_));
}

TEST_F(AddNamedStreamMutatorTest, SucceedsWithInsertionAndReplacement) {
  ASSERT_NO_FATAL_FAILURE(testing::InitMockPdbFile(&pdb_file_));

  EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1).
      WillOnce(Invoke(&mutator_, &MockAddNamedStreamMutator::AddFooStream));
  EXPECT_TRUE(mutator_.MutatePdb(&pdb_file_));

  ASSERT_NO_FATAL_FAILURE(CheckFooStreamAdded());

  EXPECT_CALL(mutator_, AddNamedStreams(Ref(pdb_file_))).Times(1).
    WillOnce(Invoke(&mutator_,
                    &MockAddNamedStreamMutator::GetAndReplaceFooStream));
  EXPECT_TRUE(mutator_.MutatePdb(&pdb_file_));

  ASSERT_NO_FATAL_FAILURE(CheckFooStreamAdded());
}

}  // namespace mutators
}  // namespace pdb


text:
  (log, system, entry, __FILE__, __LINE__, ##__VA_ARGS__);

#define xt_core_log_trace_exit(log, system, entry, ...) _x_audit_log_trace \
  (log, system, entry, __FILE__, __LINE__, ##__VA_ARGS__); exit(44);

struct xt_core_log_t;
typedef struct xt_core_log_t xt_core_log_t;

xt_core_bool_t xt_core_log_add_file(xt_core_log_t *log, FILE *file);

xt_core_log_t *xt_core_log_create(FILE *file);

void xt_core_log_destroy(xt_core_log_t *log);

xt_core_bool_t xt_core_log_enter(xt_core_log_t *log, const char *system,
    const char *entry, ...);

xt_core_bool_t xt_core_log_remove_file(xt_core_log_t *log, FILE *file);

xt_core_bool_t _x_audit_log_trace(xt_core_log_t *log, const char *system,
    const char *entry, const char *file, unsigned long line, ...);

#endif


text:
FROM busybox:latest

MAINTAINER Andrey K. Vital <andreykvital@gmail.com>

COPY ./build/horus-linux-amd64 /app/horus

WORKDIR /app

CMD /app/horus


text:
var connect = require('connect');
var request = require('supertest');

var superstatic = require('../../');

var options = function () {
  return {
    config: {
      root: '.tmp'
    }
  };
};

describe('caching', function () {

  it('default cache control', function (done) {

    var opts = options();

    opts.config.cache_control = {
      '**': true
    };

    var app = connect()
      .use(superstatic(opts));

    request(app)
      .get('/')
      .expect('Cache-Control', 'public, max-age=300')
      .end(done);
  });

  it('custom cache control', function (done) {

    var opts = options();

    opts.config.cache_control = {
      '**': 1234
    };

    var app = connect()
      .use(superstatic(opts));

    request(app)
      .get('/')
      .expect('Cache-Control', 'public, max-age=1234')
      .end(done);
  });
});


text:
#pragma once

#include "stdafx.h"
#include "Vector.cpp"
#include "Matrix.cpp"
#include "ShapeType.cpp"
#include "XForm.cpp"

using namespace System::Collections::Generic;

namespace Box2D
{
	namespace Net
	{
		ref class Body;
		public ref class Shape
		{
		internal:
			b2Shape *shape;
			Shape(b2Shape *shapeRef) : shape(shapeRef) { }

		public:
			bool TestPoint(XForm^ xf, Vector^ p)
			{
				return shape->TestPoint(xf->getXForm(), p->getVec2());
			}

			property ShapeType ShapeType
			{
				Box2D::Net::ShapeType get()
				{
					return (Box2D::Net::ShapeType)shape->GetType();
				}
			}

			/// <summary>
			/// Get the parent body of this shape.
			/// </summary>
			property Body^ Body
			{
				Box2D::Net::Body^ get();
			}

			/*
			/// <summary>
			/// Get the world position.
			/// </summary>
			property Vector^ Position
			{
				Vector^ get()
				{
					return gcnew Vector(shape->Get->GetPosition());
				}
			}
			*/

			/*
			property Matrix^ Rotation
			{
				Matrix^ get()
				{
					return gcnew Matrix(shape->GetRotationMatrix());
				}
			}
			*/

			//TODO:
			//void* GetUserData();
			//
			// Remove and then add proxy from the broad-phase.
			// This is used to refresh the collision filters.
			//virtual void ResetProxy(b2BroadPhase* broadPhase) = 0;

			/// <summary>
			/// Get the next shape in the parent body's shape list.
			/// </summary>
			Shape^ GetNext()
			{
				return gcnew Shape(shape->GetNext());
			}
		};

		public ref class CircleShape : public Shape
		{
		internal:
			b2CircleShape *circleShape;
			CircleShape(b2CircleShape *shapeRef) : Shape(shapeRef), circleShape(shapeRef) { }

		public:
			CircleShape(Shape^ shape) : Shape(shape->shape), circleShape(0)
			{
				if(shape->ShapeType == Box2D::Net::ShapeType::e_circleShape &&
					reinterpret_cast<b2CircleShape *>(shape->shape))
				{
					circleShape = reinterpret_cast<b2CircleShape*>(shape->shape);
				}
				else
				{
					throw gcnew System::Exception("Attempting to convert a Shape to a CircleShape,"
												  "but the Shape is not a circle shape.");
				}
			}

			//TODO: this is not technically part of the "public" interface for CircleShape
			property float32 Radius
			{
				float32 get()
				{
					return circleShape->m_radius;
				}

				void set(float32 value)
				{
					circleShape->m_radius = value;
				}
			}
		};

		public ref class PolyShape : public Shape
		{
		internal:
			b2PolygonShape *polyShape;
			PolyShape(b2PolygonShape *shapeRef) : Shape(shapeRef), polyShape(shapeRef) { }

		public:
			PolyShape(Shape^ shape) : Shape(shape->shape), polyShape(0)
			{
				if(shape->ShapeType == Box2D::Net::ShapeType::e_polygonShape &&
					reinterpret_cast<b2PolygonShape *>(shape->shape))
				{
					polyShape = reinterpret_cast<b2PolygonShape*>(shape->shape);
				}
				else
				{
					throw gcnew System::Exception("Attempting to convert a Shape to a PolyShape,"
												  "but the Shape is not a poly shape.");
				}
			}

			property IList<Vector^>^ Vertices
			{
				IList<Vector^>^ get()
				{
					List<Vector^>^ list = gcnew List<Vector^>();
					for(int x = 0; x < polyShape->m_vertexCount; ++x)
						list->Add(gcnew Vector(polyShape->m_vertices[x]));

					return list;
				}
			}
		};
	}
}


text:
SELECT
  pops.super_population AS super_population,
  super_population_count,
  is_common_variant,
  num_samples_in_pop_with_variant_in_category,
  num_samples_in_pop_with_variant_in_category / super_population_count
  AS percent_samples_in_pop_with_variant_in_category,
  COUNT(1) AS num_variants_shared_by_this_many_samples
FROM
  (
  SELECT
    contig,
    position,
    reference_bases,
    alt,
    vt,
    end,
    super_population,
    IF(af >= 0.05,
      1,
      0) AS is_common_variant,
    SUM(has_variant) AS num_samples_in_pop_with_variant_in_category
  FROM (
    SELECT
      contig,
      position,
      reference_bases,
      GROUP_CONCAT(alternate_bases) WITHIN RECORD AS alt,
      vt,
      end,
      super_population,
      IF(af >= 0.05,
        TRUE,
        FALSE) AS is_common_variant,
      IF(genotype.first_allele > 0
        OR genotype.second_allele > 0,
        1,
        0) AS has_variant
    FROM
      FLATTEN([google.com:biggene:1000genomes.variants1kG],
        genotype) AS samples
    JOIN
      [google.com:biggene:1000genomes.sample_info] p
    ON
      samples.genotype.sample_id = p.sample)
    GROUP EACH BY
    contig,
    position,
    reference_bases,
    alt,
    vt,
    end,
    super_population,
    is_common_variant) AS vars
JOIN (
  SELECT
    super_population,
    COUNT(population) AS super_population_count,
  FROM
    [google.com:biggene:1000genomes.sample_info]
  WHERE
    In_Phase1_Integrated_Variant_Set = TRUE
  GROUP BY
    super_population) AS pops
ON
  vars.super_population = pops.super_population
  GROUP EACH BY
  super_population,
  super_population_count,
  is_common_variant,
  num_samples_in_pop_with_variant_in_category,
  percent_samples_in_pop_with_variant_in_category
ORDER BY
  num_samples_in_pop_with_variant_in_category;


text:
<!doctype html>

		<title>circlepacker</title>

continuous drawing

the circle positions are continuously updated. you can use the buttons below to update the circles and restart the animation. you can also drag circles around.

back to index

		<button id="add-circle">add circle</button>
		<button id="delete-circle">delete circle</button>
		<button id="random-size">random size</button>
		<button id="pin-random">toggle pin</button>

			damping
			<input id="damping" type="range" min="0" max="0.05" step="0.001" value="0.025" />
			0.025


text:
package net.exodiusmc.blasteroids.layers;

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import net.exodiusmc.blasteroids.Layer;
import net.exodiusmc.blasteroids.Main;
import net.exodiusmc.blasteroids.enums.LayerEffectType;
import net.exodiusmc.blasteroids.layers.effects.FadeIn;
import net.exodiusmc.blasteroids.layers.effects.SlideFromBottom;
import net.exodiusmc.blasteroids.layers.effects.SlideToBottom;
import net.exodiusmc.blasteroids.layers.effects.SlideToTop;
import net.exodiusmc.blasteroids.manager.LayerManager;
import net.exodiusmc.blasteroids.manager.MediaManager;
import net.exodiusmc.blasteroids.utils.GeneralUtils;

public class SplashLayer extends Layer {

	public SplashLayer() {
		this.setRendering(false);
	}

	@Override
	public boolean updateOnCover() {
		return false;
	}

	@Override
	public void update(double delta, long frame) {
		if(frame == 70) {
			FadeIn fit = (FadeIn) this.applyEffect(LayerEffectType.FADE_IN);
			fit.setFadeAmount(0.008);

			this.setRendering(true);
		} else if(frame == 230) {
			this.applyEffect(LayerEffectType.FADE_OUT).setOnCompleted(() -> {
				LayerManager.getManager().pop();	// Remove this layer from the stack

				GeneralUtils.setTimeout(450L, () -> {
					MenuLayer menu = new MenuLayer();

					((FadeIn) menu.applyEffect(LayerEffectType.FADE_IN)).setFadeAmount(0.02);
					LayerManager.getManager().add(menu);
				});
			});
		}
	}

	@Override
	public void render(GraphicsContext gfx) {
		Image splash = MediaManager.getManager().getImage("splash");
		double ratio = splash.getHeight() / splash.getWidth();
		double width = Main.WIDTH * 0.8, height = width * ratio;

		gfx.drawImage(splash, Main.WIDTH * 0.1, Main.HEIGHT - (Main.HEIGHT - (Main.HEIGHT - height) / 2), width, height);
	}

	@Override
	public void dispose() {

	}

}


text:
package org.apache.accumulo.server.conf.codec;

import static java.util.Objects.requireNonNull;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.checkerframework.checker.nullness.qual.NonNull;

/**
 * Version properties maintain a {@code Map<String,String>}; of property k,v pairs along with
 * versioning information metadata.
 *

 * The metadata used to verify cached values match stored values. Storing the metadata with the
 * properties allows for comparison of properties and can be used to ensure that values being
 * written to the backend store have not changed. This metadata should be written / appear early in
 * the encoded bytes and be uncompressed so that decisions can be made that may make deserialization
 * unnecessary.
 *

 * Note: Avoid using -1 because that has significance in ZooKeeper - writing a ZooKeeper node with a
 * version of -1 disables the ZooKeeper expected version checking and just overwrites the node.
 *

 * Instances of this class are immutable.
 */
public class VersionedProperties {

  public static final DateTimeFormatter TIMESTAMP_FORMATTER =
      DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC));
  // flag value for initialization - on store both the version and next version should be 0.
  private static final int INIT_VERSION = 0;
  private final int dataVersion;
  private final Instant timestamp;
  private final Map<String,String> props;

  /**
   * Instantiate an initial instance with default version info and empty map.
   */
  public VersionedProperties() {
    this(Map.of());
  }

  /**
   * Instantiate an initial instance with default version info and provided property map.
   *
   * @param props
   *          optional map of initial property key, value pairs. The properties are assumed to have
   *          been previously validated (if required)
   */
  public VersionedProperties(Map<String,String> props) {
    this(INIT_VERSION, Instant.now(), props);
  }

  /**
   * Instantiate an instance and set the initial properties to the provided values.
   *
   * @param dataVersion
   *          version info with data version and timestamp.
   * @param timestamp
   *          timestamp of this version.
   * @param props
   *          optional map of initial property key, value pairs. The properties are assumed to have
   *          been previously validated (if required)
   */
  public VersionedProperties(final int dataVersion, final Instant timestamp,
      final Map<String,String> props) {
    this.dataVersion = dataVersion;
    this.timestamp = requireNonNull(timestamp, "A timestamp must be supplied");
    this.props = props == null ? Map.of() : Map.copyOf(props);
  }

  /**
   * Get an unmodifiable map with all property key,value pairs.
   *
   * @return An unmodifiable view of the property key, value pairs.
   */
  public @NonNull Map<String,String> asMap() {
    return props;
  }

  /**
   * Get the current data version. The version should match the node version of the stored data. The
   * value should be used on data writes as the expected version. If the data write fails do to an
   * unexpected version, it signals that the node version has changed since the instance was
   * instantiated and encoded.
   *
   * @return 0 for initial version, otherwise the data version when the properties were serialized.
   */
  public int getDataVersion() {
    return dataVersion;
  }

  /**
   * The timestamp of the instance when created or last modified.
   *
   * @return the timestamp of the instance.
   */
  public Instant getTimestamp() {
    return timestamp;
  }

  /**
   * The timestamp formatted as an ISO 8601 string with format of
   * {@code YYYY-MM-DDTHH:mm:ss.SSSSSSZ}
   *
   * @return a formatted timestamp string.
   */
  public String getTimestampISO() {
    return TIMESTAMP_FORMATTER.format(timestamp);
  }

  /**
   * Update a single property. If a property already exists it is overwritten.
   *

   * It is much more efficient to add multiple properties at a time rather than one by one.
   *

   * Because instances of this class are immutable, this method creates a new copy of the
   * properties. Other processes will continue to see original values retrieved from the data store.
   * Other processes will receive an update when the instance is encoded and stored in the data
   * store and then retrieved with the normal store update mechanisms.
   *
   * @param key
   *          the property name.
   * @param value
   *          the property value.
   * @return A new instance of this class with the property added or updated.
   */
  public VersionedProperties addOrUpdate(final String key, final String value) {
    var updated = new HashMap<>(props);
    updated.put(key, value);
    return new VersionedProperties(dataVersion, Instant.now(), updated);
  }

  /**
   * Add or update multiple properties. If a property already exists it is overwritten.
   *

   * Because instances of this class are immutable, this method creates a new copy of the
   * properties. Other processes will continue to see original values retrieved from the data store.
   * Other processes will receive an update when the instance is encoded and stored in the data
   * store and then retrieved with the normal store update mechanisms.
   *
   * @param updates
   *          A map of key, values pairs.
   * @return A new instance of this class with the properties added or updated.
   */
  public VersionedProperties addOrUpdate(final Map<String,String> updates) {
    var updated = new HashMap<>(props);
    updated.putAll(updates);
    return new VersionedProperties(dataVersion, Instant.now(), updated);
  }

  /**
   * Delete multiple properties provided as a collection of keys.
   *

   * Because instances of this class are immutable, this method creates a new copy of the
   * properties. Other processes will continue to see original values retrieved from the data store.
   * Other processes will receive an update when the instance is encoded and stored in the data
   * store and then retrieved with the normal store update mechanisms.
   *
   * @param keys
   *          a collection of the keys that if they exist, will be removed.
   * @return A new instance of this class.
   */
  public VersionedProperties remove(Collection<String> keys) {
    var updated = new HashMap<>(props);
    updated.keySet().removeAll(keys);
    return new VersionedProperties(dataVersion, Instant.now(), updated);
  }

  /**
   * Generate a formatted string for debugging, either as a single line or human-friendly,
   * multi-line format.
   *
   * @param prettyPrint
   *          if true, generate human-friendly string
   * @return a formatted string
   */
  public String print(boolean prettyPrint) {
    StringBuilder sb = new StringBuilder();

    sb.append("dataVersion=").append(dataVersion).append(prettyPrint ? "\n" : ", ");

    sb.append("timeStamp=").append(TIMESTAMP_FORMATTER.format(timestamp))
        .append(prettyPrint ? "\n" : ", ");

    Map<String,String> sorted = new TreeMap<>(props);
    sorted.forEach((k, v) -> {
      if (prettyPrint) {
        // indent if pretty
        sb.append("  ");
      }
      sb.append(k).append("=").append(v);
      sb.append(prettyPrint ? "\n" : ", ");
    });
    return sb.toString();
  }

  @Override
  public String toString() {
    return print(false);
  }
}


text:
module PaymentRunsHelper
end


text:
module EnvironmentFlag
  module ViewHelpers
    def render_environment_flag( message = nil )
      default_message = "Your are currently viewing the #{Rails.env} environment".upcase
      content_tag( "div", message || default_message, :class => "env_notice" ) unless Rails.env.production?
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Cortex\Auth\Models;

use Rinvex\Tenants\Traits\Tenantable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Cortex\Auth\Notifications\PhoneVerificationNotification;
use Cortex\Auth\Notifications\ManagerPasswordResetNotification;
use Cortex\Auth\Notifications\ManagerEmailVerificationNotification;

class Manager extends User
{
    use Tenantable;

    /**
     * {@inheritdoc}
     */
    protected $fillable = [
        'username',
        'password',
        'two_factor',
        'email',
        'email_verified_at',
        'phone',
        'phone_verified_at',
        'given_name',
        'family_name',
        'title',
        'organization',
        'country_code',
        'language_code',
        'birthday',
        'gender',
        'social',
        'is_active',
        'last_activity',
        'abilities',
        'roles',
        'tags',
        'tenants',
    ];

    /**
     * {@inheritdoc}
     */
    protected $passwordResetNotificationClass = ManagerPasswordResetNotification::class;

    /**
     * {@inheritdoc}
     */
    protected $emailVerificationNotificationClass = ManagerEmailVerificationNotification::class;

    /**
     * {@inheritdoc}
     */
    protected $phoneVerificationNotificationClass = PhoneVerificationNotification::class;

    /**
     * Create a new Eloquent model instance.
     *
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        $this->setTable(config('cortex.auth.tables.managers'));
        $this->setRules([
            'username' => 'required|alpha_dash|min:3|max:150|unique:'.config('cortex.auth.tables.managers').',username',
            'password' => 'sometimes|required|min:'.config('cortex.auth.password_min_chars'),
            'two_factor' => 'nullable|array',
            'email' => 'required|email|min:3|max:150|unique:'.config('cortex.auth.tables.managers').',email',
            'email_verified_at' => 'nullable|date',
            'phone' => 'nullable|phone:AUTO',
            'phone_verified_at' => 'nullable|date',
            'given_name' => 'required|string|max:150',
            'family_name' => 'nullable|string|max:150',
            'title' => 'nullable|string|max:150',
            'organization' => 'nullable|string|max:150',
            'country_code' => 'nullable|alpha|size:2|country',
            'language_code' => 'nullable|alpha|size:2|language',
            'birthday' => 'nullable|date_format:Y-m-d',
            'gender' => 'nullable|in:male,female',
            'social' => 'nullable',
            'is_active' => 'sometimes|boolean',
            'last_activity' => 'nullable|date',
            'tags' => 'nullable|array',
            'tenants' => 'nullable|array',
        ]);
    }

    /**
     * Attach the given tenants to the model.
     *
     * @param mixed $tenants
     *
     * @return void
     */
    public function setTenantsAttribute($tenants): void
    {
        static::saved(function (self $model) use ($tenants) {
            $tenants = collect($tenants)->filter();

            $model->tenants->pluck('id')->similar($tenants)
            || activity()
                ->performedOn($model)
                ->withProperties(['attributes' => ['tenants' => $tenants], 'old' => ['tenants' => $model->tenants->pluck('id')->toArray()]])
                ->log('updated');

            $model->syncTenants($tenants);
        });
    }

    /**
     * Get all attached tenants to the manager.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function tenants(): MorphToMany
    {
        return $this->morphToMany(config('rinvex.tenants.models.tenant'), 'tenantable', config('rinvex.tenants.tables.tenantables'), 'tenantable_id', 'tenant_id')
                    ->withTimestamps();
    }

    /**
     * Determine if this is supermanager of the given tenant.
     *
     * @param \Illuminate\Database\Eloquent\Model $tenant
     *
     * @return bool
     */
    public function isSupermanager(Model $tenant): bool
    {
        return $this->isManager($tenant) && $this->isA('supermanager');
    }

    /**
     * Determine if this is manager of the given tenant.
     *
     * @param \Illuminate\Database\Eloquent\Model $tenant
     *
     * @return bool
     */
    public function isManager(Model $tenant): bool
    {
        return $this->tenants->contains($tenant);
    }

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'username';
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">

<title>SmithWatermanGotohWindowedAffine</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <meta name="generator" content="Doc-O-Matic">
    <link rel="STYLESHEET" href="default.css" type="text/css">

<xml>
    <MSHelp:Attr Name="Locale" Value="kbEnglish"/>
    <MSHelp:Attr Name="TopicType" Value="kbSyntax"/>
</xml>

SimMetrics library v 1.5 for .NET 2.0

Contents | Index | Reference

Up | Previous

SmithWatermanGotohWindowedAffine

SimMetricsMetricUtilities | Members | Methods | Properties | Class Hierarchy

implements the smith waterman with gotoh extension using a windowed affine gap.

Class Hierarchy

AbstractStringMetric
    SmithWatermanGotohWindowedAffine
        SimMetricsMetricUtilities.SmithWatermanGotoh

[Serializable]
public class SmithWatermanGotohWindowedAffine : AbstractStringMetric;

File

SmithWatermanGotohWindowedAffine.cs

Namespace

SimMetricsMetricUtilities

Members

Properties

Property
Description

 DCostFunction
get the d(i,j) cost function.

 GGapFunction
get the g gap cost function.

 LongDescriptionString
returns the long string identifier for the metric.

 ShortDescriptionString
returns the string identifier for the metric.

Methods

Method
Description

 GetSimilarity
gets the similarity of the two strings using Smith-Waterman-Gotoh distance.

 GetSimilarityExplained
gets a div class xhtml similarity explaining the operation of the metric.

 GetSimilarityTimingEstimated
gets the estimated time in milliseconds it takes to perform a similarity timing.

 GetUnnormalisedSimilarity
gets the un-normalised similarity measure of the metric for the given strings.

 SmithWatermanGotohWindowedAffine
constructor - default (empty).

 SmithWatermanGotohWindowedAffine
constructor

 SmithWatermanGotohWindowedAffine
constructor

 SmithWatermanGotohWindowedAffine
constructor

 SmithWatermanGotohWindowedAffine
constructor

 SmithWatermanGotohWindowedAffine
constructor

 SmithWatermanGotohWindowedAffine
constructor

 SmithWatermanGotohWindowedAffine
constructor

Legend

Property

Method

Links

SimMetricsMetricUtilities, Members, Methods, Properties, Class Hierarchy

Copyright (c) 2006. All rights reserved.

Contents | Index | Reference