text:
import sys
from libsbml import *
import re
from shutil import copyfile

# A function that makes changes to the reactions
##(gets called by SBML_reactionchange)
##Arguments:
##orig_str - is the original reaction
##orig_param - is the original parameter
##replacement - is the replacement for orig_param
def stringSearch(orig_str,orig_param,replacement):

	#Regular expressions for NOT alphanumerics and NOTspaces
	not_an = re.compile(r"[^A-Za-z0-9]")
	not_space = re.compile(r"[-\s]")

	#Builds up the replacement string as strings are immutable in Python
	replaced_string = ""

	#While loop travels along the length of orig_str
	i = 0
	while i < len(orig_str):
		#Whilst going along the length of the original string if a match is found for replacement then made here
		if orig_str[i:i+len(orig_param)] == orig_param and (not_an.search(orig_str[i+len(orig_param):i+len(orig_param)+1]) or not_space.search(orig_str[i+len(orig_param):i+len(orig_param)+1]) or len(orig_str[i+len(orig_param):i+len(orig_param)+1]) == 0 or len(orig_str[i+len(orig_param):i+len(orig_param)+1]) == 0) and (not_an.search(orig_str[i-1:i]) or not_space.search(orig_str[i-1:i]) or len(orig_str[i-1:i]) == 0 or len(orig_str[i-1:i]) == 0):
			#Adds replacement to the new reaction string
			replaced_string+=replacement
			#Shifts the pointer further up the original string
			i+=len(orig_param)
		#If no replacement made then go here
		else:
			#Adds the current character to the new reaction string
			replaced_string+=orig_str[i]
			#Shifts the pointer to the adjacent character
			i+=1

	#Returns the new replaced string
	return replaced_string

# A function that creates the new SBML files based on the original
##(gets called by sorting_files)
##Arguments:
##input_files - original SBML file
##inpath - where the SBML file is in the directory
##param_changes - contains the input file containing the experimental changes
def SBML_reactionchanges(input_file, inpath="", fname="", param_changes=""):

	#Reads in param_changes, loads in data
	change_params=open(inpath+"/"+param_changes,'r')
	data = change_params.read()
	change_params.close()

	#Finds where the changes have been made in data
	start_index = re.compile(r'>Parameter - Experiment (\d+)\s*\n(.+?)\n<Parameter - Experiment (\d+)', re.DOTALL)
	#lines contains a list of tuples containing the changes for each experiment
	lines = start_index.findall(data)
	#exp_list contains the number associated to each experiment at beginning
	exp_list = [int(lines[i][0]) for i in range(0,len(lines))]
	##exp_list_end contains the number associated to each experiment at end
	exp_list_end = [int(lines[i][2]) for i in range(0,len(lines))]
	#Unpacks the original lines to only hold the changes for each experiment
	lines = [lines[i][1] for i in range(0,len(lines))]

	#Checking if parameters in the input file are properly defined
	if exp_list_end != exp_list or sum(exp_list)!=len(exp_list)*(len(exp_list)+1)/2:
		print ""
		print "Parameters not defined properly in input file"
		print "Need to be defined sequentially e.g."
		print ">Parameter - Experiment 1"
		print "..."
		print "<Parameter - Experiment 1"
		print ""
		print ">Parameter - Experiment 2"
		print "..."
		print "<Parameter - Experiment 2"
		print ""
		print ">Parameter - Experiment 3"
		print "..."
		print "<Parameter - Experiment 3"
		print ""
		print "Also if you plan to run an unchanged version of SBML file this must be Experiment 1 as:"
		print ">Parameter - Experiment 1"
		print "Unchanged"
		print "<Parameter - Experiment 1\n"
		sys.exit()

	start_point = 0
	#Unchanged SBML has to the be the first experiment if this is the case
	#Just copies the SBML file into the output folder where SBML files are stored
	if lines[0]=='Unchanged':
		copyfile(inpath+"/"+input_file,fname + "/Exp_1.xml")
		start_point = 1

	#For loop iterates over each experiments
	for i, start in enumerate(lines[start_point:]):
		#splits each line into its components and then puts them into lists
		line = start.split("\n")
		param_to_change=[] #holds which parameters to change
		mult_fact=[] #holds by what factor to change that parameter
		param_reaction=[] #holds which reaction the change needs to be made to
		#For loop fills the lists defined above
		for end in line:
			el_temp=end.split()
			param_to_change.append(el_temp[0])
			mult_fact.append(el_temp[1])
			param_reaction.append(int(el_temp[2]))
		#Function makes the appropriate changes to the reactions in the SBML files
		SBML_reactionchange(input_file, param_to_change,mult_fact,param_reaction,exp_list[i+start_point], dest=fname, inpath = inpath)

	#returns the number of experiments
	return len(lines)

# A function that changes the reactions to the original SBML file
##(gets called by SBML_reactionchanges)
##Arguments:
##input_files - original SBML file
##param_to_change - list of parameters to change
##mult_fact - list containing the factor by which to change the parameter
##param_reaction - list of which reactions that need changing for the associated parameter
##nu - the number given to the experiment
##dest - output path
##inpath - input path
def SBML_reactionchange(input_file, param_to_change, mult_fact, param_reaction, nu, dest="", inpath=""):
	#Reads in original SBML file
	reader = SBMLReader()
	SBML_master = reader.readSBML(inpath+"/"+input_file)

	#For loop over the changes that need to be made
	for i, reaction_no in enumerate(param_reaction):
		#Reads in the reaction that needs to be changed
		reaction = formulaToString(SBML_master.getModel().getListOfReactions()[reaction_no-1].getKineticLaw().getMath())
		#temp holds the change that needs to be made
		temp = r"{string1} * {string2}".format(string1=mult_fact[i],string2=param_to_change[i])
		#Calls stringSearch to make the change to the reaction
		temp = stringSearch(reaction,param_to_change[i],temp)
		#Sets the new reaction to the SBML object
		SBML_master.getModel().getListOfReactions()[reaction_no-1].getKineticLaw().setMath(parseFormula(temp))

	#Writes the final new SBML file
	if dest=="":
		#Writes it to the current working directory if dest=""
		writeSBML(SBML_master, "Exp_" + repr(nu) + ".xml")
	else:
		#Writes it to the output destination if provided
		writeSBML(SBML_master, "./" + dest + "/Exp_" + repr(nu) + ".xml")


text:
Full-Stack Developer

Currently looking for a new challenge in San Francisco

I'm looking to find a place with people that share the same values and are passionate about delivering great experiences. I'm ready to move wherever I can find those amazing people to work with, and a great cause, that can stir my passion and an enviroment that will push me to give my best, learn and become better.

Passion

I'm driven by passion, I love waking up every morning and do something that I care for, it brings me in a zone where I can create amazing stuff and it gives me an infinite source of energy. I believe that you should do the things you love, and do it often, this is the only way to do great work and add value.

People

Working with amazing people brings out the best in me. It makes me learn faster and push myself all the time.I feel that a great team it is the most important factor to the success of any product.

Focus

I believe that simplicity is an art, that you can only master when you understand the product. By making sure that you keep things simple, you can get the details that matter right.

redpajama_set_name: RedPajamaGithub


text:
package com.serotonin.bacnet4j.type.error;

import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.type.constructed.BACnetError;
import com.serotonin.bacnet4j.type.primitive.UnsignedInteger;
import org.free.bacnet4j.util.ByteQueue;

public class ChangeListError extends BaseError {
    private static final long serialVersionUID = -466623385798604884L;
    private final UnsignedInteger firstFailedElementNumber;

    public ChangeListError(byte choice, BACnetError error, UnsignedInteger firstFailedElementNumber) {
        super(choice, error);
        this.firstFailedElementNumber = firstFailedElementNumber;
    }

    @Override
    public void write(ByteQueue queue) {
        queue.push(choice);
        write(queue, error, 0);
        write(queue, firstFailedElementNumber, 1);
    }

    ChangeListError(byte choice, ByteQueue queue) throws BACnetException {
        super(choice, queue, 0);
        firstFailedElementNumber = read(queue, UnsignedInteger.class, 1);
    }

    @Override
    public int hashCode() {
        final int PRIME = 31;
        int result = super.hashCode();
        result = PRIME * result + ((firstFailedElementNumber == null) ? 0 : firstFailedElementNumber.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (!super.equals(obj))
            return false;
        if (getClass() != obj.getClass())
            return false;
        final ChangeListError other = (ChangeListError) obj;
        if (firstFailedElementNumber == null) {
            if (other.firstFailedElementNumber != null)
                return false;
        }
        else if (!firstFailedElementNumber.equals(other.firstFailedElementNumber))
            return false;
        return true;
    }
}


text:
* Cleaned up various categories and removed any uncategorized leftovers.
* Split initial big file into separate ones based on type
* Added some rspec tests
* Added version badge in project
* Added sources method

## v1.0.0 - 01/01/2016
* First functional version


text:
require 'spec_helper'

describe Nexop::Message::NewKeys do
  let(:message) { Nexop::Message::NewKeys.new }

  it "has a type" do
    message.type.should == Nexop::Message::NewKeys::SSH_MSG_NEWKEYS
  end
end


text:
using MediaButler.Common.Workflow;
using Microsoft.WindowsAzure.MediaServices.Client;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MediaButler.BaseProcess
{
    /// <summary>
    /// Create AMS Streaming locaator step.
    /// </summary>
    class CreateStreamingLocatorStep : StepHandler
    {
        private ButlerProcessRequest myRequest;
        private CloudMediaContext _MediaServiceContext;

        /// <summary>
        /// Create Streminf locatior for Asset
        /// </summary>
        /// <param name="outputAssetid">AMS asset ID</param>
        /// <returns></returns>
        private ILocator CreateStreamingLocator(string outputAssetid)
        {
            IAssetFile assetFile = null;
            ILocator locator = null;

            var daysForWhichStreamingUrlIsActive = 365;
            var outputAsset = _MediaServiceContext.Assets.Where(a => a.Id == outputAssetid).FirstOrDefault();

            var accessPolicy = _MediaServiceContext.AccessPolicies.Create(
                outputAsset.Name
                , TimeSpan.FromDays(daysForWhichStreamingUrlIsActive)
                , AccessPermissions.Read);
            var assetFiles = outputAsset.AssetFiles.ToList();

            assetFile = assetFiles.Where(f => f.Name.ToLower().EndsWith(".ism")).FirstOrDefault();
            locator = _MediaServiceContext.Locators.CreateLocator(LocatorType.OnDemandOrigin, outputAsset, accessPolicy, DateTime.UtcNow.AddMinutes(-5));
            //Add Smooth URL to Metadata
            if (!myRequest.MetaData.ContainsKey("smoothurl"))
            {
                myRequest.MetaData.Add("smoothurl", locator.Path + assetFile.Name + "/manifest");
            }
            return locator;
        }

        /// <summary>
        /// Step execution to create AMS locator for current asset
        /// </summary>
        /// <param name="request"></param>
        public override void HandleExecute(ChainRequest request)
        {
            myRequest = (ButlerProcessRequest)request;
            _MediaServiceContext = new CloudMediaContext(myRequest.MediaAccountName, myRequest.MediaAccountKey);

            var locator = CreateStreamingLocator(myRequest.AssetId);
        }

        /// <summary>
        /// Compesantion step, no action only trace
        /// </summary>
        /// <param name="request"></param>
        public override void HandleCompensation(ChainRequest request)
        {
            Trace.TraceWarning("{0} in process {1} processId {2} has not HandleCompensation", this.GetType().FullName, myRequest.ProcessTypeId, myRequest.ProcessInstanceId);
        }
    }
}


text:
Monkey-patch (hook) functions for debugging and stuff.

## Getting Started

This code should work just fine in Node.js:

First, install the module with: `npm install hooker`

```javascript
var hooker = require('hooker');
hooker.hook(Math, "max", function() {
  console.log(arguments.length + " arguments passed");
});
Math.max(5, 6, 7) // logs: "3 arguments passed", returns 7
```

Or in the browser:

```html
<script src="dist/ba-hooker.min.js"></script>
<script>
hook(Math, "max", function() {
  console.log(arguments.length + " arguments passed");
});
Math.max(5, 6, 7) // logs: "3 arguments passed", returns 7
</script>
```

In the browser, you can attach Hooker's methods to any object.

```html
<script>
this.exports = Bocoup.utils;
</script>
<script src="dist/ba-hooker.min.js"></script>
<script>
Bocoup.utils.hook(Math, "max", function() {
  console.log(arguments.length + " arguments passed");
});
Math.max(5, 6, 7) // logs: "3 arguments passed", returns 7
</script>
```

## Documentation

### hooker.hook
Monkey-patch (hook) one or more methods of an object.
#### Signature:
`hooker.hook(object, [ props, ] [options | prehookFunction])`
#### `props`
The optional `props` argument can be a method name, array of method names or null. If null (or omitted), all enumerable methods of `object` will be hooked.
#### `options`
* `pre` - (Function) a pre-hook function to be executed before the original function. Arguments passed into the method will be passed into the pre-hook function as well.
* `post` - (Function) a post-hook function to be executed after the original function. The original function's result is passed into the post-hook function as its first argument, followed by the method arguments.
* `once` - (Boolean) if true, auto-unhook the function after the first execution.
* `passName` - (Boolean) if true, pass the name of the method into the pre-hook function as its first arg (preceding all other arguments), and into the post-hook function as the second arg (after result but preceding all other arguments).

#### Returns:
An array of hooked method names.

### hooker.unhook
Un-monkey-patch (unhook) one or more methods of an object.
#### Signature:
`hooker.unhook(object [, props ])`
#### `props`
The optional `props` argument can be a method name, array of method names or null. If null (or omitted), all methods of `object` will be unhooked.
#### Returns:
An array of unhooked method names.

### hooker.orig
Get a reference to the original method from a hooked function.
#### Signature:
`hooker.orig(object, props)`

### hooker.override
When a pre- or post-hook returns the result of this function, the value
passed will be used in place of the original function's return value. Any
post-hook override value will take precedence over a pre-hook override value.
#### Signature:
`hooker.override(value)`

### hooker.preempt
When a pre-hook returns the result of this function, the value passed will
be used in place of the original function's return value, and the original
function will NOT be executed.
#### Signature:
`hooker.preempt(value)`

### hooker.filter
When a pre-hook returns the result of this function, the context and
arguments passed will be applied into the original function.
#### Signature:
`hooker.filter(context, arguments)`

## Examples
See the unit tests for more examples.

```javascript
var hooker = require('hooker');
// Simple logging.
hooker.hook(Math, "max", function() {
  console.log(arguments.length + " arguments passed");
});
Math.max(5, 6, 7) // logs: "3 arguments passed", returns 7

hooker.unhook(Math, "max"); // (This is assumed between all further examples)
Math.max(5, 6, 7) // 7

// Returning hooker.override(value) overrides the original value.
hooker.hook(Math, "max", function() {
  if (arguments.length === 0) {
    return hooker.override(9000);
  }
});
Math.max(5, 6, 7) // 7
Math.max() // 9000

// Auto-unhook after one execution.
hooker.hook(Math, "max", {
  once: true,
  pre: function() {
    console.log("Init something here");
  }
});
Math.max(5, 6, 7) // logs: "Init something here", returns 7
Math.max(5, 6, 7) // 7

// Filter `this` and arguments through a pre-hook function.
hooker.hook(Math, "max", {
  pre: function() {
    var args = [].map.call(arguments, function(num) {
      return num * 2;
    });
    return hooker.filter(this, args); // thisValue, arguments
  }
});
Math.max(5, 6, 7) // 14

// Modify the original function's result with a post-hook function.
hooker.hook(Math, "max", {
  post: function(result) {
    return hooker.override(result * 100);
  }
});
Math.max(5, 6, 7) // 700

// Hook every Math method. Note: if Math's methods were enumerable, the second
// argument could be omitted. Since they aren't, an array of properties to hook
// must be explicitly passed. Non-method properties will be skipped.
// See a more generic example here: http://bit.ly/vvJlrS
hooker.hook(Math, Object.getOwnPropertyNames(Math), {
  passName: true,
  pre: function(name) {
    console.log("=> Math." + name, [].slice.call(arguments, 1));
  },
  post: function(result, name) {
    console.log("<= Math." + name, result);
  }
});

var result = Math.max(5, 6, 7);
// => Math.max [ 5, 6, 7 ]
// <= Math.max 7
result // 7

result = Math.ceil(3.456);
// => Math.ceil [ 3.456 ]
// <= Math.ceil 4
result // 4
```

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt).

_Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!_

## Release History
2012/01/09 - v0.2.3 - First official release.

## License
Copyright (c) 2012 "Cowboy" Ben Alman
Licensed under the MIT license.
<http://benalman.com/about/license/>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CommandInterface
{
    public class ConfigLoader
    {
        public ConfigLoader()
        {

        }

        public ConfigType Load<ConfigType>(string configText) where ConfigType: class, new()
        {
            var assembly = Utility.CSharpAssembly.Compile(configText);

            foreach (var type in assembly.DefinedTypes)
            {
                if(type.AsType() == typeof(ConfigType) || type.IsSubclassOf(typeof(ConfigType)))
                {
                    var constructor = type.GetConstructor(new Type[] { });

                    return constructor.Invoke(new object[] { }) as ConfigType;
                }
            }

            return default(ConfigType);
        }

        public ConfigType Load<ConfigType>(FileInfo configFile)
        {
            return default(ConfigType);
        }
    }
}


text:
namespace yg {
class SimulateServiceImpl final : public Simulate::Service {
  grpc::Status Simulate(grpc::ServerContext *context,
                        const SimulateRequest *request,
                        SimulateResponse *response) override;
};
}  // namespace yg


text:
title: "My plans for today"
date: 2012-08-20T09:25:48+05:45
author: "Steve Maraboli"
redirect_from:
  - "/2012/09/my-plans-for-today.html"
  - "/2012/08/my-plans-for-today/"
---

I woke up early today, excited over all I get to do before the clock strikes midnight.

I have responsibilities to fulfil today.

I am important.

My job is to choose what kind of day I am going to have.

Today I can complain because the weather is rainy or I can be thankful that the grass is getting watered for free.

Today I can feel sad that I don't have more money or I can be glad that my finances encourage me to plan my purchases wisely and guide me away from waste.

Today I can grumble about my health or I can rejoice that I am alive.

Today I can lament over all that my parents didn't give me when I was growing up or I can feel grateful that they allowed me to born.

Today I can cry because roses have thorns or I can celebrate that thorns have roses.

Today I can mourn my lack of friends or I can excitedly embark upon a quest to discover new relationships.

Today I can whine because I have to go work or I can shout for joy because I have a job to do.

I can complain because I have to go to school or eagerly open my mind and fill it with rich new tidbits of knowledge.

Today I can murmur dejectedly because I have to do housework or I can feel honoured because the lord had provided shelter for my mind, body and soul.

Today stretches ahead of me, waiting to be shaped.

And here I am, the sculptor who gets to do the shaping.

What today will be like is up to me.

I get to choose what kind of day I will have!

---

*Written by Steve Maraboli*


text:
package com.m1.mimeui.renderer.contentviewer.htmlsanitizer.transformations;

import org.jsoup.nodes.Element;

public interface Transformation
{
    public String getSelector ();
    public void transform (final Element element);
}


text:
Run all Open-Falcon components in docker engine.

## Config
You need to configure threeo file _conf/fe.json_ , _conf/portal.py_ and _conf/alarm.json_.

In _conf/fe.json_, replace **192.168.1.100** with your host IP in line 31, 32 and 33.

In _conf/portal.py_, replace **192.168.1.100** with your host IP in line 19 and 20. If you have more than two network interface, you can replace with internal IP in line 19, and external IP in line 20.

In _conf/alarm.json_, replace **192.168.1.100** with your host IP in line 30, 31 and 32.
## Run

Initialize databases.
```
$sudo docker-compose -f init.yml up -d
```

After 10 seconds, run all Open-Falcon components.
```
$sudo docker-compose -f docker-compose.yml up -d
```


text:
module.exports = function (context) {
	var libxslt = require("libxslt");
	var path = context.requireCordovaModule("path");
	var et = context.requireCordovaModule("elementtree");
	var fs = context.requireCordovaModule("fs");

	function processConfigFileXsl(platform, xslConfigElement) {
		var target = xslConfigElement.attrib && xslConfigElement.attrib.target;
		if (!target) return;

		var xslStylesheetElement = xslConfigElement._children[0];
		if (!xslStylesheetElement) return;

		var xslString = et.tostring(xslStylesheetElement);
		var xmlFilename = path.join(context.opts.projectRoot, "platforms", platform, target);

		libxslt.parse(xslString, function (err, stylesheet) {
			if (err) return console.error(err);
			var documentString = fs.readFileSync(xmlFilename).toString();
			stylesheet.apply(documentString, [], function (err, result) {
				if (err) return console.error(err);
				if (result) fs.writeFileSync(xmlFilename, result, "utf-8");
			});
		});
	}

	context.opts.cordova.plugins.forEach(function (plugin) {
		var pluginFilename = path.join(context.opts.projectRoot, "plugins", plugin, "plugin.xml");
		if (fs.existsSync(pluginFilename)) {
			var data = fs.readFileSync(pluginFilename).toString();
			var etree = et.parse(data);

			etree.findall("./plugin/config-file-xsl").forEach(function (xslConfigElement) {
				processConfigFileXsl("common", xslConfigElement);
			});

			etree.findall(".//platform").forEach(function (pTree) {
				pTree.findall("./config-file-xsl").forEach(function (xslConfigElement) {
					processConfigFileXsl(pTree.attrib.name, xslConfigElement);
				});
			});
		}
	});
};


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Navigation;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Implementation.GoToDefinition
{
    internal abstract class AbstractGoToDefinitionService : IGoToDefinitionService
    {
        private readonly IEnumerable<Lazy<INavigableItemsPresenter>> _presenters;
        private readonly IEnumerable<Lazy<INavigableDefinitionProvider>> _externalDefinitionProviders;

        protected abstract ISymbol FindRelatedExplicitlyDeclaredSymbol(ISymbol symbol, Compilation compilation);

        protected AbstractGoToDefinitionService(IEnumerable<Lazy<INavigableItemsPresenter>> presenters, IEnumerable<Lazy<INavigableDefinitionProvider>> externalDefinitionProviders)
        {
            _presenters = presenters;
            _externalDefinitionProviders = externalDefinitionProviders;
        }

        private async Task<ISymbol> FindSymbolAsync(Document document, int position, CancellationToken cancellationToken)
        {
            if (!document.SupportsSemanticModel)
            {
                return null;
            }

            var workspace = document.Project.Solution.Workspace;

            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            var symbol = await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace, bindLiteralsToUnderlyingType: true, cancellationToken: cancellationToken).ConfigureAwait(false);

            return FindRelatedExplicitlyDeclaredSymbol(symbol, semanticModel.Compilation);
        }

        public async Task<IEnumerable<INavigableItem>> FindDefinitionsAsync(Document document, int position, CancellationToken cancellationToken)
        {
            var symbol = await FindSymbolAsync(document, position, cancellationToken).ConfigureAwait(false);

            // Try to compute source definitions from symbol.
            var items = symbol != null ? NavigableItemFactory.GetItemsFromPreferredSourceLocations(document.Project.Solution, symbol) : null;
            if (items == null || items.IsEmpty())
            {
                // Fallback to asking the navigation definition providers for navigable definition locations.
                items = await GoToDefinitionHelpers.FindExternalDefinitionsAsync(document, position, _externalDefinitionProviders, cancellationToken).ConfigureAwait(false);
            }

            // realize the list here so that the consumer await'ing the result doesn't lazily cause
            // them to be created on an inappropriate thread.
            return items?.ToList();
        }

        public bool TryGoToDefinition(Document document, int position, CancellationToken cancellationToken)
        {
            // First try to compute the referenced symbol and attempt to go to definition for the symbol.
            var symbol = FindSymbolAsync(document, position, cancellationToken).WaitAndGetResult(cancellationToken);
            if (symbol != null)
            {
                var isThirdPartyNavigationAllowed = IsThirdPartyNavigationAllowed(symbol, position, document, cancellationToken);

                return GoToDefinitionHelpers.TryGoToDefinition(symbol,
                    document.Project,
                    _externalDefinitionProviders,
                    _presenters,
                    thirdPartyNavigationAllowed: isThirdPartyNavigationAllowed,
                    throwOnHiddenDefinition: true,
                    cancellationToken: cancellationToken);
            }

            // Otherwise, fallback to the external navigation definition providers.
            return GoToDefinitionHelpers.TryExternalGoToDefinition(document, position, _externalDefinitionProviders, _presenters, cancellationToken);
        }

        private static bool IsThirdPartyNavigationAllowed(ISymbol symbolToNavigateTo, int caretPosition, Document document, CancellationToken cancellationToken)
        {
            var syntaxRoot = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>();
            var containingTypeDeclaration = syntaxFactsService.GetContainingTypeDeclaration(syntaxRoot, caretPosition);

            if (containingTypeDeclaration != null)
            {
                var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken);
                var containingTypeSymbol = semanticModel.GetDeclaredSymbol(containingTypeDeclaration, cancellationToken) as ITypeSymbol;

                // Allow third parties to navigate to all symbols except types/constructors
                // if we are navigating from the corresponding type.

                if (containingTypeSymbol != null &&
                    (symbolToNavigateTo is ITypeSymbol || symbolToNavigateTo.IsConstructor()))
                {
                    var candidateTypeSymbol = symbolToNavigateTo is ITypeSymbol
                        ? symbolToNavigateTo
                        : symbolToNavigateTo.ContainingType;

                    if (containingTypeSymbol == candidateTypeSymbol)
                    {
                        // We are navigating from the same type, so don't allow third parties to perform the navigation.
                        // This ensures that if we navigate to a class from within that class, we'll stay in the same file
                        // rather than navigate to, say, XAML.
                        return false;
                    }
                }
            }

            return true;
        }
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "inmueble".
 *
 * @property integer $id
 * @property integer $id_barrio
 * @property integer $id_usuario
 * @property integer $id_propietario
 * @property string $nombre
 * @property double $valor
 * @property string $estado
 * @property string $direccion
 * @property string $titulo
 * @property string $descripcion
 * @property integer $amueblado
 * @property integer $garage
 * @property integer $jardin
 * @property integer $parrillero
 * @property integer $piso
 * @property string $tipo
 * @property integer $prestamo_bancario
 * @property integer $cantidad_banios
 * @property integer $cantidad_habitaciones
 * @property integer $superficie
 * @property string $coord
 * @property string $operacion
 * @property integer $destacado
 * @property integer $favorito
 * @property integer $activo
 * @property string $fecha_creacion
 *
 * @property Imagen[] $imagens
 * @property Barrio $idBarrio
 * @property Usuario $idUsuario
 * @property Propietario $idPropietario
 */
class Inmueble extends \yii\db\ActiveRecord
{
    const STATUS_INACTIVE = 0;
    const STATUS_ACTIVE = 1;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'inmueble';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_barrio', 'id_usuario', 'id_propietario', 'amueblado', 'garage', 'jardin', 'parrillero', 'piso', 'prestamo_bancario', 'cantidad_banios', 'cantidad_habitaciones', 'superficie', 'destacado', 'favorito', 'activo'], 'integer'],
            [['id_usuario', 'activo','valor','tipo','operacion','descripcion','nombre','titulo','direccion'], 'required'],
            [['valor'], 'number'],
            [['estado', 'descripcion', 'tipo', 'coord', 'operacion'], 'string'],
            [['fecha_creacion'], 'safe'],
            [['nombre', 'titulo'], 'string', 'max' => 100],
            [['direccion'], 'string', 'max' => 500]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'id_barrio' => 'Barrio',
            'id_usuario' => 'Usuario',
            'id_propietario' => 'Propietario',
            'nombre' => 'Nombre',
            'valor' => 'Valor',
            'estado' => 'Estado',
            'direccion' => 'Dirección',
            'titulo' => 'Titulo',
            'descripcion' => 'Descripción',
            'amueblado' => 'Amueblado',
            'garage' => 'Garage',
            'jardin' => 'Jardín',
            'parrillero' => 'Parrillero',
            'piso' => 'Piso',
            'tipo' => 'Tipo',
            'prestamo_bancario' => 'Prestamo Bancario',
            'cantidad_banios' => 'Cantidad Baños',
            'cantidad_habitaciones' => 'Cantidad Habitaciones',
            'superficie' => 'Superficie',
            'coord' => 'Coord',
            'operacion' => 'Operación',
            'destacado' => 'Destacado',
            'favorito' => 'Favorito',
            'activo' => 'Activo',
            'fecha_creacion' => 'Fecha Creación',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getImagens()
    {
        return $this->hasMany(Imagen::className(), ['id_inmueble' => 'id']);
    }

    public function getImagenes()
    {
        $imagenes = Imagen::find()
            ->where(['id_inmueble' => $this->id])
            ->all();

        return $imagenes;
    }
//falta terminar
  /*  public function getDestacada($id)
    {
        return $this->hasMany(Imagen::className(), ['id_inmueble' => 'id']);
    }
*/
    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdBarrio()
    {
        return $this->hasOne(Barrio::className(), ['id' => 'id_barrio']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdUsuario()
    {
        return $this->hasOne(Usuario::className(), ['id' => 'id_usuario']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdPropietario()
    {
        return $this->hasOne(Propietario::className(), ['id' => 'id_propietario']);
    }

    public function getImagendestacada()
    {
        $imagen = Imagen::find()
            ->where(['id_inmueble' => $this->id])
            ->andwhere(['destacada' => 1])
            ->one();

        return $imagen;
    }

    public function getSubString()
    {
        $length = 160;

        //Primero eliminamos las etiquetas html y luego cortamos el string
        $stringDisplay = substr(strip_tags($this->descripcion), 0, $length);

        //Si el texto es mayor que la longitud se agrega puntos suspensivos
        if (strlen(strip_tags($this->descripcion)) > $length)
            $stringDisplay .= ' ...';
        return $stringDisplay;
    }
}


text:
using System;
using Owin;

namespace OAuthClientExt.VKontakte
{
    /// <summary>
    /// Extension methods for using <see cref="VkAuthenticationMiddleware"/>
    /// </summary>
    public static class VkAuthenticationExtensions
    {
        /// <summary>
        /// Authenticate users using Vkontakte
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="options">Middleware configuration options</param>
        /// <returns>The updated <see cref="IAppBuilder"/></returns>
        public static IAppBuilder UseVkontakteAuthentication(this IAppBuilder app, VkAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            app.Use(typeof(VkAuthenticationMiddleware), app, options);
            return app;
        }

        /// <summary>
        /// Authenticate users using Vkontakte
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="appId">The appId assigned by Vkontakte</param>
        /// <param name="appSecret">The appSecret assigned by Vkontakte</param>
        /// <param name="scope">The permissions list. Comma separated. Like "audio,video,photos"</param>
        /// <returns>The updated <see cref="IAppBuilder"/></returns>
        public static IAppBuilder UseVkontakteAuthentication(
            this IAppBuilder app,
            string appId,
            string appSecret,
            string scope)
        {
            return UseVkontakteAuthentication(
                app,
                new VkAuthenticationOptions
                {
                    AppId = appId,
                    AppSecret = appSecret,
                    Scope = scope
                });
        }
    }
}


text:
<?php

/**
 * Static helpers which return paths for the various framework parts.
 *
 * Folders paths returned :
 * - baseDir : site root dir
 * - libDir : the framework root dir
 * - configDir : the config folder under site root dir
 * - resourcesDir : the resources folder under site root dir (can be a symlink to an external folder)
 * - uploadDir : the upload folder under resourcesDir (can be a symlink to an external folder)
 * - imagesDir : the images folder under resourcesDir (can be a symlink to an external folder)
 * - logDir : the logs folder under resourcesDir (can be a symlink to an external folder)
 * - cacheDir : the cache folder under resourcesDir (can be a symlink to an external folder)
 * - langDir : the i18n gettext folder under site root dir | namespaced
 * - skinDir : the site skin data under site root dir | namespaced
 *
 * Files paths returned :
 * - configFile : path to site configuration file under configDir | When not found : N/A
 * - uploadFile : path to an uploaded resource under uploadDir | When not found : return false
 * - logFile : path to a log file under logDir | When not found : N/A
 * - cacheFile : path to a cached file under cacheDir | When not found : input or null
 * - langFile : path to a gettext resource under langDir | When not found : die
 * - skinFile : path to a skin data under skinDir | When not found : return false
 * - scriptFile : path to a script file under skinDir | When not found : return false
 *
 * MVC related paths :
 * - layoutDirs : list of paths to savant3 template layouts | namespaced
 * - modelDirs : list of paths to models | namespaced
 * - viewDirs : list of paths to view files | namespaced
 * - controllerDirs : list of paths to controller folders | namespaced
 *
 * @package smvc
 */
final class Utils_ResourceLocator

{
    const CONFIG_DIR = 'config';
    const CONFIG_FILENAME = 'config.yaml';
    const LAYOUT_DIR = 'layouts';
    const VIEW_DIR = 'views';
    const CONTROLLER_DIR = 'controllers';
    const MODEL_DIR = 'models';

    private static $_defaultConfig = null;
    private static $_namespaces = array();

    public static function setResourcesConfig($default, array $namespaces)
    {
        assert(!is_null($default));
        self::$_defaultConfig = $default;
        self::$_namespaces = $namespaces;
    }

    // ------ Directory ------ //

    public static function baseDir()
    {
        return rtrim(DATA_DIR, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
    }

    public static function libDir()
    {
        return rtrim(LIB_DIR, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
    }

    public static function configDir()
    {
        return self::baseDir().self::CONFIG_DIR.DIRECTORY_SEPARATOR;
    }

    public static function resourcesDir()
    {
        $res = self::baseDir().self::$_defaultConfig['resources'].DIRECTORY_SEPARATOR;
        if (is_link(rtrim($res, DIRECTORY_SEPARATOR))) {
            $res = realpath($res).DIRECTORY_SEPARATOR;
        }
        return $res;
    }

    public static function uploadDir()
    {
        $upd = self::resourcesDir().self::$_defaultConfig['upload'].DIRECTORY_SEPARATOR;
        if (is_link(rtrim($upd, DIRECTORY_SEPARATOR))) {
            $upd = realpath($upd).DIRECTORY_SEPARATOR;
        }
        return $upd;
    }

    public static function imagesDir()
    {
        $img = self::resourcesDir().self::$_defaultConfig['images'].DIRECTORY_SEPARATOR;
        if (is_link(rtrim($img, DIRECTORY_SEPARATOR))) {
            $img = realpath($img).DIRECTORY_SEPARATOR;
        }
        return $img;
    }

    public static function logDir()
    {
        $log = self::resourcesDir().self::$_defaultConfig['log'].DIRECTORY_SEPARATOR;
        if (is_link(rtrim($log, DIRECTORY_SEPARATOR))) {
            $log = realpath($log).DIRECTORY_SEPARATOR;
        }
        return $log;
    }

    public static function cacheDir()
    {
        $cache = self::resourcesDir().self::$_defaultConfig['cache'].DIRECTORY_SEPARATOR;
        if (is_link(rtrim($cache, DIRECTORY_SEPARATOR))) {
            $cache = realpath($cache).DIRECTORY_SEPARATOR;
        }
        return $cache;
    }

    public static function langDir()
    {
        return self::baseDir().self::$_defaultConfig['lang'].DIRECTORY_SEPARATOR;
    }

    public static function skinDir()
    {
        return self::baseDir().self::$_defaultConfig['skin'].DIRECTORY_SEPARATOR;
    }

    // ------ Files ------ //

    public static function configFile()
    {
        return self::configDir().self::CONFIG_FILENAME;
    }

    public static function uploadFile($resource)
    {
        $upd = self::uploadDir();
        $f = realpath($upd.$resource);
        if (is_file($f) && 0 === strpos($f, $upd)) {
            return $f;
        }
        return false;
    }

    public static function logFile()
    {
        $log = self::logDir();
        // reset returns the first element of the array... no array peek function in PHP
        $ns = reset(self::$_namespaces);
        return $log.$ns.'.txt';
    }

    public static function cacheFile($file, $retNullWhenNotFound=false)
    {
        $cache = self::cacheDir();
        $f = realpath($cache).DIRECTORY_SEPARATOR.$file;
        if (!(is_file($f) && 0 === strpos($f, $cache)) &&
            $retNullWhenNotFound === true) {
            $f = null;
        }
        return $f;
    }

    public static function langFile($loc)
    {
        $langPath = self::langDir().'%s'.DIRECTORY_SEPARATOR.$loc->toString().'.mo';
        foreach (self::$_namespaces as $ns) {
            $f = realpath(sprintf($langPath, $ns));
            if (is_file($f) && 0 === strpos($f, self::langDir())) {
                return $f;
            }
        }
        throw new Exception('Cannot find language resource : ' . $loc->toString());
    }

    public static function skinFile($resource)
    {
        $skinPath = self::skinDir().'%s'.DIRECTORY_SEPARATOR.$resource;
        // Include default dir for skin file
        foreach (array_merge(self::$_namespaces, array('default')) as $ns) {
            $f = realpath(sprintf($skinPath, $ns));
            if (is_file($f) && 0 === strpos($f, self::skinDir())) {
                return $f;
            }
        }
        return false;
    }

    public static function scriptFile($resource)
    {
        return self::skinFile(DIRECTORY_SEPARATOR.'scripts'.DIRECTORY_SEPARATOR.ltrim($resource,DIRECTORY_SEPARATOR));
    }

    // --------- MVC related directories ---------- //

    public static function layoutDirs()
    {
        $dirs = array();
        $layoutPath = self::baseDir().self::LAYOUT_DIR.DIRECTORY_SEPARATOR.'%s'.DIRECTORY_SEPARATOR;
        foreach (self::$_namespaces as $ns) {
            $f = realpath(sprintf($layoutPath, $ns));
            if (false !== $f) {
                $dirs[$ns] = $f.DIRECTORY_SEPARATOR;
            }
        }
        array_push($dirs, self::libDir().self::LAYOUT_DIR.DIRECTORY_SEPARATOR);
        return $dirs;
    }

    public static function modelDirs()
    {
        $dirs = array();
        $modelPath = self::baseDir().self::MODEL_DIR.DIRECTORY_SEPARATOR.'%s'.DIRECTORY_SEPARATOR;
        foreach (self::$_namespaces as $ns) {
            $f = realpath(sprintf($modelPath, $ns));
            if (false !== $f) {
                $dirs[$ns] = $f.DIRECTORY_SEPARATOR;
            }
        }
        return $dirs;
    }

    public static function viewDirs()
    {
        $dirs = array();
        $viewPath = self::baseDir().self::VIEW_DIR.DIRECTORY_SEPARATOR.'%s'.DIRECTORY_SEPARATOR;
        foreach (self::$_namespaces as $ns) {
            $f = realpath(sprintf($viewPath, $ns));
            if (false !== $f) {
                $dirs[$ns] = $f.DIRECTORY_SEPARATOR;
            }
        }
        array_push($dirs, self::libDir().self::VIEW_DIR.DIRECTORY_SEPARATOR);
        return $dirs;
    }

    public static function controllerDirs()
    {
        $dirs = array();
        $ctrlPath = self::baseDir().self::CONTROLLER_DIR.DIRECTORY_SEPARATOR.'%s'.DIRECTORY_SEPARATOR;
        foreach (self::$_namespaces as $ns) {
            $f = realpath(sprintf($ctrlPath, $ns));
            if (false !== $f) {
                $dirs[$ns] = $f.DIRECTORY_SEPARATOR;
            }
        }
        array_push($dirs, self::libDir().self::CONTROLLER_DIR.DIRECTORY_SEPARATOR);
        return $dirs;
    }
}


text:
/* eslint-disable no-unused-vars */
import mediumZoom from 'medium-zoom';

const matchesSelector =
  Element.prototype.matches ||
  Element.prototype.webkitMatchesSelector ||
  Element.prototype.msMatchesSelector;

function install(hook) {
  let zoom;

  hook.doneEach(_ => {
    let elms = Array.apply(
      null,
      document.querySelectorAll(
        '.markdown-section img:not(.emoji):not([data-no-zoom])'
      )
    );

    elms = elms.filter(elm => matchesSelector.call(elm, 'a img') === false);

    if (zoom) {
      zoom.detach();
    }

    zoom = mediumZoom(elms);
  });
}

$docsify.plugins = [].concat(install, $docsify.plugins);


text:
RenderGraphSystem::RenderGraphSystem()
{
	//UseRGISSystem = true;
	CurrentSet = new RenderGraphInstanceSet();
	CurrentSet->Init();
	PatchLib = new RenderGraphPatchLibrary();
}

RenderGraphSystem::~RenderGraphSystem()
{
	SafeDelete(CurrentGraph);
}

void RenderGraphSystem::InitGraph()
{
	if (UseRGISSystem)
	{
		CurrentInstance = BuildInstance(CurrentSet->GetInstanceForSettings(RHI::GetRenderSettings()));
		CurrentGraph = CurrentInstance->Instance;
	}
	else
	{
		//during dev this is easier to use.
		CurrentGraph = CreateGraph(new RenderGraphInstance(RHI::GetRenderSettings()->SelectedGraph, EBuiltInRenderGraphPatch::NONE));
	}
}

RenderGraph* RenderGraphSystem::CreateGraph(RenderGraphInstance* instance)
{
	RenderGraph* Graph = new RenderGraph();
	instance->Instance = Graph;
#if !BUILD_SHIPPING
	if (RHI::GetRenderSettings()->GetVRXSettings().UseVRX())
	{
		instance->Patches.push_back(EBuiltInRenderGraphPatch::VRX);
	}
	if (instance->GraphBaseType == EBuiltinRenderGraphs::DeferredRenderer_RT)
	{
		instance->Patches.push_back(EBuiltInRenderGraphPatch::RT_Reflections);
		instance->GraphBaseType = EBuiltinRenderGraphs::DeferredRenderer;
	}
	if (instance->GraphBaseType == EBuiltinRenderGraphs::DeferredRenderer_VX)
	{
		instance->Patches.push_back(EBuiltInRenderGraphPatch::Voxel_Reflections);
		instance->GraphBaseType = EBuiltinRenderGraphs::DeferredRenderer;
	}
	if (instance->GraphBaseType == EBuiltinRenderGraphs::DeferredRenderer_VX_RT)
	{
		instance->Patches.push_back(EBuiltInRenderGraphPatch::RT_Voxel_Reflections);
		instance->GraphBaseType = EBuiltinRenderGraphs::DeferredRenderer;
	}
#endif
	BuildingGraph = Graph;
	InitDefaultGraph(Graph, instance->GraphBaseType);
	PatchGraph(instance);
	CheckGraph(Graph);

	Graph->BuildGraph();
	Graph->RunTests();
	return Graph;
}

void RenderGraphSystem::CheckGraph(RenderGraph* Graph)
{
	if (!Graph->IsGraphValid())
	{
		Graph->DestoryGraph();
		std::string Data = "Selected graph '" + Graph->GetGraphName() + "' is invalid. Engine will use the fallback graph";
		Log::LogMessage(Data, Log::Error);
		PlatformApplication::DisplayMessageBox("Error", Data);
		Graph->CreateFallbackGraph();
	}
}

void RenderGraphSystem::InitDefaultGraph(RenderGraph* Graph, EBuiltinRenderGraphs::Type SelectedGraph)
{
	switch (SelectedGraph)
	{
	case EBuiltinRenderGraphs::Fallback:
		Graph->CreateFallbackGraph();
		break;
	case EBuiltinRenderGraphs::ForwardRenderer:
		Graph->CreateFWDGraph();
		break;
	case EBuiltinRenderGraphs::DeferredRenderer:
		Graph->CreateDefTestgraph();
		break;
	case EBuiltinRenderGraphs::DeferredRenderer_RT:
		Graph->CreateDefGraphWithRT();
		break;
	case EBuiltinRenderGraphs::DeferredRenderer_VX_RT:
		Graph->CreateDefGraphWithVoxelRT();
		break;
	case EBuiltinRenderGraphs::VRForwardRenderer:
		Graph->CreateVRFWDGraph();
		break;
	case EBuiltinRenderGraphs::Pathtracing:
		Graph->CreatePathTracedGraph();
		break;
	case EBuiltinRenderGraphs::RayTracing:
		Graph->CreateRaytracingGraph();
		break;
	case EBuiltinRenderGraphs::VoxelTracing:
		Graph->CreateVoxelTracingGraph();
		break;
	case EBuiltinRenderGraphs::TEST_MGPU:
		Graph->CreateMGPU_TESTGRAPH();
		break;
	case EBuiltinRenderGraphs::MGPU_SFR:
		Graph->CreateSFR();
		break;
	case EBuiltinRenderGraphs::MGPU_ASYNCSHADOWS:
		Graph->CreateMGPUShadows();
		break;
	}
}

void RenderGraphSystem::PatchGraph(RenderGraphInstance* Instance)
{
	for (int i = 0; i < Instance->Patches.size(); i++)
	{
		AD_Assert(PatchLib->ApplyPatch(Instance->Patches[i], Instance->Instance),"Failed to apply patch");
	}
}

void RenderGraphSystem::Render()
{
	const int frmae = 1;
	if (RHI::GetFrameCount() < frmae + 3)
	{
		RHI::RunGPUTests();
	}
	else
	{
		//RHI::RunGPUTests();
	}
	if (RHI::GetFrameCount() == frmae)
	{
		//RHI::RunGPUTests();
	}
	else if (RHI::GetFrameCount() == frmae + 3)
	{
		RHI::Get()->GetTestManager()->GatherResults();
	}
	//else if (RHI::GetFrameCount() == frmae + 10)
	//{
	//	RHI::Get()->GetTestManager()->DestoryTests();
	//}
	CurrentGraph->RunGraph();
}

void RenderGraphSystem::Update()
{
	if (Input::GetKeyDown(KeyCode::U))
	{
		CurrentGraph->ToggleCondition("PREZ");
	}
	if (Input::GetKeyDown(KeyCode::Y))
	{
		CurrentGraph->ToggleCondition("Debug");
	}
	if (Input::GetKeyDown(KeyCode::R))
	{
		RHI::GetRenderSettings()->SetVRXActive(!RHI::GetRenderSettings()->GetVRXSettings().VRXActive);
	}
#if 0
	if (Input::GetKeyDown(KeyCode::I))
	{
		RenderGraph* Test = new RenderGraph();
		Test->CreateVRFWDGraph();
		SwitchGraph(Test);
	}
#endif
}

void RenderGraphSystem::SwitchGraph(RenderGraph* NewGraph)
{
	RHI::WaitForGPU();
	SafeDelete(CurrentGraph);
	CurrentGraph = NewGraph;
	CurrentGraph->BuildGraph();
}

RenderGraphInstance* RenderGraphSystem::BuildInstance(RenderGraphInstance* Inst)
{
	Inst->Instance = CreateGraph(Inst);
	return Inst;
}

RenderGraph * RenderGraphSystem::GetCurrentGraph()
{
	return CurrentGraph;
}

RenderGraph* RenderGraphSystem::GetGraphBuilding()
{
	return BuildingGraph;
}

RenderGraphInstance * RenderGraphInstanceSet::GetInstanceForSettings(RenderSettings * set)
{
	CapabilityData MaxCaps = CapabilityData();
	RHI::GetRenderSettings()->MaxSupportedCaps(MaxCaps);
	if (set->GetRTSettings().Enabled && MaxCaps.RTSupport >= ERayTracingSupportType::DriverBased)
	{
		return RTGraph;
	}
	return HDGraph;
}

void RenderGraphInstanceSet::Init()
{
	RTGraph = new RenderGraphInstance(EBuiltinRenderGraphs::DeferredRenderer_RT);
	HDGraph = new RenderGraphInstance(EBuiltinRenderGraphs::DeferredRenderer);
}


text:
  <button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">
    Button dropdown
  </button>

Action

Another action

Something else
      here

<button type="button" class="btn btn-primary" (click)="dropdown.isOpen = !dropdown.isOpen">Toggle</button>


text:
package org.apache.ibatis.jdbc;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.BaseDataTest;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.apache.ibatis.io.Resources;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

class ScriptRunnerTest extends BaseDataTest {

  private static final String LINE_SEPARATOR = System.lineSeparator();

  @Test
  @Disabled("This fails with HSQLDB 2.0 due to the create index statements in the schema script")
  void shouldRunScriptsBySendingFullScriptAtOnce() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    Connection conn = ds.getConnection();
    ScriptRunner runner = new ScriptRunner(conn);
    runner.setSendFullScript(true);
    runner.setAutoCommit(true);
    runner.setStopOnError(false);
    runner.setErrorLogWriter(null);
    runner.setLogWriter(null);
    conn.close();
    runJPetStoreScripts(runner);
    assertProductsTableExistsAndLoaded();
  }

  @Test
  void shouldRunScriptsUsingConnection() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    try (Connection conn = ds.getConnection()) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(true);
      runner.setStopOnError(false);
      runner.setErrorLogWriter(null);
      runner.setLogWriter(null);
      runJPetStoreScripts(runner);
    }
    assertProductsTableExistsAndLoaded();
  }

  @Test
  void shouldRunScriptsUsingProperties() throws Exception {
    Properties props = Resources.getResourceAsProperties(JPETSTORE_PROPERTIES);
    DataSource dataSource = new UnpooledDataSource(
        props.getProperty("driver"),
        props.getProperty("url"),
        props.getProperty("username"),
        props.getProperty("password"));
    ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
    runner.setAutoCommit(true);
    runner.setStopOnError(false);
    runner.setErrorLogWriter(null);
    runner.setLogWriter(null);
    runJPetStoreScripts(runner);
    assertProductsTableExistsAndLoaded();
  }

  @Test
  void shouldReturnWarningIfEndOfLineTerminatorNotFound() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    String resource = "org/apache/ibatis/jdbc/ScriptMissingEOLTerminator.sql";
    try (Connection conn = ds.getConnection();
         Reader reader = Resources.getResourceAsReader(resource)) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(true);
      runner.setStopOnError(false);
      runner.setErrorLogWriter(null);
      runner.setLogWriter(null);

      try {
        runner.runScript(reader);
        fail("Expected script runner to fail due to missing end of line terminator.");
      } catch (Exception e) {
        assertTrue(e.getMessage().contains("end-of-line terminator"));
      }
    }
  }

  @Test
  void commentAferStatementDelimiterShouldNotCauseRunnerFail() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    String resource = "org/apache/ibatis/jdbc/ScriptCommentAfterEOLTerminator.sql";
    try (Connection conn = ds.getConnection();
         Reader reader = Resources.getResourceAsReader(resource)) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(true);
      runner.setStopOnError(true);
      runner.setErrorLogWriter(null);
      runner.setLogWriter(null);
      runJPetStoreScripts(runner);
      runner.runScript(reader);
    }
  }

  @Test
  void shouldReturnWarningIfNotTheCurrentDelimiterUsed() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    String resource = "org/apache/ibatis/jdbc/ScriptChangingDelimiterMissingDelimiter.sql";
    try (Connection conn = ds.getConnection();
         Reader reader = Resources.getResourceAsReader(resource)) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(false);
      runner.setStopOnError(true);
      runner.setErrorLogWriter(null);
      runner.setLogWriter(null);
      try {
        runner.runScript(reader);
        fail("Expected script runner to fail due to the usage of invalid delimiter.");
      } catch (Exception e) {
        assertTrue(e.getMessage().contains("end-of-line terminator"));
      }
    }
  }

  @Test
  void changingDelimiterShouldNotCauseRunnerFail() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    String resource = "org/apache/ibatis/jdbc/ScriptChangingDelimiter.sql";
    try (Connection conn = ds.getConnection();
         Reader reader = Resources.getResourceAsReader(resource)) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(false);
      runner.setStopOnError(true);
      runner.setErrorLogWriter(null);
      runner.setLogWriter(null);
      runJPetStoreScripts(runner);
      runner.runScript(reader);
    }
  }

  @Test
  void testLogging() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    try (Connection conn = ds.getConnection()) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(true);
      runner.setStopOnError(false);
      runner.setErrorLogWriter(null);
      runner.setSendFullScript(false);
      StringWriter sw = new StringWriter();
      PrintWriter logWriter = new PrintWriter(sw);
      runner.setLogWriter(logWriter);

      Reader reader = new StringReader("select userid from account where userid = 'j2ee';");
      runner.runScript(reader);

      assertEquals(
              "select userid from account where userid = 'j2ee'" + LINE_SEPARATOR
                      + LINE_SEPARATOR + "USERID\t" + LINE_SEPARATOR
                      + "j2ee\t" + LINE_SEPARATOR, sw.toString());
    }
  }

  @Test
  void testLoggingFullScipt() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    try (Connection conn = ds.getConnection()) {
      ScriptRunner runner = new ScriptRunner(conn);
      runner.setAutoCommit(true);
      runner.setStopOnError(false);
      runner.setErrorLogWriter(null);
      runner.setSendFullScript(true);
      StringWriter sw = new StringWriter();
      PrintWriter logWriter = new PrintWriter(sw);
      runner.setLogWriter(logWriter);

      Reader reader = new StringReader("select userid from account where userid = 'j2ee';");
      runner.runScript(reader);

      assertEquals(
              "select userid from account where userid = 'j2ee';" + LINE_SEPARATOR
                      + LINE_SEPARATOR + "USERID\t" + LINE_SEPARATOR
                      + "j2ee\t" + LINE_SEPARATOR, sw.toString());
    }
  }

  private void runJPetStoreScripts(ScriptRunner runner) throws IOException, SQLException {
    runScript(runner, JPETSTORE_DDL);
    runScript(runner, JPETSTORE_DATA);
  }

  private void assertProductsTableExistsAndLoaded() throws IOException, SQLException {
    PooledDataSource ds = createPooledDataSource(JPETSTORE_PROPERTIES);
    try (Connection conn = ds.getConnection()) {
      SqlRunner executor = new SqlRunner(conn);
      List<Map<String, Object>> products = executor.selectAll("SELECT * FROM PRODUCT");
      assertEquals(16, products.size());
    } finally {
      ds.forceCloseAll();
    }
  }

  @Test
  void shouldAcceptDelimiterVariations() throws Exception {
    Connection conn = mock(Connection.class);
    Statement stmt = mock(Statement.class);
    when(conn.createStatement()).thenReturn(stmt);
    when(stmt.getUpdateCount()).thenReturn(-1);
    ScriptRunner runner = new ScriptRunner(conn);

    String sql = "-- @DELIMITER | \n"
        + "line 1;\n"
        + "line 2;\n"
        + "|\n"
        + "//  @DELIMITER  ;\n"
        + "line 3; \n"
        + "-- //@deLimiTer $  blah\n"
        + "line 4$\n"
        + "// //@DELIMITER %\n"
        + "line 5%\n";
    Reader reader = new StringReader(sql);
    runner.runScript(reader);

    verify(stmt, Mockito.times(1)).execute(eq("line 1;" + LINE_SEPARATOR + "line 2;" + LINE_SEPARATOR + LINE_SEPARATOR));
    verify(stmt, Mockito.times(1)).execute(eq("line 3" + LINE_SEPARATOR));
    verify(stmt, Mockito.times(1)).execute(eq("line 4" + LINE_SEPARATOR));
    verify(stmt, Mockito.times(1)).execute(eq("line 5" + LINE_SEPARATOR));
  }

  @Test
  void test() {
    StringBuilder sb = new StringBuilder();
    StringBuilder sb2 = y(sb);
    assertSame(sb, sb2);
  }

  private StringBuilder y(StringBuilder sb) {
    sb.append("ABC");
    return sb;
  }

  @Test
  void shouldAcceptMultiCharDelimiter() throws Exception {
    Connection conn = mock(Connection.class);
    Statement stmt = mock(Statement.class);
    when(conn.createStatement()).thenReturn(stmt);
    when(stmt.getUpdateCount()).thenReturn(-1);
    ScriptRunner runner = new ScriptRunner(conn);

    String sql = "-- @DELIMITER || \n"
        + "line 1;\n"
        + "line 2;\n"
        + "||\n"
        + "//  @DELIMITER  ;\n"
        + "line 3; \n";
    Reader reader = new StringReader(sql);
    runner.runScript(reader);

    verify(stmt, Mockito.times(1)).execute(eq("line 1;" + LINE_SEPARATOR + "line 2;" + LINE_SEPARATOR + LINE_SEPARATOR));
    verify(stmt, Mockito.times(1)).execute(eq("line 3" + LINE_SEPARATOR));
  }
}


text:
import { TestBed, inject } from '@angular/core/testing';

import { Service163Service } from './service-163.service';

describe('Service163Service', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [Service163Service]
    });
  });

  it('should ...', inject([Service163Service], (service: Service163Service) => {
    expect(service).toBeTruthy();
  }));
});


text:
package com.github.probe.backend
package data

import org.scala_tools.time.Imports._

object LogEntry {
  object Severity extends Enumeration {
    val Assert = Value("Assert")
    val Error = Value("Error")
    val Warn = Value("Warn")
    val Info = Value("Info")
    val Debug = Value("Debug")
    val Verbose = Value("Verbose")
  }

  def apply(application: Option[String], time: LocalDateTime, processId: Int, threadId: Int, severity: LogEntry.Severity.Value, tag: String, msg: String): LogEntry =
    LogEntry(None, application, time, processId, threadId, severity, tag, msg)
}

case class LogEntry(id: Option[db.Log.idType], application: Option[String], time: LocalDateTime, processId: Int, threadId: Int, severity: LogEntry.Severity.Value, tag: String, msg: String)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KaoriStudio.Core.Configuration
{
	public partial class ConfigurationDictionary
	{
		/// <summary>
		/// Tries to retrieve a value given a key
		/// </summary>
		/// <param name="key">The key</param>
		/// <param name="value">The value output</param>
		/// <returns>Whether the key could be found</returns>
		public bool TryGetValue(string key, out object value)
		{
			if (this.arrayData != null)
			{
				if (key == null)
				{
					value = this.arrayData[0];
					return true;
				}
				else
				{
					value = default(object);
					return false;
				}
			}
			else if (this.mapData != null)
			{
				for (int i = 0; i < this.mapData.Count; i++)
				{
					var pair = this.mapData[i];

					if (key == pair.Key)
					{
						value = pair.Value;
						return true;
					}
				}

				value = default(object);
				return false;

			}
			else
			{
				value = default(object);
				return false;
			}
		}

		/// <summary>
		/// Addresses values of this configuration map by key
		/// </summary>
		/// <param name="key">The key of the pair</param>
		/// <returns>The value of the associated value</returns>
		public object this[string key]
		{
			get
			{
				if (this.arrayData != null)
				{
					if (key == null)
						return this.arrayData[0];
					else
						throw KNFException(key);
				}
				else if (this.mapData != null)
				{
					for (int i = 0; i < this.mapData.Count; i++)
					{
						var pair = this.mapData[i];

						if (key == pair.Key)
							return pair.Value;
					}
					throw KNFException(key);
				}
				else
					throw KNFException(key);
			}

			set
			{
				if (key == null)
				{
					if (this.arrayData != null)
					{
						this.arrayData.Add(value);
					}
					else if (this.mapData != null)
					{
						this.mapData.Add(new KeyValuePair<string, object>(null, value));
					}
					else
					{
						this.arrayData = new List<object>();
						this.arrayData.Add(value);
					}
				}
				else
				{
					if (this.arrayData != null)
						this.ConvertToMap();

					if (this.mapData == null)
						this.mapData = new List<KeyValuePair<string, object>>();
					else
					{
						for (int i = 0; i < this.mapData.Count; i++)
						{
							var pair = this.mapData[i];

							if (pair.Key == null)
								continue;
							else if (pair.Key == key)
							{
								this.mapData[i] = new KeyValuePair<string, object>(key, value);
								this._version++;
								return;
							}
						}
					}

					this.mapData.Add(new KeyValuePair<string, object>(key, value));
				}
			}
		}

		/// <summary>
		/// Addresses pairs of this configuration map by index
		/// </summary>
		/// <param name="index">The index</param>
		/// <returns>The pair at the index</returns>
		public KeyValuePair<string, object> this[int index]
		{
			get
			{
				if (this.arrayData != null)
				{
					return new KeyValuePair<string, object>(null, this.arrayData[index]);
				}
				else if (this.mapData != null)
				{
					return this.mapData[index];
				}
				else
				{
					throw new IndexOutOfRangeException();
				}
			}
			set
			{
				if (this.arrayData != null)
				{
					if (value.Key == null)
					{
						this.arrayData[index] = value.Value;
						this._version++;
					}
					else
					{
						this.ConvertToMap();
						this.mapData[index] = value;
					}
				}
				else if (this.mapData != null)
				{
					this.mapData[index] = value;
					this._version++;
				}
				else
					throw new IndexOutOfRangeException();
			}
		}

		/// <summary>
		/// Gets an accessor for casting values
		/// </summary>
		/// <typeparam name="T">The type to cast</typeparam>
		/// <returns>Accessor for casting values</returns>
		public CastAccessor<T> Caster<T>()
		{
			return new CastAccessor<T>(this);
		}

		/// <summary>
		/// Gets an accessor for converting values
		/// </summary>
		/// <typeparam name="T">The type to cast</typeparam>
		/// <returns>Accessor for converting values</returns>
		public ConvertAccessor<T> Converter<T>()
		{
			return new ConvertAccessor<T>(this);
		}

		/// <summary>
		/// Gets an accessor for parsing values
		/// </summary>
		/// <typeparam name="T">The type to cast</typeparam>
		/// <returns>Accessor for parsing values</returns>
		public ParseAccessor<T> Parser<T>()
		{
			return new ParseAccessor<T>(this);
		}

		/// <summary>
		/// Accessor for casting values
		/// </summary>
		/// <typeparam name="T">The type to cast</typeparam>
		public struct CastAccessor<T>
		{
			private ConfigurationDictionary map;

			/// <summary>
			/// Creates a CastAccessor
			/// </summary>
			/// <param name="map">The map</param>
			public CastAccessor(ConfigurationDictionary map)
			{
				this.map = map;
			}

			/// <summary>
			/// Accessor for casted values
			/// </summary>
			/// <param name="key">The key</param>
			/// <returns>The value</returns>
			public T this[string key]
			{
				get
				{
					return map.ValueAs<T>(key);
				}
				set
				{
					map.SetValueAs(key, value);
				}
			}

			/// <summary>
			/// Accessor for casted values
			/// </summary>
			/// <param name="key">The key</param>
			/// <param name="def">The default value</param>
			/// <returns>The value</returns>
			public T this[string key, T def]
			{
				get
				{
					return map.ValueAs<T>(key, def);
				}
			}
		}

		/// <summary>
		/// Accessor for converting values
		/// </summary>
		/// <typeparam name="T">The type to convert</typeparam>
		public struct ConvertAccessor<T>
		{
			private ConfigurationDictionary map;

			/// <summary>
			/// Creates a ConvertAccessor
			/// </summary>
			/// <param name="map">The map</param>
			public ConvertAccessor(ConfigurationDictionary map)
			{
				this.map = map;
			}

			/// <summary>
			/// Accessor for converted values
			/// </summary>
			/// <param name="key">The key</param>
			/// <returns>The value</returns>
			public T this[string key]
			{
				get
				{
					return map.ConvertValueAs<T>(key);
				}
				set
				{
					map.ConvertSetValueAs(key, value);
				}
			}

			/// <summary>
			/// Accessor for converted values
			/// </summary>
			/// <param name="key">The key</param>
			/// <param name="def">The default value</param>
			/// <returns>The value</returns>
			public T this[string key, T def]
			{
				get
				{
					return map.ConvertValueAs<T>(key, def);
				}
			}
		}

		/// <summary>
		/// Accessor for parsing values
		/// </summary>
		/// <typeparam name="T">The type to parse</typeparam>
		public struct ParseAccessor<T>
		{
			private ConfigurationDictionary map;

			/// <summary>
			/// Creates a ParseAccessor
			/// </summary>
			/// <param name="map">The map</param>
			public ParseAccessor(ConfigurationDictionary map)
			{
				this.map = map;
			}

			/// <summary>
			/// Accessor for parsed values
			/// </summary>
			/// <param name="key">The key</param>
			/// <returns>The value</returns>
			public T this[string key]
			{
				get
				{
					return map.ParseValueAs<T>(key);
				}
				set
				{
					map.ConvertSetValueAs(key, value);
				}
			}

			/// <summary>
			/// Accessor for parsed values
			/// </summary>
			/// <param name="key">The key</param>
			/// <param name="def">The default value</param>
			/// <returns>The value</returns>
			public T this[string key, T def]
			{
				get
				{
					return map.ParseValueAs<T>(key, def);
				}
			}
		}
	}
}


text:
module Sass
  module CacheStores
    # An abstract base class for backends for the Sass cache.
    # Any key-value store can act as such a backend;
    # it just needs to implement the
    # \{#_store} and \{#_retrieve} methods.
    #
    # To use a cache store with Sass,
    # use the {file:SASS_REFERENCE.md#cache_store-option `:cache_store` option}.
    #
    # @abstract
    class Base
      # Store cached contents for later retrieval
      # Must be implemented by all CacheStore subclasses
      #
      # Note: cache contents contain binary data.
      #
      # @param key [String] The key to store the contents under
      # @param version [String] The current sass version.
      #                Cached contents must not be retrieved across different versions of sass.
      # @param sha [String] The sha of the sass source.
      #                Cached contents must not be retrieved if the sha has changed.
      # @param contents [String] The contents to store.
      def _store(key, version, sha, contents)
        raise "#{self.class} must implement #_store."
      end

      # Retrieved cached contents.
      # Must be implemented by all subclasses.
      #
      # Note: if the key exists but the sha or version have changed,
      # then the key may be deleted by the cache store, if it wants to do so.
      #
      # @param key [String] The key to retrieve
      # @param version [String] The current sass version.
      #                Cached contents must not be retrieved across different versions of sass.
      # @param sha [String] The sha of the sass source.
      #                Cached contents must not be retrieved if the sha has changed.
      # @return [String] The contents that were previously stored.
      # @return [NilClass] when the cache key is not found or the version or sha have changed.
      def _retrieve(key, version, sha)
        raise "#{self.class} must implement #_retrieve."
      end

      # Store a {Sass::Tree::RootNode}.
      #
      # @param key [String] The key to store it under.
      # @param sha [String] The checksum for the contents that are being stored.
      # @param root [Object] The root node to cache.
      def store(key, sha, root)
        _store(key, Sass::VERSION, sha, Marshal.dump(root))
      rescue TypeError, LoadError => e
        Sass::Util.sass_warn "Warning. Error encountered while saving cache #{path_to(key)}: #{e}"
        nil
      end

      # Retrieve a {Sass::Tree::RootNode}.
      #
      # @param key [String] The key the root element was stored under.
      # @param sha [String] The checksum of the root element's content.
      # @return [Object] The cached object.
      def retrieve(key, sha)
        contents = _retrieve(key, Sass::VERSION, sha)
        Marshal.load(contents) if contents
      rescue EOFError, TypeError, ArgumentError, LoadError => e
        Sass::Util.sass_warn "Warning. Error encountered while reading cache #{path_to(key)}: #{e}"
        nil
      end

      # Return the key for the sass file.
      #
      # The `(sass_dirname, sass_basename)` pair
      # should uniquely identify the Sass document,
      # but otherwise there are no restrictions on their content.
      #
      # @param sass_dirname [String]
      #   The fully-expanded location of the Sass file.
      #   This corresponds to the directory name on a filesystem.
      # @param sass_basename [String] The name of the Sass file that is being referenced.
      #   This corresponds to the basename on a filesystem.
      def key(sass_dirname, sass_basename)
        dir = Digest::SHA1.hexdigest(sass_dirname)
        filename = "#{sass_basename}c"
        "#{dir}/#{filename}"
      end
    end
  end
end


text:
@class WAAppTask;

@protocol WAAppTaskDelegate <NSObject>
- (void)taskDidClose:(WAAppTask *)arg1;
- (void)taskDidOpen:(WAAppTask *)arg1;
- (void)taskLeaveForeground:(WAAppTask *)arg1;
- (void)taskEnterForeground:(WAAppTask *)arg1;
@end


text:
<?php namespace App\Http\Controllers;

use App\Http\Controllers\BaseController;
use App\Telefone;
use Illuminate\Http\Request;

class TelefoneController extends BaseController {

  public function __construct(Request $request, Telefone $model){
    $this->_model = $model;
    parent::__construct($request);
  }

}


text:
package com.bruno.db.activeandroid.model;

/**
 * Created by bruno on 31/03/15.
 */
public class Product {
}


text:
using System;

namespace RolfMichelsen.Dragon.DragonTools.IO.Filesystem.Flex
{
    /// <summary>
    /// Class for working with Flex filenames.
    /// </summary>
    public class FlexFileName : IFileName
    {
        /// <summary>
        /// Character used to separate the base and the extension in a Flex file name.
        /// </summary>
        private const char ExtensionSeparator = '.';

        /// <summary>
        /// The name of a file, omitting any directory information for hierarchical filesystems.
        /// </summary>
        public string Name { get; private set; }

        /// <summary>
        /// The complete path of the file.  This is equal to Name for flat filesystems.
        /// </summary>
        public string Path { get { return Name; }}

        /// <summary>
        /// The name of a file, omitting any file name extensions.
        /// </summary>
        public string Base { get; private set; }

        /// <summary>
        /// The extension of the file.
        /// </summary>
        public string Extension { get; private set; }

        /// <summary>
        /// Returns the path of the directory containing this file.  Returns <value>null</value> if this file
        /// is the root directory or the filesystem is flat.
        /// </summary>
        public string Ascend()
        {
            return null;
        }

        /// <summary>
        /// Returns the path of the child file contained in the directory represented by the current file name.
        /// </summary>
        /// <param name="child">Name of file to descend to.</param>
        /// <exception cref="InvalidOperationException">Thrown for a flat filesystem.</exception>
        public string Descend(string child)
        {
            throw new InvalidOperationException(GetType().FullName + " is not a hierarchical filesystem.");
        }

        /// <summary>
        /// True for a valid filename.
        /// </summary>
        public bool IsValid()
        {
            throw new NotImplementedException();
        }

        public FlexFileName(string name)
        {
            Name = name;
            int extsep = name.LastIndexOf(ExtensionSeparator);
            if (extsep == -1)
            {
                Base = Name;
                Extension = null;
            }
            else
            {
                Base = Name.Substring(0, extsep);
                Extension = Name.Substring(extsep + 1, Name.Length - extsep - 1);
            }
        }

        public override string ToString()
        {
            return Name;
        }
    }
}


text:
package util

type OperationResult struct {
	Success bool
	Message string // Mandatory message
	Detail  string // Optional detail message
	Payload string // Optional payload - may be present whether or not the operation was success
}

func Success(message string) OperationResult {
	return OperationResult{Success: true, Message: message}
}

func SuccessWithPayload(message string, payload string) OperationResult {
	return OperationResult{Success: true, Message: message, Payload: payload}
}

func Failure(message string) OperationResult {
	return OperationResult{Success: false, Message: message}
}

func FailureWithPayload(message string, payload string) OperationResult {
	return OperationResult{Success: false, Message: message, Payload: payload}
}

func FailureWithDetail(message string, detail string) OperationResult {
	return OperationResult{Success: false, Message: message, Detail: detail}
}


text:
module Conduit::Driver::Atom
  # Restore a line based on either the mdn, the uuid or the line id
  # (following this hierarchical order).
  #
  # Takes an optional `callback` url that will be called when the async
  # operation is complete.
  class Restore < Conduit::Driver::Atom::Base
    # Optional Attributes
    #
    # One of the following should be set: `line_id`, `line_uuid` or `mdn`.
    optional_attributes :line_id, :line_uuid, :mdn, :callback
    http_method         :post
    url_route           "/lines"

    # Builds the url manually since it contains dynamic parts.
    def remote_url
      resource_key = @options[:mdn] || @options[:line_uuid] || @options[:line_id]
      super + "/#{resource_key}/restore"
    end
  end
end


text:
@implementation PieSeries
static NSUInteger kDefaultSliceZOrder = 100;
@synthesize showPercentage;
@synthesize selectedSliceIndex;
@synthesize labels;
-(id) init
{
    self = [super init];
    if (self)
    {
        animations = [[NSMutableArray alloc] init];
        selectedSliceOffsetRadius = MAX(10, radius/10);
        showPercentage = YES;
        showLabel = YES;
        selectedSliceIndex = -1;
        labelBounds = [[NSMutableArray alloc] init];
        labels = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void) onDrawHandler : (UIView*) view
{
    [super onDrawHandler:view];
    [labelBounds removeAllObjects];
    pieView = view;
    CGPoint pieCenter = CGPointMake(centerX, centerY);
    float shortRadius = radius * 0.9f;
    float longRadius = radius * 1.2f;
    labelDrawer = [[RoundLabelDrawer alloc] init:context centerPoint: pieCenter shortRadius:shortRadius longRadius:longRadius labelColor:labelColor];
    labelDrawer.radius = radius;
    labelDrawer.fontSize = fontSize;
    CALayer * parentLayer = [view layer];
    NSArray *slicelayers = [parentLayer sublayers];
    float totalValue = 0;
    for (int index = 0;index < dataSize; index++)
    {
        totalValue += [[propertyValues objectAtIndex:index] floatValue];
    }
    [CATransaction begin];
    [CATransaction setAnimationDuration:1.0];
    [view setUserInteractionEnabled:NO];
    __block NSMutableArray *layersToRemove = nil;
    [CATransaction setCompletionBlock:^{
        [layersToRemove enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [obj removeFromSuperlayer];
        }];
        [layersToRemove removeAllObjects];
        for(SliceLayer *layer in parentLayer.sublayers)
        {
            [layer setZPosition:kDefaultSliceZOrder];
        }
        [view setUserInteractionEnabled:YES];
    }];
    BOOL isOnStart = [slicelayers count] == 0 && dataSize;
    NSInteger diff = dataSize - [slicelayers count];
    layersToRemove = [NSMutableArray arrayWithArray:slicelayers];
    double startPieAngle = 0;//M_PI_2*3;
    double startToAngle = 0.0;
    double endToAngle = startToAngle;
    float drawAngle = 0;
    for (int index = 0; index < dataSize; index++)
    {
        SliceLayer *layer;
        UIColor * color = [colorsCache objectAtIndex:index];
        float value = [[propertyValues objectAtIndex:index] floatValue];
        double precentValue = value * 100 / totalValue;
        double angle = (double) (value / totalValue * M_PI * 2);
        double startFromAngle = startPieAngle + startToAngle;
        double endFromAngle = startPieAngle + endToAngle;
        drawAngle = value / totalValue * 360;
        [self addClickPoint:index angle:drawAngle];
        if (showLabel)
        {
            NSString * labelValue = [self getCategoryName:index];
            [labels addObject:labelValue];
            [labelDrawer drawLabel: labelValue currentAngle:endToAngle angle:angle];
        }
        endToAngle += angle;
        if( index >= [slicelayers count] )
        {
            layer = [SliceLayer createSliceLayer:labelColor centerPoint:pieCenter];
            if (isOnStart)
            {
                startFromAngle = endFromAngle = startPieAngle;
            }
            [parentLayer addSublayer:layer];
            diff--;
        }
        else
        {
            SliceLayer *onelayer = [slicelayers objectAtIndex:index];
            if (diff > 0)
            {
                layer = onelayer;
                [parentLayer insertSublayer:layer atIndex:index];
                diff--;
            }
            else if(diff < 0)
            {
                while(diff < 0)
                {
                    [onelayer removeFromSuperlayer];
                    [parentLayer addSublayer:onelayer];
                    diff++;
                    onelayer = [slicelayers objectAtIndex:index];
                    if(onelayer.value == value || diff == 0)
                    {
                        layer = onelayer;
                        [layersToRemove removeObject:layer];
                        break;
                    }
                }
            }
        }
        [self updateLabelForLayer:layer value:precentValue];
        layer.value = value;
        layer.percentage = precentValue;
        [layer setFillColor:color.CGColor];
        [layer createAnimationForKey:@"startValue"
                              fromValue:[NSNumber numberWithDouble:startFromAngle]
                                toValue:[NSNumber numberWithDouble:startToAngle+startPieAngle]
                               delegate:self];
        NSLog(@"startAngle %f+++++ %f",startFromAngle,startToAngle+startPieAngle);
        [layer createAnimationForKey:@"endValue"
                              fromValue:[NSNumber numberWithDouble:endFromAngle]
                                toValue:[NSNumber numberWithDouble:endToAngle+startPieAngle]
                               delegate:self];
         NSLog(@"endAngle %f+++++ %f",endFromAngle,endToAngle+startPieAngle);
        startToAngle = endToAngle;
    }
    [CATransaction setDisableActions:YES];
    for(SliceLayer *layer in layersToRemove)
    {
        [layer setFillColor:[view backgroundColor].CGColor];
        [layer setDelegate:nil];
        [layer setZPosition:0];
        CATextLayer *textLayer = [[layer sublayers] objectAtIndex:0];
        [textLayer setHidden:YES];
    }
    [CATransaction setDisableActions:NO];
    [CATransaction commit];
}

- (void)updateShapeHandler:(NSTimer *)timer
{

    CALayer *parentLayer = [pieView layer];
    NSArray *pieLayers = [parentLayer sublayers];
    [pieLayers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
    {

        NSNumber *presentationLayerStartAngle = [[obj presentationLayer] valueForKey:@"startValue"];
        CGFloat interpolatedStartAngle = [presentationLayerStartAngle doubleValue];
        NSNumber *presentationLayerEndAngle = [[obj presentationLayer] valueForKey:@"endValue"];
         NSLog(@"updateTimerFired%@%@----------%@", @"---updateTimerFired", presentationLayerStartAngle, presentationLayerEndAngle);
        CGFloat interpolatedEndAngle = [presentationLayerEndAngle doubleValue];
        CGPoint pieCenter = CGPointMake(centerX, centerY);
        CGPathRef path = CGPathCreateArc(pieCenter, radius, interpolatedStartAngle, interpolatedEndAngle);
        [(CAShapeLayer*)obj setPath:path];
        CFRelease(path);
        {
            CATextLayer *labelLayer = [[obj sublayers] objectAtIndex:0];
            CGFloat interpolatedMidAngle = (interpolatedEndAngle + interpolatedStartAngle) / 2;
            [CATransaction setDisableActions:YES];
            [labelLayer setPosition:CGPointMake(pieCenter.x + (radius/2 * cos(interpolatedMidAngle)), pieCenter.y + (radius/2 * sin(interpolatedMidAngle)))];
            [CATransaction setDisableActions:NO];
        }
    }];
    NSLog(@"updateTimerFired%@",@"---updateTimerFired");
}

- (void)updateLabelForLayer : (SliceLayer *)pieLayer value : (CGFloat)value
{
    CATextLayer *textLayer = [[pieLayer sublayers] objectAtIndex:0];
    [textLayer setHidden:!showPercentage];
    NSString * label = [NSString stringWithFormat:@"%0.0f%@", value, @"%"];
    UIFont * labelFont = [UIFont systemFontOfSize:15.0];
    CGSize size = [label sizeWithFont:labelFont];
    [CATransaction setDisableActions:YES];
    if(M_PI*2*10*pieLayer.percentage < MAX(size.width,size.height) || value <= radius/2)
    {
        [textLayer setString:label];
    }
    else
    {
        [textLayer setString:label];
        [textLayer setBounds:CGRectMake(0, 0, size.width, size.height)];
    }
    [CATransaction setDisableActions:NO];
}

static CGPathRef CGPathCreateArc(CGPoint center, CGFloat radius, CGFloat startAngle, CGFloat endAngle)
{
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, center.x, center.y);
    CGPathAddArc(path, NULL, center.x, center.y, radius, startAngle, endAngle, 0);
    CGPathCloseSubpath(path);
    return path;
}

- (void)notifySelectionChangeFrom : (NSUInteger)previousSelection to : (NSUInteger)newSelection
{
    if (previousSelection != newSelection)
    {
        selectedSliceIndex = newSelection;
        if (newSelection != -1)
        {
            [self setSliceSelectedAtIndex:newSelection];
        }
        if(previousSelection != -1)
        {
            [self setSliceDeselectedAtIndex:previousSelection];
        }
    }
    else if (newSelection != -1)
    {
        SliceLayer *layer = [pieView.layer.sublayers objectAtIndex:newSelection];
        if(selectedSliceOffsetRadius > 0 && layer)
        {
            if (layer.isSelected)
            {
                [self setSliceDeselectedAtIndex:newSelection];
                return;
            }
            [self setSliceSelectedAtIndex:newSelection];
        }
    }
}

- (void)setSliceSelectedAtIndex : (NSInteger)index
{
    if(selectedSliceOffsetRadius <= 0)
        return;
    SliceLayer *layer = [pieView.layer.sublayers objectAtIndex:index];
    if (layer && !layer.isSelected)
    {
        CGPoint currPos = layer.position;
        double middleAngle = (layer.startValue + layer.endValue)/2.0;
        CGPoint newPos = CGPointMake(currPos.x + selectedSliceOffsetRadius*cos(middleAngle), currPos.y + selectedSliceOffsetRadius*sin(middleAngle));
        layer.position = newPos;
        layer.isSelected = YES;
    }
}

- (void)setSliceDeselectedAtIndex : (NSInteger)index
{
    if(selectedSliceOffsetRadius <= 0)
        return;
    SliceLayer *layer = [pieView.layer.sublayers objectAtIndex:index];
    if (layer && layer.isSelected)
    {
        layer.position = CGPointMake(0, 0);
        layer.isSelected = NO;
    }
}

@end


text:
/**
 *
 */
package org.crazyit.net;

import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * Description:
 *
ÍøÕ¾: ·è¿ñJavaÁªÃË
 *
Copyright (C), 2001-2014, Yeeku.H.Lee
 *
This program is protected by copyright laws.
 *
Program Name:
 *
Date:
 * @author  Yeeku.H.Lee kongyeeku@163.com
 * @version  1.0
 */
public class ListAdapter extends BaseAdapter
{
	private Context context;
	private List<String> values;

	public ListAdapter(Context context , List<String> values)
	{
		this.context = context;
		this.values = values;
	}

	@Override
	public int getCount()
	{
		return values.size();
	}

	@Override
	public Object getItem(int position)
	{
		return values.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		TextView text = new TextView(context);
		text.setText(values.get(position));
		text.setTextSize(20);
		text.setTextColor(Color.WHITE);
		return text;
	}
}


text:
package org.apache.solr.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.lucene.util.LuceneTestCase;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;

/**
 */
public class SolrDocumentTest extends LuceneTestCase
{
  public void testSimple()
  {
    Float fval = new Float( 10.01f );
    Boolean bval = Boolean.TRUE;
    String sval = "12qwaszx";

    // Set up a simple document
    SolrDocument doc = new SolrDocument();
    doc.addField( "f", fval );
    doc.addField( "b", bval );
    doc.addField( "s", sval );
    doc.addField( "f", 100 ); // again, but something else

    // make sure we can pull values out of it
    assertEquals( fval, doc.getFirstValue( "f" ) );
    assertEquals( fval, doc.getFieldValues( "f" ).iterator().next() );
    assertEquals( fval, ((Collection<Object>)doc.getFieldValue( "f" )).iterator().next() );
    assertEquals( bval, doc.getFieldValue( "b" ) );
    assertEquals( sval, doc.getFieldValue( "s" ) );
    assertEquals( 2, doc.getFieldValues( "f" ).size() );
    assertNull( doc.getFieldValue( "xxxxx" ) );
    assertNull( doc.getFieldValues( "xxxxx" ) );

    List<String> keys = new ArrayList<>();
    for( String s : doc.getFieldNames() ) {
      keys.add( s );
    }
    Collections.sort( keys );
    assertEquals( 3, keys.size() );
    assertEquals( "[b, f, s]", keys.toString() );

    // set field replaced existing values:
    doc.setField( "f", fval );
    assertEquals( 1, doc.getFieldValues( "f" ).size() );
    assertEquals( fval, doc.getFieldValue( "f" ) );

    doc.setField( "n", null );
    assertEquals( null, doc.getFieldValue( "n" ) );

    // now remove some fields
    assertEquals( true, doc.removeFields( "f" ) );
    assertEquals( false, doc.removeFields( "asdgsadgas" ) );
    assertNull( doc.getFieldValue( "f" ) );
    assertNull( doc.getFieldValues( "f" ) );
  }

  public void testUnsupportedStuff()
  {
    SolrDocument doc = new SolrDocument();

    try { doc.getFieldValueMap().clear();               fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().containsValue( null ); fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().entrySet();            fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().putAll( null );        fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().values();              fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().remove( "key" );       fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().put( "key", "value" ); fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}

    try { doc.getFieldValuesMap().clear();               fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValuesMap().containsValue( null ); fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValuesMap().entrySet();            fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValuesMap().putAll( null );        fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValuesMap().values();              fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValuesMap().remove( "key" );       fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}
    try { doc.getFieldValueMap().put( "key", Collections.EMPTY_LIST ); fail( "should be unsupported!" ); } catch( UnsupportedOperationException ex ){}

    assertEquals( null, doc.getFieldValueMap().get( "aaa" ) );
    doc.setField( "aaa", "bbb" );
    assertEquals( "bbb", doc.getFieldValueMap().get( "aaa" ) );
  }

  public void testAddCollections()
  {
    final List<String> c0 = new ArrayList<>();
    c0.add( "aaa" );
    c0.add( "aaa" );
    c0.add( "aaa" );
    c0.add( "bbb" );
    c0.add( "ccc" );
    c0.add( "ddd" );

    SolrDocument doc = new SolrDocument();
    doc.addField( "v", c0 );
    assertEquals( c0.size(), doc.getFieldValues("v").size() );
    assertEquals( c0.get(0), doc.getFirstValue( "v" ) );

    // Same thing with an array
    Object[] arr = new Object[] { "aaa", "aaa", "aaa", 10, 'b' };
    doc = new SolrDocument();
    doc.addField( "v", arr );
    assertEquals( arr.length, doc.getFieldValues("v").size() );
    // try the same thing with 'setField'
    doc.setField( "v", arr );
    assertEquals( arr.length, doc.getFieldValues("v").size() );

    doc.clear();
    assertEquals( 0, doc.getFieldNames().size() );

    Iterable iter = new Iterable() {
      @Override
      public Iterator iterator() {
        return c0.iterator();
      }
    };
    doc.addField( "v", iter );
    assertEquals( c0.size(), doc.getFieldValues("v").size() );
    // do it again to get twice the size...
    doc.addField( "v", iter );
    assertEquals( c0.size()*2, doc.getFieldValues("v").size() );

    // An empty list:
    doc.setField( "empty", new ArrayList<String>() );
    assertNull( doc.getFirstValue( "empty" ) );

    // Try the JSTL accessor functions...
    assertFalse( doc.getFieldValueMap().isEmpty() );
    assertFalse( doc.getFieldValuesMap().isEmpty() );
    assertEquals( 2, doc.getFieldValueMap().size() );
    assertEquals( 2, doc.getFieldValuesMap().size() );
    assertTrue( doc.getFieldValueMap().containsKey( "v" ) );
    assertTrue( doc.getFieldValuesMap().containsKey( "v" ) );
    assertTrue( doc.getFieldValueMap().keySet().contains( "v" ) );
    assertTrue( doc.getFieldValuesMap().keySet().contains( "v" ) );
    assertFalse( doc.getFieldValueMap().containsKey( "g" ) );
    assertFalse( doc.getFieldValuesMap().containsKey( "g" ) );
    assertFalse( doc.getFieldValueMap().keySet().contains( "g" ) );
    assertFalse( doc.getFieldValuesMap().keySet().contains( "g" ) );

    // A read-only list shouldn't break addField("v", ...).
    List<String> ro = Collections.unmodifiableList(c0);
    doc = new SolrDocument();
    doc.addField( "v", ro );

    // This should NOT throw an UnsupportedOperationException.
    doc.addField( "v", "asdf" );

    // set field using a collection is documented to be backed by
    // that collection, so changes should affect it.
    Collection<String> tmp = new ArrayList<>(3);
    tmp.add("one");
    doc.setField( "collection_backed", tmp );
    assertEquals("collection not the same",
                 tmp, doc.getFieldValues( "collection_backed" ));
    tmp.add("two");
    assertEquals("wrong size",
                 2, doc.getFieldValues( "collection_backed" ).size());
    assertEquals("collection not the same",
                 tmp, doc.getFieldValues( "collection_backed" ));

  }

  public void testDuplicate()
  {
    Float fval0 = new Float( 10.01f );
    Float fval1 = new Float( 11.01f );
    Float fval2 = new Float( 12.01f );

    // Set up a simple document
    SolrInputDocument doc = new SolrInputDocument();
    for( int i=0; i<5; i++ ) {
      doc.addField( "f", fval0, 1.0f );
      doc.addField( "f", fval1, 1.0f );
      doc.addField( "f", fval2, 1.0f );
    }
    assertEquals( (3*5), doc.getField("f").getValueCount() );
  }

  public void testMapInterface()
  {
    SolrDocument doc = new SolrDocument();
    assertTrue( doc instanceof Map );
    assertTrue( Map.class.isAssignableFrom( SolrDocument.class ) );

    SolrInputDocument indoc = new SolrInputDocument();
    assertTrue( indoc instanceof Map );
    assertTrue( Map.class.isAssignableFrom( indoc.getClass() ) );
  }
}