text:
NSString * const APDocumentScanStarted          = @"APDocumentScanStarted";
NSString * const APDocumentScanFinished         = @"APDocumentScanFinished";
NSString * const APDocumentScanCancelled        = @"APDocumentScanCancelled";
NSString * const APNewDocumentFound             = @"APNewDocumentFound";

static __strong APManagedDocumentManager* gInstance;

@interface APManagedDocumentManager () {
    BOOL _randomSeeded;
    NSMutableArray* _documentIdentifiers;
    NSMetadataQuery* _documentQuery;
    id<NSObject,NSCopying,NSCoding> _currentUbiquityIdentityToken;
    void (^_documentOpenedOverride)(APManagedDocument*,BOOL);
    BOOL _orphanedLocalFileScanDone;
}

@end

@implementation APManagedDocumentManager

- (id)init {
    self = [super init];
    if (self != nil) {
        NSBundle* mainBundle = [NSBundle mainBundle];
        NSString* transactionLogsSubFolder = [mainBundle objectForInfoDictionaryKey:@"APTransactionLogsSubFolder"];
        if (transactionLogsSubFolder) {
            self.transactionLogsSubFolder = transactionLogsSubFolder;
        } else {
            self.transactionLogsSubFolder = @"CoreDataSupport";
        }
        NSString* documentsSubFolder = [mainBundle objectForInfoDictionaryKey:@"APDocumentsSubFolder"];
        if (documentsSubFolder) {
            self.documentsSubFolder = documentsSubFolder;
        } else {
            self.documentsSubFolder = @"managedDocuments";
        }
        NSString* documentSetIdentifier = [mainBundle objectForInfoDictionaryKey:@"APDocumentSetIdentifier"];
        if (documentSetIdentifier) {
            self.documentSetIdentifier = documentSetIdentifier;
        } else {
            self.documentSetIdentifier = @"APMD_DATA";
        }
        NSString* documentsExtention = [mainBundle objectForInfoDictionaryKey:@"APDocumentsExtention"];
        if (documentSetIdentifier) {
            self.documentsExtention = documentsExtention;
        } else {
            self.documentSetIdentifier = @"";
        }
        [self _prepDocumentsFolder];
        _currentUbiquityIdentityToken = [[NSFileManager defaultManager] ubiquityIdentityToken];
        [[NSNotificationCenter defaultCenter] addObserver: self
                                                 selector: @selector (_iCloudAccountAvailabilityChanged:)
                                                     name: NSUbiquityIdentityDidChangeNotification
                                                   object: nil];
    }
    return self;
}

+ (void)initialize {
    if (self == [APManagedDocumentManager class]) {
        gInstance = [[self alloc] init];
    }
}

+ (APManagedDocumentManager*)sharedDocumentManager {
    return gInstance;
}

- (void)_contextInitializedForDocument:(APManagedDocument*)document success:(BOOL)success {
    if (_documentOpenedOverride) {
        _documentOpenedOverride(document, success);
        _documentOpenedOverride = nil;
    } else {
        if ([self.documentDelegate respondsToSelector:@selector(documentInitialized:success:)]) {
            [self.documentDelegate documentInitialized:document success:success];
        }
    }
}

- (void)_iCloudAccountAvailabilityChanged:(NSNotification*)notif {
    if (![_currentUbiquityIdentityToken isEqual:[[NSFileManager defaultManager] ubiquityIdentityToken]]) {
        // Update the current token and rescan for documents.
        _currentUbiquityIdentityToken = [[NSFileManager defaultManager] ubiquityIdentityToken];
        [self startDocumentScan];
    }
}

- (void)_prepDocumentsFolder {
    NSURL* documentsURL = self.documentsURL;
    if (documentsURL && self.documentsSubFolder.length > 0) {

        if (![[NSFileManager defaultManager] fileExistsAtPath:[documentsURL path] isDirectory:nil]) {
            NSError* error = nil;
            if (![[NSFileManager defaultManager] createDirectoryAtPath:[documentsURL path] withIntermediateDirectories:YES attributes:nil error:&error]) {
                NSLog(@"Failed to create Documents path: %@ - %@", [documentsURL path], [error description]);
            }
        }
    }
}

- (NSURL*)documentsURL {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSURL* documentsURL = [NSURL fileURLWithPath:[paths objectAtIndex:0]];
    if (self.documentsSubFolder.length > 0) {
        documentsURL = [documentsURL URLByAppendingPathComponent:self.documentsSubFolder];
    }
    return documentsURL;
}

- (NSURL*)urlForDocumentWithIdentifier:(NSString*)identifier {
    NSString* fileName = identifier;
    if (self.documentsExtention.length > 0)
        fileName = [NSString stringWithFormat:@"%@.%@", fileName, self.documentsExtention];
    return  [[self documentsURL] URLByAppendingPathComponent:fileName];
}

- (APManagedDocument*)createDocumentWithIdentifier:(NSString*)identifier {
   APManagedDocument* document = [[APManagedDocument alloc] initWithDocumentIdentifier:identifier];
   if (document)
      [self _processDocumentWithIdentifier:identifier];
   return document;
}

- (APManagedDocument*)createNewManagedDocumentWithName:(NSString*)documentName {
   NSString* identifier = [NSString stringWithFormat:@"%@_%@_%@", documentName, self.documentSetIdentifier, [self _generateUniqueIdentifier]];
   return [self createDocumentWithIdentifier:identifier];
}

- (APManagedDocument*)createNewManagedDocumentWithAbsoluteName:(NSString*)documentName
{
   NSString* identifier = [NSString stringWithFormat:@"%@_%@", documentName, self.documentSetIdentifier];
   return [self createDocumentWithIdentifier:identifier];
}

- (APManagedDocument*)openExistingManagedDocumentWithIdentifier:(NSString*)identifier {
    APManagedDocument* doc = nil;
    if ([_documentIdentifiers containsObject:identifier]) {
        doc = [[APManagedDocument alloc] initWithDocumentIdentifier:identifier];
    }
    return doc;
}

- (APManagedDocument*)openExistingManagedDocumentWithName:(NSString*)documentName {
   NSString* identifier = [NSString stringWithFormat:@"%@_%@", documentName, self.documentSetIdentifier];
   APManagedDocument* doc = nil;
   if ([_documentIdentifiers containsObject:identifier]) {
      doc = [[APManagedDocument alloc] initWithDocumentIdentifier:identifier];
   }
   return doc;
}

- (BOOL)deleteManagedDocumentWithIdentifier:(NSString*)identifier {
    BOOL success = NO;
    NSError* err = nil;
    __unsafe_unretained typeof(self) weakSelf = self;
    NSURL* documentURL = [self urlForDocumentWithIdentifier:identifier];
    if (_currentUbiquityIdentityToken) {
        // Deleting ubiquitous content is a bit trickier...
        // First we open the document so that we can obtain the document's
        // store URL. Once we have the store URL we close the document
        // and perform the removeUbiquitousContentAndPersistentStoreAtURL method
        // to remove the ubiquitous content.
        // Finally we remove the local document package.
        _documentOpenedOverride = ^(APManagedDocument* doc, BOOL success) {
            if (success) {
                NSDictionary* options = doc.persistentStoreOptions;
                NSPersistentStore* store = [doc.managedObjectContext.persistentStoreCoordinator.persistentStores firstObject];
                [doc closeWithCompletionHandler:^(BOOL success) {
                    if(success) {
                        NSError* err = nil;
                        if ([NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:store.URL options:options error:&err])
                        {
                            if([[NSFileManager defaultManager] fileExistsAtPath:[documentURL path]]) {
                                success = [[NSFileManager defaultManager] removeItemAtURL:documentURL error:&err];
                                if (success) {
                                    [weakSelf startDocumentScan];
                                }else {
                                    NSLog(@"Failed to delete: %@", [err description]);
                                }
                            }
                        } else {
                            NSLog(@"FAILED: Remove Ubiquitous Content And Persistent Store: %@", [err description]);
                        }
                    }
                }];
            }
        };
        // Kicking off here an open will eventually land in the _documentOpenedOverride above
        [self openExistingManagedDocumentWithIdentifier:identifier];
    } else if([[NSFileManager defaultManager] fileExistsAtPath:[documentURL path]]) {
        // iCloud is not enabled right now so we simply remove the document.
        success = [[NSFileManager defaultManager] removeItemAtURL:documentURL error:&err];
        if (success) {
            [self startDocumentScan];
        }else {
            NSLog(@"Failed to delete: %@", [err description]);
        }
    }

    return success;
}

- (void)prepareForMigrationToNewiCloudAccount {
    for (NSString* identifier in _documentIdentifiers) {
        APManagedDocument* doc = [self openExistingManagedDocumentWithIdentifier:identifier];
        doc.persistentStoreOptions = @{ NSPersistentStoreRemoveUbiquitousMetadataOption : [NSNumber numberWithBool:1] };
        [doc closeWithCompletionHandler:^(BOOL success) {}];
    }
}

- (NSDictionary*)optionsForDocumentWithIdentifier:(NSString*)identifier {
    NSDictionary* options = @{
                             NSMigratePersistentStoresAutomaticallyOption   :[NSNumber numberWithBool:YES],
                             NSInferMappingModelAutomaticallyOption         :[NSNumber numberWithBool:YES]
                             };

    if (_currentUbiquityIdentityToken != nil) {
        options = @{
                 NSMigratePersistentStoresAutomaticallyOption   :[NSNumber numberWithBool:YES],
                 NSInferMappingModelAutomaticallyOption         :[NSNumber numberWithBool:YES],
                 NSPersistentStoreUbiquitousContentNameKey      :identifier,
                 NSPersistentStoreUbiquitousContentURLKey       :self.transactionLogsSubFolder
                 };
    }
    return  options;
}

- (NSString *)_generateUniqueIdentifier {
    if(!_randomSeeded)
    {
        srandomdev();
        _randomSeeded = YES;
    }
    return [NSString stringWithFormat:@"%08X_%08X", (int32_t)[[NSDate date] timeIntervalSince1970] * 1000, (int32_t)random()];
}

#pragma mark - Document Scan

- (void)startDocumentScan {
    [[NSNotificationCenter defaultCenter] postNotificationName:APDocumentScanStarted object:self];
    _documentIdentifiers = [[NSMutableArray alloc] init];

    if (_currentUbiquityIdentityToken != nil) {
        // We have iCloud access so we will do a metadata query
        [self stopDocumentScan];
        if (!_orphanedLocalFileScanDone)
            [self _migrateOrphanedLocalFiles];
        [self _scanForUbiquitousFiles];
    } else {
        // iCloud is currently unavailable (user is signed out or has disabled
        //   iCloud for our app). We need to do an intelligent local file scan.
        [self _scanForLocalFiles];
    }
}

- (void)stopDocumentScan {
    [_documentQuery stopQuery];
    _documentQuery = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:APDocumentScanCancelled object:self];
}

- (void)_scanForLocalFiles {
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSArray* contents =
    [fileManager contentsOfDirectoryAtURL:self.documentsURL
                                  includingPropertiesForKeys:nil
                                                     options:0
                                                       error:nil];

    for (NSURL* url in contents) {
        // Determine if this is can be considered a local store
        NSString* identifier = [self _identifierIfURLIsForValidLocalStorePath:url];
        if (identifier)
            [self _processDocumentWithIdentifier:identifier];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:APDocumentScanFinished object:self];
}

- (NSString*)_identifierIfURLIsForValidLocalStorePath:(NSURL*)url {
    NSString* identifier = nil;
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSArray *keys = @[NSURLPathKey, NSURLNameKey, NSURLParentDirectoryURLKey];
    NSDirectoryEnumerator *enumerator = [fileManager
                                         enumeratorAtURL:url
                                         includingPropertiesForKeys:keys
                                         options:0
                                         errorHandler:^(NSURL *url, NSError *error) {
                                             NSLog(@"Local file scan error: %@", [error description]);
                                             return YES;
                                         }];
    for (NSURL *subURL in enumerator) {
        NSError *error;
        NSString* fileName = nil;
        NSString* urlPathKey = nil;
        if (![subURL getResourceValue:&fileName forKey:NSURLNameKey error:&error]) {
            NSLog(@"Something went wrong. NSURLNameKey seems to be missing. %@", [error description]);
        }
        else if ([fileName isEqualToString:[APManagedDocument persistentStoreName]]) {
            if (![subURL getResourceValue:&urlPathKey forKey:NSURLPathKey error:&error]) {
                NSLog(@"Something went wrong. NSURLPathKey seems to be missing. %@", [error description]);
            }
            else
            {
                NSString* searchPattern = [NSString stringWithFormat:@"([^/.]+_%@(_[A-F0-9]{8}_[A-F0-9]{8}|))%@/StoreContent/%@",
                                           self.documentSetIdentifier,
                                           self.documentsExtention ?
                                                [NSString stringWithFormat:@"\\.%@", self.documentsExtention] :
                                                @"",
                                           [APManagedDocument persistentStoreName]];

                NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:searchPattern
                                                                                options:NSRegularExpressionCaseInsensitive
                                                                                error:&error];
                NSTextCheckingResult* match = [regex firstMatchInString:urlPathKey options:0 range:NSMakeRange(0, [urlPathKey length])];
                if (match && !NSEqualRanges([match rangeAtIndex:1], NSMakeRange(NSNotFound, 0))) {
                    identifier = [urlPathKey substringWithRange:[match rangeAtIndex:1]];
                    break;
                }
            }
        }
    }
    return identifier;
}

- (void) _migrateOrphanedLocalFiles {
    if ([[NSFileManager defaultManager] ubiquityIdentityToken]) {
        NSFileManager* fileManager = [NSFileManager defaultManager];
        NSArray* contents =
        [fileManager contentsOfDirectoryAtURL:self.documentsURL
                   includingPropertiesForKeys:nil
                                      options:0
                                        error:nil];

        __block int orphanedFilesOpened = 0;
        __unsafe_unretained typeof(self) weakSelf = self;
        for (NSURL* url in contents) {
            // Determine if this is can be considered a local store
            NSString* identifier = [self _identifierIfURLIsForValidLocalStorePath:url];
            if (identifier){
                // Opening and then closing the document is enough to get it moved over to the
                // iCloud space.
                _documentOpenedOverride = ^(APManagedDocument* doc, BOOL success) {
                    [doc closeWithCompletionHandler:^(BOOL success){
                        if (!success)
                            NSLog(@"Something went wrong. The document failed to close");
                        orphanedFilesOpened--;
                        if (orphanedFilesOpened == 0) {
                            weakSelf->_orphanedLocalFileScanDone = YES;
                            // Now that all the orphaned files have been
                            // migrated to use iCloud sync we can kick off a
                            // fresh document scan and find these files using a
                            // meta data scan
                            [weakSelf startDocumentScan];
                        }
                    }];
                };
                orphanedFilesOpened++;
                NSLog(@"Migrating document: %@", identifier);
                [self openExistingManagedDocumentWithIdentifier:identifier];
            }
        }
    }
}

- (void)_scanForUbiquitousFiles {
        _documentQuery = [[NSMetadataQuery alloc] init];
        [_documentQuery setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDataScope]];
        [_documentQuery setPredicate:[NSPredicate predicateWithFormat:@"%K like %@",
                                        NSMetadataItemFSNameKey,
                                        @"*"]];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_queryStarted:) name:NSMetadataQueryDidStartGatheringNotification object:_documentQuery];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_queryUpdated:) name:NSMetadataQueryDidUpdateNotification object:_documentQuery];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_queryGatheringProgress:) name:NSMetadataQueryGatheringProgressNotification object:_documentQuery];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_queryFinished:) name:NSMetadataQueryDidFinishGatheringNotification object:_documentQuery];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (![_documentQuery startQuery]) {
                NSLog(@"NSMetadataQuery failed to start!");
            }
        });
}

- (void)_processDocumentWithIdentifier:(NSString*)identifier {
    if (identifier && ![_documentIdentifiers containsObject:identifier])
    {
        NSLog(@"Processing Document: %@", identifier);
        [_documentIdentifiers addObject:identifier];
        NSDictionary* userInfo = [NSDictionary dictionaryWithObject:identifier forKey:@"documentIdentifier"];
        [[NSNotificationCenter defaultCenter] postNotificationName:APNewDocumentFound object:self userInfo:userInfo];
    }
}

- (NSString*)_findIdentifierInPath:(NSString*)path {
    NSString* identifier = nil;
    NSError* error = nil;
    NSString* searchPattern = [NSString stringWithFormat:@"([^/.]+_%@_[A-F0-9]{8}_[A-F0-9]{8})",self.documentSetIdentifier];

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:searchPattern
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:path options:0 range:NSMakeRange(0, [path length])];
    if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
        identifier = [path substringWithRange:rangeOfFirstMatch];
    }
    return identifier;
}

- (void)_queryStarted:(NSNotification*)notif {
    NSLog(@"Scan started gathering...");
}

- (void)_queryUpdated:(NSNotification*)notif {
    NSLog(@"Scan did update...");
}

- (void)_queryGatheringProgress:(NSNotification*)notif {
    NSLog(@"Scan gathering progress...");
}

- (void)_queryFinished:(NSNotification*)notif {
    [_documentQuery disableUpdates];
    NSArray *results = [_documentQuery results];

    for (NSMetadataItem *item in results) {
        NSURL *itemurl = [item valueForAttribute:NSMetadataItemURLKey];
        NSString* identifier = [self _findIdentifierInPath:[itemurl path]];
        [self _processDocumentWithIdentifier:identifier];
    }

    [_documentQuery enableUpdates];
    [[NSNotificationCenter defaultCenter] postNotificationName:APDocumentScanFinished object:self];
}

- (NSArray*)documentIdentifiers {
    return [NSArray arrayWithArray:_documentIdentifiers];
}
@end


text:
+++
author = "Hugo Authors"
title = "Emoji Support"
date = "2019-03-05"
description = "Guide to emoji usage in Hugo"
tags = [
    "emoji",
]
draft = true
+++

Emoji can be enabled in a Hugo project in a number of ways.

The [`emojify`](https://gohugo.io/functions/emojify/) function can be called directly in templates or [Inline Shortcodes](https://gohugo.io/templates/shortcode-templates/#inline-shortcodes).

To enable emoji globally, set `enableEmoji` to `true` in your site's [configuration](https://gohugo.io/getting-started/configuration/) and then you can type emoji shorthand codes directly in content files; e.g.

🙈 :see_no_evil:  🙉 :hear_no_evil:  🙊 :speak_no_evil:

The [Emoji cheat sheet](http://www.emoji-cheat-sheet.com/) is a useful reference for emoji shorthand codes.

***

**N.B.** The above steps enable Unicode Standard emoji characters and sequences in Hugo, however the rendering of these glyphs depends on the browser and the platform. To style the emoji you can either use a third party emoji font or a font stack; e.g.

{{< highlight html >}}
.emoji {
  font-family: Apple Color Emoji, Segoe UI Emoji, NotoColorEmoji, Segoe UI Symbol, Android Emoji, EmojiSymbols;
}
{{< /highlight >}}

{{< css.inline >}}

{{< /css.inline >}}

redpajama_set_name: RedPajamaGithub


text:
package org.kuali.kfs.coa.businessobject;

import java.util.LinkedHashMap;

import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
import org.kuali.rice.krad.bo.PersistableBusinessObjectBase;

/**
 *
 */
public class ObjectConsolidation extends PersistableBusinessObjectBase implements MutableInactivatable {

    /**
     * Default no-arg constructor.
     */
    public ObjectConsolidation() {

    }

    private String chartOfAccountsCode;
    private String finConsolidationObjectCode;
    private String finConsolidationObjectName;
    private String finConsolidationObjShortName;
    private boolean active;
    private String financialReportingSortCode;

    private Chart chartOfAccounts;

    /**
     * Gets the chartOfAccountsCode attribute.
     *
     * @return Returns the chartOfAccountsCode.
     */
    public String getChartOfAccountsCode() {
        return chartOfAccountsCode;
    }

    /**
     * Sets the chartOfAccountsCode attribute value.
     *
     * @param chartOfAccountsCode The chartOfAccountsCode to set.
     */
    public void setChartOfAccountsCode(String chartOfAccountsCode) {
        this.chartOfAccountsCode = chartOfAccountsCode;
    }

    /**
     * Gets the finConsolidationObjectCode attribute.
     *
     * @return Returns the finConsolidationObjectCode.
     */
    public String getFinConsolidationObjectCode() {
        return finConsolidationObjectCode;
    }

    /**
     * Sets the finConsolidationObjectCode attribute value.
     *
     * @param finConsolidationObjectCode The finConsolidationObjectCode to set.
     */
    public void setFinConsolidationObjectCode(String finConsolidationObjectCode) {
        this.finConsolidationObjectCode = finConsolidationObjectCode;
    }

    /**
     * Gets the finConsolidationObjectName attribute.
     *
     * @return Returns the finConsolidationObjectName
     */
    public String getFinConsolidationObjectName() {
        return finConsolidationObjectName;
    }

    /**
     * Sets the finConsolidationObjectName attribute.
     *
     * @param finConsolidationObjectName The finConsolidationObjectName to set.
     */
    public void setFinConsolidationObjectName(String finConsolidationObjectName) {
        this.finConsolidationObjectName = finConsolidationObjectName;
    }

    /**
     * Gets the finConsolidationObjShortName attribute.
     *
     * @return Returns the finConsolidationObjShortName
     */
    public String getFinConsolidationObjShortName() {
        return finConsolidationObjShortName;
    }

    /**
     * Sets the finConsolidationObjShortName attribute.
     *
     * @param finConsolidationObjShortName The finConsolidationObjShortName to set.
     */
    public void setFinConsolidationObjShortName(String finConsolidationObjShortName) {
        this.finConsolidationObjShortName = finConsolidationObjShortName;
    }

    /**
     * Gets the active attribute.
     *
     * @return Returns the active
     */
    public boolean isActive() {
        return active;
    }

    /**
     * Sets the active attribute.
     *
     * @param active The active to set.
     */
    public void setActive(boolean active) {
        this.active = active;
    }

    /**
     * Gets the financialReportingSortCode attribute.
     *
     * @return Returns the financialReportingSortCode
     */
    public String getFinancialReportingSortCode() {
        return financialReportingSortCode;
    }

    /**
     * Sets the financialReportingSortCode attribute.
     *
     * @param financialReportingSortCode The financialReportingSortCode to set.
     */
    public void setFinancialReportingSortCode(String financialReportingSortCode) {
        this.financialReportingSortCode = financialReportingSortCode;
    }

    /**
     * Gets the chartOfAccounts attribute.
     *
     * @return Returns the chartOfAccounts
     */
    public Chart getChartOfAccounts() {
        return chartOfAccounts;
    }

    /**
     * Sets the chartOfAccounts attribute.
     *
     * @param chartOfAccounts The chartOfAccounts to set.
     * @deprecated
     */
    public void setChartOfAccounts(Chart chartOfAccounts) {
        this.chartOfAccounts = chartOfAccounts;
    }

    /**
     * @see org.kuali.rice.krad.bo.BusinessObjectBase#toStringMapper()
     */
    protected LinkedHashMap toStringMapper_RICE20_REFACTORME() {
        LinkedHashMap m = new LinkedHashMap();

        m.put("chartOfAccountsCode", this.chartOfAccountsCode);
        m.put("finConsolidationObjectCode", this.finConsolidationObjectCode);

        return m;
    }

}


text:
using System.Collections.Generic;
using KPI.Infrastructure;

namespace KPI.Catalog.Domain
{
    public class ProductAttributeGroup : Entity
    {
        public string Name { get; set; }

        public virtual IList<ProductAttribute> Attributes { get; set; } = new List<ProductAttribute>();
    }
}


text:
module Fixtures
  module CodeUnionAPI
    def self.search_results
      { "REST API" =>
        [{
          "name"        => "linkedout-example",
          "description" => "Example code for codeunion/linkedout: a one-page resume management system.",
          "private"     => true,
          "url"         => "https://github.com/codeunion/linkedout-example",
          "category"    => "examples",
          "tags"        => ["ruby", "sinatra", "javascript", "jquery", "ajax", "request-routing", "json", "dom-manipulation"],
          "access"      => ["students", "staff"],
          "license"     => true,
          "has_wiki"    => false,
          "notes"       => "",
          "excerpt"     => "<match>api</match>-post]:http://api.jquery.com/jquery.post/\n[jquery-<match>api</match>-append]:http://api.jquery.com/append/\n[jquery-<match>api</match>-serialize]:http://api.jquery.com"
        }, {
          "name"        => "overheard-server",
          "description" => "Example project for a web app that stores and shares hilarious, out of context quotess and quips.",
          "private"     =>  false,
          "url"         => "https://github.com/codeunion/overheard-server",
          "category"    => "examples",
          "tags"        => ["ruby", "sinatra", "datamapper", "sqlite"],
          "access"      => ["public", "students", "staff"],
          "license"     => true,
          "has_wiki"    => false,
          "notes"       => "Unclear purpose. Is it an example project or a tool?",
          "excerpt"     => "<match>REST</match> <match>API</match> to add and list Overheards\n\nFor a list of planned and implemented features"
        }]
      }
    end
  end
end


text:
			<input
				type="radio"
				class="t3-install-tool-configuration-radio"
				id="t3-install-tool-configuration-context-custom"
				name="install[values][{feature.name}][enable]"
				value="{preset.name}"
				{f:if(condition: preset.isActive, then:'checked="checked"')}
			/>

					Custom configuration

				{f:if(condition: preset.isActive, then:' [Active]')}

">

			Custom configuration mixture if no other preset fits.

		<f:for each="{preset.configurationValues}" as="configurationValue" key="configurationKey">

				{configurationKey}

					<input
						id="{feature.name}{preset.name}{configurationKey}"
						type="text"
						name="install[values][{feature.name}][{preset.name}][{configurationKey}]"
						value="{configurationValue}"
						class="form-control t3js-custom-preset"
						data-radio="t3-install-tool-configuration-context-custom"
					/>

		</f:for>


text:
EXTENSION = history
DATA = history--0.1.sql

PG_CONFIG = pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)


text:
export const LOAD_ALL_ENROLMENTS_START = 'LOAD_ALL_ENROLMENTS_START';
export const LOAD_ALL_ENROLMENTS_SUCCESS = 'LOAD_ALL_ENROLMENTS_SUCCESS';
export const LOAD_ALL_ENROLMENTS_FAIL = 'LOAD_ALL_ENROLMENTS_START';

export const LOAD_ONE_ENROLMENT_START = 'LOAD_ONE_ENROLMENT_START';
export const LOAD_ONE_ENROLMENT_SUCCESS = 'LOAD_ONE_ENROLMENT_SUCCESS';
export const LOAD_ONE_ENROLMENT_FAIL = 'LOAD_ONE_ENROLMENT_FAIL';

export const LOAD_ONE_BENEFIT_START = 'LOAD_ONE_BENEFIT_START';
export const LOAD_ONE_BENEFIT_SUCCESS = 'LOAD_ONE_BENEFIT_SUCCESS';
export const LOAD_ONE_BENEFIT_FAIL = 'LOAD_ONE_BENEFIT_FAIL';

export const LOAD_ONE_STATUS_START = 'LOAD_ONE_STATUS_START';
export const LOAD_ONE_STATUS_SUCCESS = 'LOAD_ONE_STATUS_SUCCESS';
export const LOAD_ONE_STATUS_FAIL = 'LOAD_ONE_STATUS_FAIL';

export const ENROLMENTS_LIST_PAGE_WIDTH_CHANGED = 'ENROLMENTS_LIST_PAGE_WIDTH_CHANGED';

export const ENROLMENTS_FIELD_NAMES = {
  id:               {'name': '№',                       'width': 40},
  personId:         {'name': 'Персона (id)',            'width': 70},
  specofferId:      {'name': 'Пропозиція (id)',         'width': 90},
  isState:          {'name': 'Бюджет',                  'width': 70},
  isContract:       {'name': 'Контракт',                'width': 80},
  departmentId:     {'name': 'Підрозділ',               'width': 100},
  mark:             {'name': 'Загальний бал',           'width': 90},
  isPrivilege:      {'name': 'Наявність пільг',         'width': 80},
  docSeries:        {'name': 'Серія док.',              'width': 80},
  docNum:           {'name': 'Номер док.',              'width': 80},
  isHostel:         {'name': 'Потреб. гуртож',          'width': 80},
  enrolmentTypeId:  {'name': 'Тип поступлення',         'width': 100},
  isInterview:      {'name': 'Відмітка про співбесіду', 'width': 100}
};

export const isStateNames = ['\u2718', '\u2713'];
export const isContractNames = ['\u2718', '\u2713'];
export const isPrivilegeNames = ['пільги відсутні', 'є пільги'];
export const isHostelNames = ['не потреб. гуртож.', 'потреб. гуртож.'];

export const isEducationStateNames = {
  0: 'Не отримую освіти',
  1: 'Отримую освіту',
  11: 'Є вища освіта'
};

export const isInterviewNames = {
  '-1': 'Не пройшов співбесіду',
  '0': 'Не потрібно співбесіди',
  '1': 'Потрібна співбесіда',
  '11': 'Співбесіда пройдена'
};

export const isOriginalNames = ['\u2718', '\u2713'];


text:
package org.ovirt.engine.core.bll;

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

import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.MigrateVmToServerParameters;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.compat.Guid;

@NonTransactiveCommandAttribute
public class MigrateVmToServerCommand<T extends MigrateVmToServerParameters> extends MigrateVmCommand<T> {
    public MigrateVmToServerCommand(T parameters) {
        this(parameters, null);
    }

    public MigrateVmToServerCommand(T parameters, CommandContext commandContext) {
        super(parameters, commandContext);
        setDestinationVdsId(parameters.getVdsId());
    }

    @Override
    protected LockProperties applyLockProperties(LockProperties lockProperties) {
        return lockProperties.withScope(Scope.Command);
    }

    @Override
    protected boolean canDoAction() {
        if (getDestinationVds() == null) {
            return failCanDoAction(EngineMessage.VDS_INVALID_SERVER_ID);
        }

        if (getDestinationVds().getStatus() != VDSStatus.Up) {
            addCanDoActionMessage(EngineMessage.VAR__HOST_STATUS__UP);
            return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL);
        }

        if (!super.canDoAction()) {
            return false;
        }

        if (getParameters().getTargetVdsGroupId() != null && !getParameters().getTargetVdsGroupId().equals(getDestinationVds().getVdsGroupId())) {
            return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_DESTINATION_HOST_NOT_IN_DESTINATION_CLUSTER);
        }

        if (getVm().getRunOnVds() != null && getVm().getRunOnVds().equals(getDestinationVdsId())) {
            return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_MIGRATION_TO_SAME_HOST);
        }

        if (!getVm().getVdsGroupId().equals(getDestinationVds().getVdsGroupId()) && getParameters().getTargetVdsGroupId() == null) {
            return failCanDoAction(EngineMessage.ACTION_TYPE_FAILED_MIGRATE_BETWEEN_TWO_CLUSTERS);
        }

        return true;
    }

    @Override
    protected AuditLogType getAuditLogForMigrationFailure() {
        return AuditLogType.VM_MIGRATION_TO_SERVER_FAILED;
    }

    /**
     * In case we failed to migrate to that specific server, the VM should no longer be pending,
     * and we report failure, without an attempt to rerun
     */
    @Override
    public void rerun() {
        // make VM property to null in order to refresh it from db
        setVm(null);
        determineMigrationFailureForAuditLog();
        runningFailed();
    }

    @Override
    protected List<Guid> getVdsWhiteList() {
        return Arrays.asList(getDestinationVdsId());
    }

    @Override
    public Map<String, String> getJobMessageProperties() {
        jobProperties = super.getJobMessageProperties();
        if (getDestinationVdsName() != null) {
            jobProperties.put(VdcObjectType.VDS.name().toLowerCase(), getDestinationVdsName());
        }
        return jobProperties;
    }
}


text:
package org.apache.tomcat.util.collections;

import java.util.Enumeration;
import java.util.NoSuchElementException;

public class EmptyEnumeration implements Enumeration {

    static EmptyEnumeration staticInstance=new EmptyEnumeration();

    public EmptyEnumeration() {
    }

    public static Enumeration getEmptyEnumeration() {
	return staticInstance;
    }

    public Object nextElement( ) {
	throw new NoSuchElementException( "EmptyEnumeration");
    }

    public boolean hasMoreElements() {
	return false;
    }

}


text:
@interface ImageAnimations : NSObject

+ (void)spinLayer:(CALayer *)inLayer duration:(CFTimeInterval)inDuration direction:(int)direction;

@end


text:
<?php

namespace api\modules\v2\controllers;

use Yii;
use yii\rest\ActiveController;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
use yii\helpers\Response;

class UserController extends ActiveController
{
    public $modelClass = 'api\modules\v2\models\User';
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',

    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        // token 验证  请按需开启
         /*$behaviors['authenticator'] = [
             'class' => CompositeAuth::className(),
             'authMethods' => [
                 QueryParamAuth::className(),
             ],
         ];*/
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        // 注销系统自带的实现方法
        unset($actions['index'], $actions['update'], $actions['create'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionIndex()
    {
        $modelClass = $this->modelClass;
        $query = $modelClass::find();

        return new ActiveDataProvider([
            'query' => $query,
        ]);
    }

    public function actionCreate()
    {
       /* $model = new $this->modelClass();
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if (!$model->save()) {
            return array_values($model->getFirstErrors())[0];
        }

        return $model;*/
        Response::show(401,'不允许的操作');

    }

    public function actionUpdate($id)
    {
      $model = $this->findModel($id);
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if (!$model->save()) {
            return array_values($model->getFirstErrors())[0];
        }
        //return $model;

        Response::show(202,'修改成功');
    }

    public function actionDelete($id)
    {
        /*return $this->findModel($id)->delete();*/
        Response::show(401,'不允许的操作');
    }

    public function actionView($id)
    {
        $command = Yii::$app->db->createCommand('SELECT u.id as user_id,u.groupid,u.username,u.nickname,u.email,u.cellphone,u.sex,u.status,u.avatar,u.created_at,
                                                        ud.post_count,ud.feed_count,ud.following_count,ud.follower_count,ud.thread_count,ud.empirical_value,ud.unread_message_count,
                                                        up.birthdate,up.signature,up.address,up.description as self_introduction,up.mark,up.make_friend,up.hobby,up.height,up.weight
                                                        FROM {{%user}} as u LEFT JOIN {{%user_data}} as ud ON ud.user_id=u.id LEFT JOIN {{%user_profile}} as up ON up.user_id=u.id WHERE id='.$id);
        $post = $command->queryOne();

        $post['mark'] = json_decode($post['mark']);
        $post['make_friend'] = json_decode($post['make_friend']);
        $post['hobby'] = json_decode($post['hobby']);
        return $post;
/*        $model = $this->findModel($id);
        $model->avatar = 'http://182.254.217.147:8888/uploads/user/avatar/'.$model->avatar;
        return $model;*/

    }

    protected function findModel($id)
    {
        $modelClass = $this->modelClass;
        if (($model = $modelClass::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

}


text:
__author__ = 'reggie'

import pika
import time
import ujson as json

from Queue import *
from PmkShared import *

class mx(Queue):
    def __init__(self, maxsize=0):
        Queue.__init__(self, maxsize)
        pass

class lx(Queue):
    def __init__(self, maxsize=0):
        Queue.__init__(self, maxsize)
        pass

class Monitor(object):

    def get_id(self):
        pass
    def connect(self, connect_to):
        pass
    def write(self, message):
        pass
    def close(self):
        pass

class LogDisptacher(SThread):
    def __init__(self, context):
        SThread.__init__(self)
        self.context = context
        self.mx = self.context.get_mx()
        self.monitors = {}

    def add_monitor(self, monitor):
        self.monitors[monitor.get_id()] = monitor

    def run(self):
        while 1:
            message = self.mx.get(True)
            for monitor in self.monitors.keys():
                mon = self.monitors[monitor]
                mon.write(message)

        pass

class RabbitMqLog(Monitor):
    def __init__(self, context):
        Monitor.__init__(self)
        self.context = context
        self.connection = None
        self.channel = None
        self.queue = None
        logging.info("Created RabbitMQMonitor")
        pass

    def __open_rabbitmq_connection(self):
        host, port, username, password, vhost = self.context.get_rabbitmq_cred()
        credentials = pika.PlainCredentials(username, password)
        connection = pika.BlockingConnection(pika.ConnectionParameters(host=host, credentials=credentials, virtual_host=vhost))
        #channel = self.connection.channel()
        return connection

    def connect(self, queue):
        self.queue = queue
        self.connection = self.__open_rabbitmq_connection()
        self.channel = self.connection.channel()
        self.channel.exchange_declare(exchange=str(self.queue), type='fanout')
        #self.channel.queue_declare(exchange=str(self.queue), queue=str(self.queue), durable=False)

    def write(self, data):
        send = False
        message = json.dumps(data)
        while not send:
            try:
                if not self.connection.is_closed:
                    logging.info("Sending message to rabbitmq")
                    self.channel.basic_publish(exchange=str(self.queue),routing_key='',body=message)
                    send = True
                else:
                    self.connect(None)
                    logging.info("Sending message to rabbitmq")
                    self.channel.basic_publish(exchange=str(self.queue),routing_key='',body=message)
                    send = True
            except:
                time.sleep(1)
        pass


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE546_Suspicious_Comment__TODO_01.c
Label Definition File: CWE546_Suspicious_Comment.label.xml
Template File: point-flaw-01.tmpl.c
*/
/*
 * @description
 * CWE: 546 Suspicious Comment
 * Sinks: TODO
 *    GoodSink: Comments show no indications that the code is unfinished
 *    BadSink : Comment contains the word TODO
 * Flow Variant: 01 Baseline
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE546_Suspicious_Comment__TODO_01_bad()
{
    /* FLAW: The following comment has the letters 'TODO' in it*/
    /* TODO: This comment has the letters 'TODO' in it, which is certainly
     * suspicious, because it could indicate this code is not finished.
     */
    printLine("Hello");
}

#endif /* OMITBAD */

#ifndef OMITGOOD

static void good1()
{
    /* FIX: Removed the suspicious comments */
    printLine("Hello");
}

void CWE546_Suspicious_Comment__TODO_01_good()
{
    good1();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE546_Suspicious_Comment__TODO_01_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE546_Suspicious_Comment__TODO_01_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
import * as assert from 'assert';
import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock';
import URI from 'vs/base/common/uri';
import { TestEditorService, workbenchInstantiationService } from 'vs/workbench/test/workbenchTestServices';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { ModeServiceImpl } from 'vs/editor/common/services/modeServiceImpl';
import WorkbenchEditorService = require('vs/workbench/services/editor/common/editorService');
import { RangeHighlightDecorations } from 'vs/workbench/common/editor/rangeDecorations';
import { Model } from 'vs/editor/common/model/model';
import { mockCodeEditor, MockCodeEditor } from 'vs/editor/test/common/mocks/mockCodeEditor';
import * as editorCommon from 'vs/editor/common/editorCommon';
import { IEditorInput } from 'vs/platform/editor/common/editor';
import { FileEditorInput } from 'vs/workbench/parts/files/common/editors/fileEditorInput';
import { TextModel } from 'vs/editor/common/model/textModel';
import { Range } from 'vs/editor/common/core/range';
import { Position } from 'vs/editor/common/core/position';
import { Cursor } from 'vs/editor/common/controller/cursor';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { ModelServiceImpl } from 'vs/editor/common/services/modelServiceImpl';

suite('Editor - Range decorations', () => {

	let instantiationService: TestInstantiationService;
	let editorService: WorkbenchEditorService.IWorkbenchEditorService;
	let modelService: IModelService;
	let modeService: IModeService;
	let codeEditor: editorCommon.ICommonCodeEditor;
	let cursor: Cursor;
	let model: Model;
	let text: string;
	let testObject: RangeHighlightDecorations;
	let modelsToDispose: Model[] = [];

	setup(() => {
		instantiationService = <TestInstantiationService>workbenchInstantiationService();
		editorService = <WorkbenchEditorService.IWorkbenchEditorService>instantiationService.stub(WorkbenchEditorService.IWorkbenchEditorService, new TestEditorService());
		modeService = instantiationService.stub(IModeService, ModeServiceImpl);
		modelService = <IModelService>instantiationService.stub(IModelService, stubModelService(instantiationService));
		text = 'LINE1' + '\n' + 'LINE2' + '\n' + 'LINE3' + '\n' + 'LINE4' + '\r\n' + 'LINE5';
		model = aModel(URI.file('some_file'));
		codeEditor = mockCodeEditor([], { model });
		cursor = (<MockCodeEditor>codeEditor).getCursor();
		mockEditorService(codeEditor.getModel().uri);

		instantiationService.stub(WorkbenchEditorService.IWorkbenchEditorService, 'getActiveEditor', { getControl: () => { return codeEditor; } });

		testObject = instantiationService.createInstance(RangeHighlightDecorations);
	});

	teardown(() => {
		codeEditor.dispose();
		modelsToDispose.forEach(model => model.dispose());
	});

	test('highlight range for the resource if it is an active editor', function () {
		let range: editorCommon.IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 };
		testObject.highlightRange({ resource: model.uri, range });

		let actuals = rangeHighlightDecorations(model);

		assert.deepEqual([range], actuals);
	});

	test('remove highlight range', function () {
		testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } });
		testObject.removeHighlightRange();

		let actuals = rangeHighlightDecorations(model);

		assert.deepEqual([], actuals);
	});

	test('highlight range for the resource removes previous highlight', function () {
		testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } });
		let range: editorCommon.IRange = { startLineNumber: 2, startColumn: 2, endLineNumber: 4, endColumn: 3 };
		testObject.highlightRange({ resource: model.uri, range });

		let actuals = rangeHighlightDecorations(model);

		assert.deepEqual([range], actuals);
	});

	test('highlight range for a new resource removes highlight of previous resource', function () {
		testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } });

		let anotherModel = prepareActiveEditor('anotherModel');
		let range: editorCommon.IRange = { startLineNumber: 2, startColumn: 2, endLineNumber: 4, endColumn: 3 };
		testObject.highlightRange({ resource: anotherModel.uri, range });

		let actuals = rangeHighlightDecorations(model);
		assert.deepEqual([], actuals);
		actuals = rangeHighlightDecorations(anotherModel);
		assert.deepEqual([range], actuals);
	});

	test('highlight is removed on model change', function () {
		testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } });
		prepareActiveEditor('anotherModel');

		let actuals = rangeHighlightDecorations(model);
		assert.deepEqual([], actuals);
	});

	test('highlight is removed on cursor position change', function () {
		testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } });
		cursor.trigger('mouse', editorCommon.Handler.MoveTo, {
			position: new Position(2, 1)
		});

		let actuals = rangeHighlightDecorations(model);
		assert.deepEqual([], actuals);
	});

	test('range is not highlight if not active editor', function () {
		let model = aModel(URI.file('some model'));
		testObject.highlightRange({ resource: model.uri, range: { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 } });

		let actuals = rangeHighlightDecorations(model);
		assert.deepEqual([], actuals);
	});

	test('previous highlight is not removed if not active editor', function () {
		let range: editorCommon.IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 1 };
		testObject.highlightRange({ resource: model.uri, range });

		let model1 = aModel(URI.file('some model'));
		testObject.highlightRange({ resource: model1.uri, range: { startLineNumber: 2, startColumn: 1, endLineNumber: 2, endColumn: 1 } });

		let actuals = rangeHighlightDecorations(model);
		assert.deepEqual([range], actuals);
	});

	function prepareActiveEditor(resource: string): Model {
		let model = aModel(URI.file(resource));
		codeEditor.setModel(model);
		mockEditorService(model.uri);
		return model;
	}

	function aModel(resource: URI, content: string = text): Model {
		let model = Model.createFromString(content, TextModel.DEFAULT_CREATION_OPTIONS, null, resource);
		modelsToDispose.push(model);
		return model;
	}

	function mockEditorService(editorInput: IEditorInput);
	function mockEditorService(resource: URI);
	function mockEditorService(arg: any) {
		let editorInput: IEditorInput = arg instanceof URI ? instantiationService.createInstance(FileEditorInput, arg, void 0) : arg;
		instantiationService.stub(WorkbenchEditorService.IWorkbenchEditorService, 'getActiveEditorInput', editorInput);
	}

	function rangeHighlightDecorations(m: Model): editorCommon.IRange[] {
		let rangeHighlights: editorCommon.IRange[] = [];

		for (let dec of m.getAllDecorations()) {
			if (dec.options.className === 'rangeHighlight') {
				rangeHighlights.push(dec.range);
			}
		}

		rangeHighlights.sort(Range.compareRangesUsingStarts);
		return rangeHighlights;
	}

	function stubModelService(instantiationService: TestInstantiationService): IModelService {
		instantiationService.stub(IConfigurationService, new TestConfigurationService());
		return instantiationService.createInstance(ModelServiceImpl);
	}
});


text:
module Spree
  module Core
    class Engine < ::Rails::Engine
      def self.add_routes(&block)
        @spree_routes ||= []

        # Anything that causes the application's routes to be reloaded,
        # will cause this method to be called more than once
        # i.e. https://github.com/plataformatec/devise/blob/31971e69e6a1bcf6c7f01eaaa44f227c4af5d4d2/lib/devise/rails.rb#L14
        # In the case of Devise, this *only* happens in the production env
        # This coupled with Rails 4's insistence that routes are not drawn twice,
        # poses quite a serious problem.
        #
        # This is mainly why this whole file exists in the first place.
        #
        # Thus we need to make sure that the routes aren't drawn twice.
        unless @spree_routes.include?(block)
          @spree_routes << block
        end
      end

      def self.append_routes(&block)
        @append_routes ||= []
        # See comment in add_routes.
        unless @append_routes.include?(block)
          @append_routes << block
        end
      end

      def self.draw_routes(&block)
        @spree_routes ||= []
        @append_routes ||= []
        eval_block(block) if block_given?
        @spree_routes.each { |r| eval_block(&r) }
        @append_routes.each { |r| eval_block(&r) }
        # # Clear out routes so that they aren't drawn twice.
        @spree_routes = []
        @append_routes = []
      end

      private

        def eval_block(&block)
          Spree::Core::Engine.routes.eval_block(block)
        end
    end
  end
end


text:
package com.airlenet.scheduler.module.controller;

import java.util.Set;

import com.airlenet.data.domain.Result;
import com.airlenet.scheduler.module.entity.JobEntity;
import com.airlenet.scheduler.module.entity.JobPrimaryKey;
import com.airlenet.scheduler.module.model.JobModel;
import com.airlenet.scheduler.module.service.JobService;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.jobs.ee.mail.SendMailJob;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;

import com.airlenet.scheduler.module.entity.JobType;
import com.airlenet.scheduler.module.model.JobModel;
import com.airlenet.webapp.BaseController;

import javax.validation.Valid;

@Controller
@RequestMapping("/job")
public class JobController extends BaseController {

	@Autowired
	private ObjectFactory<Scheduler> scheduler;

	@Autowired
	private JobService jobService;
	@RequestMapping(value = "/page", method = RequestMethod.POST)
	@ResponseBody
	public Page<JobModel> doPage(Pageable pageable) throws SchedulerException {
		Set<JobKey> jobKeys = scheduler.getObject().getJobKeys(GroupMatcher.anyJobGroup());
		return new PageImpl<>(Lists.newArrayList(jobKeys), pageable, jobKeys.size()).map(jobKey -> {
			JobModel jobModel = new JobModel();
			try {
				JobDetail jobDetail = scheduler.getObject().getJobDetail(jobKey);
				jobModel.setJobName(jobDetail.getKey().getName());
				jobModel.setJobGroup(jobDetail.getKey().getGroup());
				jobModel.setJobClass(jobDetail.getJobClass());
				jobModel.setDescription(jobDetail.getDescription());
				jobModel.setDurable(jobDetail.isDurable());
				jobModel.setRequestsRecovery(jobDetail.requestsRecovery());
				// jobModel.setData(jobDetail.getJobDataMap());
			} catch (SchedulerException e) {
				e.printStackTrace();
			}
			return jobModel;
		});
	}

	@RequestMapping(value = { "", "/", "/list" }, method = RequestMethod.GET)
	public String show(Model model) {
		model.addAttribute("jobTypes", JobType.values());
		return "/job/list";
	}

	@RequestMapping(value = { "/add", "/edit" }, method = RequestMethod.GET)
	public String add(Model model) {
		JobModel jobModel = new JobModel();
		JobType jobType = getParameter("type", JobType.class, JobType.no_op);
		jobModel.setJobClass(jobType.getJobClass());
		return edit(jobModel, model);
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(JobModel entity, Model model) {
		model.addAttribute("jobType", jobClassToType(entity.getJobClass()));
		model.addAttribute("entity", entity);
		return "/job/edit";
	}

	private JobType jobClassToType(Class<? extends Job> jobClass) {
		for (JobType jobType : JobType.values()) {
			if (jobType.getJobClass().isAssignableFrom(jobClass)) {
				return jobType;
			}
		}

		return null;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Result doSave(@ModelAttribute @Valid JobModel jobModel, BindingResult bindingResult) {

		try {
			scheduler.getObject().addJob(JobBuilder.newJob(SendMailJob.class)
					.usingJobData(new JobDataMap(jobModel.getData()))
					.withDescription(jobModel.getDescription())
					.storeDurably(true)
					.requestRecovery(true)
					.withIdentity(jobModel.getJobName())

					.build(),false);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
//		onValidate(entity, bindingResult);
//		if (bindingResult.hasErrors()) {
//			return Result.validateError().error(bindingResult.getAllErrors());
//		}JobPrimaryKey jobPrimaryKey = new JobPrimaryKey();
//		jobPrimaryKey.setName("");
//		jobPrimaryKey.setGroup("");
//		jobPrimaryKey.setScheduler("");
//		entity.setId(jobPrimaryKey);
//		entity.setJobClassName("org.quartz.jobs.ee.mail.SendMailJob");
//		jobService.save(entity);
//		onBeforeSave(entity);

//		getService().save(entity);
//		onAfterSave(entity);

		return Result.success();
	}

}


text:
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');

var path = require('path');

var paths = {
    src: ['src/**/*.js'],
    dist: 'dist',
    // Must be absolute or relative to source map
    sourceRoot: path.join(__dirname, 'src'),
};
gulp.task('babel', function () {
    return gulp.src(paths.src)
        .pipe(sourcemaps.init())
        .pipe(plumber())
        .pipe(babel())
        .pipe(sourcemaps.write('.',
                  { sourceRoot: paths.sourceRoot }))
        .pipe(gulp.dest(paths.dist));
});
gulp.task('watch', function() {
    gulp.watch(paths.src, ['babel']);
});
gulp.task('default', ['watch']);


text:
package com.sun.jmx.remote.opt.security;

import java.security.AccessController;
import java.security.AccessControlContext;
import java.security.Permission;
import java.security.Principal;
import java.security.PrivilegedAction;
import javax.security.auth.Subject;

import javax.management.remote.SubjectDelegationPermission;

import com.sun.jmx.remote.opt.util.CacheMap;

public class SubjectDelegator {
    private static final int PRINCIPALS_CACHE_SIZE = 10;
    private static final int ACC_CACHE_SIZE = 10;

    private CacheMap principalsCache;
    private CacheMap accCache;

    /* Return the AccessControlContext appropriate to execute an
       operation on behalf of the delegatedSubject.  If the
       authenticatedAccessControlContext does not have permission to
       delegate to that subject, throw SecurityException.  */
    public synchronized AccessControlContext
	delegatedContext(AccessControlContext authenticatedACC,
			 Subject delegatedSubject)
	    throws SecurityException {

	if (principalsCache == null || accCache == null) {
	    principalsCache = new CacheMap(PRINCIPALS_CACHE_SIZE);
	    accCache = new CacheMap(ACC_CACHE_SIZE);
	}

	// Retrieve the principals for the given
	// delegated subject from the cache
	//
	Principal[] delegatedPrincipals = (Principal[])
	    principalsCache.get(delegatedSubject);

	// Convert the set of principals stored in the
	// delegated subject into an array of principals
	// and store it in the cache
	//
	if (delegatedPrincipals == null) {
	    delegatedPrincipals = (Principal[])
		delegatedSubject.getPrincipals().toArray(new Principal[0]);
	    principalsCache.put(delegatedSubject, delegatedPrincipals);
	}

	// Retrieve the access control context for the
	// given delegated subject from the cache
	//
	AccessControlContext delegatedACC = (AccessControlContext)
	    accCache.get(delegatedSubject);

	// Build the access control context to be used
	// when executing code as the delegated subject
	// and store it in the cache
	//
	if (delegatedACC == null) {
	    final JMXSubjectDomainCombiner sdc = new
		JMXSubjectDomainCombiner(delegatedSubject);
	    delegatedACC =
		new AccessControlContext(AccessController.getContext(), sdc);
	    accCache.put(delegatedSubject, delegatedACC);
	}

	// Check if the subject delegation permission allows the
	// authenticated subject to assume the identity of each
	// principal in the delegated subject
	//
	final Principal[] dp = delegatedPrincipals;
	PrivilegedAction action =
	    new PrivilegedAction() {
		public Object run() {
		    for (int i = 0 ; i < dp.length ; i++) {
			final String pname =
			    dp[i].getClass().getName() + "." + dp[i].getName();
			Permission sdp =
			    new SubjectDelegationPermission(pname);
			AccessController.checkPermission(sdp);
		    }
		    return null;
		}
	    };
	AccessController.doPrivileged(action, authenticatedACC);

	return delegatedACC;
    }
}


text:
<!doctype html>

    <meta charset="utf-8">

    <meta name="apple-mobile-web-app-capable" content="yes">

    <title>鹿秀金融</title>
    <link rel="stylesheet" href="/static/css/animate.min.css"/>
<link rel="stylesheet" href="/static/css/index.css"/>

        找回密码



请输入有效的手机号码

        <form action="/static/data/api.json" method="post" data-link="login07.html">

            <input type="number" class="lx_inp_1" placeholder="请输入手机号" id="vphone" value="13511111111" maxlength="11"/>

            <input type="number" class="lx_inp_3" placeholder="请输入验证码" id="vvalidate" maxlength="6" value="111111" />
            获取验证码

下一步

        </form>


text:
package no.deichman.services.rdf;

import no.deichman.services.uridefaults.BaseURI;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;

/**
 * Responsibility: provide constants for MediaType URIs.
 */
public final class MediaType {

    private MediaType() {}

    public static final Resource NAMESPACE = ResourceFactory.createResource(BaseURI.root() + "mediaType#");

    public static final Resource AUDIOBOOK = ResourceFactory.createResource(NAMESPACE + "Audiobook");
    public static final Resource BOOK = ResourceFactory.createResource(NAMESPACE + "Book");
    public static final Resource COMICBOOK = ResourceFactory.createResource(NAMESPACE + "ComicBook");
    public static final Resource E_BOOK = ResourceFactory.createResource(NAMESPACE + "E-book");
    public static final Resource FILM = ResourceFactory.createResource(NAMESPACE + "Film");
    public static final Resource GAME = ResourceFactory.createResource(NAMESPACE + "Game");
    public static final Resource LANGUAGECOURSE = ResourceFactory.createResource(NAMESPACE + "LanguageCourse");
    public static final Resource MUSICRECORDING = ResourceFactory.createResource(NAMESPACE + "MusicRecording");
    public static final Resource OTHER = ResourceFactory.createResource(NAMESPACE + "Other");
    public static final Resource PERIODICAL = ResourceFactory.createResource(NAMESPACE + "Periodical");
    public static final Resource SHEETMUSIC = ResourceFactory.createResource(NAMESPACE + "SheetMusic");
}


text:
.Tooltip {
  position: fixed;
}

.TooltipSection,
.TooltipWarningSection,
.SingleLineTextSection {
  display: block;
  border-radius: 0.125rem;
  padding: 0.25rem;
  user-select: none;
  pointer-events: none;
  background-color: var(--color-tooltip-background);
  box-shadow: 1px 1px 2px var(--color-shadow);
  color: var(--color-tooltip-text);
  font-size: 11px;
}
.TooltipWarningSection {
  margin-top: 0.25rem;
  background-color: var(--color-warning-background);
}
.TooltipSection,
.TooltipWarningSection {
  max-width: 300px;
}
.SingleLineTextSection {
  white-space: nowrap;
}

.Divider {
  height: 1px;
  background-color: #aaa;
  margin: 0.25rem 0;
}

.DetailsGrid {
  display: grid;
  padding-top: 5px;
  grid-gap: 2px 5px;
  grid-template-columns: min-content auto;
}

.DetailsGridLabel {
  color: var(--color-dim);
  text-align: right;
  white-space: nowrap;
}

.DetailsGridURL {
  word-break: break-all;
  max-height: 50vh;
  overflow: hidden;
}

.FlamechartStackFrameName {
  word-break: break-word;
}

.ComponentName {
  font-weight: bold;
  word-break: break-word;
  margin-right: 0.25rem;
}

.ReactMeasureLabel {
}

.UserTimingLabel {
  word-break: break-word;
}

.NativeEventName {
  font-weight: bold;
  word-break: break-word;
  margin-right: 0.25rem;
}

.InfoText,
.WarningText {
  color: var(--color-warning-text-color);
}

.Image {
  border: 1px solid var(--color-border);
}

.DimText {
  color: var(--color-dim);
}


text:
package arithmospora

import (
	"encoding/json"
	"fmt"
	"sync"
	"time"
)

type StatData interface {
	Refresh() error
	json.Marshaler
	fmt.Stringer
}

type StatDataLoader interface {
	Load(*Stat) (StatData, error)
	fmt.Stringer
}

type StatDataPointLoader interface {
	DataPointNames() ([]string, error)
	NewDataLoader(StatDataLoader, string) StatDataLoader
	NewDataPointLoader(string) StatDataPointLoader
}

type StatUpdateListener interface {
	Subscribe(chan<- bool)
}

type Stat struct {
	sync.Mutex
	Name            string
	Depth           int
	DataLoader      StatDataLoader
	DataPointLoader StatDataPointLoader
	UpdateListener  StatUpdateListener
	data            StatData
	dataPointNames  []string
	dataPoints      map[string]*Stat
	listeners       []chan<- bool
}

func (s *Stat) Reset() {
	s.Lock()
	defer s.Unlock()
	s.data = nil
	s.dataPointNames = []string{}
	s.dataPoints = make(map[string]*Stat)
}

func (s *Stat) Load() (err error) {
	s.Lock()
	defer s.Unlock()
	s.data, err = s.DataLoader.Load(s)
	if err != nil {
		return err
	}

	s.dataPointNames, err = s.DataPointLoader.DataPointNames()
	if err != nil {
		return err
	}

	for _, dpName := range s.dataPointNames {
		dp := Stat{
			Name:            dpName,
			DataLoader:      s.DataPointLoader.NewDataLoader(s.DataLoader, dpName),
			DataPointLoader: s.DataPointLoader.NewDataPointLoader(dpName),
			Depth:           s.Depth + 1,
		}
		if err := dp.Reload(); err != nil {
			return err
		}
		s.dataPoints[dpName] = &dp
	}

	return err
}

func (s *Stat) Reload() error {
	s.Reset()
	return s.Load()
}

func (s *Stat) RefreshData() error {
	s.Lock()
	defer s.Unlock()
	return s.data.Refresh()
}

func (s *Stat) RefreshDataPoints() error {
	for _, dpName := range s.dataPointNames {
		if err := s.dataPoints[dpName].Refresh(); err != nil {
			return err
		}
	}
	return nil
}

func (s *Stat) Refresh() error {
	if err := s.RefreshData(); err != nil {
		return err
	}
	return s.RefreshDataPoints()
}

func (s *Stat) MarshalJSON() ([]byte, error) {
	s.Lock()
	defer s.Unlock()
	dataJSON, err := json.Marshal(s.data)
	if err != nil {
		return nil, fmt.Errorf("json marshalling stat %s data: ", err)
	}
	dataPointsJSON, err := json.Marshal(s.dataPoints)
	if err != nil {
		return nil, fmt.Errorf("json marshalling stat %s dataPoints: ", err)
	}

	return []byte(fmt.Sprintf(`{"name":"%s","data":%s,"dataPoints":%s}`, s.Name, dataJSON, dataPointsJSON)), nil
}

func (s *Stat) String() string {
	s.Lock()
	defer s.Unlock()
	statString := fmt.Sprintf("%s %s %s", s.Name, s.data, s.dataPointNames)
	for _, dp := range s.dataPoints {
		statString += fmt.Sprintf("\n%*s%s", dp.Depth*2, "", dp)
	}
	return statString
}

func (s *Stat) ListenForUpdates(min time.Duration, max time.Duration, errors chan<- error) error {
	if err := s.Reload(); err != nil {
		return err
	}

	updated := make(chan bool)
	s.UpdateListener.Subscribe(updated)

	go func() {
		var (
			ok       bool
			minTimer <-chan time.Time
			maxTimer <-chan time.Time
		)
		for {
			select {
			case _, ok = <-updated:
				if !ok {
					return
				}
				minTimer = time.After(min)
				if maxTimer == nil {
					maxTimer = time.After(max)
				}
			case <-minTimer:
				minTimer, maxTimer = nil, nil
				if err := s.Refresh(); err != nil {
					errors <- fmt.Errorf("%v Stat.refresh(): %v", s.Name, err)
					return
				}
				s.NotifyListeners()
			case <-maxTimer:
				minTimer, maxTimer = nil, nil
				if err := s.Refresh(); err != nil {
					errors <- fmt.Errorf("%v Stat.refresh(): %v", s.Name, err)
					return
				}
				s.NotifyListeners()
			}
		}
	}()

	return nil
}

func (s *Stat) RegisterListener(listener chan<- bool) {
	s.Lock()
	defer s.Unlock()
	s.listeners = append(s.listeners, listener)
}

func (s *Stat) NotifyListeners() {
	for _, listener := range s.listeners {
		listener <- true
	}
}


text:
package io.atomix.protocols.raft.storage.log.entry;

import io.atomix.utils.misc.TimestampPrinter;

import static com.google.common.base.MoreObjects.toStringHelper;

/**
 * Close session entry.
 */
public class CloseSessionEntry extends SessionEntry {
  private final boolean expired;
  private final boolean delete;

  public CloseSessionEntry(long term, long timestamp, long session, boolean expired, boolean delete) {
    super(term, timestamp, session);
    this.expired = expired;
    this.delete = delete;
  }

  /**
   * Returns whether the session is expired.
   *
   * @return Indicates whether the session is expired.
   */
  public boolean expired() {
    return expired;
  }

  /**
   * Returns whether to delete the service.
   *
   * @return whether to delete the service
   */
  public boolean delete() {
    return delete;
  }

  @Override
  public String toString() {
    return toStringHelper(this)
        .add("term", term)
        .add("timestamp", new TimestampPrinter(timestamp))
        .add("session", session)
        .add("expired", expired)
        .add("delete", delete)
        .toString();
  }
}


text:
#ifndef IDBUSSKELETONWRAPPER_H
#define IDBUSSKELETONWRAPPER_H

#include <chrono>
#include <string>

#include <CommonAPI/CommonAPI.h>

#include "joynr/JoynrExport.h"
#include "joynr/Logger.h"
#include "joynr/PrivateCopyAssign.h"

namespace joynr
{

template <class _SkeletonClass, class _CallBackClass>
class JOYNR_EXPORT IDbusSkeletonWrapper
{
public:
    IDbusSkeletonWrapper(_CallBackClass& callBack, std::string serviceAddress)
            : // factory(NULL),
              serviceAddress(serviceAddress)
    {
        JOYNR_LOG_TRACE(logger, "Registering dbus skeleton on address: {}", serviceAddress);

        // create the skeleton
        std::shared_ptr<_SkeletonClass> skeleton = std::make_shared<_SkeletonClass>(callBack);

        // register skeleton
        auto runtime = CommonAPI::Runtime::load("DBus");
        bool success = runtime->getServicePublisher()->registerService(
                skeleton, serviceAddress, runtime->createFactory());
        // wait some time so that the service is registered and ready to use on dbus level
        std::this_thread::sleep_for(std::chrono::milliseconds(25));

        if (success) {
            JOYNR_LOG_INFO(logger, "registering service {}: SUCCESS", serviceAddress);
        } else {
            JOYNR_LOG_FATAL(logger, "registering service {} : ERROR", serviceAddress);
        }
    }

    ~IDbusSkeletonWrapper()
    {
        JOYNR_LOG_TRACE(logger, "Unregistering dbus skeleton from address: {}", serviceAddress);

        auto runtime = CommonAPI::Runtime::load("DBus");
        bool success = runtime->getServicePublisher()->unregisterService(serviceAddress);
        // wait some time so that the service is unregistered on dbus level
        std::this_thread::sleep_for(std::chrono::milliseconds(25));

        if (success) {
            JOYNR_LOG_INFO(logger, "unregistering service {}: SUCCESS", serviceAddress);
        } else {
            JOYNR_LOG_FATAL(logger, "unregistering service {}: ERROR", serviceAddress);
        }
    }

    void logMethodCall(const std::string& method, const std::string& adapter)
    {
        JOYNR_LOG_INFO(logger, "Call method {}:{}-> {}", adapter, serviceAddress, method);
    }

private:
    DISALLOW_COPY_AND_ASSIGN(IDbusSkeletonWrapper);
    std::string serviceAddress;
    ADD_LOGGER(IDbusSkeletonWrapper);
};

template <class _SkeletonClass, class _CallBackClass>
INIT_LOGGER(SINGLE_MACRO_ARG(IDbusSkeletonWrapper<_SkeletonClass, _CallBackClass>));

} // namespace joynr
#endif // IDBUSSKELETONWRAPPER_H


text:
{% extends "system/settings_base.html" %}

{% load static i18n humanize %}

{% block settings_content %}

{% trans 'Index' %}

        {% trans 'This is the settings index page.' %}

{% endblock %}


text:
package com.gdn.venice.server.app.kpi.presenter;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gdn.venice.client.app.DataNameTokens;
import com.gdn.venice.server.app.kpi.presenter.commands.AddKpiSetupPartySlaDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.AddPeriodKpiSetupCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.DeleteKpiSetupPartySlaDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.DeletePeriodeKpiSetupDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchItemPartyData;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiDashboardDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiDetailViewerDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiPeriodDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiSetupPartySlaDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiSetupPartySlaDataCommandComboBoxBaseline;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiSetupPartySlaDataCommandComboBoxKpi;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiSetupPartySlaDataCommandComboBoxParty;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiSetupPartySlaDataCommandComboBoxPeriod;
import com.gdn.venice.server.app.kpi.presenter.commands.FetchKpiTopMerchantDataDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.UpdateKpiSetupPartySlaDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.UpdatePeriodeKpiSetupDataCommand;
import com.gdn.venice.server.app.kpi.presenter.commands.fetchValueBaselineFromPartyTarget;
import com.gdn.venice.server.command.RafDsCommand;
import com.gdn.venice.server.command.RafRpcCommand;
import com.gdn.venice.server.data.RafDsRequest;
import com.gdn.venice.server.data.RafDsResponse;
import com.gdn.venice.server.util.Util;

/**
 * Servlet implementation class BlackListMaintenancePresenterServlet
 */
public class KpiMaintenancePresenterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public KpiMaintenancePresenterServlet() {
        super();

    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		String retVal =  "";

		if (type.equals(RafDsCommand.DataSource)) {
			String requestBody = Util.extractRequestBody(request);
			RafDsRequest rafDsRequest = null;
			try {
				rafDsRequest = RafDsRequest.convertXmltoRafDsRequest(requestBody);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String method = request.getParameter("method");

			if (method.equals("fetchPeriodKpiCaseData")) {
				RafDsCommand fetchKpiPeriodDataCommand = new FetchKpiPeriodDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = fetchKpiPeriodDataCommand.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(method.equals("addPeriodKpiCaseData")){
				RafDsCommand addPeriodKpiSetupCommand = new AddPeriodKpiSetupCommand(rafDsRequest);
				RafDsResponse rafDsResponse = addPeriodKpiSetupCommand.execute();
				try {
					if (rafDsResponse.getStatus() == 0){
						retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
					}
					else {
						String errorMessage = "Please check again of Date data is selected to be Added";
						retVal = "<response><status>-1</status><data>" + errorMessage + "</data></response>";
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(method.equals("updatePeriodKpiCaseData")){
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(DataNameTokens.KPIMEASUREMENTPERIOD_PERIODID, request.getParameter(DataNameTokens.KPIMEASUREMENTPERIOD_PERIODID));
				rafDsRequest.setParams(params);
				RafDsCommand updatePeriodeKpiSetupDataCommand = new UpdatePeriodeKpiSetupDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = updatePeriodeKpiSetupDataCommand.execute();
				try {
					if (rafDsResponse.getStatus() == 0){
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
					}else {
						String errorMessage = "Please check again of Date data is selected to be Updated";
						retVal = "<response><status>-1</status><data>" + errorMessage + "</data></response>";
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if(method.equals("deletePeriodKpiCaseData")){
				RafDsCommand deletePeriodKpiSetupDataCommand = new DeletePeriodeKpiSetupDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = deletePeriodKpiSetupDataCommand.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if (method.equals("fetchKpiSetupPartySlaDataCommand")) {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(DataNameTokens.KPIPARTYTARGET_KPIPARTYSLA_VENPARTY_PARTYID, request.getParameter(DataNameTokens.KPIPARTYTARGET_KPIPARTYSLA_VENPARTY_PARTYID));
				params.put(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID, request.getParameter(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID));
				rafDsRequest.setParams(params);
				RafDsCommand fetchKpiSetupPartySlaDataCommand = new FetchKpiSetupPartySlaDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = fetchKpiSetupPartySlaDataCommand.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}	else if (method.equals("fetchItemPartyData")) {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID, request.getParameter(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID));
				params.put(DataNameTokens.VENPARTY_PARTYID, request.getParameter(DataNameTokens.VENPARTY_PARTYID));
				rafDsRequest.setParams(params);
				RafDsCommand fetchItemPartyData = new FetchItemPartyData(rafDsRequest);
				RafDsResponse rafDsResponse = fetchItemPartyData.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if (method.equals("fetchKpiDetailViewerDataCommand")) {

				RafDsCommand fetchKpiDetailViewerDataCommand = new FetchKpiDetailViewerDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = fetchKpiDetailViewerDataCommand.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if (method.equals("fetchKKpiDashboardDataCommand")) {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID, request.getParameter(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID));
				params.put(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPERIODID, request.getParameter(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPERIODID));
				params.put(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPARTYID, request.getParameter(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPARTYID));
				rafDsRequest.setParams(params);
				RafDsCommand fetchKKpiDashboardDataCommand = new FetchKpiDashboardDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = fetchKKpiDashboardDataCommand.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else if (method.equals("fetchKpiTopMerchantDataDataCommand")) {
				HashMap<String, String> params = new HashMap<String, String>();
				params.put("sum", request.getParameter("sum"));
				params.put(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPARTYID, request.getParameter(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPARTYID));
				params.put(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPERIODID, request.getParameter(DataNameTokens.KPIPARTYPERIODACTUAL_KPIPARTYMEASUREMENTPERIOD_KPIMEASUREMENTPERIOD_KPIPERIODID));
				params.put(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID, request.getParameter(DataNameTokens.VENPARTY_VENPARTYTYPE_VENPARTYTYPEID));
				rafDsRequest.setParams(params);
				RafDsCommand fetchKpiTopMerchantDataDataCommand = new FetchKpiTopMerchantDataDataCommand(rafDsRequest);
				RafDsResponse rafDsResponse = fetchKpiTopMerchantDataDataCommand.execute();
				try {
					retVal = RafDsResponse.convertRafDsResponsetoXml(rafDsResponse);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		} else if (type.equals(RafRpcCommand.RPC)) {
			String method = request.getParameter("method");
			if(method.equals("fetchKpiSetupPartySlaDataCommandComboBoxKpi")){
				RafRpcCommand fetchKpiSetupPartySlaDataCommandComboBoxKpi = new FetchKpiSetupPartySlaDataCommandComboBoxKpi();
				retVal = fetchKpiSetupPartySlaDataCommandComboBoxKpi.execute();
			}else if(method.equals("fetchKpiSetupPartySlaDataCommandComboBoxBaseline")){
				RafRpcCommand fetchKpiSetupPartySlaDataCommandComboBoxBaseline = new FetchKpiSetupPartySlaDataCommandComboBoxBaseline();
				retVal = fetchKpiSetupPartySlaDataCommandComboBoxBaseline.execute();
			}
			else if(method.equals("fetchKpiSetupPartySlaDataCommandComboBoxPeriod")){
				RafRpcCommand fetchKpiSetupPartySlaDataCommandComboBoxPeriod = new FetchKpiSetupPartySlaDataCommandComboBoxPeriod();
				retVal = fetchKpiSetupPartySlaDataCommandComboBoxPeriod.execute();
			}else if(method.equals("fetchKpiSetupPartySlaDataCommandComboBoxParty")){
				RafRpcCommand fetchKpiSetupPartySlaDataCommandComboBoxParty = new FetchKpiSetupPartySlaDataCommandComboBoxParty();
				retVal = fetchKpiSetupPartySlaDataCommandComboBoxParty.execute();
			}else if(method.equals("addKpiSetupPartySlaDataCommand")){
				String requestBody = Util.extractRequestBody(request);
				RafRpcCommand addKpiSetupPartySlaDataCommand = new AddKpiSetupPartySlaDataCommand(requestBody);
				retVal = addKpiSetupPartySlaDataCommand.execute();
			}else if(method.equals("updateKpiSetupPartySlaDataCommand")){
				String requestBody = Util.extractRequestBody(request);
				RafRpcCommand updateKpiSetupPartySlaDataCommand = new UpdateKpiSetupPartySlaDataCommand(requestBody);
				retVal = updateKpiSetupPartySlaDataCommand.execute();
			}else if(method.equals("deleteKpiSetupPartySlaDataCommand")){
				String requestBody = Util.extractRequestBody(request);
				RafRpcCommand deleteKpiSetupPartySlaDataCommand = new DeleteKpiSetupPartySlaDataCommand(requestBody);
				retVal = deleteKpiSetupPartySlaDataCommand.execute();
			}else if(method.equals("fetchValueBaselineFromPartyTarget")){
				String requestBody = Util.extractRequestBody(request);
				RafRpcCommand fetchValueBaselineFromPartyTarget = new fetchValueBaselineFromPartyTarget(requestBody);
				retVal = fetchValueBaselineFromPartyTarget.execute();

			}
		}
		response.getOutputStream().println(retVal);
	}
}


text:
courseid: 114901
layout: course
category: courses
tags:
- Web Development
- JavaScript
- AJAX
- jQuery
- JSON
- DOM
---


text:
import scipy
import pyfits
import numpy
import VLTTools

ciao = VLTTools.VLTConnection(simulate=False)

ciao.averageIntensities()


text:
  (function() {
    'use strict';

    var PaperMenuButton = Polymer({
      is: 'paper-menu-button',

      /**
       * Fired when the dropdown opens.
       *
       * @event paper-dropdown-open
       */

      /**
       * Fired when the dropdown closes.
       *
       * @event paper-dropdown-close
       */

      behaviors: [
        Polymer.IronA11yKeysBehavior,
        Polymer.IronControlState
      ],

      properties: {

        /**
         * True if the content is currently displayed.
         */
        opened: {
          type: Boolean,
          value: false,
          notify: true,
          observer: '_openedChanged'
        },

        /**
         * The orientation against which to align the menu dropdown
         * horizontally relative to the dropdown trigger.
         */
        horizontalAlign: {
          type: String,
          value: 'left',
          reflectToAttribute: true
        },

        /**
         * The orientation against which to align the menu dropdown
         * vertically relative to the dropdown trigger.
         */
        verticalAlign: {
          type: String,
          value: 'top',
          reflectToAttribute: true
        },

        /**
         * A pixel value that will be added to the position calculated for the
         * given `horizontalAlign`. Use a negative value to offset to the
         * left, or a positive value to offset to the right.
         */
        horizontalOffset: {
          type: Number,
          value: 0,
          notify: true
        },

        /**
         * A pixel value that will be added to the position calculated for the
         * given `verticalAlign`. Use a negative value to offset towards the
         * top, or a positive value to offset towards the bottom.
         */
        verticalOffset: {
          type: Number,
          value: 0,
          notify: true
        },

        /**
         * Set to true to disable animations when opening and closing the
         * dropdown.
         */
        noAnimations: {
          type: Boolean,
          value: false
        },

        /**
         * Set to true to disable automatically closing the dropdown after
         * a selection has been made.
         */
        ignoreSelect: {
          type: Boolean,
          value: false
        },

        /**
         * An animation config. If provided, this will be used to animate the
         * opening of the dropdown.
         */
        openAnimationConfig: {
          type: Object,
          value: function() {
            return [{
              name: 'fade-in-animation',
              timing: {
                delay: 100,
                duration: 200
              }
            }, {
              name: 'paper-menu-grow-width-animation',
              timing: {
                delay: 100,
                duration: 150,
                easing: PaperMenuButton.ANIMATION_CUBIC_BEZIER
              }
            }, {
              name: 'paper-menu-grow-height-animation',
              timing: {
                delay: 100,
                duration: 275,
                easing: PaperMenuButton.ANIMATION_CUBIC_BEZIER
              }
            }];
          }
        },

        /**
         * An animation config. If provided, this will be used to animate the
         * closing of the dropdown.
         */
        closeAnimationConfig: {
          type: Object,
          value: function() {
            return [{
              name: 'fade-out-animation',
              timing: {
                duration: 150
              }
            }, {
              name: 'paper-menu-shrink-width-animation',
              timing: {
                delay: 100,
                duration: 50,
                easing: PaperMenuButton.ANIMATION_CUBIC_BEZIER
              }
            }, {
              name: 'paper-menu-shrink-height-animation',
              timing: {
                duration: 200,
                easing: 'ease-in'
              }
            }];
          }
        },

        /**
         * This is the element intended to be bound as the focus target
         * for the `iron-dropdown` contained by `paper-menu-button`.
         */
        _dropdownContent: {
          type: Object
        }
      },

      hostAttributes: {
        role: 'group',
        'aria-haspopup': 'true'
      },

      listeners: {
        'iron-select': '_onIronSelect'
      },

      /**
       * The content element that is contained by the menu button, if any.
       */
      get contentElement() {
        return Polymer.dom(this.$.content).getDistributedNodes()[0];
      },

      /**
       * Make the dropdown content appear as an overlay positioned relative
       * to the dropdown trigger.
       */
      open: function() {
        if (this.disabled) {
          return;
        }

        this.$.dropdown.open();
      },

      /**
       * Hide the dropdown content.
       */
      close: function() {
        this.$.dropdown.close();
      },

      /**
       * When an `iron-select` event is received, the dropdown should
       * automatically close on the assumption that a value has been chosen.
       *
       * @param {CustomEvent} event A CustomEvent instance with type
       * set to `"iron-select"`.
       */
      _onIronSelect: function(event) {
        if (!this.ignoreSelect) {
          this.close();
        }
      },

      /**
       * When the dropdown opens, the `paper-menu-button` fires `paper-open`.
       * When the dropdown closes, the `paper-menu-button` fires `paper-close`.
       *
       * @param {boolean} opened True if the dropdown is opened, otherwise false.
       * @param {boolean} oldOpened The previous value of `opened`.
       */
      _openedChanged: function(opened, oldOpened) {
        if (opened) {
          // TODO(cdata): Update this when we can measure changes in distributed
          // children in an idiomatic way.
          // We poke this property in case the element has changed. This will
          // cause the focus target for the `iron-dropdown` to be updated as
          // necessary:
          this._dropdownContent = this.contentElement;
          this.fire('paper-dropdown-open');
        } else if (oldOpened != null) {
          this.fire('paper-dropdown-close');
        }
      },

      /**
       * If the dropdown is open when disabled becomes true, close the
       * dropdown.
       *
       * @param {boolean} disabled True if disabled, otherwise false.
       */
      _disabledChanged: function(disabled) {
        Polymer.IronControlState._disabledChanged.apply(this, arguments);
        if (disabled && this.opened) {
          this.close();
        }
      }
    });

    PaperMenuButton.ANIMATION_CUBIC_BEZIER = 'cubic-bezier(.3,.95,.5,1)';
    PaperMenuButton.MAX_ANIMATION_TIME_MS = 400;

    Polymer.PaperMenuButton = PaperMenuButton;
  })();


text: CONTENT


text:
package com.msd.gin.halyard.tools;

import com.msd.gin.halyard.common.HBaseServerTestInstance;
import com.msd.gin.halyard.common.HalyardTableUtils;
import org.apache.commons.cli.MissingOptionException;
import org.junit.Test;
import org.apache.commons.cli.ParseException;
import org.apache.hadoop.util.ToolRunner;
import org.eclipse.rdf4j.query.MalformedQueryException;
import org.eclipse.rdf4j.repository.RepositoryException;

/**
 *
 * @author Adam Sotona (MSD)
 */
public class HalyardProfileTest {

    @Test
    public void testHelp() throws Exception {
        runProfile("-h");
    }

    @Test(expected = MissingOptionException.class)
    public void testRunNoArgs() throws Exception {
        runProfile();
    }

    @Test
    public void testVersion() throws Exception {
        runProfile("-v");
    }

    @Test(expected = ParseException.class)
    public void testMissingArgs() throws Exception {
        runProfile("-s", "whatever");
    }

    @Test(expected = ParseException.class)
    public void testUnknownArg() throws Exception {
        runProfile("-y");
    }

    @Test(expected = ParseException.class)
    public void testDupArgs() throws Exception {
        runProfile("-s", "whatever", "-q", "query", "-s", "whatever2");
    }

    @Test(expected = MalformedQueryException.class)
    public void testInvalidQuery() throws Exception {
        HalyardTableUtils.getTable(HBaseServerTestInstance.getInstanceConfig(), "profile", true, -1);
        runProfile("-s", "profile", "-q", "invalid * query {}");
    }

    @Test(expected = RepositoryException.class)
    public void testNonexistentRepository() throws Exception {
        runProfile("-s", "whatever", "-q", "construct {?s ?p ?o} where {?s ?p ?o}");
    }

    @Test
    public void testProfile() throws Exception {
        HalyardTableUtils.getTable(HBaseServerTestInstance.getInstanceConfig(), "profile", true, -1);
        runProfile("-s", "profile", "-q", "select * where {{?s <http://whatever/pred> ?o, ?o2} union {?s ?p ?o3. optional {?s ?p2 ?o4 }}}");
    }

    @Test
    public void testProfileGraph() throws Exception {
        HalyardTableUtils.getTable(HBaseServerTestInstance.getInstanceConfig(), "profile", true, -1);
        runProfile("-s", "profile", "-q", "construct {?s ?o ?o2} where {{?s <http://whatever/pred> ?o, ?o2} union {?s ?p ?o3. optional {?s ?p2 ?o4 }}}");
    }

    @Test
    public void testProfileBoolean() throws Exception {
        HalyardTableUtils.getTable(HBaseServerTestInstance.getInstanceConfig(), "profile", true, -1);
        runProfile("-s", "profile", "-q", "ask where {{?s <http://whatever/pred> ?o, ?o2} union {?s ?p ?o3. optional {?s ?p2 ?o4 }}}");
    }

    private static int runProfile(String ... args) throws Exception {
        return ToolRunner.run(HBaseServerTestInstance.getInstanceConfig(), new HalyardProfile(), args);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 450 (1898)

#### Original name
Uromyces holwayi Lagerh., 1889

### Remarks
null


text:
<?php
/**
 * Display manages an array of Filters and metadata
 * (exported template variables), and renders files.
 */
class Display
{
	public $filters;
	public $meta;

	public function __construct($filters=array(), $meta=array())
	{
		$this->filters = (array) $filters;
		$this->meta    = (array) $meta;
	}

	/**
	 * Apply the Display's filters to a file.
	 */
	public function render($resource_name, $group='views')
	{
		global $config;

		$dotpos = strrpos($resource_name, '.');

		if ($dotpos !== false) {
			$type = substr($resource_name, $dotpos + 1);
			$resource_name = substr($resource_name, 0, $dotpos);
		} else {
			$type = false;
		}

		# Find the actual file.
		$resource = Core::find_resource($resource_name, $group, $type);

		# Load the inital data.
		list($data, $meta) = $resource->parse($this->meta);

		# Apply filters, if any.

		foreach($this->filters as $filter) {
			list($data, $meta) = self::apply_filter($filter, $data, $meta);
		}

		return $data;
	}

	public static function read_filter_entry($filter)
	{
		if (is_array($filter)) {
			$args = $filter;
			$name = array_shift($args);
		} else {
			$name = $filter;
			$args = array();
		}

		return array($name, $args);
	}

	public static function apply_parser($parsers, $file, $meta=array())
	{
		$data = false;

		foreach ((array) $parsers as $parser) {
			if (class_exists($parser))
			{
				if ($data) {
					$parse_file = false;
				} else {
					$parse_file = method_exists($parser, 'parse_file');
					$data = ($parse_file === true) ? $file : file_get_contents($file);
				}
				list($data, $meta) = self::apply_filter($parser, $data, $meta, $parse_file);
			}
			else if (function_exists($parser))
			{
				$data = $parser(file_get_contents($file));
			}
			else
			{
				exit('Resource '.$file.' does not have a parser!'); // TODO FIXME very ugly.
			}
		}

		return array($data, $meta);
	}

	public static function apply_filter($filter, $data, $meta, $parse_file=false)
	{
		# Array entries are Filters with arguments.
		list($filter_name, $filter_args) = self::read_filter_entry($filter);

		# Add the data to the filter arguments.
		array_unshift($filter_args, $data);

		if (class_exists($filter_name))
		{
			# Initialize filter.
			$filter = new $filter_name($meta);

			# Run the filter.
			$method = ($parse_file) ? 'parse_file' : 'parse';
			$parsed_data = call_user_func_array(array($filter, $method), $filter_args);
			$meta = $filter->meta;
		}
		else if (function_exists($filter_name))
		{
			$parsed_data = $filter_name($data);
		}

		return array($parsed_data, $meta);
	}
}
?>