text:
#include "light.h"
#include "scene.h"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_access.hpp"
#include "objects/components/shadow_map.h"
#include "objects/textures/render_texture.h"

namespace gvr
{
    Light::~Light()
    { }

    void Light::onAddedToScene(Scene *scene)
    {
        scene->addLight(this);
    }

    void Light::onRemovedFromScene(Scene *scene)
    {
        scene->removeLight(this);
    }

    ShadowMap* Light::getShadowMap()
    {
        SceneObject* owner = owner_object();
        ShadowMap* shadowMap = nullptr;

        if (owner == nullptr)
        {
            return nullptr;
        }
        shadowMap = (ShadowMap*) owner->getComponent(RenderTarget::getComponentType());
        if ((shadowMap != nullptr) &&
            shadowMap->enabled() &&
            (shadowMap->getCamera() != nullptr))
        {
            return shadowMap;
        }
        return nullptr;
    }

    bool Light::makeShadowMap(Scene* scene, jobject javaSceneObject, ShaderManager* shader_manager, int layerIndex)
    {
        ShadowMap* shadowMap = getShadowMap();
        float shadow_map_index = -1;
        getFloat("shadow_map_index", shadow_map_index);
        if ((shadowMap == nullptr) || !shadowMap->hasTexture())
        {
            if (shadow_map_index >= 0)
            {
                setFloat("shadow_map_index", -1);
#ifdef DEBUG_LIGHT
                LOGD("LIGHT: %s shadow_map_index = %f", getLightClass(), shadow_map_index);
#endif
            }
            return false;
        }
        else if (shadow_map_index != layerIndex)
        {
            #ifdef DEBUG_LIGHT
                LOGD("LIGHT: %s shadow_map_index = %d", getLightClass(), layerIndex);
            #endif
            setFloat("shadow_map_index", (float) layerIndex);
        }
        Renderer* renderer = gRenderer->getInstance();
        shadowMap->setLayerIndex(layerIndex);
        shadowMap->setMainScene(scene);
        shadowMap->cullFromCamera(scene, javaSceneObject, shadowMap->getCamera(),renderer, shader_manager);

        renderer->renderRenderTarget(scene, javaSceneObject, shadowMap,shader_manager, nullptr, nullptr);

        return true;
    }

    int Light::makeShaderLayout(std::string& layout)
    {
        std::ostringstream stream;

        forEachUniform([&stream, this](const DataDescriptor::DataEntry& entry) mutable
        {
            int nelems = entry.Count;
            if (nelems > 1)
                stream << entry.Type << " " << entry.Name << "[" << nelems << "];" << std::endl;
            else
                stream << entry.Type << " " << entry.Name << ";" << std::endl;
        });
        layout = stream.str();
        return uniforms().uniforms().getTotalSize();
    }

    void Light::updateLayout()
    {

    }

}


text: DEFAULT DETAIL SETTINGS

redpajama_set_name: RedPajamaGithub


text:
title: How to Start a JavaScript Synthpop Band
author: lon
layout: post
categories:
- posts
- meetups
when: 2017-10-17T19:30:00-05:00
---

{% assign speakr = 'J. Kyle Fagan' %}
{% assign handle = 'jkyle' %}
{% assign twiturl = 'https://twitter.com/jkyle' %}

Synthesizers! JavaScript! Aleatoricism?? Using an actual analog synthesizer as a
guide, Kyle will build a feature-for-feature replica in the browser with the Web
Audio API and show how to use JavaScript to overcome a lack of musical training.
You'll learn the capabilities and limitations of the Web Audio API, and how it
can be used for applications like gaming, WebVR, and 80s retro synthwave. With
live coding, live synth playing, and a touch of music theory, what could go wrong?

Our speaker

  {{speakr}}
  is an Austin local and writes javascript for Eduphoria.
  He's an aspirational artist, aspirational musician, and aspirational cool dad.

Make sure to thank our gracious hosts [Spredfast][], and our sponsors
 +[eRelevance][] for the food and drinks!

{% include give-em-the-business.html location='spredfast' %}

[Spredfast]: https://www.spredfast.com/
[eRelevance]: http://www.erelevancecorp.com/careers/


text:
{% extends "../../layout_search.html" %}

{% block page_title %}
  Service Green
{% endblock %}

{% block content %}

Home

Computer games developer
	                Computer games designer, video games designer

Computer games developers make games for the internet, mobile phones, PCs and games consoles.

                        Salary:
                        £19,000 to £70,000
                        per year

                        Hours:
                        30 to 40
                        per week

                                    How to become a computer games developer

                                    Skills

                                    What you'll do

                                    Salary

                                    Working hours, patterns and environment

                                    Career path and progression

                                	Current opportunities

                        5. Working hours, patterns and environment

                    Working hours in the computer games industry can vary. In many jobs you'll work standard office hours, with some unsocial hours (such as evenings and weekends) and overtime to meet deadlines.

                    You could be based in an office or a studio, depending on your role. You'll spend most of your time sitting at a computer.

				    Useful links

			                Find a course

			                Apprenticeships

			                Thinking about university

			                Help with funding

			                Become a volunteer

{% endblock %}


text:
from django.http import FileResponse
from rest_framework import generics, permissions
from rest_framework.reverse import reverse

from collectionjson import services
from core.renderers import BinaryFileRenderer

from .models import PACSFile, PACSFileFilter
from .serializers import PACSFileSerializer
from .permissions import IsChrisOrReadOnly

class PACSFileList(generics.ListCreateAPIView):
    """
    A view for the collection of PACS files.
    """
    http_method_names = ['get', 'post']
    queryset = PACSFile.objects.all()
    serializer_class = PACSFileSerializer
    permission_classes = (permissions.IsAuthenticated, IsChrisOrReadOnly,)

    def list(self, request, *args, **kwargs):
        """
        Overriden to append document-level link relations and a collection+json
        template to the response.
        """
        response = super(PACSFileList, self).list(request, *args, **kwargs)
        # append query list
        query_list = [reverse('pacsfile-list-query-search', request=request)]
        response = services.append_collection_querylist(response, query_list)
        # append write template
        template_data = {'path': '', 'PatientID': '', 'PatientName': '',
                         'PatientBirthDate': '', 'PatientAge': '', 'PatientSex': '',
                         'StudyDate': '', 'AccessionNumber': '', 'Modality': '',
                         'ProtocolName': '', 'StudyInstanceUID': '',
                         'StudyDescription': '', 'SeriesInstanceUID': '',
                         'SeriesDescription': '', 'pacs_name': ''}
        return services.append_collection_template(response, template_data)

    def create(self, request, *args, **kwargs):
        """
        Overriden to remove computed descriptors from the request if submitted.
        """
        self.request.data.pop('fname', None)
        return super(PACSFileList, self).create(request, *args, **kwargs)

class PACSFileListQuerySearch(generics.ListAPIView):
    """
    A view for the collection of PACS files resulting from a query search.
    """
    http_method_names = ['get']
    serializer_class = PACSFileSerializer
    queryset = PACSFile.objects.all()
    permission_classes = (permissions.IsAuthenticated,)
    filterset_class = PACSFileFilter

class PACSFileDetail(generics.RetrieveAPIView):
    """
    A PACS file view.
    """
    http_method_names = ['get']
    queryset = PACSFile.objects.all()
    serializer_class = PACSFileSerializer
    permission_classes = (permissions.IsAuthenticated,)

class PACSFileResource(generics.GenericAPIView):
    """
    A view to enable downloading of a file resource .
    """
    http_method_names = ['get']
    queryset = PACSFile.objects.all()
    renderer_classes = (BinaryFileRenderer,)
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, *args, **kwargs):
        """
        Overriden to be able to make a GET request to an actual file resource.
        """
        pacs_file = self.get_object()
        return FileResponse(pacs_file.fname)


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DAL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Paulo
 */
public class ProdutoDAO {
    private Connection con;

    public ProdutoDAO() {
        con = new DataSource().getCon();
    }

    public void inserir(Produto obj, int quantidade) {
        PreparedStatement stm;

        try
        {
            stm = con.prepareStatement("INSERT INTO produto (nome, descricao, foto, valor) VALUES (?, ?, ?, ?)");
            stm.setString(1, obj.getNome());
            stm.setString(2, obj.getDescricao());
            stm.setString(3, obj.getFoto());
            stm.setDouble(4, obj.getValor());
            stm.execute();

            new EstoqueDAO().inserir(obj, quantidade);
        } catch (SQLException e) {
            System.err.println("Falha na insercao");
            System.err.println(e);
            System.exit(1);
        }
    }

    public Produto selecionar(int codigo) {
        Produto res = new Produto();

        try {
            PreparedStatement stm = con.prepareStatement("SELECT nome, descricao, foto, valor FROM produto WHERE codigo = ?");
            stm.setInt(1, codigo);
            ResultSet rs = stm.executeQuery();

            rs.next();

            res.setNome(rs.getString("nome"));
            res.setDescricao(rs.getString("descricao"));
            res.setCodigo(codigo);
            res.setFoto(rs.getString("foto"));
            res.setValor(rs.getDouble("valor"));
        } catch (SQLException e) {
            System.err.println("Falha ao selecionar o produto.");
            System.err.println(e);
            System.exit(1);
        }

        return res;
    }
}


text:
namespace Security.HMAC
{
    using System;
    using Microsoft.Owin.Security;

    public class HmacAuthenticationOptions : AuthenticationOptions
    {
        public HmacAuthenticationOptions(ISigningAlgorithm algorithm, ISecretRepository secretRepository, string signInAsAuthenticationType = Schemas.HMAC)
            : base(Schemas.HMAC)
        {
            Algorithm = algorithm;
            SecretRepository = secretRepository;
            SignInAsAuthenticationType = signInAsAuthenticationType;
        }

        public ISigningAlgorithm Algorithm { get; set; }
        public ISecretRepository SecretRepository { get; set; }
        public ITime Time { get; set; } = SystemTime.Instance;
        public TimeSpan ClockSkew { get; set; } = Constants.DefaultClockSkew;
        public MapUserClaimsDelegate MapClaims { get; set; }
        public string SignInAsAuthenticationType { get; set; }
    }
}


text:
package com.doodeec.utils.network;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.doodeec.utils.network.listener.BaseRequestListener;

import java.io.InputStream;
import java.util.Arrays;

/**
 * Server request for Image resource
 * {@link android.os.AsyncTask} wrapper around {@link java.net.HttpURLConnection}
 * Can be executed with {@link #THREAD_POOL_EXECUTOR} to evaluate requests in parallel
 *
 * @author dusan.bartos
 * @see com.doodeec.utils.network.BaseServerRequest
 * @see com.doodeec.utils.network.listener.JSONRequestListener
 * @see RequestError
 */
@SuppressWarnings("unused")
public class ImageServerRequest extends BaseServerRequest<Bitmap, Bitmap> {

    // response types
    private static final String[] IMAGE_RESPONSE = new String[]{"image/png", "image/jpg", "image/jpeg"};

    /**
     * Request listener
     *
     * @see com.doodeec.utils.network.listener.JSONRequestListener
     */
    protected BaseRequestListener<Bitmap> mListener;

    public ImageServerRequest(RequestType type, BaseRequestListener<Bitmap> listener) {
        super(type);
        mListener = listener;
    }

    @Override
    protected Bitmap processInputStream(String contentType, InputStream inputStream) {
        if (Arrays.asList(IMAGE_RESPONSE).contains(contentType)) {
            // decoding stream data back into image Bitmap that android understands
            return BitmapFactory.decodeStream(inputStream);
        } else {
            return null;
        }
    }

    @Override
    protected Bitmap instantiateStream(Bitmap bitmap) {
        return bitmap;
    }

    @Override
    protected void onPostExecute(CommunicatorResponse<Bitmap> response) {
        if (response.isIntercepted()) {
            //do nothing
            if (sDebugEnabled) {
                Log.d(getClass().getSimpleName(), "Response intercepted. Not proceeding to response listener");
            }
        } else if (response.hasError()) {
            mListener.onError(response.getError());
        } else if (response.getData() != null) {
            // POST can have empty response, but 200 response code
            mListener.onSuccess(response.getData());
        } else {
            mListener.onError(new RequestError("Response bitmap empty", response.getUrl()));
        }
    }

    @Override
    public ImageServerRequest cloneRequest() {
        ImageServerRequest clonedRequest = new ImageServerRequest(mType, mListener);
        clonedRequest.mTimeout = mTimeout;
        clonedRequest.mReadTimeout = mReadTimeout;
        clonedRequest.mRequestHeaders = mRequestHeaders;
        return clonedRequest;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        mListener.onProgress(values[0]);
    }

    @Override
    protected void onCancelled() {
        mListener.onCancelled();
    }
}


text:
package io.github.gernd.sqaas;

import io.github.gernd.sqaas.model.QuoteEntity;
import io.github.gernd.sqaas.model.QuoteRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Initializes all quotes
 */
@Component
@Slf4j
public class QuoteInitializer implements ApplicationRunner {

    @Autowired
    private QuoteRepository quoteRepository;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {

        List<QuoteEntity> predefinedQuotes = Arrays.asList(
                QuoteEntity.builder().quote("Premature optimzation is the root of all evil").author("Donald Knuth").build(),
                QuoteEntity.builder().quote("YAGNI").author("Unknown").build(),
                QuoteEntity.builder().quote("Untested code does not exist").author("Unknown").build()
        );

        predefinedQuotes.forEach(q -> log.info("Adding quote {} by {}", q.getQuote(), q.getAuthor()));
        quoteRepository.save(predefinedQuotes);
    }
}


text:
package com.izforge.izpack.gui;

import javax.swing.plaf.ColorUIResource;

/**
 * The IzPack Kunststoff L&F theme.
 *
 * @author Julien Ponge
 */
@Deprecated
public class IzPackKMetalTheme extends IzPackMetalTheme
{

    /**
     * Primary color.
     */
    private final ColorUIResource primary1 = new ColorUIResource(32, 32, 64);

    /**
     * Primary color.
     */
    private final ColorUIResource primary2 = new ColorUIResource(160, 160, 180);

    /**
     * Primary color.
     */
    private final ColorUIResource primary3 = new ColorUIResource(200, 200, 224);

    /**
     * Secondary color.
     */
    private final ColorUIResource secondary1 = new ColorUIResource(130, 130, 130);

    /**
     * Secondary color.
     */
    private final ColorUIResource secondary2 = new ColorUIResource(180, 180, 180);

    /**
     * Secondary color.
     */
    private final ColorUIResource secondary3 = new ColorUIResource(224, 224, 224);

    /**
     * The constructor.
     */
    public IzPackKMetalTheme()
    {
        super();
    }

    /**
     * Returns the wished color.
     *
     * @return The wished color.
     */
    public ColorUIResource getPrimary1()
    {
        return primary1;
    }

    /**
     * Returns the wished color.
     *
     * @return The wished color.
     */
    public ColorUIResource getPrimary2()
    {
        return primary2;
    }

    /**
     * Returns the wished color.
     *
     * @return The wished color.
     */
    public ColorUIResource getPrimary3()
    {
        return primary3;
    }

    /**
     * Returns the wished color.
     *
     * @return The wished color.
     */
    public ColorUIResource getSecondary1()
    {
        return secondary1;
    }

    /**
     * Returns the wished color.
     *
     * @return The wished color.
     */
    public ColorUIResource getSecondary2()
    {
        return secondary2;
    }

    /**
     * Returns the wished color.
     *
     * @return The wished color.
     */
    public ColorUIResource getSecondary3()
    {
        return secondary3;
    }
}


text:
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var __decorate = this.__decorate || function (decorators, target, key, value) {
    var kind = typeof (arguments.length == 2 ? value = target : value);
    for (var i = decorators.length - 1; i >= 0; --i) {
        var decorator = decorators[i];
        switch (kind) {
            case "function": value = decorator(value) || value; break;
            case "number": decorator(target, key, value); break;
            case "undefined": decorator(target, key); break;
            case "object": value = decorator(target, key, value) || value; break;
        }
    }
    return value;
};
var vm_turn_zone_1 = require('angular2/src/core/zone/vm_turn_zone');
var MockVmTurnZone = (function (_super) {
    __extends(MockVmTurnZone, _super);
    function MockVmTurnZone() {
        _super.call(this, { enableLongStackTrace: false });
    }
    MockVmTurnZone.prototype.run = function (fn) {
        fn();
    };
    MockVmTurnZone.prototype.runOutsideAngular = function (fn) {
        fn();
    };
    return MockVmTurnZone;
})(vm_turn_zone_1.VmTurnZone);
exports.MockVmTurnZone = MockVmTurnZone;


text:
package com.robomigos.squadgames.robomigos.Scenes;

import com.framework.Input;
import com.framework.Pixmap;
import com.framework.Screen;
import com.framework.Game;
import com.framework.Graphics;
import com.robomigos.squadgames.robomigos.Button;

import java.util.List;

/**
 * Created by Carlo Albino on 2016-11-14.
 */

public class ReleaseScreen extends Screen {

    private static Pixmap background;
    private static Pixmap yesButtonImage;
    private static Pixmap noButtonImage;

    private Button yesButton;
    private Button noButton;

    public ReleaseScreen(Game game)
    {
        super(game);
        Graphics g = game.getGraphics();

        // Load the bitmaps
        background = g.newPixmap("ReleaseScreenBackground.png", Graphics.PixmapFormat.RGB565);   // RGB565 non - transparent
        yesButtonImage = g.newPixmap("YesButton.png", Graphics.PixmapFormat.ARGB4444);        // ARGB4444 transparent
        noButtonImage = g.newPixmap("NoButton.png", Graphics.PixmapFormat.ARGB4444);

        // Get the background to screen ratio
        bgToScreenRatio = (float)g.getHeight() / (float)background.getHeight(); // Have this line in each screen constructor after background is set

        // Create buttons
        yesButton = new Button(g, yesButtonImage, yesButtonImage, 30, 50, 0, 0, g.getWidth(), g.getHeight(), bgToScreenRatio);
        noButton = new Button(g, noButtonImage, noButtonImage, 30, yesButton.Bottom() + 5, 0, 0, g.getWidth(), g.getHeight(), bgToScreenRatio);

    }

    @Override
    public void update(float deltaTime) {
        List<Input.TouchEvent> touchEvents = game.getInput().getTouchEvents();

        int len = touchEvents.size();
        for (int i = 0; i < len; i++)
        {
            Input.TouchEvent event = touchEvents.get(i);
            if(event.type == Input.TouchEvent.TOUCH_UP)
            {
                if(yesButton.IsInBounds(event))
                {
                    game.getData().ResetAll(game.getFileIO());
                    game.setScreen(new TitleScreen(game));
                    return;
                }

                if(noButton.IsInBounds(event))
                {
                    // Do stuff
                    game.setScreen(new ChooseBattleScreen(game));
                    return;
                }

            }
        }
    }

    @Override
    public void present(float deltaTime) {
        Graphics g = game.getGraphics();
        g.drawPixmap(background, 0, 0, 100, 100, 0, 0, background.getWidth(), background.getHeight(), g.getWidth(), g.getHeight());
        yesButton.Draw();
        noButton.Draw();
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void dispose() {

    }
}


text:
//
//  MGSColourSchemeController.m
//  Fragaria
//
//  Created by Jim Derry on 3/16/15.
//
//

#import "MGSColourSchemeController.h"
#import "MGSColourScheme.h"
#import "MGSColourSchemeSaveController.h"

#pragma mark - Constants

NSString * const KMGSColourSchemesFolder = @"Colour Schemes";
NSString * const KMGSColourSchemeExt = @"plist";

#pragma mark - Category

@interface MGSColourSchemeController ()

@property (nonatomic, strong, readwrite) NSMutableArray *colourSchemes;

@property (nonatomic, strong) MGSColourScheme *currentScheme;
@property (nonatomic, assign) BOOL currentSchemeIsCustom;

@property (nonatomic, assign) BOOL ignoreObservations;

@property (nonatomic, strong) MGSColourSchemeSaveController *saveController;

@end

#pragma mark - Implementation

@implementation MGSColourSchemeController

#pragma mark - Initialization and Startup

/*
 *  - awakeFromNib
 */
- (void)awakeFromNib
{
    /* The objectController that gets its data from MGSUserDefaults
       might not be connected to any data, so we don't want to do too much
       while we wait for it to connect by monitoring it via KVO. */

    [self setupEarly];
}

/*
 * - dealloc
 */
- (void)dealloc
{
    [self teardownObservers];
}

/*
 * - setupEarly
 */
- (void)setupEarly
{
    /* Load our schemes and get them ready for use. */
	[self loadColourSchemes];

    [self setSortDescriptors:@[ [[NSSortDescriptor alloc] initWithKey:@"displayName"
                                                            ascending:YES
                                                             selector:@selector(localizedCaseInsensitiveCompare:)]
                                ]];

    [self setContent:self.colourSchemes];

    /* Listen for the objectController to connect, if it didn't already */
    if (!self.objectController.content)
        [self addObserver:self forKeyPath:@"objectController.content" options:NSKeyValueObservingOptionNew context:@"objectController"];
    else
        [self setupLate];
}

/*
 * - setupLate
 */
- (void)setupLate
{
    /* Setup observation of the properties of the connected outlets. */
    [self setupObservers];

    /* Set our current scheme based on the view settings. */
    self.currentScheme = [self makeColourSchemeFromViewForScheme:nil];

    /* If the current scheme matches an existing theme, then set it. */
    [self findAndSetCurrentScheme];
}

#pragma mark - Properties

/*
 * @property buttonSaveDeleteEnabled
 */
+ (NSSet *)keyPathsForValuesAffectingButtonSaveDeleteEnabled
{
    return [NSSet setWithArray:@[ @"self.selectionIndex", @"self.currentScheme", @"self.schemeMenu.selectedObject", @"self.currentScheme.loadedFromBundle" ]];
}
- (BOOL)buttonSaveDeleteEnabled
{
    BOOL result;
    result = self.currentScheme && !self.currentScheme.loadedFromBundle;
    result = result || self.currentSchemeIsCustom;

    return result;
}

/*
 * @property buttonSaveDeleteTitle
 */
+ (NSSet *)keyPathsForValuesAffectingButtonSaveDeleteTitle
{
    return [NSSet setWithArray:@[ @"self.selectionIndex", @"self.currentScheme", @"self.schemeMenu.selectedObject", @"self.currentScheme.loadedFromBundle" ]];
}
- (NSString *)buttonSaveDeleteTitle
{
    // Rules:
    // - If the current scheme is self.currentSchemeIsCustom, can save.
    // - If the current scheme is not built-in, can delete.
    // - Otherwise the button should read as saving (will be disabled).

    if ( self.currentSchemeIsCustom || self.currentScheme.loadedFromBundle)
    {
        return NSLocalizedStringFromTableInBundle(@"Save Scheme…", nil, [NSBundle bundleForClass:[self class]],  @"The text for the save/delete scheme button when it should read Save Scheme…");
    }

    return NSLocalizedStringFromTableInBundle(@"Delete Scheme…", nil, [NSBundle bundleForClass:[self class]],  @"The text for the save/delete scheme button when it should read Delete Scheme…");
}

#pragma mark - Actions

/*
 * - addDeleteButtonAction
 */
- (IBAction)addDeleteButtonAction:(id)sender
{
    // Rules:
    // - If the current scheme is self.currentSchemeIsCustom, will save.
    // - If the current scheme is not built-in, will delete.
    // - Otherwise someone forgot to bind to the enabled property properly.

    if (self.currentSchemeIsCustom)
    {
        __block NSString *path = [self applicationSupportDirectory];
        path = [path stringByAppendingPathComponent:KMGSColourSchemesFolder];

        [[NSFileManager defaultManager] createDirectoryAtPath: path
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:nil];

        self.saveController = [[MGSColourSchemeSaveController alloc] init];
        self.saveController.schemeName = NSLocalizedStringFromTableInBundle(@"New Scheme", nil, [NSBundle bundleForClass:[self class]],  @"Default name for new schemes.");

        [self.saveController showSchemeNameGetter:self.parentView.window completion:^void (BOOL confirmed) {
            if (confirmed)
            {
                path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@",self.saveController.fileName, KMGSColourSchemeExt]];
                self.currentScheme.displayName = self.saveController.schemeName;
                [self.currentScheme propertiesSaveToFile:path];
                [self willChangeValueForKey:@"buttonSaveDeleteEnabled"];
                [self willChangeValueForKey:@"buttonSaveDeleteTitle"];
                self.currentSchemeIsCustom = NO;
                [self didChangeValueForKey:@"buttonSaveDeleteEnabled"];
                [self didChangeValueForKey:@"buttonSaveDeleteTitle"];

            }
        }];
    }
    else if (!self.currentScheme.loadedFromBundle)
    {
        self.saveController = [[MGSColourSchemeSaveController alloc] init];
        [self.saveController showDeleteConfirmation: self.parentView.window completion:^void (BOOL confirmed) {
            if (confirmed)
            {
                NSError *error;
                [[NSFileManager defaultManager] removeItemAtPath:self.currentScheme.sourceFile error:&error];
                if (error)
                {
                    NSLog(@"%@", error);
                }
                [self removeObject:self.currentScheme];
            }
        }];
    }

}

#pragma mark - KVO/KVC

/*
 * -setupObservers
 */
- (void)setupObservers
{
    for (NSString *key in [[MGSColourScheme class] propertiesOfScheme])
    {
        if ([[self.objectController.content allKeys] containsObject:key])
        {
            NSString *keyPath = [NSString stringWithFormat:@"selection.%@", key];
            [self.objectController addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:(__bridge void *)(key)];
        }
    }

    [self addObserver:self forKeyPath:@"selectionIndex" options:NSKeyValueObservingOptionNew context:@"schemeMenu"];
}

/*
 * - teardownObservers
 */
- (void)teardownObservers
{
    for (NSString *key in [[MGSColourScheme class] propertiesOfScheme])
    {
        if ([[self.objectController.content allKeys] containsObject:key])
        {
            NSString *keyPath = [NSString stringWithFormat:@"selection.%@", key];
            [self.objectController removeObserver:self forKeyPath:keyPath context:(__bridge void *)(key)];
        }
    }

    [self removeObserver:self forKeyPath:@"selectionIndex" context:@"schemeMenu"];
}

/*
 * - observeValueForKeyPath:ofObject:change:context:
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSString *localContext = (__bridge NSString *)(context);

    if ([localContext isEqualToString:@"objectController"])
    {
        [self removeObserver:self forKeyPath:@"objectController.content" context:@"objectController"];
        [self setupLate];
    }
    else if ( !self.ignoreObservations && [[[MGSColourScheme class] propertiesOfScheme] containsObject:localContext] )
    {
        [self willChangeValueForKey:@"buttonSaveDeleteEnabled"];
        [self willChangeValueForKey:@"buttonSaveDeleteTitle"];
        [self findAndSetCurrentScheme];
        [self didChangeValueForKey:@"buttonSaveDeleteEnabled"];
        [self didChangeValueForKey:@"buttonSaveDeleteTitle"];
    }
    else if ([object isEqualTo:self] && !self.ignoreObservations && [localContext isEqualToString:@"schemeMenu"])
    {
        [self willChangeValueForKey:@"buttonSaveDeleteEnabled"];
        [self willChangeValueForKey:@"buttonSaveDeleteTitle"];
        MGSColourScheme *newScheme = [self.arrangedObjects objectAtIndex:self.selectionIndex];
        if (self.currentSchemeIsCustom)
        {
            self.ignoreObservations = YES;
            [self removeObject:self.currentScheme];
            self.currentSchemeIsCustom = NO;
            self.ignoreObservations = NO;
        }
        self.currentScheme = newScheme;
        [self applyColourSchemeToView];
        [self didChangeValueForKey:@"buttonSaveDeleteEnabled"];
        [self didChangeValueForKey:@"buttonSaveDeleteTitle"];
    }
}

#pragma mark - Private/Internal

/*
 * - findMatchingSchemeForScheme:
 *   We're not forcing applications to store the name of a scheme, so try
 *   to determine what the current theme is based on the properties.
 */
- (MGSColourScheme *)findMatchingSchemeForScheme:(MGSColourScheme *)scheme
{
	// arrangedObjects may not exist yet, so lets sort things ourselves...
    NSArray *sortedArray = [self.colourSchemes sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        return [[a valueForKey:@"displayName"] localizedCaseInsensitiveCompare:[b valueForKey:@"displayName"]];
    }];

    // ignore the custom theme if it's in the list. Convoluted, but avoids string checking.
    sortedArray = [sortedArray objectsAtIndexes:[sortedArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return !( self.currentSchemeIsCustom && [self.currentScheme isEqual:obj] );
    }]];

    for (MGSColourScheme *item in sortedArray)
	{
		if ([scheme isEqualToScheme:item])
		{
            return item;
		}
	}

	return nil;
}

/*
 * - makeColourSchemeFromView
 *   The defaultsObjectController contains all of the current colour settings
 *   for the instance of FragariaView, so return an instance of MGSColourScheme
 *   with these settings.
 */
- (MGSColourScheme *)makeColourSchemeFromViewForScheme:(MGSColourScheme *)currentViewScheme
{
    if (!currentViewScheme)
    {
        currentViewScheme = [[MGSColourScheme alloc] init];
    }

    for (NSString *key in [[MGSColourScheme class] propertiesOfScheme])
    {
        if ([[self.objectController.content allKeys] containsObject:key])
        {
            [currentViewScheme setValue:[self.objectController.selection valueForKey:key] forKey:key];
        }
    }

	return currentViewScheme;
}

/*
 * - applyColourSchemeToView
 *   apply the current colour scheme directly to the defaultsObjectController.
 */
- (void)applyColourSchemeToView
{
    self.ignoreObservations = YES;
    for (NSString *key in [[MGSColourScheme class] propertiesOfScheme])
    {
        if ([[self.objectController.content allKeys] containsObject:key])
        {
            id remote = [self.objectController.selection valueForKey:key];
            id local = [self.currentScheme valueForKey:key];
            if (![remote isEqual:local])
            {
                [self.objectController.selection setValue:[self.currentScheme valueForKey:key] forKey:key];
            }
        }
    }
    self.ignoreObservations = NO;
}

/*
 * - findAndSetCurrentScheme
 *   If the view's settings match a known scheme, then set that as the active
 *   scheme, otherwise create a new (unsaved) scheme.
 */
- (void)findAndSetCurrentScheme
{
	MGSColourScheme *currentViewScheme = [self makeColourSchemeFromViewForScheme:nil];
    MGSColourScheme *matchingScheme = [self findMatchingSchemeForScheme:currentViewScheme];

	if (matchingScheme)
    {
        if (self.currentSchemeIsCustom)
        {
            [self removeObject:self.currentScheme];
        }
		self.currentScheme = matchingScheme;
        self.selectionIndex = [self.arrangedObjects indexOfObject:self.currentScheme];
        self.currentSchemeIsCustom = NO;
    }
    else
    {
        if (!self.currentSchemeIsCustom)
        {
            // Create and activate a custom scheme.
			self.currentScheme = currentViewScheme;
            self.currentSchemeIsCustom = YES;
            self.ignoreObservations = YES;
            [self addObject:self.currentScheme];
            self.ignoreObservations = NO;
		}
        else
        {
            // Take the current controller values.
            self.currentScheme = [self makeColourSchemeFromViewForScheme:self.currentScheme];
        }
    }
}

#pragma mark - I/O and File Loading

/*
 * - applicationSupportDirectory
 *   Get access to the user's Application Support directory, creating if needed.
 */
- (NSString *)applicationSupportDirectory
{
    NSArray *URLS = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory
                                                           inDomains:NSUserDomainMask];
    if (URLS)
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *appSup = [URLS firstObject];
        NSURL *finalURL;
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

        if (infoDictionary.count != 0)
        {
            finalURL = [appSup URLByAppendingPathComponent:[infoDictionary objectForKey:@"CFBundleExecutable"] isDirectory:YES];
        }
        else
        {
            // Unit testing results in empty infoDictionary, so use a custom location.
            finalURL = [appSup URLByAppendingPathComponent:@"MGSFragaria Framework Unit Tests" isDirectory:YES];
        }

        if (![fileManager changeCurrentDirectoryPath:[finalURL path]])
        {
            [fileManager createDirectoryAtURL:finalURL
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:nil];
        }
        return [finalURL path];
    }
    else
    {
        return nil;
    }
}

/*
 * - loadColourSchemes
 *   Look in several possible locations for scheme files.
 */
- (void)loadColourSchemes
{
    self.colourSchemes = [[NSMutableArray alloc] init];

    // Load schemes from this bundle
    NSString *path = [[NSBundle bundleForClass:[self class]] bundlePath];
    path = [path stringByAppendingPathComponent:@"Resources"];
    [self addColourSchemesFromPath:path bundleFlag:YES];

    // Load schemes from app bundle
    path = [[NSBundle mainBundle] resourcePath];
    [self addColourSchemesFromPath:path bundleFlag:YES];

    // Load schemes from application support
    path = [self applicationSupportDirectory];
    [self addColourSchemesFromPath:path bundleFlag:NO];
}

/*
 * - addColourSchemesFromPath
 *   Given a directory path, load all of the plist files that are there.
 */
- (void)addColourSchemesFromPath:(NSString *)path bundleFlag:(BOOL)bundleFlag
{
    // Build list of files to load.
    NSString *directory = [path stringByAppendingPathComponent:KMGSColourSchemesFolder];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *filter = [NSString stringWithFormat:@"self ENDSWITH '.%@'", KMGSColourSchemeExt];
    NSArray *fileArray = [fileManager contentsOfDirectoryAtPath:directory error:nil];
    fileArray = [fileArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:filter]];

    // Append each file to the dictionary of colour schemes. By design,
    // subsequently loaded schemes with the same name replace existing.
    // This lets the application bundle override the framework, and lets
    // the user's Application Support override everything else.
    for (NSString *file in fileArray)
    {
        NSString *complete = [directory stringByAppendingPathComponent:file];
        MGSColourScheme *scheme = [[MGSColourScheme alloc] initWithFile:complete];
        scheme.loadedFromBundle = bundleFlag;
        [self.colourSchemes addObject:scheme];
    }
}

@end


text:
static dispatch_queue_t ZYNetworkManagerOperationQueue = nil;

@interface ZYNetWorkManager ()

@property (nonatomic,strong)NSMutableArray *waitJsonTasks;

@property (nonatomic,strong)NSMutableArray *waitDownloadTasks;

@property (nonatomic,strong)NSMutableArray *excutingTasks;

@property (nonatomic,assign)NSInteger maxExcutingTaskCount;

@property (nonatomic,strong)AFHTTPRequestOperationManager *requestManager;

@property (nonatomic,assign)NSInteger currenPiroriy;

@end

@implementation ZYNetWorkManager

+ (ZYNetWorkManager *)shareManager
{
    static ZYNetWorkManager *_networkInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        if (!_networkInstance) {

            _networkInstance = [[self alloc]init];

        }

    });

    return _networkInstance;
}

- (instancetype)init
{
    if (self = [super init]) {

        self.waitJsonTasks = [[NSMutableArray alloc]init];

        self.waitDownloadTasks = [[NSMutableArray alloc]init];

        self.excutingTasks = [[NSMutableArray alloc]init];

        self.maxExcutingTaskCount = 5.f;

        self.currenPiroriy = 0;

        ZYNetworkManagerOperationQueue = dispatch_queue_create("ZYNetworkManagerOperationQueue", DISPATCH_QUEUE_SERIAL);

        self.requestManager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:@""]];
        self.requestManager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
        self.requestManager.responseSerializer.stringEncoding = NSUTF8StringEncoding;
        self.requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/javascript",@"application/json",@"text/html",@"application/xhtml+xml",@"*/*",@"application/xhtml+xml",@"image/webp", nil];

    }
    return self;
}

#pragma mark - 内部调度

//获取任务的更高优先级
- (NSInteger)getCurrentNewHighPirority
{
    self.currenPiroriy = self.currenPiroriy -1;

    return self.currenPiroriy;
}

//获取当前等待任务的最低优先级
- (NSInteger)getCurrentNewLowPirority
{
    self.currenPiroriy = self.currenPiroriy +1;

    return self.currenPiroriy;
}

- (NSArray *)sortedExcutingDownloadTasks
{
    NSMutableArray *downloadTasks = [NSMutableArray array];
    for (ZYNetWorkTask *task in self.excutingTasks) {

        if (task.taskType == ZYNetworkTaskTypeDownloadFile) {

            [downloadTasks addObject:task];
        }
    }

    return [downloadTasks sortedArrayUsingSelector:@selector(compare:)];
}

- (ZYNetWorkTask *)nextDownloadTask
{
    NSArray *sortArray = [self.waitDownloadTasks sortedArrayUsingSelector:@selector(compare:)];

    return [sortArray firstObject];
}

- (void)cancelDownloadImageTaskForNewJoinedTask
{
    [self cancelTaskThenWaitNextTime:[self.waitDownloadTasks firstObject]];
}

- (void)cancelTaskThenWaitNextTime:(ZYNetWorkTask *)task
{
    dispatch_async(ZYNetworkManagerOperationQueue, ^{

        for (AFHTTPRequestOperation *operation in self.requestManager.operationQueue.operations ) {

            NSString *operationTaskIdentifier = [operation.userInfo objectForKey:@"taskIdentifier"];

            if ([operationTaskIdentifier isEqualToString:task.taskIdentifier]) {

                [operation cancel];
            }
        }

        for (ZYNetWorkTask *excutingTask in self.excutingTasks) {

            if ([excutingTask.taskIdentifier isEqual:task.taskIdentifier]) {

                //重新等待下一次请求
                excutingTask.taskState = ZYNetworkTaskStateWait;

                //从执行队列移除
                [self.excutingTasks removeObject:excutingTask];

                //加入等待队列
                if (excutingTask.taskType == ZYNetworkTaskTypeDownloadFile) {
                    [self.waitDownloadTasks addObject:excutingTask];
                }
                if (excutingTask.taskType == ZYNetworkTaskTypeJsonRequest) {
                    [self.waitJsonTasks addObject:excutingTask];
                }

            }
        }

    });
}

- (void)startNextTaskIfNeccessary
{
    ZYNetWorkTask *nextTask = [self.waitJsonTasks lastObject];

    if (nextTask) {

        //如果json接口被正在执行的任务挡住了
        if (self.excutingTasks.count == self.maxExcutingTaskCount) {

            [self cancelDownloadImageTaskForNewJoinedTask];

        }

        //添加一个json请求
        [self.waitJsonTasks removeObject:nextTask];

        [self addTask:nextTask];

        return;
    }

    //执行一个下载图片的
    ZYNetWorkTask *downloadTask = [self nextDownloadTask];

    if (downloadTask) {

        [self.waitDownloadTasks removeObject:downloadTask];

        [self addTask:downloadTask];
    }
}

#pragma mark - 公开接口

- (void)addTask:(ZYNetWorkTask *)task{

    //任务串行
    dispatch_async(ZYNetworkManagerOperationQueue, ^{

        //如果是一个相同的下载任务
        if (task.taskType == ZYNetworkTaskTypeDownloadFile) {

            for (ZYNetWorkTask *waitTask in self.waitDownloadTasks) {

                if ( [waitTask isEqualRequest:task]) {

                    //提高下载优先级
                    waitTask.priority = [self getCurrentNewLowPirority];

                    if (self.excutingTasks.count == self.maxExcutingTaskCount) {

                        return ;

                    }
                }
            }
        }

        //如果是json接口请求,直接干掉一个下载请求来支持json请求开始
        if (task.taskType == ZYNetworkTaskTypeJsonRequest) {

            [self cancelDownloadImageTaskForNewJoinedTask];

        }

        //添加优先级索引
        if (task.priority == -999) {
            task.priority = [self getCurrentNewLowPirority];
        }

        //判定是否已经到了最大任务执行数
        if (self.excutingTasks.count > self.maxExcutingTaskCount) {

            if (task.taskType == ZYNetworkTaskTypeJsonRequest) {
                [self.waitJsonTasks addObject:task];
            }

            if (task.taskType == ZYNetworkTaskTypeDownloadFile) {
                [self.waitDownloadTasks addObject:task];
            }

            return;
        }

        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:task.requestUrl]];

        if (task.requestMethod == ZYNetworkRequestMethodGET) {
            urlRequest.HTTPMethod = @"GET";
        }else{
            urlRequest.HTTPMethod = @"POST";
        }

        AFHTTPRequestOperation *request = [[AFHTTPRequestOperation alloc]initWithRequest:urlRequest];

        [request setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            [self successWithTask:task response:responseObject];

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

            [self faildWithTask:task error:error];

        }];

        [request setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {

            CGFloat uploadKbSize = totalBytesRead/1024.0f;
            CGFloat totoalSize = totalBytesExpectedToRead/1024.0f;
            CGFloat downloadProgreessValue = (uploadKbSize/1024.f)/(totoalSize/1024.f);

            [self progressTask:task progress:downloadProgreessValue];

        }];

        NSString *groupTaskIdentifier = task.groupTaskIdentifier;
        if (!groupTaskIdentifier) {
            groupTaskIdentifier = @"NotGroupTask";
        }
        request.userInfo = @{@"taskIdentifier":task.taskIdentifier,@"taskType":@(task.taskType),@"groupTask":groupTaskIdentifier};
        task.taskState = ZYNetworkTaskStateLoading;

        [self.requestManager.operationQueue addOperation:request];

        [self.excutingTasks addObject:task];

    });
}

#pragma mark - 任务取消

- (void)cancelTask:(ZYNetWorkTask *)task
{
    [self cancelTaskByIdentifier:task.taskIdentifier];
}

- (void)cancelTaskByUserInfoValues:(NSDictionary *)userInfo
{
    dispatch_async(ZYNetworkManagerOperationQueue, ^{

        NSString *firstKey = [userInfo.allKeys firstObject];
        NSString *firstValue = [userInfo objectForKey:firstKey];

        //是否正在执行的任务
        for (ZYNetWorkTask *excutingTask in self.excutingTasks) {

            for (AFHTTPRequestOperation *operation in self.requestManager.operationQueue.operations ) {

                if ([operation.userInfo.allKeys containsObject: firstKey]) {

                    if ([[operation.userInfo objectForKey:firstKey] isEqualToString:firstValue]) {

                        [operation cancel];

                    }
                }
            }

            if ([excutingTask.userInfo.allKeys containsObject: firstKey]) {

                if ([[excutingTask.userInfo objectForKey:firstKey] isEqualToString:firstValue]) {

                    [self.excutingTasks removeObject:excutingTask];

                }

            }
        }

        //等待中的下载任务任务直接移除
        for (ZYNetWorkTask *waitTask in self.waitDownloadTasks) {

            if ([waitTask.userInfo.allKeys containsObject: firstKey]) {

                if ([[waitTask.userInfo objectForKey:firstKey] isEqualToString:firstValue]) {

                    [self.waitDownloadTasks removeObject:waitTask];

                }

            }
        }

        //等待中的json任务任务直接移除
        for (ZYNetWorkTask *waitTask in self.waitDownloadTasks) {

            if ([waitTask.userInfo.allKeys containsObject: firstKey]) {

                if ([[waitTask.userInfo objectForKey:firstKey] isEqualToString:firstValue]) {

                    [self.waitDownloadTasks removeObject:waitTask];

                }

            }
        }

    });
}

- (void)cancelTaskByIdentifier:(NSString *)taskIdentifier
{
    dispatch_async(ZYNetworkManagerOperationQueue, ^{

        //是否正在执行的任务
        for (ZYNetWorkTask *excutingTask in self.excutingTasks) {

            for (AFHTTPRequestOperation *operation in self.requestManager.operationQueue.operations ) {

                NSString *operationTaskIdentifier = [operation.userInfo objectForKey:@"taskIdentifier"];

                if ([operationTaskIdentifier isEqualToString:taskIdentifier]) {

                    [operation cancel];
                }
            }

            if ([excutingTask.taskIdentifier isEqual:taskIdentifier]) {

                [self.excutingTasks removeObject:excutingTask];

            }
        }

        //等待中的下载任务直接移除
        for (ZYNetWorkTask *waitTask in self.waitDownloadTasks) {

            if ([waitTask.taskIdentifier isEqual:taskIdentifier]) {

                [self.waitDownloadTasks removeObject:waitTask];

            }
        }

        //等待中的json任务直接移除
        for (ZYNetWorkTask *waitTask in self.waitJsonTasks) {

            if ([waitTask.taskIdentifier isEqual:taskIdentifier]) {

                [self.waitJsonTasks removeObject:waitTask];

            }
        }

    });
}

- (void)cancelGroupTask:(NSString *)groupTaskIdentifier
{
    dispatch_async(ZYNetworkManagerOperationQueue, ^{

        //是否正在执行的任务
        for (ZYNetWorkTask *excutingTask in self.excutingTasks) {

            for (AFHTTPRequestOperation *operation in self.requestManager.operationQueue.operations ) {

                NSString *operationTaskIdentifier = [operation.userInfo objectForKey:@"groupTask"];

                if ([operationTaskIdentifier isEqualToString:groupTaskIdentifier]) {

                    [operation cancel];
                }
            }

            if ([excutingTask.groupTaskIdentifier isEqual:groupTaskIdentifier]) {

                [self.excutingTasks removeObject:excutingTask];

            }
        }

        //等待中的下载任务直接移除
        for (ZYNetWorkTask *waitTask in self.waitDownloadTasks) {

            if ([waitTask.groupTaskIdentifier isEqual:groupTaskIdentifier]) {

                [self.waitDownloadTasks removeObject:waitTask];

            }
        }

        //等待中的json任务直接移除
        for (ZYNetWorkTask *waitTask in self.waitJsonTasks) {

            if ([waitTask.groupTaskIdentifier isEqual:groupTaskIdentifier]) {

                [self.waitJsonTasks removeObject:waitTask];

            }
        }

    });

}

#pragma mark - 内部请求结果处理

- (void)successWithTask:(ZYNetWorkTask *)task response:(id)responseObject
{
    //执行完成任务的回调
    if (task.successBlock) {
        task.successBlock(task,responseObject);
    }

    //移除任务
    [self.excutingTasks removeObject:task];

    //执行下一个任务,如果有的话
    [self startNextTaskIfNeccessary];
}

- (void)faildWithTask:(ZYNetWorkTask *)task error:(NSError *)error
{
    //执行任务失败回调
    if (task.faildBlock) {
        task.faildBlock(task,error);
    }

    //移除任务
    [self.excutingTasks removeObject:task];

    //执行下一个等待的任务
    [self startNextTaskIfNeccessary];
}

- (void)progressTask:(ZYNetWorkTask *)task progress:(CGFloat)progress
{
    if (task.progressBlock) {
        task.progressBlock(task,progress);
    }
}

@end


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Roger Kumpf, Hewlett-Packard Company (roger_kumpf@hp.com)
//
// Modified By: Carol Ann Krug Graves, Hewlett-Packard Company
//                  (carolann_graves@hp.com)
//              Dave Sudlik, IBM (dsudlik@us.ibm.com)
//              David Dillard, VERITAS Software Corp.
//                  (david.dillard@veritas.com)
//
//%/////////////////////////////////////////////////////////////////////////////

#include <Pegasus/Common/Config.h>
#include <cstdlib>
#include <cstdio>
#include "Constants.h"
#include "CIMClass.h"
#include "CIMClassRep.h"
#include "CIMInstance.h"
#include "CIMInstanceRep.h"
#include "CIMProperty.h"
#include "CIMPropertyRep.h"
#include "CIMMethod.h"
#include "CIMMethodRep.h"
#include "CIMParameter.h"
#include "CIMParameterRep.h"
#include "CIMQualifier.h"
#include "CIMQualifierRep.h"
#include "CIMQualifierDecl.h"
#include "CIMQualifierDeclRep.h"
#include "CIMObjectPath.h"
#include "CIMValue.h"
#include "CIMFlavor.h"
#include "CIMScope.h"
#include "XmlWriter.h"
#include "MofWriter.h"
#include "Tracer.h"

PEGASUS_NAMESPACE_BEGIN

//------------------------------------------------------------------------------
//
// Helper functions for appendValueElement()
//
//------------------------------------------------------------------------------

inline void _mofWriter_appendValue(Array<char>& out, Boolean x)
{
    XmlWriter::append(out, x);
}

inline void _mofWriter_appendValue(Array<char>& out, Uint8 x)
{
    XmlWriter::append(out, Uint32(x));
}

inline void _mofWriter_appendValue(Array<char>& out, Sint8 x)
{
    XmlWriter::append(out, Sint32(x));
}

inline void _mofWriter_appendValue(Array<char>& out, Uint16 x)
{
    XmlWriter::append(out, Uint32(x));
}

inline void _mofWriter_appendValue(Array<char>& out, Sint16 x)
{
    XmlWriter::append(out, Sint32(x));
}

inline void _mofWriter_appendValue(Array<char>& out, Uint32 x)
{
    XmlWriter::append(out, x);
}

inline void _mofWriter_appendValue(Array<char>& out, Sint32 x)
{
    XmlWriter::append(out, x);
}

inline void _mofWriter_appendValue(Array<char>& out, Uint64 x)
{
    XmlWriter::append(out, x);
}

inline void _mofWriter_appendValue(Array<char>& out, Sint64 x)
{
    XmlWriter::append(out, x);
}

inline void _mofWriter_appendValue(Array<char>& out, Real32 x)
{
    XmlWriter::append(out, Real64(x));
}

inline void _mofWriter_appendValue(Array<char>& out, Real64 x)
{
    XmlWriter::append(out, x);
}

inline void _mofWriter_appendValue(Array<char>& out, Char16 x)
{
    XmlWriter::appendSpecial(out, x);
}

/** Convert the string back to MOF format and output it.
    The conversions are:
    \b // \x0008: backspace BS
    \t // \x0009: horizontal tab HT
    \n // \x000A: linefeed LF
    \f // \x000C: form feed FF
    \r // \x000D: carriage return CR
    \" // \x0022: double quote "
    \' // \x0027: single quote '
    \\ // \x005C: backslash \
    \x<hex> // where <hex> is one to four hex digits
    \X<hex> // where <hex> is one to four hex digits
*/
/* ATTN:KS - We need to account for characters greater than x'7f
*/
inline void _mofWriter_appendValue(Array<char>& out, const String& x)
{
    out << "\"";
    const Uint32 size = x.size();
    for (Uint32 i = 0; i < size; i++)
    {
        switch (x[i])
        {
        case '\\':
                out.append("\\\\",2);
                break;

            case '\b':
                out.append("\\b",2);
                break;

            case '\t':
                out.append("\\t",2);
                break;

            case '\n':
                out.append("\\n",2);
                break;

            case '\f':
                out.append("\\f",2);
                break;

            case '\r':
                out.append("\\r",2);
                break;

           /* case '\'':
                out.append("\\'", 2);
                break;*/

            case '"':
                out.append("\\\"", 2);
                break;

            default:
                out.append(Sint8(x[i]));
        }

    }
    out << "\"";
}

inline void _mofWriter_appendValue(Array<char>& out, const CIMDateTime& x)
{
    _mofWriter_appendValue(out, x.toString());
}

inline void _mofWriter_appendValue(Array<char>& out, const CIMObjectPath& x)
{
    _mofWriter_appendValue(out, x.toString());
}

inline void _mofWriter_appendValue(Array<char>& out, const CIMObject& x)
{
    _mofWriter_appendValue(out, x.toString());
}

/** Array -
    arrayInitializer = "{" constantValue*( "," constantValue)"}"
*/
template<class T>

void _mofWriter_appendValueArrayMof(Array<char>& out, const T* p, Uint32 size)
{
    Boolean isFirstEntry = true;
    // if there are any entries in the array output them
    if (size)
    {
        out << "{";
        while (size--)
        {
            // Put comma on all but first entry.
            if (!isFirstEntry)
            {
                out << ", ";
            }
            isFirstEntry = false;
            _mofWriter_appendValue(out, *p++);
        }
        out << "}";
    }
}

//------------------------------------------------------------------------------
//
// appendValueElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendValueElement(
    Array<char>& out,
    const CIMValue& value)
{
    // if the CIMValue is Null we return the Null indicator.
    if (value.isNull())
    {
        out << "null";
        return;
    }

    if (value.isArray())
    {
        switch (value.getType())
        {
            case CIMTYPE_BOOLEAN:
            {
                Array<Boolean> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_UINT8:
            {
                Array<Uint8> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_SINT8:
            {
                Array<Sint8> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_UINT16:
            {
                Array<Uint16> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_SINT16:
            {
                Array<Sint16> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_UINT32:
            {
                Array<Uint32> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_SINT32:
            {
                Array<Sint32> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_UINT64:
            {
                Array<Uint64> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_SINT64:
            {
                Array<Sint64> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_REAL32:
            {
                Array<Real32> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_REAL64:
            {
                Array<Real64> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_CHAR16:
            {
                Array<Char16> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_STRING:
            {
                Array<String> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_DATETIME:
            {
                Array<CIMDateTime> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_REFERENCE:
            {
                Array<CIMObjectPath> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            case CIMTYPE_OBJECT:
            {
                Array<CIMObject> a;
                value.get(a);
                _mofWriter_appendValueArrayMof(out, a.getData(), a.size());
                break;
            }

            default:
                PEGASUS_ASSERT(false);
        }
    }
    else
    {
        switch (value.getType())
        {
            case CIMTYPE_BOOLEAN:
            {
                Boolean v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_UINT8:
            {
                Uint8 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_SINT8:
            {
                Sint8 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_UINT16:
            {
                Uint16 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_SINT16:
            {
                Sint16 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_UINT32:
            {
                Uint32 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_SINT32:
            {
                Sint32 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_UINT64:
            {
                Uint64 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_SINT64:
            {
                Sint64 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_REAL32:
            {
                Real32 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_REAL64:
            {
                Real64 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_CHAR16:
            {
                Char16 v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_STRING:
            {
                String v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_DATETIME:
            {
                CIMDateTime v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_REFERENCE:
            {
                CIMObjectPath v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            case CIMTYPE_OBJECT:
            {
                CIMObject v;
                value.get(v);
                _mofWriter_appendValue(out, v);
                break;
            }

            default:
                PEGASUS_ASSERT(false);
        }
    }
}

//------------------------------------------------------------------------------
//
// appendValueReferenceElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendValueReferenceElement(
    Array<char>& out,
    const CIMObjectPath& reference)
{
    _mofWriter_appendValue(out, reference);
}

//------------------------------------------------------------------------------
//
// appendClassElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendClassElement(
    Array<char>& out,
    const CIMConstClass& cimclass)
{
    cimclass._checkRep();
    cimclass._rep->toMof(out);
}

void MofWriter::printClassElement(
    const CIMConstClass& cimclass,
    PEGASUS_STD(ostream)& os)
{
    Array<char> tmp;
    appendClassElement(tmp, cimclass);
    tmp.append('\0');
    os << tmp.getData() << PEGASUS_STD(endl);
}

//------------------------------------------------------------------------------
//
// appendInstanceElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendInstanceElement(
    Array<char>& out,
    const CIMConstInstance& instance)
{
    instance._checkRep();
    instance._rep->toMof(out);
}

//------------------------------------------------------------------------------
//
// appendPropertyElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendPropertyElement(
    Array<char>& out,
    const CIMConstProperty& property)
{
    property._checkRep();
    property._rep->toMof(out);
}

//------------------------------------------------------------------------------
//
// appendMethodElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendMethodElement(
    Array<char>& out,
    const CIMConstMethod& method)
{
    method._checkRep();
    method._rep->toMof(out);
}

//------------------------------------------------------------------------------
//
// appendParameterElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendParameterElement(
    Array<char>& out,
    const CIMConstParameter& parameter)
{
    parameter._checkRep();
    parameter._rep->toMof(out);
}

//------------------------------------------------------------------------------
//
// appendQualifierElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendQualifierElement(
    Array<char>& out,
    const CIMConstQualifier& qualifier)
{
    qualifier._checkRep();
    qualifier._rep->toMof(out);
}

//------------------------------------------------------------------------------
//
// appendQualifierDeclElement()
//
//------------------------------------------------------------------------------

void MofWriter::appendQualifierDeclElement(
    Array<char>& out,
    const CIMConstQualifierDecl& qualifierDecl)
{
    qualifierDecl._checkRep();
    qualifierDecl._rep->toMof(out);
}

//------------------------------------------------------------------------------
//
// getQualifierFlavor()
//
// Convert the Qualifier flavors to a string of MOF flavor keywords.
//
//   <pre>
//   Keyword            Function                             Default
//     EnableOverride  Qualifier is overridable.               yes
//     DisableOverride Qualifier cannot be overridden.         no
//     ToSubclass      Qualifier is inherited by any subclass. yes
//     Restricted      Qualifier applies only to the class     no
//                     in which it is declared
//     Translatable    Indicates the value of the qualifier
//                     can be specified in multiple languages  no
//     NOTE: There is an open issue with the keyword toinstance.
//
//     flavor            = ENABLEOVERRIDE | DISABLEOVERRIDE | RESTRICTED |
//                         TOSUBCLASS | TRANSLATABLE
//     DISABLEOVERRIDE   = "disableoverride"
//
//     ENABLEOVERRIDE    = "enableoverride"
//
//     RESTRICTED        = "restricted"
//
//     TOSUBCLASS        = "tosubclass"
//
//     TRANSLATABLE      = "translatable"
//    </pre>
//
//    The keyword toinstance is not in the CIM specification. For the moment
//    we are assuming that it is the same as the toSubclass. We had a choice
//    of using one entity for both or separating them and letting the
//    compiler set both.
//
//------------------------------------------------------------------------------

String MofWriter::getQualifierFlavor(const CIMFlavor & flavor)
{
    String tmp;

    if (!(flavor.hasFlavor (CIMFlavor::OVERRIDABLE)))
        tmp.append("DisableOverride, ");

    if (!(flavor.hasFlavor (CIMFlavor::TOSUBCLASS)))
        tmp.append("Restricted, ");

    // ATTN-RK-P3-20020515: FUTURE: Need to check toInstance flavor?
    //if (!(flavor.hasFlavor (CIMFlavor::TOINSTANCE)))
    //    tmp.append("Restricted, ");

    if (flavor.hasFlavor (CIMFlavor::TRANSLATABLE))
        tmp.append("Translatable, ");

    if (tmp.size())
        tmp.remove(tmp.size() - 2);

    return tmp;
}

//------------------------------------------------------------------------------
//
// getQualifierScope()
//
//------------------------------------------------------------------------------

String MofWriter::getQualifierScope (const CIMScope & scope)
{
    if (scope.equal (CIMScope::ANY))
    {
        return "any";
    }
    else
    {
        String tmp = scope.toString ();
        tmp.toLower();
        return tmp;
    }
}

PEGASUS_NAMESPACE_END


text:
package nxt.env;

import java.io.File;
import java.net.URI;

public class CommandLineMode implements RuntimeMode {

    @Override
    public void init() {}

    @Override
    public void setServerStatus(String status, URI wallet, File logFileDir) {}

    @Override
    public void shutdown() {}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Moq;
using Moq.Language.Flow;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NavigateTo
{
    [UseExportProvider]
    [Trait(Traits.Feature, Traits.Features.NavigateTo)]
    public class NavigateToSearcherTests
    {
        private static void SetupSearchProject(
            Mock<INavigateToSearchService> searchService,
            string pattern,
            bool isFullyLoaded,
            INavigateToSearchResult? result)
        {
            if (isFullyLoaded)
            {
                // First do a full search
                searchService.Setup(ss => ss.SearchProjectAsync(
                    It.IsAny<Project>(),
                    It.IsAny<ImmutableArray<Document>>(),
                    pattern,
                    ImmutableHashSet<string>.Empty,
                    It.IsAny<Document?>(),
                    It.IsAny<CancellationToken>())).Returns(GetEnumerable(result));

                searchService.Setup(ss => ss.SearchGeneratedDocumentsAsync(
                    It.IsAny<Project>(),
                    pattern,
                    ImmutableHashSet<string>.Empty,
                    It.IsAny<Document?>(),
                    It.IsAny<CancellationToken>())).Returns(GetEnumerable(result));

                // Followed by a generated doc search.
            }
            else
            {
                searchService.Setup(ss => ss.SearchCachedDocumentsAsync(
                    It.IsAny<Project>(),
                    It.IsAny<ImmutableArray<Document>>(),
                    pattern,
                    ImmutableHashSet<string>.Empty,
                    It.IsAny<Document?>(),
                    It.IsAny<CancellationToken>())).Returns(GetEnumerable(result));
            }
        }

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        private static async IAsyncEnumerable<INavigateToSearchResult> GetEnumerable(INavigateToSearchResult? result)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            if (result != null)
                yield return result;
        }

        private static ValueTask<bool> IsFullyLoadedAsync(bool projectSystem, bool remoteHost)
            => new(projectSystem && remoteHost);

        [Fact]
        public async Task NotFullyLoadedOnlyMakesOneSearchProjectCallIfValueReturned()
        {
            using var workspace = TestWorkspace.CreateCSharp("");

            var pattern = "irrelevant";

            var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0));

            var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict);
            SetupSearchProject(searchService, pattern, isFullyLoaded: false, result);

            // Simulate a host that says the solution isn't fully loaded.
            var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict);
            hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystem: false, remoteHost: false));
            hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object);

            var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict);
            callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>()));
            callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>())).Returns(Task.CompletedTask);

            // Because we returned a result when not fully loaded, we should notify the user that data was not complete.
            callbackMock.Setup(c => c.Done(false));

            var searcher = NavigateToSearcher.Create(
                workspace.CurrentSolution,
                AsynchronousOperationListenerProvider.NullListener,
                callbackMock.Object,
                pattern,
                kinds: ImmutableHashSet<string>.Empty,
                CancellationToken.None,
                hostMock.Object);

            await searcher.SearchAsync(searchCurrentDocument: false, CancellationToken.None);
        }

        [Theory]
        [CombinatorialData]
        public async Task NotFullyLoadedMakesTwoSearchProjectCallIfValueNotReturned(bool projectSystemFullyLoaded)
        {
            using var workspace = TestWorkspace.CreateCSharp("");

            var pattern = "irrelevant";

            var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0));

            var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict);

            // First call will pass in that we're not fully loaded.  If we return null, we should get
            // another call with the request to search the fully loaded data.
            SetupSearchProject(searchService, pattern, isFullyLoaded: false, result: null);
            SetupSearchProject(searchService, pattern, isFullyLoaded: true, result);

            // Simulate a host that says the solution isn't fully loaded.
            var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict);
            hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystemFullyLoaded, remoteHost: false));
            hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object);

            var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict);
            callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>()));
            callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>()))
                        .Returns(Task.CompletedTask);

            // Because the remote host wasn't fully loaded, we still notify that our results may be incomplete.
            callbackMock.Setup(c => c.Done(false));

            var searcher = NavigateToSearcher.Create(
                workspace.CurrentSolution,
                AsynchronousOperationListenerProvider.NullListener,
                callbackMock.Object,
                pattern,
                kinds: ImmutableHashSet<string>.Empty,
                CancellationToken.None,
                hostMock.Object);

            await searcher.SearchAsync(searchCurrentDocument: false, CancellationToken.None);
        }

        [Theory]
        [CombinatorialData]
        public async Task NotFullyLoadedStillReportsAsNotCompleteIfRemoteHostIsStillHydrating(bool projectIsFullyLoaded)
        {
            using var workspace = TestWorkspace.CreateCSharp("");

            var pattern = "irrelevant";

            var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict);

            // First call will pass in that we're not fully loaded.  If we return null, we should get another call with
            // the request to search the fully loaded data.  If we don't report anything the second time, we will still
            // tell the user the search was complete.
            SetupSearchProject(searchService, pattern, isFullyLoaded: false, result: null);
            SetupSearchProject(searchService, pattern, isFullyLoaded: true, result: null);

            // Simulate a host that says the solution isn't fully loaded.
            var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict);
            hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectIsFullyLoaded, remoteHost: false));
            hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object);

            var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict);
            callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>()));

            // Because the remote host wasn't fully loaded, we still notify that our results may be incomplete.
            callbackMock.Setup(c => c.Done(false));

            var searcher = NavigateToSearcher.Create(
                workspace.CurrentSolution,
                AsynchronousOperationListenerProvider.NullListener,
                callbackMock.Object,
                pattern,
                kinds: ImmutableHashSet<string>.Empty,
                CancellationToken.None,
                hostMock.Object);

            await searcher.SearchAsync(searchCurrentDocument: false, CancellationToken.None);
        }

        [Fact]
        public async Task FullyLoadedMakesSingleSearchProjectCallIfValueNotReturned()
        {
            using var workspace = TestWorkspace.CreateCSharp("");

            var pattern = "irrelevant";

            var result = new TestNavigateToSearchResult(workspace, new TextSpan(0, 0));

            var searchService = new Mock<INavigateToSearchService>(MockBehavior.Strict);

            // First call will pass in that we're fully loaded.  If we return null, we should not get another call.
            SetupSearchProject(searchService, pattern, isFullyLoaded: true, result: null);

            // Simulate a host that says the solution is fully loaded.
            var hostMock = new Mock<INavigateToSearcherHost>(MockBehavior.Strict);
            hostMock.Setup(h => h.IsFullyLoadedAsync(It.IsAny<CancellationToken>())).Returns(() => IsFullyLoadedAsync(projectSystem: true, remoteHost: true));
            hostMock.Setup(h => h.GetNavigateToSearchService(It.IsAny<Project>())).Returns(searchService.Object);

            var callbackMock = new Mock<INavigateToSearchCallback>(MockBehavior.Strict);
            callbackMock.Setup(c => c.ReportProgress(It.IsAny<int>(), It.IsAny<int>()));
            callbackMock.Setup(c => c.AddItemAsync(It.IsAny<Project>(), result, It.IsAny<CancellationToken>()))
                        .Returns(Task.CompletedTask);

            // Because we did a full search, we should let the user know it was totally accurate.
            callbackMock.Setup(c => c.Done(true));

            var searcher = NavigateToSearcher.Create(
                workspace.CurrentSolution,
                AsynchronousOperationListenerProvider.NullListener,
                callbackMock.Object,
                pattern,
                kinds: ImmutableHashSet<string>.Empty,
                CancellationToken.None,
                hostMock.Object);

            await searcher.SearchAsync(searchCurrentDocument: false, CancellationToken.None);
        }

        private class TestNavigateToSearchResult : INavigateToSearchResult, INavigableItem
        {
            private readonly TestWorkspace _workspace;
            private readonly TextSpan _sourceSpan;

            public TestNavigateToSearchResult(TestWorkspace workspace, TextSpan sourceSpan)
            {
                _workspace = workspace;
                _sourceSpan = sourceSpan;
            }

            public Document Document => _workspace.CurrentSolution.Projects.Single().Documents.Single();
            public TextSpan SourceSpan => _sourceSpan;

            public string AdditionalInformation => throw new NotImplementedException();
            public string Kind => throw new NotImplementedException();
            public NavigateToMatchKind MatchKind => throw new NotImplementedException();
            public bool IsCaseSensitive => throw new NotImplementedException();
            public string Name => throw new NotImplementedException();
            public ImmutableArray<TextSpan> NameMatchSpans => throw new NotImplementedException();
            public string SecondarySort => throw new NotImplementedException();
            public string Summary => throw new NotImplementedException();
            public INavigableItem NavigableItem => this;
            public Glyph Glyph => throw new NotImplementedException();
            public ImmutableArray<TaggedText> DisplayTaggedParts => throw new NotImplementedException();
            public bool DisplayFileLocation => throw new NotImplementedException();
            public bool IsImplicitlyDeclared => throw new NotImplementedException();
            public bool IsStale => throw new NotImplementedException();
            public ImmutableArray<INavigableItem> ChildItems => throw new NotImplementedException();
        }
    }
}


text:
package org.fineract.module.stellar.restdomain;

import java.math.BigDecimal;

public class TrustLineConfiguration {

  private BigDecimal maximumAmount;

  @SuppressWarnings("unused") //needed for Json Mapping.
  TrustLineConfiguration() {super();}

  public TrustLineConfiguration(final BigDecimal maximumAmount) {
    this.maximumAmount = maximumAmount;
  }

  public BigDecimal getMaximumAmount() {
    return maximumAmount;
  }
}