text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Meredith's UX Design Portfolio">
    <meta name="author" content="Meredith Yuhan Xie">

    <title>Meredith Yuhan Xie | Product & UX Designer</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">
    <link rel="icon" type="image/png" href="favicon.png"/>

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

For companies that already have a relatively mature selling process, Salesforce is one excellent tool that helps them manage their business. However, Salesforce's products have not been serving people who own local business, which provide goods or services to a local population. They have a very different way to manage their data. My design product, Salesforce for local business, is to serve owners of local business.

*This is my personal project. I am not affiliate with Salesforce.

Goal and Target User

Goal

1) Finding out what are pain points of current local business running system

                        2)Solving the pain points.

Target users

People who own local business.

User Research Process

Before anything, collecting data is the starting point for any user-centered design. I defined local business to be business that do not belong to big chain store, those who serve a local population.

I conducted user research at University Way NE, Seattle, WA 98105, or, as most people call it, the Ave. I chose to conduct user research on the ave, because it is right next to University of Washington, Seattle campus. UW students and faculty members make the Ave rather crowded and popular, which enriches the data for my user research. Also, based on data provided by Yelp, about 70% of all stores on the ave are local business (i.e, stores like Starbucks, 7–11, American Apparel not counted as local business). It makes the Ave a great location for my user research.

Before I went on to the Ave, I decided the best way to get data would be interviewing the business owners and field study (observation). Based on Yelp data, about 80% of all local business stores here are food and dining services (i.e., restaurants, dessert stores, cafe). So I picked several food service local business owners to interview. I went on the Ave, stayed there from 2 to 5 p.m on weekdays, because that's when most of the stores are not busy. In the end, I successfully conducted 4 interview sessions with 2 restaurants owners , 1 bubble store owner and 1 cup cake store owner.

                     Some notes and data analysis

After finishing my very first interview with a restaurant owner, I got to know that they a product called Clover. According to the owner, that is now what most people use in local business. So I Googled clover, did some competitive analysis, before I move on to the second interview.

By the end of the four interviews, I realized the information my interviewees can provide start to get more and more repetitive, and that is when I know that I can stop on user research and start analyse my data.

During the interview process, I was so tempted to conduct more field study, where I observe how owners run their business. However, their actual business data are too sensitive for them to show me. I ended up conducting one field study at the bubble tea store, while it was crowded and busy, and I got the chance to see how customers and cashiers interact with Clover and data involved.

Pain points

I collected and analysed data from interviews, field study and competitive analysis. I then generated these five pain points:

1. Anyone can access and edit data

Authorization is a big issue in the current local business managing system, AKA Clove. A restaurant owner reported in interview that anyone who log into the system can input, edit or delete any order. He described a former employee of his delete some of the orders and stole the money, and he can still edit data on Clove after he's fired. Clover, however, never reported any of it.

"We fired him because he was deleting orders and taking the money. Now he is not working for us anymore and yet he can still log into the system to change whatever he wants. And Clove never report it!"

2. Useless categorization and visualization

According to the owner of bubble tea store and the owner of cupcake store, data in Clove system is hard to manage. All the data appear to be categorized by time. However, the owners would love to see the data categorized by type of drink/cupcake or others. Visualized chart, on the scale of time/date is not so helpful.

3. No customize categorization or sub-categorization

Unable to customize categorization and sub-categorization is extremely inconvenient. For local business owner, the items they sell are customizable. For example, bubble tea customers can add extra servings of tapioca or herbal jelly, restaurant customers might order dish with extra meat. These data are important to owners, and yet the current system, Clove, fail to create sub-categorization for them.

4. Have to manually input tips

Restaurant owners have to manually input the amount of tip per order every night. It takes quite long time.

"It is tedious to input manually tips at the end of the day."

However, I believe, instead of being a design problem, this is a bank policy issue. Bank does not charge tips from credit/debit card unless seeing signature of customers. Therefore, these number have to be provided to the bank afterwards.

5. Data don't sync between two stores

Local business, though only serves local residents, still has the chance of expanding the business to other region. The bubble tea owner reported that syncing.

"I have another bubble tea shop at Renton, and the data just don't sync. "

The owner now pays for two different account of clover. He has to check and analyze data from one store, then do exactly the same thing to the other. It takes time and extra calculation to add everything together using a calculator.

User Needs

I generated user needs based on users' pain points. Also, I did not treat the manually-tips-inputing as a design problem, since it's a problem because of bank policy.

Different Authorisation level

One way to solve the data access/editing problem is to have different authorization of one account. For example, the owner has the highest authorisation level, where he/she gets to see all the on-time sales data, shifts, and orders, and authorizing employees to edit sales data.

Customised data management

Local Business owners need to customize data based on different type of items they sell. Customizable data categorization and sub-categorization is important.

Able to sync among multiple (usually 2) stores

Data from more than one store should be able to sync and analyzed together.

Able to manage data and also people

This user need is based on my field study. I observe that these local business often run on owners assigning shifts and employees dropping and picking up shifts. It is a critical process of running the business, so I take it as a user need as well.

Sample Data

The data below came from interview + field study with at the bubble tea store. The owner did not show me the actual data. He only listed the types of data for me, because the actual number is a sensitive subject. I then stayed in the store for another half an hour after the interview to conduct field study, observing and documenting the data involved.

                    Sample Data from the bubble tea store

From the sample data, I was able to brainstorm and define key path.

Key Path

                    Key Path of local business owners using the product

Brainstorm

I then started brainstorming the features and tools local business owners need based on the key path above. I wrote down one idea on one post-it and combined them with key path.

                    Brainstorming post-its

Sketches

I chose to design on web app platform, because when owners are running the store, it is unlikely for them to check the data online. They prefer to check everything at the end of the day, where they can take close look to the data. My interviewees reported so, that they do it on their own computer.

                    BInformation Architecture + Low fidelity UI

                    BInformation Architecture + Low fidelity UI

The design above solves the design pain points listed. Authorization are customizable by store owners. When employees try to edit sales data, they need to request the action and owners can either approve, disapprove or message the employees.

Data management and categorization/sub-categorization are all customizable, where owners get to view the data on scale of time, date, type, add-on, and more.

Owner can only register for one account, and manage multiple stores, where data are generated together. Besides manage data, owners can manage people by assigning shifts to employees, and employees can drop and pick up shift through the product under owner's aware.

Prototype

I made some high fidelity prototypes here to deliver the user interface design idea.

Constraints

Clover is a pos machine that takes in data from each transaction. So far, there is no way to connect Salesforce products with Clover. In other words, data that are in Clover system cannot be transferred into Salesforce system. Therefore, my design is based on an assumption that Salesforce products are able to access those transaction data in Clover.

Also, ideally, this should be a pretty big product. As a college student, I am not able to get all the data I need. I only reached the data I could access, tried my best to design it out. I did not conduct any usability test either, because it is difficult for me to recruit participants.

Designed and programmed by Meredith Yuhan Xie. All all all Rights Reserved.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Plugin.InAppBilling;
using Plugin.InAppBilling.Abstractions;
using SplitAndMerge;

namespace scripting
{
    public class PurchaseFunction : ParserFunction
    {
        protected override Variable Evaluate(ParsingScript script)
        {
            List<Variable> args = script.GetFunctionArgs();
            Utils.CheckArgs(args.Count, 2, m_name, true);

            string productId = args[0].AsString();
            string strAction = args[1].AsString();
#if __IOS__
            return scripting.iOS.PurchaseFunction.Purchase(productId, strAction);
#else
            InAppBilling.RegisterCallbacks(strAction);
            InAppBilling.PurchaseItem(productId);

            return Variable.EmptyInstance;
#endif
        }
    }
    public class RestoreFunction : ParserFunction
    {
        protected override Variable Evaluate(ParsingScript script)
        {
            List<Variable> args = script.GetFunctionArgs();
            Utils.CheckArgs(args.Count, 1, m_name);
#if __IOS__
            return scripting.iOS.RestoreFunction.Restore(args);
#else
            string strAction = args[0].AsString();

            for (int i = 1; i < args.Count; i++)
            {
                string productId = Utils.GetSafeString(args, i);
                InAppBilling.AddProductId(productId);
            }

            InAppBilling.RegisterCallbacks(strAction);
            InAppBilling.Restore();

            return Variable.EmptyInstance;
#endif
        }
    }
    public class ProductIdDescriptionFunction : ParserFunction
    {
        protected override Variable Evaluate(ParsingScript script)
        {
            List<Variable> args = script.GetFunctionArgs();
            Utils.CheckArgs(args.Count, 1, m_name);

            string productId = args[0].AsString();
            string strAction = Utils.GetSafeString(args, 1);
#if __IOS__
            return scripting.iOS.ProductIdDescriptionFunction.GetDescription(productId);
#else
            if (string.IsNullOrWhiteSpace(strAction))
            {
                var desc = InAppBilling.GetDescription(productId);
                return new Variable(desc);
            }

            InAppBilling.RegisterCallbacks(strAction);
            InAppBilling.GetDescriptionAsync(productId);

            return Variable.EmptyInstance;
#endif
        }
    }

    public class InAppBilling
    {
        public static Action<string> OnIAPOK;
        public static Action<string> OnIAPError;

        public static int IAP_REQUEST = 1001;

        static string m_key;
        static bool m_pricesLoaded;
        // The product we are currently buying. If null, then we are in the restore mode.
        static string m_buyingProductId;

        static HashSet<string> m_availableProducts = new HashSet<string>();
        static HashSet<string> m_purchasedProducts = new HashSet<string>();
        static Dictionary<string, string> m_id2Description = new Dictionary<string, string>();

        static bool s_errorConnecting;
        static string s_prevAction;

        public static void  RegisterCallbacks(string strAction)
        {
            OnIAPOK = null;
            OnIAPError = null;

            InAppBilling.OnIAPOK += (productIds) =>
            {
                UIVariable.GetAction(strAction, "", productIds);
            };
            InAppBilling.OnIAPError += (errorStr) =>
            {
                UIVariable.GetAction(strAction, errorStr, "");
            };
            s_prevAction = strAction;
        }

        public static void AddProductId(string productId)
        {
            m_availableProducts.Add(productId); // Hasn't been purchased
        }
        static bool ConnectionFailed()
        {
            s_errorConnecting = true;
            OnIAPError?.Invoke("Couldn't connect to the App Store");
            return false;
        }

        public static string GetDescription(string productId)
        {
            string desciption;
            if (!m_id2Description.TryGetValue(productId, out desciption))
            {
                desciption = productId;
            }
            OnIAPOK?.Invoke(desciption);
            return desciption;
        }
        public static async Task<string> GetDescriptionAsync(string productId)
        {
            string desciption;
            if (!m_id2Description.TryGetValue(productId, out desciption))
            {
                await GetInventory(productId);
                if (!m_id2Description.TryGetValue(productId, out desciption))
                {
                    desciption = productId;
                }
            }
            OnIAPOK?.Invoke(desciption);
            return desciption;
        }
        static bool ProductPurchased(string productId)
        {
            m_purchasedProducts.Add(productId);
            OnIAPOK?.Invoke(productId);
            return true;
        }
        public async static Task GetInventory(string productId = "")
        {
            if (!string.IsNullOrEmpty(productId) && m_id2Description.ContainsKey(productId))
            {
                return;
            }
            var billing = CrossInAppBilling.Current;
            try
            {
                var connected = await billing.ConnectAsync();
                if (!connected)
                {
                    ConnectionFailed();
                    return;
                }

                var items = await billing.GetProductInfoAsync(ItemType.InAppPurchase,
                                                              m_availableProducts.ToArray());
                if (items == null)
                {
                    return;
                }
                foreach (var item in items)
                {
                    Console.WriteLine("Got {0}: [{1}] {2} {3}",
                            item.ProductId, item.Description, item.LocalizedPrice, item.Name);
                    m_id2Description[item.ProductId] = item.Name;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error getting AppStore data: " + ex.Message);
                OnIAPError?.Invoke(ex.Message);
            }
            finally
            {
                await billing.DisconnectAsync();
            }
        }
        public static async Task<bool> PurchaseItem(string productId, string payload = "notused")
        {
            s_errorConnecting = false;
            await GetInventory();
            if (s_errorConnecting)
            {
                return false;
            }

            bool alreadyPurchased = await WasItemPurchased(productId);
            if (alreadyPurchased)
            {
                OnIAPOK?.Invoke(productId);
                return true;
            }
            if (s_errorConnecting)
            {
                return false;
            }

            var billing = CrossInAppBilling.Current;
            try
            {
                var connected = await billing.ConnectAsync();
                if (!connected)
                {
                    return ConnectionFailed();
                }

                var purchase = await billing.PurchaseAsync(productId,
                    ItemType.InAppPurchase, payload);

                //possibility that a null came through.
                if (purchase == null)
                {
                    OnIAPError?.Invoke("Couldn't purchase " + productId);
                    return false;
                }
                else if (purchase.State == PurchaseState.Purchased)
                {
                    ProductPurchased(productId);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                OnIAPError?.Invoke(ex.Message);
            }
            finally
            {
                await billing.DisconnectAsync();
            }
            return false;
        }

        public static async Task Restore()
        {
            s_errorConnecting = false;
            await GetInventory();
            if (s_errorConnecting)
            {
                return;
            }

            string restored = "";
            foreach (string productId in m_availableProducts)
            {
                bool purchased = await WasItemPurchased(productId);
                if (s_errorConnecting)
                {
                    return;
                }
                if (purchased)
                {
                    if (!string.IsNullOrEmpty(restored))
                    {
                        restored += ",";
                    }
                    restored += productId;
                }
            }

            OnIAPOK?.Invoke(restored);
        }

        static async Task<bool> WasItemPurchased(string productId)
        {
            if (m_purchasedProducts.Contains(productId))
            {
                return true;
            }
            var billing = CrossInAppBilling.Current;
            try
            {
                var connected = await billing.ConnectAsync();
                if (!connected)
                {
                    return ConnectionFailed();
                }

                //check purchases
                var purchases = await billing.GetPurchasesAsync(ItemType.InAppPurchase);

                //check for null just incase
                if (purchases?.Any(p => p.ProductId == productId) ?? false)
                {
                    m_purchasedProducts.Add(productId);
                    return true;
                }
                else
                {
                    //no purchases found
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
                s_errorConnecting = true;
                OnIAPError?.Invoke(ex.Message);
            }
            finally
            {
                await billing.DisconnectAsync();
            }

            return false;
        }

#if __ANDROID__
    public static void OnIAPCallback(int requestCode, Android.App.Result resultCode, Android.Content.Intent data)
    {
      // For Plugin.InAppBilling.
      try {
        Plugin.InAppBilling.InAppBillingImplementation.HandleActivityResult(requestCode, resultCode, data);
      } catch (Exception exc) {
        Console.WriteLine("Got exception IAP: {0}:", exc);
      }
    }
#endif
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.repositories.azure;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.mocksocket.MockHttpServer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.Map;

import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;

/**
 * {@link AzureStorageFixture} is a fixture that emulates an Azure Storage service.
 * <p>
 * It starts an asynchronous socket server that binds to a random local port. The server parses
 * HTTP requests and uses a {@link AzureStorageTestServer} to handle them before returning
 * them to the client as HTTP responses.
 */
public class AzureStorageFixture {

    public static void main(String[] args) throws Exception {
        if (args == null || args.length != 2) {
            throw new IllegalArgumentException("AzureStorageFixture <working directory> <container>");
        }

        final InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
        final HttpServer httpServer = MockHttpServer.createHttp(socketAddress, 0);

        try {
            final Path workingDirectory = workingDir(args[0]);
            /// Writes the PID of the current Java process in a `pid` file located in the working directory
            writeFile(workingDirectory, "pid", ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);

            final String addressAndPort = addressToString(httpServer.getAddress());
            // Writes the address and port of the http server in a `ports` file located in the working directory
            writeFile(workingDirectory, "ports", addressAndPort);

            // Emulates Azure
            final String storageUrl = "http://" + addressAndPort;
            final AzureStorageTestServer testServer = new AzureStorageTestServer(storageUrl);
            testServer.createContainer(args[1]);

            httpServer.createContext("/", new ResponseHandler(testServer));
            httpServer.start();

            // Wait to be killed
            Thread.sleep(Long.MAX_VALUE);

        } finally {
            httpServer.stop(0);
        }
    }

    @SuppressForbidden(reason = "Paths#get is fine - we don't have environment here")
    private static Path workingDir(final String dir) {
        return Paths.get(dir);
    }

    private static void writeFile(final Path dir, final String fileName, final String content) throws IOException {
        final Path tempPidFile = Files.createTempFile(dir, null, null);
        Files.write(tempPidFile, singleton(content));
        Files.move(tempPidFile, dir.resolve(fileName), StandardCopyOption.ATOMIC_MOVE);
    }

    private static String addressToString(final SocketAddress address) {
        final InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
        if (inetSocketAddress.getAddress() instanceof Inet6Address) {
            return "[" + inetSocketAddress.getHostString() + "]:" + inetSocketAddress.getPort();
        } else {
            return inetSocketAddress.getHostString() + ":" + inetSocketAddress.getPort();
        }
    }

    static class ResponseHandler implements HttpHandler {

        private final AzureStorageTestServer server;

        private ResponseHandler(final AzureStorageTestServer server) {
            this.server = server;
        }

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            String method = exchange.getRequestMethod();
            String path = server.getEndpoint() + exchange.getRequestURI().getRawPath();
            String query = exchange.getRequestURI().getRawQuery();
            Map<String, List<String>> headers = exchange.getRequestHeaders();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Streams.copy(exchange.getRequestBody(), out);

            final AzureStorageTestServer.Response response = server.handle(method, path, query, headers, out.toByteArray());

            Map<String, List<String>> responseHeaders = exchange.getResponseHeaders();
            responseHeaders.put("Content-Type", singletonList(response.contentType));
            response.headers.forEach((k, v) -> responseHeaders.put(k, singletonList(v)));
            exchange.sendResponseHeaders(response.status.getStatus(), response.body.length);
            if (response.body.length > 0) {
                exchange.getResponseBody().write(response.body);
            }
            exchange.close();
        }
    }
}


text:
using huys::UDialogBox;

const TCHAR *g_Filename = _T("test.file");
const TCHAR *g_TestString = _T("Hi, I am here!");

class UDialogExt : public UDialogBox
{
    enum {
        IDC_ED_CONTENT = 11111
    };
public:
    UDialogExt(HINSTANCE hInst, UINT nID)
        : UDialogBox(hInst, nID)
    {}

    virtual BOOL onInit()
    {
        m_pEditContent = new UEdit(m_hDlg, IDC_ED_CONTENT, m_hInst);
        m_pEditContent->create();

        huys::URectL rcClient;
        ::GetClientRect(m_hDlg, rcClient);
        RECT rc = { 5, 5, rcClient.right()-5, 150 };
        m_pEditContent->setPosition(&rc);

        return TRUE;
    }

    BOOL onCommand(WPARAM wParam, LPARAM lParam)
    {
        switch (LOWORD (wParam))
        {
        case IDC_BN_READ:
            return onBnRead();
        case IDC_BN_WRITE:
            return onBnWrite();
        defalut:
            return UDialogBox::onCommand(wParam, lParam);
        }
    }

private:
    huys::ADT::UAutoPtr<UEdit> m_pEditContent;
private:
    BOOL onBnRead()
    {
        UFile tfile;
        tfile.open(g_Filename);
        DWORD dwRead;
        TCHAR buf[512] = {0};
        tfile.read((LPBYTE)buf, 512, &dwRead);
        tfile.close();

        m_pEditContent->setWindowText(buf);

        return FALSE;
    }

    BOOL onBnWrite()
    {
        UFile tfile;
        tfile.create(g_Filename);
        TCHAR buf[512] = {0};
        m_pEditContent->getWindowText(buf, 511);
        tfile.write((LPBYTE)buf, lstrlen(buf)*sizeof(TCHAR));
        tfile.close();
        return FALSE;
    }
};

UDLGAPP_T(UDialogExt, IDD_TEST);


text:
class CreateJoinTableInstancesUsers < ActiveRecord::Migration[5.0]
  def self.up
    create_join_table :instances, :users do |t|
      # t.index [:event_id, :user_id]
      # t.index [:user_id, :event_id]
    end
    execute "ALTER TABLE instances_users ADD UNIQUE (instance_id, user_id)"
    drop_table :events_users
  end

  def self.down
    drop_table :instances_users
  end

end


text:
package com.intellij.core;

import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.psi.impl.DocumentCommitProcessor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
* @author nik
*/
class MockDocumentCommitProcessor extends DocumentCommitProcessor {
  @Override
  public void commitSynchronously(@NotNull Document document, @NotNull Project project) {
  }

  @Override
  public void commitAsynchronously(@NotNull Project project,
                                   @NotNull Document document,
                                   @NonNls @NotNull Object reason,
                                   @NotNull ModalityState currentModalityState) {
  }
}


text:
package fr.vidal.oss.jaxb.atom.core;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.stream.Stream;

import static fr.vidal.oss.jaxb.atom.core.Preconditions.checkState;
import static java.util.Collections.*;

/**
 * Definition of a structured extension element.
 * Refer to the ATOM specification: @link https://tools.ietf.org/html/rfc4287#section-6.4.2
 */
public class StructuredElement extends ExtensionElement {

    static final String SHOULD_CONTAIN_ATTRIBUTE_OR_CHILD = "A structured element should contain at least a child element or an attribute.";

    private Namespace namespace;
    private String tagName;
    private Collection<Attribute> attributes;

    @XmlAnyElement
    private Collection<ExtensionElement> extensionElements;

    @SuppressWarnings("unused") //jaxb
    private StructuredElement() {
    }

    private StructuredElement(Builder builder) {
        this.namespace = builder.namespace;
        this.tagName = builder.tagName;
        this.attributes = builder.attributes;
        this.extensionElements = builder.extensionElements;
    }

    @Override
    public JAXBElement toJAXBElement() {
        return new JAXBElement<>(qualifiedName(), StructuredElement.class, this);
    }

    @Override
    public Namespace namespace() {
        return namespace;
    }

    @Override
    public String tagName() {
        return tagName;
    }

    @Override
    public Collection<Attribute> attributes() {
        return unmodifiableCollection(attributes);
    }

    public Collection<ExtensionElement> getExtensionElements() {
        return unmodifiableCollection(extensionElements);
    }

    @Override
    public int hashCode() {
        return Objects.hash(namespace, tagName, attributes, extensionElements);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StructuredElement that = (StructuredElement) o;
        return Objects.equals(namespace, that.namespace) &&
            Objects.equals(tagName, that.tagName) &&
            Objects.equals(attributes, that.attributes) &&
            Objects.equals(extensionElements, that.extensionElements);
    }

    @Override
    public String toString() {
        return "StructuredElement{" +
            "namespace=" + namespace +
            ", tagName='" + tagName + '\'' +
            ", attributes=" + attributes +
            ", extensionElements=" + extensionElements +
            '}';
    }

    public static class Builder implements ExtensionElement.Builder<StructuredElement, Builder> {

        private Namespace namespace;
        private String tagName;
        private Collection<Attribute> attributes;
        private Collection<ExtensionElement> extensionElements;

        Builder(String tagName, ExtensionElement extensionElement) {
            this(tagName, singleton(extensionElement));
        }

        Builder(String tagName, Collection<ExtensionElement> extensionElements) {
            this(tagName, emptyList(), extensionElements);
        }

        Builder(String tagName, Attribute attribute) {
            this(tagName, singleton(attribute), emptyList());
        }

        private Builder(String tagName, Collection<Attribute> attributes, Collection<ExtensionElement> extensionElements) {
            this.tagName = tagName;
            this.attributes = new LinkedHashSet<>(attributes);
            this.extensionElements = new LinkedHashSet<>(extensionElements);
        }

        public Builder withNamespace(Namespace namespace) {
            this.namespace = namespace;
            return this;
        }

        public Builder addChild(ExtensionElement child) {
            this.extensionElements.add(child);
            return this;
        }

        public Builder addChildren(ExtensionElement... children) {
            return addChildren(Arrays.asList(children));
        }

        public Builder addChildren(Iterable<ExtensionElement> children) {
            children.forEach(this::addChild);
            return this;
        }

        public Builder addChildren(Stream<ExtensionElement> children) {
            children.forEach(this::addChild);
            return this;
        }

        public Builder addAttribute(Attribute attribute) {
            this.attributes.add(attribute);
            return this;
        }

        public Builder addAttributes(Attribute... attributes) {
            return addAttributes(Arrays.asList(attributes));
        }

        public Builder addAttributes(Iterable<Attribute> attributes) {
            attributes.forEach(this::addAttribute);
            return this;
        }

        public StructuredElement build() {
            checkState(tagName != null, TAG_NAME_IS_MANDATORY);
            checkState(hasAttributeOrChild(), SHOULD_CONTAIN_ATTRIBUTE_OR_CHILD);
            return new StructuredElement(this);
        }

        private boolean hasAttributeOrChild() {
            return containsValue(attributes)
                || containsValue(extensionElements);
        }

        private boolean containsValue(Collection<?> collection) {
            return collection.stream()
                .anyMatch(Objects::nonNull);
        }
    }
}


text:
package org.rioproject.impl.watch;

import org.rioproject.impl.sla.SLAPolicyHandler;
import org.rioproject.servicebean.ServiceBeanContext;
import org.rioproject.system.SystemWatchID;
import org.rioproject.watch.WatchDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.rmi.NoSuchObjectException;
import java.util.*;

/**
 * An implementation of a {@link WatchRegistry}
 */
public class WatchDataSourceRegistry implements WatchRegistry {
    /** Collection of Watch instances that have been registered */
    private final List<Watch> watchRegistry = new ArrayList<>();
    /** Table of ThresholdWatch class names and ThresholdListener objects */
    private final Map<String, Collection<ThresholdListener>> thresholdListenerTable = new Hashtable<>();
    /** The ServiceBeanContext */
    private ServiceBeanContext context;
    /** A Logger */
    private static Logger logger = LoggerFactory.getLogger(WatchDataSourceRegistry.class);

    /**
     * @see WatchRegistry#deregister
     */
    public void deregister(Watch... watches) {
        if (watches == null)
            throw new IllegalArgumentException("Watches cannot be null");
        watchRegistry.removeAll(Arrays.asList(watches));
        for (Watch watch : watches) {
            try {
                if(watch instanceof PeriodicWatch)
                    ((PeriodicWatch)watch).stop();
                watch.getWatchDataSource().close();

            } catch (NoSuchObjectException e) {
                if (logger.isTraceEnabled())
                    logger.trace("Deregistering Watch", e);
            } catch (Throwable t) {
                logger.warn("Deregistering Watch", t);
            }
            /// unregister ThresholdListeners
            thresholdListenerTable.remove(watch.getId());
        }
    }

    /**
     * @see WatchRegistry#closeAll()
     */
    public void closeAll() {
        Watch[] watches = watchRegistry.toArray(new Watch[0]);
        for(Watch w : watches) {
            //unregisterJMX(w);
            if(w instanceof PeriodicWatch)
                ((PeriodicWatch)w).stop();
            try {
                WatchDataSource wd = w.getWatchDataSource();
                if (wd != null)
                    wd.close();
                watchRegistry.remove(w);
            } catch (Exception e) {
                logger.warn("Closing WatchDataSource", e);
            }
        }
    }

    /**
     * @see WatchRegistry#register
     */
    public void register(Watch... watches) {
        if(watches == null)
            throw new IllegalArgumentException("Watches cannot be null");
        watchRegistry.addAll(Arrays.asList(watches));
        for (Watch watch : watches) {
            associateThresholdListener(watch);
        }
    }

    /**
     * @see WatchRegistry#addThresholdListener
     */
    public void addThresholdListener(String id, ThresholdListener thresholdListener) {
        if(id==null)
            throw new IllegalArgumentException("id is null");
        if(thresholdListener==null)
            throw new IllegalArgumentException("thresholdListener is null");
        Collection<ThresholdListener> collection;
        if(thresholdListenerTable.containsKey(id)) {
            collection = thresholdListenerTable.get(id);
        } else {
            collection = new ArrayList<>();
        }
        if(!collection.contains(thresholdListener)) {
            if(logger.isTraceEnabled())
                logger.trace("Add [{}] for watch [{}]", thresholdListener.getClass().getName(), id);
            collection.add(thresholdListener);
            thresholdListenerTable.put(id, collection);

            Watch watch = findWatch(id);
            if(logger.isTraceEnabled())
                logger.trace("Found [{}] previously registered watch [{}]", (watch==null?0:1), id);
            if(watch!=null) {
                associateThresholdListener(watch);
            }
        }
    }

    /**
     * @see WatchRegistry#removeThresholdListener
     */
    public void removeThresholdListener(String id, ThresholdListener thresholdListener) {
        if(thresholdListenerTable.containsKey(id)) {
            Collection<ThresholdListener> collection = thresholdListenerTable.get(id);
            collection.remove(thresholdListener);
        }
    }

    /*
     * This method will associate a Watch to a ThresholdListener, iff the Watch
     * is a ThresholdWatch and the Watch objects classname is found in the table
     *
     * @param watch The Watch to associate
     */
    private void associateThresholdListener(Watch watch) {
        if(!(watch instanceof ThresholdWatch))
            return;
        ThresholdWatch tWatch = (ThresholdWatch)watch;
        if(thresholdListenerTable.containsKey(tWatch.getId())) {
            Collection<ThresholdListener> collection = thresholdListenerTable.get(tWatch.getId());
            for (ThresholdListener tListener : collection) {
                if (logger.isTraceEnabled())
                    logger.trace("Associate Watch [{}] to [{}]", tWatch.getId(), tListener.getClass().getName());
                if (tListener instanceof SLAPolicyHandler) {
                    SLAPolicyHandler slaPolicyHandler = (SLAPolicyHandler)tListener;
                    tWatch.setThresholdValues(slaPolicyHandler.getSLA());
                }
                if(tListener instanceof SettableThresholdListener) {
                    ((SettableThresholdListener)tListener).setThresholdManager(tWatch.getThresholdManager());
                }
            }
        }
    }

    /**
     * @see WatchRegistry#findWatch(String)
     */
    public Watch findWatch(String id) {
        if(id == null)
            throw new IllegalArgumentException("id is null");

        Watch watch = null;
        for(Watch w : watchRegistry) {
            if(id.equals(w.getId())) {
                watch = w;
                break;
            }
        }
        return watch;
    }

    /**
     * @see WatchRegistry#fetch()
     */
    public WatchDataSource[] fetch() {
        WatchDataSource[] wds = new WatchDataSource[watchRegistry.size()];
        int i = 0;
        for(Watch watch : watchRegistry) {
            wds[i++] = watch.getWatchDataSource();
        }
        return wds;
    }

    /**
     * @see WatchRegistry#fetch(String)
     */
    public WatchDataSource fetch(String id) {
        WatchDataSource wds = null;
        Watch watch = findWatch(id);
        if(watch != null) {
            wds = watch.getWatchDataSource();
        } else {
            boolean isSystemWatch = false;
            for(String s : SystemWatchID.IDs) {
                if(s.equals(id)) {
                    isSystemWatch = true;
                    break;
                }
            }
            if(isSystemWatch && context!=null) {
                Watch w = context.getComputeResourceManager().getComputeResource().getMeasurableCapability(id);
                if(w!=null)
                    wds = w.getWatchDataSource();
            }
        }
        return wds;
    }

    /**
     * @see WatchRegistry#setServiceBeanContext
     */
    public void setServiceBeanContext(ServiceBeanContext context) {
        this.context = context;
    }
}


text:
package com.ait.lienzo.client.core.image.filter;

import com.ait.lienzo.client.core.shape.json.IFactory;
import com.ait.lienzo.client.core.shape.json.validators.ValidationContext;
import com.ait.lienzo.client.core.shape.json.validators.ValidationException;
import com.ait.lienzo.client.core.types.ImageData;
import com.ait.lienzo.shared.core.types.ImageFilterType;
import com.google.gwt.canvas.dom.client.CanvasPixelArray;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;

/**
 * A class that allows for easy creation of a Invert Color Image Filter.
 */
public class InvertColorImageDataFilter extends AbstractImageDataFilter<InvertColorImageDataFilter>
{
    public InvertColorImageDataFilter()
    {
        super(ImageFilterType.InvertColorImageDataFilterType);
    }

    protected InvertColorImageDataFilter(final JSONObject node, final ValidationContext ctx) throws ValidationException
    {
        super(ImageFilterType.InvertColorImageDataFilterType, node, ctx);
    }

    @Override
    public ImageData filter(ImageData source, final boolean copy)
    {
        if (null == source)
        {
            return null;
        }
        if (copy)
        {
            source = source.copy();
        }
        if (false == isActive())
        {
            return source;
        }
        final CanvasPixelArray data = source.getData();

        if (null == data)
        {
            return source;
        }
        filter_(data, FilterCommonOps.getLength(source));

        return source;
    }

    private final native void filter_(JavaScriptObject data, int length)
    /*-{
		for (var i = 0; i < length; i += 4) {
			data[i] = 255 - data[i];
			data[i + 1] = 255 - data[i + 1];
			data[i + 2] = 255 - data[i + 2];
		}
    }-*/;

    @Override
    public IFactory<InvertColorImageDataFilter> getFactory()
    {
        return new InvertColorImageDataFilterFactory();
    }

    public static class InvertColorImageDataFilterFactory extends ImageDataFilterFactory<InvertColorImageDataFilter>
    {
        public InvertColorImageDataFilterFactory()
        {
            super(ImageFilterType.InvertColorImageDataFilterType);
        }

        @Override
        public InvertColorImageDataFilter create(final JSONObject node, final ValidationContext ctx) throws ValidationException
        {
            return new InvertColorImageDataFilter(node, ctx);
        }
    }
}


text:
using namespace std;
using namespace deepblue;

DebugProgram::DebugProgram(const GLchar *vs_path, const GLchar *fs_path) :
Program(readFile(vs_path).c_str(), readFile(fs_path).c_str()) {

}


text:
import getBoardSquares from './getBoardSquares';

/**
 * Get board position index from canvas click position
 * @param {*} size size of the canvas
 * @param {*} position position clicked in the canvas
 * @return {Number} index
 */
const getSquareIndex = (size, position) => {
  const squares = getBoardSquares(size);

  for (var i = 0; i < squares.length; i += 1) {
    const square = squares[i];
    const fromX = square[0][0];
    const fromY = square[0][1];
    const toX = square[1][0];
    const toY = square[1][1];

    if (position.x >= fromX && position.x <= toX &&
      position.y >= fromY && position.y <= toY) {
      return i;
    }
  }

  return null;
};

export default getSquareIndex;


text:
machines
========

[![Build Status](https://secure.travis-ci.org/ekmett/machines.png?branch=master)](http://travis-ci.org/ekmett/machines)

*Ceci n'est pas une pipe*

Machines are demand driven input sources like pipes or conduits, but can support multiple inputs.

You design a `Machine` by writing a `Plan`. You then `construct` the machine.

Simple machines that take one input are called a `Process` and processes form a `Category`. More generally you can attach a
`Process` to the output of any type of `Machine`, yielding a new `Machine`.

More complicated machines provide other ways of connecting to them.

Typically the use of machines proceeds by using simple plans into machine `Tee`s and `Wye`s, capping many of the inputs to
those with possibly monadic sources, feeding the rest input (possibly repeatedly) and calling `run` or `runT` to get the
answers out.

There is a lot of flexibility when building a machine in choosing between empowering the machine to run its own monadic effects
or delegating that responsibility to a custom driver.

A port of this design to scala is available from runarorama/scala-machines

Runar's slides are also available from https://dl.dropbox.com/u/4588997/Machines.pdf

Contact Information
-------------------

Contributions and bug reports are welcome!

Please feel free to contact me through github or on the #haskell IRC channel on irc.freenode.net.

-Edward Kmett


text:
module Modesty
  module LoadMethods
    attr_writer :metrics_dir
    def metrics_dir
      @metrics_dir ||= File.join(
        Modesty.root,
        'metrics'
      )
    end

    def load_all_metrics!
      Dir.glob(
        File.join(self.metrics_dir, '**', '*.rb')
      ).each { |f| load f }
    end
  end
end


text:
package org.wso2.developerstudio.eclipse.platform.core.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.wso2.developerstudio.eclipse.platform.core.MediaManager;

public class DeveloperStudioProviderUtils {
	public static void addFilter(Map<String, List<String>> filters, String filterId, String filterValue) {
		if (!filters.containsKey(filterId)) {
			filters.put(filterId, new ArrayList<String>());
		}
		List<String> list = getFilterValues(filters, filterId);
		list.add(filterValue);
	}

	public static boolean isFilterPresent(Map<String, List<String>> filters, String filterId) {
		if (filters.containsKey(filterId)) {
			return getFilterValues(filters, filterId).size() > 0;
		} else {
			return false;
		}

	}

	public static List<String> getFilterValues(Map<String, List<String>> filters, String filterId) {
		List<String> list = filters.get(filterId);
		return list;
	}

	public static boolean isInProjectFilterPassed(Map<String, List<String>> filters, IResource registryResource) {
		boolean passed = true;
		if (DeveloperStudioProviderUtils.isFilterPresent(filters, CSProviderConstants.FILTER_PROJECT)) {
			String projectName = registryResource.getProject().getName();
			passed = false;
			List<String> filterValues =
			                            DeveloperStudioProviderUtils.getFilterValues(filters,
			                                                                         CSProviderConstants.FILTER_PROJECT);
			for (String filter : filterValues) {
				if (filter.equals(projectName)) {
					passed = true;
					break;
				}
			}
		}
		return passed;
	}

	public static boolean isMediaTypeFilterPassed(Map<String, List<String>> filters, IFile workspaceFile) {
		File file = workspaceFile.getLocation().toFile();
		return isMediaTypeFilterPassed(filters, file);
	}

	public static boolean isMediaTypeFilterPassed(Map<String, List<String>> filters, File file) {
		boolean passed = true;
		try {
			if (DeveloperStudioProviderUtils.isFilterPresent(filters, CSProviderConstants.FILTER_MEDIA_TYPE)) {
				String mediaType = MediaManager.getMediaType(file);
				passed = DeveloperStudioProviderUtils.isMediaTypeFilterPassed(filters, mediaType);
			}
		} catch (Exception e) {
			passed = false;
		}
		return passed;
	}

	public static boolean isMediaTypeFilterPassed(Map<String, List<String>> filters, String mediaType) {
		boolean passed = true;
		if (DeveloperStudioProviderUtils.isFilterPresent(filters, CSProviderConstants.FILTER_MEDIA_TYPE)) {
			passed = false;
			if (mediaType != null) {
				List<String> filterValues =
				                            DeveloperStudioProviderUtils.getFilterValues(filters,
				                                                                         CSProviderConstants.FILTER_MEDIA_TYPE);
				for (String filter : filterValues) {
					if (filter.equalsIgnoreCase(mediaType)) {
						passed = true;
						break;
					}
				}
			}
		}
		return passed;
	}

	/**
	 * This method will return an array of IConfigurationElements of all the instances that extends a given extension point
	 * @param extensionID - the id of the extension point
	 * @return the IConfigurationElements array of data of all extended instances
	 */
	public IConfigurationElement[] getExtensionPointmembers(String extensionID){
		IExtensionRegistry reg = Platform.getExtensionRegistry();
	    IConfigurationElement[] elements = reg.getConfigurationElementsFor(extensionID);
	    return elements;
	}

}


text:
import type { Behavior } from "../behavior";
import type { Scene } from "../../scene";
import type { Nullable } from "../../types";
import type { Observer } from "../../Misc/observable";
import type { Camera } from "../../Cameras/camera";
import { Matrix, Quaternion, Vector3 } from "../../Maths/math.vector";
import { Scalar } from "../../Maths/math.scalar";
import type { TransformNode } from "../../Meshes/transformNode";
import { Epsilon } from "../../Maths/math.constants";

/**
 * A behavior that when attached to a mesh will follow a camera
 * @since 5.0.0
 */
export class FollowBehavior implements Behavior<TransformNode> {
    private _scene: Scene;

    // Memory cache to avoid GC usage
    private _tmpQuaternion: Quaternion = new Quaternion();
    private _tmpVectors: Vector3[] = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
    private _tmpMatrix: Matrix = new Matrix();
    private _tmpInvertView: Matrix = new Matrix();
    private _tmpForward: Vector3 = new Vector3();
    private _tmpNodeForward: Vector3 = new Vector3();
    private _tmpPosition: Vector3 = new Vector3();

    private _followedCamera: Nullable<Camera>;
    private _onBeforeRender: Nullable<Observer<Scene>>;

    private _workingPosition: Vector3 = new Vector3();
    private _workingQuaternion: Quaternion = new Quaternion();
    private _lastTick: number = -1;
    private _recenterNextUpdate = true;

    /**
     * Attached node of this behavior
     */
    public attachedNode: Nullable<TransformNode>;

    /**
     * Set to false if the node should strictly follow the camera without any interpolation time
     */
    public interpolatePose = true;

    /**
     * Rate of interpolation of position and rotation of the attached node.
     * Higher values will give a slower interpolation.
     */
    public lerpTime = 500;

    /**
     * If the behavior should ignore the pitch and roll of the camera.
     */
    public ignoreCameraPitchAndRoll = false;

    /**
     * Pitch offset from camera (relative to Max Distance)
     * Is only effective if `ignoreCameraPitchAndRoll` is set to `true`.
     */
    public pitchOffset = 15;

    /**
     * The vertical angle from the camera forward axis to the owner will not exceed this value
     */
    public maxViewVerticalDegrees = 30;

    /**
     * The horizontal angle from the camera forward axis to the owner will not exceed this value
     */
    public maxViewHorizontalDegrees = 30;
    /**
     * The attached node will not reorient until the angle between its forward vector and the vector to the camera is greater than this value
     */
    public orientToCameraDeadzoneDegrees = 60;
    /**
     * Option to ignore distance clamping
     */
    public ignoreDistanceClamp = false;
    /**
     * Option to ignore angle clamping
     */
    public ignoreAngleClamp = false;
    /**
     * Max vertical distance between the attachedNode and camera
     */
    public verticalMaxDistance = 0;
    /**
     *  Default distance from eye to attached node, i.e. the sphere radius
     */
    public defaultDistance = 0.8;
    /**
     *  Max distance from eye to attached node, i.e. the sphere radius
     */
    public maximumDistance = 2;
    /**
     *  Min distance from eye to attached node, i.e. the sphere radius
     */
    public minimumDistance = 0.3;

    /**
     * Ignore vertical movement and lock the Y position of the object.
     */
    public useFixedVerticalOffset = false;

    /**
     * Fixed vertical position offset distance.
     */
    public fixedVerticalOffset = 0;

    /**
     * Enables/disables the behavior
     * @internal
     */
    public _enabled = true;

    /**
     * The camera that should be followed by this behavior
     */
    public get followedCamera(): Nullable<Camera> {
        return this._followedCamera || this._scene.activeCamera;
    }

    public set followedCamera(camera: Nullable<Camera>) {
        this._followedCamera = camera;
    }

    /**
     *  The name of the behavior
     */
    public get name(): string {
        return "Follow";
    }

    /**
     *  Initializes the behavior
     */
    public init() {}

    /**
     * Attaches the follow behavior
     * @param ownerNode The mesh that will be following once attached
     * @param followedCamera The camera that should be followed by the node
     */
    public attach(ownerNode: TransformNode, followedCamera?: Camera): void {
        this._scene = ownerNode.getScene();
        this.attachedNode = ownerNode;

        if (followedCamera) {
            this.followedCamera = followedCamera;
        }

        this._addObservables();
    }

    /**
     *  Detaches the behavior from the mesh
     */
    public detach(): void {
        this.attachedNode = null;
        this._removeObservables();
    }

    /**
     * Recenters the attached node in front of the camera on the next update
     */
    public recenter() {
        this._recenterNextUpdate = true;
    }

    private _angleBetweenVectorAndPlane(vector: Vector3, normal: Vector3) {
        // Work on copies
        this._tmpVectors[0].copyFrom(vector);
        vector = this._tmpVectors[0];
        this._tmpVectors[1].copyFrom(normal);
        normal = this._tmpVectors[1];

        vector.normalize();
        normal.normalize();

        return Math.PI / 2 - Math.acos(Vector3.Dot(vector, normal));
    }

    private _length2D(vector: Vector3) {
        return Math.sqrt(vector.x * vector.x + vector.z * vector.z);
    }

    private _distanceClamp(currentToTarget: Vector3, moveToDefault: boolean = false) {
        let minDistance = this.minimumDistance;
        let maxDistance = this.maximumDistance;
        const defaultDistance = this.defaultDistance;

        const direction = this._tmpVectors[0];
        direction.copyFrom(currentToTarget);
        let currentDistance = direction.length();
        direction.normalizeFromLength(currentDistance);

        if (this.ignoreCameraPitchAndRoll) {
            // If we don't account for pitch offset, the casted object will float up/down as the reference
            // gets closer to it because we will still be casting in the direction of the pitched offset.
            // To fix this, only modify the XZ position of the object.
            minDistance = this._length2D(direction) * minDistance;
            maxDistance = this._length2D(direction) * maxDistance;

            const currentDistance2D = this._length2D(currentToTarget);
            direction.scaleInPlace(currentDistance / currentDistance2D);
            currentDistance = currentDistance2D;
        }

        let clampedDistance = currentDistance;

        if (moveToDefault) {
            clampedDistance = defaultDistance;
        } else {
            clampedDistance = Scalar.Clamp(currentDistance, minDistance, maxDistance);
        }

        currentToTarget.copyFrom(direction).scaleInPlace(clampedDistance);

        return currentDistance !== clampedDistance;
    }

    private _applyVerticalClamp(currentToTarget: Vector3) {
        if (this.verticalMaxDistance !== 0) {
            currentToTarget.y = Scalar.Clamp(currentToTarget.y, -this.verticalMaxDistance, this.verticalMaxDistance);
        }
    }

    private _toOrientationQuatToRef(vector: Vector3, quaternion: Quaternion) {
        Quaternion.RotationYawPitchRollToRef(Math.atan2(vector.x, vector.z), Math.atan2(vector.y, Math.sqrt(vector.z * vector.z + vector.x * vector.x)), 0, quaternion);
    }

    private _applyPitchOffset(invertView: Matrix) {
        const forward = this._tmpVectors[0];
        const right = this._tmpVectors[1];
        forward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
        right.copyFromFloats(1, 0, 0);
        Vector3.TransformNormalToRef(forward, invertView, forward);
        forward.y = 0;
        forward.normalize();
        Vector3.TransformNormalToRef(right, invertView, right);

        Quaternion.RotationAxisToRef(right, (this.pitchOffset * Math.PI) / 180, this._tmpQuaternion);
        forward.rotateByQuaternionToRef(this._tmpQuaternion, forward);
        this._toOrientationQuatToRef(forward, this._tmpQuaternion);
        this._tmpQuaternion.toRotationMatrix(this._tmpMatrix);

        // Since we already extracted position from the invert view matrix, we can
        // disregard the position part of the matrix in the copy
        invertView.copyFrom(this._tmpMatrix);
    }

    private _angularClamp(invertView: Matrix, currentToTarget: Vector3): boolean {
        const forward = this._tmpVectors[5];
        forward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
        const right = this._tmpVectors[6];
        right.copyFromFloats(1, 0, 0);

        // forward and right are related to camera frame of reference
        Vector3.TransformNormalToRef(forward, invertView, forward);
        Vector3.TransformNormalToRef(right, invertView, right);

        // Up is global Z
        const up = Vector3.UpReadOnly;

        const dist = currentToTarget.length();

        if (dist < Epsilon) {
            return false;
        }

        let angularClamped = false;
        const rotationQuat = this._tmpQuaternion;

        // X-axis leashing
        if (this.ignoreCameraPitchAndRoll) {
            const angle = Vector3.GetAngleBetweenVectorsOnPlane(currentToTarget, forward, right);
            Quaternion.RotationAxisToRef(right, angle, rotationQuat);
            currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget);
        } else {
            const angle = -Vector3.GetAngleBetweenVectorsOnPlane(currentToTarget, forward, right);
            const minMaxAngle = ((this.maxViewVerticalDegrees * Math.PI) / 180) * 0.5;
            if (angle < -minMaxAngle) {
                Quaternion.RotationAxisToRef(right, -angle - minMaxAngle, rotationQuat);
                currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget);
                angularClamped = true;
            } else if (angle > minMaxAngle) {
                Quaternion.RotationAxisToRef(right, -angle + minMaxAngle, rotationQuat);
                currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget);
                angularClamped = true;
            }
        }

        // Y-axis leashing
        const angle = this._angleBetweenVectorAndPlane(currentToTarget, right) * (this._scene.useRightHandedSystem ? -1 : 1);
        const minMaxAngle = ((this.maxViewHorizontalDegrees * Math.PI) / 180) * 0.5;
        if (angle < -minMaxAngle) {
            Quaternion.RotationAxisToRef(up, -angle - minMaxAngle, rotationQuat);
            currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget);
            angularClamped = true;
        } else if (angle > minMaxAngle) {
            Quaternion.RotationAxisToRef(up, -angle + minMaxAngle, rotationQuat);
            currentToTarget.rotateByQuaternionToRef(rotationQuat, currentToTarget);
            angularClamped = true;
        }

        return angularClamped;
    }

    private _orientationClamp(currentToTarget: Vector3, rotationQuaternion: Quaternion) {
        // Construct a rotation quat from up vector and target vector
        const toFollowed = this._tmpVectors[0];
        toFollowed.copyFrom(currentToTarget).scaleInPlace(-1).normalize();

        const up = this._tmpVectors[1];
        const right = this._tmpVectors[2];
        // We use global up vector to orient the following node (global +Y)
        up.copyFromFloats(0, 1, 0);

        // Gram-Schmidt to create an orthonormal frame
        Vector3.CrossToRef(toFollowed, up, right);
        const length = right.length();

        if (length < Epsilon) {
            return;
        }

        right.normalizeFromLength(length);

        Vector3.CrossToRef(right, toFollowed, up);
        if (this.attachedNode?.getScene().useRightHandedSystem) {
            Quaternion.FromLookDirectionRHToRef(toFollowed, up, rotationQuaternion);
        } else {
            Quaternion.FromLookDirectionLHToRef(toFollowed, up, rotationQuaternion);
        }
    }

    private _passedOrientationDeadzone(currentToTarget: Vector3, forward: Vector3) {
        const leashToFollow = this._tmpVectors[5];
        leashToFollow.copyFrom(currentToTarget);
        leashToFollow.normalize();

        const angle = Math.abs(Vector3.GetAngleBetweenVectorsOnPlane(forward, leashToFollow, Vector3.UpReadOnly));
        return (angle * 180) / Math.PI > this.orientToCameraDeadzoneDegrees;
    }

    private _updateLeashing(camera: Camera) {
        if (this.attachedNode && this._enabled) {
            const oldParent = this.attachedNode.parent;
            this.attachedNode.setParent(null);

            const worldMatrix = this.attachedNode.getWorldMatrix();
            const currentToTarget = this._workingPosition;
            const rotationQuaternion = this._workingQuaternion;
            const pivot = this.attachedNode.getPivotPoint();
            const invertView = this._tmpInvertView;
            invertView.copyFrom(camera.getViewMatrix());
            invertView.invert();

            Vector3.TransformCoordinatesToRef(pivot, worldMatrix, currentToTarget);
            const position = this._tmpPosition;
            position.copyFromFloats(0, 0, 0);
            Vector3.TransformCoordinatesToRef(position, worldMatrix, position);
            position.scaleInPlace(-1).subtractInPlace(pivot);
            currentToTarget.subtractInPlace(camera.globalPosition);

            if (this.ignoreCameraPitchAndRoll) {
                this._applyPitchOffset(invertView);
            }

            let angularClamped = false;
            const forward = this._tmpForward;
            forward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
            Vector3.TransformNormalToRef(forward, invertView, forward);

            const nodeForward = this._tmpNodeForward;
            nodeForward.copyFromFloats(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
            Vector3.TransformNormalToRef(nodeForward, worldMatrix, nodeForward);

            if (this._recenterNextUpdate) {
                currentToTarget.copyFrom(forward).scaleInPlace(this.defaultDistance);
            } else {
                if (this.ignoreAngleClamp) {
                    const currentDistance = currentToTarget.length();
                    currentToTarget.copyFrom(forward).scaleInPlace(currentDistance);
                } else {
                    angularClamped = this._angularClamp(invertView, currentToTarget);
                }
            }

            let distanceClamped = false;
            if (!this.ignoreDistanceClamp) {
                distanceClamped = this._distanceClamp(currentToTarget, angularClamped);
                this._applyVerticalClamp(currentToTarget);
            }

            if (this.useFixedVerticalOffset) {
                currentToTarget.y = position.y - camera.globalPosition.y + this.fixedVerticalOffset;
            }

            if (angularClamped || distanceClamped || this._passedOrientationDeadzone(currentToTarget, nodeForward) || this._recenterNextUpdate) {
                this._orientationClamp(currentToTarget, rotationQuaternion);
            }

            this._workingPosition.subtractInPlace(pivot);
            this._recenterNextUpdate = false;

            this.attachedNode.setParent(oldParent);
        }
    }

    private _updateTransformToGoal(elapsed: number) {
        if (!this.attachedNode || !this.followedCamera || !this._enabled) {
            return;
        }

        if (!this.attachedNode.rotationQuaternion) {
            this.attachedNode.rotationQuaternion = Quaternion.Identity();
        }

        const oldParent = this.attachedNode.parent;
        this.attachedNode.setParent(null);

        if (!this.interpolatePose) {
            this.attachedNode.position.copyFrom(this.followedCamera.globalPosition).addInPlace(this._workingPosition);
            this.attachedNode.rotationQuaternion.copyFrom(this._workingQuaternion);
            return;
        }

        // position
        const currentDirection = new Vector3();
        currentDirection.copyFrom(this.attachedNode.position).subtractInPlace(this.followedCamera.globalPosition);
        Vector3.SmoothToRef(currentDirection, this._workingPosition, elapsed, this.lerpTime, currentDirection);
        currentDirection.addInPlace(this.followedCamera.globalPosition);
        this.attachedNode.position.copyFrom(currentDirection);

        // rotation
        const currentRotation = new Quaternion();
        currentRotation.copyFrom(this.attachedNode.rotationQuaternion);
        Quaternion.SmoothToRef(currentRotation, this._workingQuaternion, elapsed, this.lerpTime, this.attachedNode.rotationQuaternion);

        this.attachedNode.setParent(oldParent);
    }

    private _addObservables() {
        this._lastTick = Date.now();
        this._onBeforeRender = this._scene.onBeforeRenderObservable.add(() => {
            if (!this.followedCamera) {
                return;
            }

            const tick = Date.now();
            this._updateLeashing(this.followedCamera);
            this._updateTransformToGoal(tick - this._lastTick);
            this._lastTick = tick;
        });
    }

    private _removeObservables() {
        if (this._onBeforeRender) {
            this._scene.onBeforeRenderObservable.remove(this._onBeforeRender);
        }
    }
}


text:
package org.xiwc.semantic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;

@SpringApplicationConfiguration(classes = Application.class)
public class SecurityTest extends AbstractTestNGSpringContextTests {

	@Autowired
	ApplicationContext context;

	@Test
	public void f() {
		System.out.println(context);
	}
}


text:
"""
A bot to remove stale protection templates from pages that are not protected.

Very often sysops block the pages for a set time but then they forget to
remove the warning! This script is useful if you want to remove those useless
warning left in these pages.

These command line parameters can be used to specify which pages to work on:

&params;

Furthermore, the following command line parameters are supported:

-protectedpages  Check all the blocked pages; useful when you have not
                 categories or when you have problems with them. (add the
                 namespace after ":" where you want to check - default checks
                 all protected pages.)

-moveprotected   Same as -protectedpages, for moveprotected pages

-always          Doesn't ask every time whether the bot should make the change.
                 Do it always.

-show            When the bot can't delete the template from the page (wrong
                 regex or something like that) it will ask you if it should
                 show the page on your browser.
                 (attention: pages included may give false positives!)

-move            The bot will check if the page is blocked also for the move
                 option, not only for edit

Examples:

    python pwb.py blockpageschecker -always

    python pwb.py blockpageschecker -cat:Geography -always

    python pwb.py blockpageschecker -show -protectedpages:4

"""
#
# (C) Pywikibot team, 2007-2020
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals

import re
import time
import webbrowser

import pywikibot

from pywikibot import config
from pywikibot import i18n
from pywikibot import pagegenerators
from pywikibot.tools.formatter import color_format

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp,
}

# PREFERENCES

templateSemiProtection = {
    'cs': [r'\{\{(?:[Tt]emplate:|[Šš]ablona:|)([Dd]louhodobě[ _]p|[Pp])'
           r'olozamčeno(|[^\}]*)\}\}\s*'],
    'fr': [r'\{\{(?:[Tt]emplate:|[Mm]odèle:|)[Ss]emi[- ]?'
           r'protection(|[^\}]*)\}\}'],
    'it': [r'\{\{(?:[Tt]emplate:|)[Aa]vvisobloccoparziale'
           r'(?:|[ _]scad\|.*?|\|.*?)\}\}',
           r'\{\{(?:[Tt]emplate:|)[Aa]bp(?:|[ _]scad\|(?:.*?))\}\}'],
    'ja': [r'(?<!\<nowiki\>)\{\{(?:[Tt]emplate:|)半保護'
           r'(?:[Ss]|)(?:\|.+|)\}\}(?!\<\/nowiki\>)\s*'],
    'sr': [r'\{\{(?:[Tt]emplate:|[Зз]акључано-анон)\}\}'],
    'ur': [r'\{\{(?:[Tt]emplate:|سانچہ:|)(نیم\sمحفوظ)\}\}']
}
# Regex to get the total-protection template
templateTotalProtection = {
    'cs': [r'\{\{(?:[Tt]emplate:|[Šš]ablona:|)([Dd]louhodobě[ _]z|[Zz])'
           r'amčeno(|[^\}]*)\}\}\s*'],
    'fr': [r'\{\{(?:[Tt]emplate:|[Mm]odèle:|)[Pp]rotection(|[^\}]*)\}\}',
           r'\{\{(?:[Tt]emplate:|[Mm]odèle:|)(?:[Pp]age|[Aa]rchive|'
           r'[Mm]odèle) protégée?(|[^\}]*)\}\}'],
    'it': [r'\{\{(?:[Tt]emplate:|)[Aa]vvisoblocco(?:|[ _]scad\|(?:.*?)'
           r'|minaccia|cancellata)\}\}',
           r'\{\{(?:[Tt]emplate:|)(?:[Cc][Tt]|[Cc]anc fatte|[Cc][Ee])\}\}',
           r'<div class="toccolours[ _]itwiki[ _]template[ _]avviso">\s*?'
           r'[Qq]uesta pagina'],
    'ja': [r'(?<!\<nowiki\>)\{\{(?:[Tt]emplate:|)保護(?:性急|)'
           r'(?:[Ss]|)(?:\|.+|)\}\}(?!\<\/nowiki\>)\s*'],
    'sr': [r'\{\{(?:[Tt]emplate:|[Зз]акључано)\}\}'],
    'ur': [r'\{\{(?:[Tt]emplate:|سانچہ:|)(محفوظ)\}\}']
}

# Regex to get the semi-protection move template
templateSemiMoveProtection = {
    'it': [r'\{\{(?:[Tt]emplate:|)[Aa]vvisobloccospostamento(?:|[ _]scad\|.*?'
           r'|\|.*?)\}\}'],
    'ja': [r'(?<!\<nowiki\>)\{\{(?:[Tt]emplate:|)移動半保護'
           r'(?:[Ss]|)(?:\|.+|)\}\}(?!\<\/nowiki\>)\s*'],
}

# Regex to get the total-protection move template
templateTotalMoveProtection = {
    'it': [r'\{\{(?:[Tt]emplate:|)[Aa]vvisobloccospostamento(?:|[ _]scad\|.*?'
           r'|\|.*?)\}\}'],
    'ja': [r'(?<!\<nowiki\>)\{\{(?:[Tt]emplate:|)移動保護'
           r'(?:[Ss]|)(?:\|.+|)\}\}(?!\<\/nowiki\>)\s*'],
}

# If you use only one template for all the type of protection, put it here.
# You may use only one template or an unique template and some other "old"
# template that the script should still check (as on it.wikipedia)
templateUnique = {
    'it': [r'\{\{(?:[Tt]emplate:|)[Pp]rotetta\}\}'],
}

# Array: 0 => Semi-block, 1 => Total Block, 2 => Semi-Move, 3 => Total-Move,
#        4 => template-unique
templateNoRegex = {
    'cs': ['{{Polozamčeno}}', '{{Zamčeno}}', None, None, None],
    'fr': ['{{Semi-protection}}', '{{Protection}}', None, None, None],
    'it': ['{{Avvisobloccoparziale}}', '{{Avvisoblocco}}', None, None,
           '{{Protetta}}'],
    'ja': ['{{半保護}}', '{{保護}}', '{{移動半保護}}', '{{移動保護}}', None],
    'sr': ['{{Закључано-анон}}', '{{Закључано}}', None, None, None],
    'ur': ['{{نیم محفوظ}}', '{{محفوظ}}', None, None, None],
}

# Category where the bot will check
categoryToCheck = {
    'ar': ['تصنيف:محتويات محمية'],
    'cs': ['Kategorie:Wikipedie:Zamčené stránky',
           'Kategorie:Wikipedie:Polozamčené stránky',
           'Kategorie:Wikipedie:Dlouhodobě zamčené stránky',
           'Kategorie:Wikipedie:Dlouhodobě polozamčené stránky'],
    'fr': ['Category:Page semi-protégée', 'Category:Page protégée',
           'Catégorie:Article protégé'],
    'en': ['Category:Wikipedia protected pages'],
    'he': ['קטגוריה:ויקיפדיה: דפים מוגנים',
           'קטגוריה:ויקיפדיה: דפים מוגנים חלקית'],
    'it': ['Categoria:Pagine protette - scadute',
           'Categoria:Pagine semiprotette', 'Categoria:Voci protette'],
    'ja': ['Category:編集保護中のページ', 'Category:編集半保護中のページ',
           'Category:移動保護中のページ'],
    'pt': ['Category:!Páginas protegidas',
           'Category:!Páginas semiprotegidas'],
    'sr': ['Category:Странице закључане за анонимне кориснике',
           'Category:Закључане странице'],
    'ur': ['زمرہ:محفوظ شدہ صفحات'],
    'zh': ['Category:被保护的页面', 'Category:被保護的模板',
           'Category:暂时不能移动的页面', 'Category:被半保护的页面'],
}

# Check list to block the users that haven't set their preferences
project_inserted = ['cs', 'fr', 'it', 'ja', 'pt', 'sr', 'ur', 'zh']

# END PREFERENCES

def understandBlock(text, TTP, TSP, TSMP, TTMP, TU):
    """Understand if the page is blocked and if it has the right template."""
    if TTP:
        for catchRegex in TTP:  # TTP = templateTotalProtection
            resultCatch = re.findall(catchRegex, text)
            if resultCatch:
                return ('sysop-total', catchRegex)
    if TSP:
        for catchRegex in TSP:
            resultCatch = re.findall(catchRegex, text)
            if resultCatch:
                return ('autoconfirmed-total', catchRegex)
    if TU:
        for catchRegex in TU:
            resultCatch = re.findall(catchRegex, text)
            if resultCatch:
                return ('unique', catchRegex)
    if TSMP and TTMP and TTP != TTMP and TSP != TSMP:
        for catchRegex in TTMP:
            resultCatch = re.findall(catchRegex, text)
            if resultCatch:
                return ('sysop-move', catchRegex)
        for catchRegex in TSMP:
            resultCatch = re.findall(catchRegex, text)
            if resultCatch:
                return ('autoconfirmed-move', catchRegex)
    # If editable means that we have no regex, won't change anything with this
    # regex
    return ('editable', r'\A\n')

def showQuest(page):
    """Ask for an editor and invoke it."""
    quest = pywikibot.input_choice(
        'Do you want to open the page?',
        [('with browser', 'b'), ('with gui', 'g'), ('no', 'n')], 'n',
        automatic_quit=False)
    if quest == 'b':
        webbrowser.open('%s?redirect=no' % page.full_url())
    elif quest == 'g':
        from pywikibot import editor as editarticle
        editor = editarticle.TextEditor()
        editor.edit(page.text)

def main(*args):
    """
    Process command line arguments and perform task.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: str
    """
    # Loading the comments
    global categoryToCheck, project_inserted
    # always, define a generator to understand if the user sets one,
    # defining what's genFactory
    always = False
    generator = False
    show = False
    moveBlockCheck = False
    protectedpages = False
    protectType = 'edit'
    namespace = 0

    # Process global args and prepare generator args parser
    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()

    # Process local args
    for arg in local_args:
        option, sep, value = arg.partition(':')
        if option == '-always':
            always = True
        elif option == '-move':
            moveBlockCheck = True
        elif option == '-show':
            show = True
        elif option in ('-protectedpages', '-moveprotected'):
            protectedpages = True
            if option == '-moveprotected':
                protectType = 'move'
            if value:
                namespace = int(value)
        else:
            genFactory.handleArg(arg)

    if config.mylang not in project_inserted:
        pywikibot.output('Your project is not supported by this script.\n'
                         'You have to edit the script and add it!')
        return

    site = pywikibot.Site()

    if protectedpages:
        generator = site.protectedpages(namespace=namespace, type=protectType)
    # Take the right templates to use, the category and the comment
    TSP = i18n.translate(site, templateSemiProtection)
    TTP = i18n.translate(site, templateTotalProtection)
    TSMP = i18n.translate(site, templateSemiMoveProtection)
    TTMP = i18n.translate(site, templateTotalMoveProtection)
    TNR = i18n.translate(site, templateNoRegex)
    TU = i18n.translate(site, templateUnique)

    categories = i18n.translate(site, categoryToCheck)
    commentUsed = i18n.twtranslate(site, 'blockpageschecker-summary')
    if not generator:
        generator = genFactory.getCombinedGenerator()
    if not generator:
        generator = []
        pywikibot.output('Loading categories...')
        # Define the category if no other generator has been set
        for CAT in categories:
            cat = pywikibot.Category(site, CAT)
            # Define the generator
            gen = pagegenerators.CategorizedPageGenerator(cat)
            for pageCat in gen:
                generator.append(pageCat)
        pywikibot.output('Categories loaded, start!')
    # Main Loop
    if not genFactory.nopreload:
        generator = pagegenerators.PreloadingGenerator(generator,
                                                       groupsize=60)
    for page in generator:
        pagename = page.title(as_link=True)
        pywikibot.output('Loading %s...' % pagename)
        try:
            text = page.text
        except pywikibot.NoPage:
            pywikibot.output("%s doesn't exist! Skipping..." % pagename)
            continue
        except pywikibot.IsRedirectPage:
            pywikibot.output('{} is a redirect! Skipping...'.format(pagename))
            if show:
                showQuest(page)
            continue
        # FIXME: This check does not work :
        # PreloadingGenerator cannot set correctly page.editRestriction
        # (see bug T57322)
        # if not page.has_permission():
        #    pywikibot.output(
        #        "%s is sysop-protected : this account can't edit "
        #        "it! Skipping..." % pagename)
        #    continue
        restrictions = page.protection()
        try:
            editRestr = restrictions['edit']
        except KeyError:
            editRestr = None
        if not page.has_permission():
            pywikibot.output('%s is protected: '
                             "this account can't edit it! Skipping..."
                             % pagename)
            continue

        # Understand, according to the template in the page, what should be the
        # protection and compare it with what there really is.
        TemplateInThePage = understandBlock(text, TTP, TSP, TSMP, TTMP, TU)
        # Only to see if the text is the same or not...
        oldtext = text
        # keep track of the changes for each step (edit then move)
        changes = -1

        if not editRestr:
            # page is not edit-protected
            # Deleting the template because the page doesn't need it.
            if not (TTP or TSP):
                raise pywikibot.Error(
                    'This script is not localized to use it on \n{0}. '
                    'Missing "templateSemiProtection" or'
                    '"templateTotalProtection"'.format(site.sitename))

            if TU:
                replaceToPerform = '|'.join(TTP + TSP + TU)
            else:
                replaceToPerform = '|'.join(TTP + TSP)
            text, changes = re.subn('<noinclude>(%s)</noinclude>'
                                    % replaceToPerform, '', text)
            if changes == 0:
                text, changes = re.subn('(%s)' % replaceToPerform, '', text)
            msg = 'The page is editable for all'
            if not moveBlockCheck:
                msg += ', deleting the template..'
            pywikibot.output(msg + '.')

        elif editRestr[0] == 'sysop':
            # total edit protection
            if (TemplateInThePage[0] == 'sysop-total' and TTP) or \
               (TemplateInThePage[0] == 'unique' and TU):
                msg = 'The page is protected to the sysop'
                if not moveBlockCheck:
                    msg += ', skipping...'
                pywikibot.output(msg)
            else:
                if not TNR or TU and not TNR[4] or not (TU or TNR[1]):
                    raise pywikibot.Error(
                        'This script is not localized to use it on \n{0}. '
                        'Missing "templateNoRegex"'.format(
                            site.sitename))

                pywikibot.output('The page is protected to the sysop, but the '
                                 'template seems not correct. Fixing...')
                if TU:
                    text, changes = re.subn(TemplateInThePage[1], TNR[4], text)
                else:
                    text, changes = re.subn(TemplateInThePage[1], TNR[1], text)

        elif TSP or TU:
            # implicitly editRestr[0] = 'autoconfirmed', edit-Semi-protection
            if TemplateInThePage[0] == 'autoconfirmed-total' or \
               TemplateInThePage[0] == 'unique':
                msg = 'The page is editable only for the autoconfirmed users'
                if not moveBlockCheck:
                    msg += ', skipping...'
                pywikibot.output(msg)
            else:
                if not TNR or TU and not TNR[4] or not (TU or TNR[1]):
                    raise pywikibot.Error(
                        'This script is not localized to use it on \n{0}. '
                        'Missing "templateNoRegex"'.format(
                            site.sitename))
                pywikibot.output('The page is editable only for the '
                                 'autoconfirmed users, but the template '
                                 'seems not correct. Fixing...')
                if TU:
                    text, changes = re.subn(TemplateInThePage[1], TNR[4], text)
                else:
                    text, changes = re.subn(TemplateInThePage[1], TNR[0], text)

        if changes == 0:
            # We tried to fix edit-protection templates, but it did not work.
            pywikibot.warning('No edit-protection template could be found')

        if moveBlockCheck and changes > -1:
            # checking move protection now
            try:
                moveRestr = restrictions['move']
            except KeyError:
                moveRestr = False
            changes = -1

            if not moveRestr:
                pywikibot.output('The page is movable for all, deleting the '
                                 'template...')
                # Deleting the template because the page doesn't need it.
                if TU:
                    replaceToPerform = '|'.join(TSMP + TTMP + TU)
                else:
                    replaceToPerform = '|'.join(TSMP + TTMP)
                text, changes = re.subn('<noinclude>(%s)</noinclude>'
                                        % replaceToPerform, '', text)
                if changes == 0:
                    text, changes = re.subn('({})'.format(replaceToPerform),
                                            '', text)
            elif moveRestr[0] == 'sysop':
                # move-total-protection
                if (TemplateInThePage[0] == 'sysop-move' and TTMP) or \
                   (TemplateInThePage[0] == 'unique' and TU):
                    pywikibot.output('The page is protected from moving to '
                                     'the sysop, skipping...')
                    if TU:
                        # no changes needed, better to revert the old text.
                        text = oldtext
                else:
                    pywikibot.output('The page is protected from moving to '
                                     'the sysop, but the template seems not '
                                     'correct. Fixing...')
                    if TU:
                        text, changes = re.subn(TemplateInThePage[1], TNR[4],
                                                text)
                    else:
                        text, changes = re.subn(TemplateInThePage[1], TNR[3],
                                                text)

            elif TSMP or TU:
                # implicitly moveRestr[0] = 'autoconfirmed',
                # move-semi-protection
                if TemplateInThePage[0] == 'autoconfirmed-move' or \
                   TemplateInThePage[0] == 'unique':
                    pywikibot.output('The page is movable only for the '
                                     'autoconfirmed users, skipping...')
                    if TU:
                        # no changes needed, better to revert the old text.
                        text = oldtext
                else:
                    pywikibot.output('The page is movable only for the '
                                     'autoconfirmed users, but the template '
                                     'seems not correct. Fixing...')
                    if TU:
                        text, changes = re.subn(TemplateInThePage[1], TNR[4],
                                                text)
                    else:
                        text, changes = re.subn(TemplateInThePage[1], TNR[2],
                                                text)

            if changes == 0:
                # We tried to fix move-protection templates but it did not work
                pywikibot.warning('No move-protection template could be found')

        if oldtext != text:
            # Ok, asking if the change has to be performed and do it if yes.
            pywikibot.output(color_format(
                '\n\n>>> {lightpurple}{0}{default} <<<', page.title()))
            pywikibot.showDiff(oldtext, text)
            if not always:
                choice = pywikibot.input_choice('Do you want to accept these '
                                                'changes?',
                                                [('Yes', 'y'), ('No', 'n'),
                                                 ('All', 'a')], 'n')
                if choice == 'a':
                    always = True
            if always or choice == 'y':
                save_page(page, text, commentUsed)

def save_page(page, text, comment):
    """Save a given page."""
    # To prevent Infinite loops
    error_count = 0
    while True:
        try:
            page.put(text, comment, force=True)
        except pywikibot.EditConflict:
            pywikibot.output('Edit conflict! skip!')
        except pywikibot.ServerError:
            # Sometimes there is this error that's quite annoying
            # because can block the whole process for nothing.
            error_count += 1
            if error_count < 5:
                pywikibot.output('Server Error! Wait..')
                time.sleep(3)
                continue
            else:
                # Prevent Infinite Loops
                raise pywikibot.ServerError('Fifth Server Error!')
        except pywikibot.SpamfilterError as e:
            pywikibot.output('Cannot change %s because of '
                             'blacklist entry %s'
                             % (page.title(), e.url))
        except pywikibot.LockedPage:
            pywikibot.output('The page is still protected. '
                             'Skipping...')
        except pywikibot.PageNotSaved as error:
            pywikibot.output('Error putting page: %s'
                             % (error.args,))
        break

if __name__ == '__main__':
    main()


text:
#import "NSObject-Protocol.h"

@protocol IDEUnitTestsObserver <NSObject>
- (void)testOperationGroupDidFinish;
- (void)testOperation:(id)arg1 willFinishWithSuccess:(BOOL)arg2 withError:(id)arg3;
- (void)testSuiteDidFinish:(long long)arg1 withFailures:(long long)arg2 unexpected:(long long)arg3 testDuration:(double)arg4 totalDuration:(double)arg5 rawOutput:(id)arg6;
- (void)testSuite:(id)arg1 willFinishAt:(id)arg2 rawOutput:(id)arg3;
- (void)testDidOutput:(id)arg1;
- (void)testCaseDidProducePerformanceOutput:(id)arg1 rawOutput:(id)arg2;
- (void)testCaseDidFailForTestClass:(id)arg1 method:(id)arg2 withMessage:(id)arg3 file:(id)arg4 line:(long long)arg5 rawOutput:(id)arg6;
- (void)testCaseDidFinishForTestClass:(id)arg1 method:(id)arg2 withStatus:(id)arg3 duration:(double)arg4 rawOutput:(id)arg5;
- (void)testCaseDidStartForTestClass:(id)arg1 method:(id)arg2 rawOutput:(id)arg3;
- (void)testSuite:(id)arg1 didStartAt:(id)arg2 rawOutput:(id)arg3;
- (void)testOperationDidStartExecution:(id)arg1;
@end


text:
using System;
using System.Diagnostics;
using GSD.Models;

namespace GSD.ViewModels
{
	internal class TodoTagViewModel : ViewModelBaseEx
	{
		public TodoTagViewModel( Tag tag )
		{
			Model = tag;
		}

		public event EventHandler Deselected;

		public event EventHandler Selected;

		public bool IsSelected
		{
			[DebuggerStepThrough]
			get
			{
				return _IsSelected;
			}
			set
			{
				if( _IsSelected == value )
				{
					return;
				}

				_IsSelected = value;
				RaisePropertyChanged();

				if( value )
				{
					Selected?.Invoke( this, EventArgs.Empty );
				}
				else
				{
					Deselected?.Invoke( this, EventArgs.Empty );
				}
			}
		}

		public Tag Model { get; }

		[DebuggerBrowsable( DebuggerBrowsableState.Never )]
		private bool _IsSelected;
	}
}


text:
package api

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

	"github.com/docker/notary/signer"
	"github.com/docker/notary/signer/keys"
	"github.com/endophage/gotuf/data"
	"github.com/gorilla/mux"

	pb "github.com/docker/notary/proto"
)

// Handlers sets up all the handers for the routes, injecting a specific SigningService object for them to use
func Handlers(sigServices signer.SigningServiceIndex) *mux.Router {
	r := mux.NewRouter()

	r.Methods("GET").Path("/{ID}").Handler(KeyInfo(sigServices))
	r.Methods("POST").Path("/new/{Algorithm}").Handler(CreateKey(sigServices))
	r.Methods("POST").Path("/delete").Handler(DeleteKey(sigServices))
	r.Methods("POST").Path("/sign").Handler(Sign(sigServices))
	return r
}

// getSigningService handles looking up the correct signing service, given the
// algorithm specified in the HTTP request. If the algorithm isn't specified
// or isn't supported, an error is returned to the client and this function
// returns a nil SigningService
func getSigningService(w http.ResponseWriter, algorithm string, sigServices signer.SigningServiceIndex) signer.SigningService {
	if algorithm == "" {
		http.Error(w, "algorithm not specified", http.StatusBadRequest)
		return nil
	}

	service := sigServices[data.KeyAlgorithm(algorithm)]

	if service == nil {
		http.Error(w, "algorithm "+algorithm+" not supported", http.StatusBadRequest)
		return nil
	}

	return service
}

// KeyInfo returns a Handler that given a specific Key ID param, returns the public key bits of that key
func KeyInfo(sigServices signer.SigningServiceIndex) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)

		key, _, err := FindKeyByID(sigServices, &pb.KeyID{ID: vars["ID"]})
		if err != nil {
			switch err {
			// If we received an ErrInvalidKeyID, the key doesn't exist, return 404
			case keys.ErrInvalidKeyID:
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte(err.Error()))
				return
			// If we received anything else, it is unexpected, and we return a 500
			default:
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
				return
			}
		}
		json.NewEncoder(w).Encode(key)
		return
	})
}

// CreateKey returns a handler that generates a new
func CreateKey(sigServices signer.SigningServiceIndex) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		sigService := getSigningService(w, vars["Algorithm"], sigServices)
		if sigService == nil {
			// Error handled inside getSigningService
			return
		}

		key, err := sigService.CreateKey()
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}
		json.NewEncoder(w).Encode(key)
		return
	})
}

// DeleteKey returns a handler that delete a specific KeyID
func DeleteKey(sigServices signer.SigningServiceIndex) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var keyID *pb.KeyID
		err := json.NewDecoder(r.Body).Decode(&keyID)
		defer r.Body.Close()
		if err != nil || keyID.ID == "" {
			w.WriteHeader(http.StatusBadRequest)
			jsonErr, _ := json.Marshal("Malformed request")
			w.Write([]byte(jsonErr))
			return
		}

		_, sigService, err := FindKeyByID(sigServices, keyID)

		if err != nil {
			switch err {
			// If we received an ErrInvalidKeyID, the key doesn't exist, return 404
			case keys.ErrInvalidKeyID:
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte(err.Error()))
				return
			// If we received anything else, it is unexpected, and we return a 500
			default:
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
				return
			}
		}

		_, err = sigService.DeleteKey(keyID)

		if err != nil {
			switch err {
			// If we received an ErrInvalidKeyID, the key doesn't exist, return 404
			case keys.ErrInvalidKeyID:
				w.WriteHeader(http.StatusNotFound)
				w.Write([]byte(err.Error()))
				return
			// If we received anything else, it is unexpected, and we return a 500
			default:
				w.WriteHeader(http.StatusInternalServerError)
				w.Write([]byte(err.Error()))
				return
			}
		}
		// In case we successfully delete this key, return 200
		return
	})
}

// Sign returns a handler that is able to perform signatures on a given blob
func Sign(sigServices signer.SigningServiceIndex) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var sigRequest *pb.SignatureRequest
		err := json.NewDecoder(r.Body).Decode(&sigRequest)
		defer r.Body.Close()
		if err != nil || sigRequest.Content == nil ||
			sigRequest.KeyID == nil {
			w.WriteHeader(http.StatusBadRequest)
			jsonErr, _ := json.Marshal("Malformed request")
			w.Write([]byte(jsonErr))
			return
		}

		_, sigService, err := FindKeyByID(sigServices, sigRequest.KeyID)
		if err == keys.ErrInvalidKeyID {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(err.Error()))
			return
		} else if err != nil {
			// We got an unexpected error
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}

		signer, err := sigService.Signer(sigRequest.KeyID)
		if err == keys.ErrInvalidKeyID {
			w.WriteHeader(http.StatusNotFound)
			w.Write([]byte(err.Error()))
			return
		} else if err != nil {
			// We got an unexpected error
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}

		signature, err := signer.Sign(sigRequest)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte(err.Error()))
			return
		}

		json.NewEncoder(w).Encode(signature)
		return
	})
}