text:
NSString * const kAppsFlyerLocationIdKey = @"locationId";
NSString * const kAppsFlyerIataIdKey = @"destination";
NSString * const kAppsFlyerHolelIdKey = @"hotelId";
NSString * const kAppsFlyerHotelKey = @"H";
NSString * const kAppsFlyerIataKey = @"I";
NSString * const kAppsFlyerLocationKey = @"L";
NSString * const kAppsFlyerAdultsKey = @"adults";
NSString * const kAppsFlyerCheckInKey = @"checkIn";
NSString * const kAppsFlyerCheckOutKey = @"checkOut";
NSString * const kHotelWebsiteString = @"hotelWebsite";
NSString * const kNonBreakingSpaceString = @"\u00a0";

@implementation StringUtils

+ (NSString *)destinationStringBySearchInfo:(HLSearchInfo *)searchInfo
{
    NSString *result = nil;
    switch (searchInfo.searchInfoType) {
        case HLSearchInfoTypeUserLocation: {
            result = NSLS(@"HL_LOC_FILTERS_POINT_MY_LOCATION_TEXT");
        } break;

        default: {
            result = [StringUtils defaultDestinationStringBySearchInfo:searchInfo];
        } break;
    }

    return result;
}

+ (NSString *)searchDestinationDescriptionStringBySearchInfo:(HLSearchInfo *)searchInfo
{
    NSString *result = nil;
    switch (searchInfo.searchInfoType) {
        case HLSearchInfoTypeUserLocation:
        {
            result = NSLS(@"HL_LOC_HOTELS_NEARBY_TEXT");
        }
            break;

        default:
        {
            result = [StringUtils defaultDestinationStringBySearchInfo:searchInfo];
        }
            break;
    }

    return result;
}

+ (NSString *)defaultDestinationStringBySearchInfo:(HLSearchInfo *)searchInfo
{
    NSString *result = nil;
    switch (searchInfo.searchInfoType) {
        case HLSearchInfoTypeHotel:
        {
            result = searchInfo.hotel.name;
        }
            break;

        case HLSearchInfoTypeCity:
        {
            NSString *name = [StringUtils cityName:searchInfo.city];
            if (name.length > 0) {
                result = name;
            } else {
                result = NSLS(@"HL_LOC_CITY_PLACEHOLDER_TEXT");
            }
        }
            break;

        case HLSearchInfoTypeCityCenterLocation:
        {
            NSString *name = [StringUtils cityName:searchInfo.locationPoint.city] ?: @"";
            result = [NSString stringWithFormat:NSLS(@"HL_LOC_NEARBY_CITIES_SEARCH_DESTINATION_TEXT"), name];
        }
            break;

        case HLSearchInfoTypeCustomLocation:
        {
            result = NSLS(@"HL_LOC_POINT_ON_MAP_TEXT");
        }
            break;

        case HLSearchInfoTypeAirport: {
            result = searchInfo.locationPoint.title;
        }
            break;

        default:
            break;
    }

    return result;
}

+ (NSString *)shortDateDescription:(NSDate *)date localeIdentifier:(NSString *)localeIdentifier
{
    if (!date) {
		return @"…";
	}

    NSLocale *locale = [NSLocale localeWithLocaleIdentifier:localeIdentifier];
    NSDateFormatter *formatter = [HDKDateUtil standardFormatter];
    [formatter setLocale:locale];

    NSString * dayDesc = nil;
    NSInteger indexToSubString = MIN(2, localeIdentifier.length);
    NSString *lang = [localeIdentifier substringToIndex:indexToSubString];
    BOOL useExtendedDescription = [[HLLocaleInspector sharedInspector] isLanguageRussian:lang] || iPhone47Inch() || iPhone55Inch();
    NSString *template = useExtendedDescription ? @"EEdMMMM" : @"EEdMMM";

    template = [NSDateFormatter dateFormatFromTemplate:template options:0 locale:locale];
    formatter.dateFormat = template;
    dayDesc = [formatter stringFromDate:date];

    return dayDesc;
}

+ (NSString *)ipadShortDateDescription:(NSDate *)date localeIdentifier:(NSString *)localeIdentifier
{
    NSDateFormatter *formatter = [HDKDateUtil standardFormatter];
    [formatter setLocale:[NSLocale localeWithLocaleIdentifier:localeIdentifier]];
    formatter.dateStyle = NSDateFormatterShortStyle;

    return [formatter stringFromDate:date];
}

+ (NSString *)shortDateDescription:(NSDate *)date
{
    NSString *lang = [NSLocale currentLocale].localeIdentifier;
    return [self shortDateDescription:date localeIdentifier:lang];
}

+ (NSString *)datesDescriptionWithCheckIn:(NSDate *)checkIn checkOut:(NSDate *)checkOut localeIdentifier:(NSString *)lang
{
	return [NSString stringWithFormat:@"%@ – %@", [self shortDateDescription:checkIn localeIdentifier:lang], [self shortDateDescription:checkOut localeIdentifier:lang]];
}

+ (NSString *)ipadDatesDescriptionWithCheckIn:(NSDate *)checkIn checkOut:(NSDate *)checkOut localeIdentifier:(NSString *)lang
{
    return [NSString stringWithFormat:@"%@ – %@", [self ipadShortDateDescription:checkIn localeIdentifier:lang], [self ipadShortDateDescription:checkOut localeIdentifier:lang]];
}

+ (NSString *)datesDescriptionWithCheckIn:(NSDate *)checkIn checkOut:(NSDate *)checkOut
{
    NSString *lang = [NSLocale currentLocale].localeIdentifier;
	return [self datesDescriptionWithCheckIn:checkIn checkOut:checkOut localeIdentifier:lang];
}

+ (NSString *)ipadDatesDescriptionWithCheckIn:(NSDate *)checkIn checkOut:(NSDate *)checkOut
{
    NSString *lang = [NSLocale currentLocale].localeIdentifier;
    return [self ipadDatesDescriptionWithCheckIn:checkIn checkOut:checkOut localeIdentifier:lang];
}

+ (NSString *)guestsDescriptionWithGuestsCount:(NSInteger)count
{
	NSString * format = NSLSP(@"HL_LOC_GUEST", count);
	NSString * text = [NSString stringWithFormat:@"%li %@", (long)count, format];
	return text;
}

+ (NSString *)guestsDescriptionWithAdultsCount:(NSInteger)adultsCount kidsCount:(NSInteger)kidsCount
{
    NSString *adultLocString = NSLSP(@"HL_LOC_GUEST_ADULT", adultsCount);
    NSString *adultString = [NSString stringWithFormat:@"%li %@", (long)adultsCount, adultLocString];

    if (kidsCount > 0) {
        NSString *kidsLocString = NSLSP(@"HL_LOC_GUEST_KID", kidsCount);
        NSString *kidsString = [NSString stringWithFormat:@"%li %@", (long)kidsCount, kidsLocString];

        return [NSString stringWithFormat:@"%@, %@", adultString, kidsString];
    }
    else {
        return adultString;
    }
}

+ (NSString *)kidAgeTextWithAge:(NSInteger)age
{
    if (age == 0) {
        return NSLS(@"HL_KIDS_PICKER_LESS_THAN_ONE_YEAR_TITLE");
    }

    NSString *format = NSLSP(@"HL_LOC_YEAR", age);
    NSString *text = [NSString stringWithFormat:@"%li %@", (long)age, format];

    return text;
}

+ (NSString *)bestPriceStringWithDays:(NSInteger)days
{
        NSString *duration = [StringUtils durationDescriptionWithDays:days];
        return [NSString stringWithFormat:@"%@%@", NSLS(@"HL_HOTEL_DETAIL_CTA_HEADER_TITLE"), duration];
}

+ (NSString *)durationDescriptionWithDays:(NSInteger)days
{
    NSString *nightString = NSLSP(@"HL_LOC_NIGHT", days);
    NSString *result = [NSString stringWithFormat:@"%li %@", (long)days, nightString];

    return result;
}

+ (NSString *)userSettingsDurationWithPrefixWithDays:(NSInteger)days
{
    NSString *nightString = NSLSP(@"HL_LOC_FOR_NIGHT", days);
    NSString *result = [NSString stringWithFormat:nightString, (long)days];

    return result;
}

+ (NSString *)intervalDescriptionWithDate:(NSDate *)start andDate:(NSDate *)finish
{
    NSDateFormatter *formatter = [HDKDateUtil standardFormatter];
    NSString *template = @"dd.MM";
    template = [NSDateFormatter dateFormatFromTemplate:template options:0 locale:[NSLocale currentLocale]];

    formatter.dateFormat = template;
    NSString *checkInDateDescription = [formatter stringFromDate:start];
    NSString *checkOutDateDescription = [formatter stringFromDate:finish];

    return [NSString stringWithFormat:@"%@–%@", checkInDateDescription, checkOutDateDescription];
}

+ (nullable NSString *)searchInfoStringBySearchInfo:(nullable HLSearchInfo *)info
{
    if (info == nil) {
        return nil;
    }

    NSString *datesText = [StringUtils intervalDescriptionWithDate:info.checkInDate andDate:info.checkOutDate];
    NSString *passengersText = [StringUtils guestsDescriptionWithGuestsCount:info.adultsCount + info.kidAgesArray.count];

    return [NSString stringWithFormat:@"%@, %@", datesText, passengersText];
}

#pragma mark - CheckInOut Date formatting

+ (NSString *)shortCheckInOutDateAndTime:(NSDate *)time locale:(NSLocale *)locale timePrefix:(NSString *)timePrefix
{
    NSDateFormatter *dateFormatter = [HDKDateUtil standardFormatter];
    dateFormatter.dateFormat = @"dd MMM";
    dateFormatter.locale = locale;
    NSString *dateString = [dateFormatter stringFromDate:time];

    NSDateFormatter *timeFormatter = [HDKDateUtil standardFormatter];
    timeFormatter.timeStyle = NSDateFormatterShortStyle;
    timeFormatter.dateStyle = NSDateFormatterNoStyle;
    timeFormatter.locale = locale;
    NSString *timeString = [timeFormatter stringFromDate:time];

    return [NSString stringWithFormat:@"%@, %@ %@", dateString, timePrefix, timeString];
}

+ (NSString *)shortCheckInDateAndTime:(NSDate *)time
{
    return [self shortCheckInDateAndTime:time locale:[NSLocale currentLocale]];
}

+ (NSString *)shortCheckInDateAndTime:(NSDate *)time locale:(NSLocale *)locale
{
    return [self shortCheckInOutDateAndTime:time locale:locale timePrefix:NSLS(@"HL_LOC_CHECKIN_AFTER")];
}

+ (NSString *)shortCheckOutDateAndTime:(NSDate *)time
{
    return [self shortCheckOutDateAndTime:time locale:[NSLocale currentLocale]];
}

+ (NSString *)shortCheckOutDateAndTime:(NSDate *)time locale:(NSLocale *)locale
{
    return [self shortCheckInOutDateAndTime:time locale:locale timePrefix:NSLS(@"HL_LOC_CHECKOUT_BEFORE")];
}

+ (NSString *)longCheckInOutDateAndTime:(NSDate *)time locale:(NSLocale *)locale timePrefix:(NSString *)timePrefix
{
    NSString *shortString = [self shortCheckInOutDateAndTime:time locale:locale timePrefix:timePrefix];

    NSDateFormatter *formatter = [HDKDateUtil standardFormatter];
    formatter.dateFormat = @"EEEE";
    [formatter setLocale:locale];
    NSString *dayOfWeek = [formatter stringFromDate:time];

    return [NSString stringWithFormat:@"%@, %@", dayOfWeek, shortString];
}

+ (NSString *)longCheckInDateAndTime:(NSDate *)time
{
    return [self longCheckInDateAndTime:time locale:[NSLocale currentLocale]];
}

+ (NSString *)longCheckInDateAndTime:(NSDate *)time locale:(NSLocale *)locale
{
    return [self longCheckInOutDateAndTime:time locale:locale timePrefix:NSLS(@"HL_LOC_CHECKIN_AFTER")];
}

+ (NSString *)longCheckOutDateAndTime:(NSDate *)time
{
    return [self longCheckOutDateAndTime:time locale:[NSLocale currentLocale]];
}

+ (NSString *)longCheckOutDateAndTime:(NSDate *)time locale:(NSLocale *)locale
{
    return [self longCheckInOutDateAndTime:time locale:locale timePrefix:NSLS(@"HL_LOC_CHECKOUT_BEFORE")];
}

#pragma mark -

+ (NSString *)cityNameWithStateAndCountry:(nullable HDKCity *)city
{
	if ((city.name.length == 0 || city.countryName.length == 0) && city.fullName) {
        return city.fullName;
	}
    NSMutableString *result = [NSMutableString new];
    if (city.name.length > 0) {
        result = [NSMutableString stringWithString:city.name];
        if (city.state.length > 0) {
            [result appendFormat:@", %@", city.state];
        }
        if (city.countryName.length > 0) {
            [result appendFormat:@", %@", city.countryName];
        }
    }

	return result;
}

+ (nullable NSString *)cityName:(nullable HDKCity *)city
{
    if (city.name.length > 0) {
        return city.name;
    }
    if (city.fullName.length > 0) {
        return city.fullName;
    }
    return nil;
}

+ (nullable NSString *)cityFullName:(nullable HDKCity *)city
{
    if (city.fullName.length > 0) {
        return city.fullName;
    }
    if (city.name.length > 0) {
        return city.name;
    }

    return nil;
}

+ (NSString *)searchInfoDescription:(HLSearchInfo *)searchInfo
{
    NSString * locationDescription = nil;
    switch (searchInfo.searchInfoType) {
        case HLSearchInfoTypeUserLocation:
        case HLSearchInfoTypeCustomLocation:
        case HLSearchInfoTypeAirport:
            locationDescription = searchInfo.locationPoint.title;
            break;

        case HLSearchInfoTypeCity:
            locationDescription = [StringUtils cityNameWithStateAndCountry:searchInfo.city];
            break;

        case HLSearchInfoTypeCityCenterLocation:
            locationDescription = [StringUtils cityNameWithStateAndCountry:searchInfo.locationPoint.city];
            break;

        default:
            break;
    }
	NSString * datesText = [StringUtils intervalDescriptionWithDate:searchInfo.checkInDate andDate:searchInfo.checkOutDate];
	NSString * passengersText = [StringUtils guestsDescriptionWithGuestsCount:searchInfo.adultsCount + searchInfo.kidAgesArray.count];
	NSString * result = [NSString stringWithFormat:@"%@, %@; %@", locationDescription, datesText, passengersText];

    return result;
}

+ (NSAttributedString *)attributedRangeValueTextWithPercentFormatForMinValue:(CGFloat)minValue maxValue:(CGFloat)maxValue
{
    UIFont *textFont = [UIFont systemFontOfSize:12.0];
    UIFont *numberFont = [UIFont systemFontOfSize:12.0];
    UIColor *textColor = [JRColorScheme lightTextColor];
    UIColor *numberColor = [JRColorScheme darkTextColor];

    NSString *lowerString = [NSString stringWithFormat:@"%.0f%%", floorf(minValue * 100.0)];
    NSAttributedString *lowerAttributedString = [[NSAttributedString alloc] initWithString:lowerString attributes:@{NSFontAttributeName : numberFont}];

    NSString *upperString = [NSString stringWithFormat:@"%.0f%%", ceilf(maxValue * 100.0)];
    NSAttributedString *upperAttributedString = [[NSAttributedString alloc] initWithString:upperString attributes:@{NSFontAttributeName : numberFont}];

    NSString *str = [NSString stringWithFormat:NSLS(@"HL_LOC_FILTER_RANGE"), @"lowerValue", @"upperValue"];
    NSMutableAttributedString *range = [[NSMutableAttributedString alloc] initWithString:str];
    [range addAttribute:NSFontAttributeName value:textFont range:NSRangeFromString(str)];
    [range addAttribute:NSForegroundColorAttributeName value:textColor range:NSRangeFromString(str)];

    [range replaceCharactersInRange:[range.string rangeOfString:@"lowerValue"] withAttributedString:lowerAttributedString];
    [range replaceCharactersInRange:[range.string rangeOfString:@"upperValue"] withAttributedString:upperAttributedString];

    [range addAttribute:NSForegroundColorAttributeName value:numberColor range:[range.string rangeOfString:lowerAttributedString.string]];
    [range addAttribute:NSForegroundColorAttributeName value:numberColor range:[range.string rangeOfString:upperAttributedString.string options:NSBackwardsSearch]];

    return range;
}

+ (NSString *)formattedNumberStringWithNumber:(NSInteger)number
{
    static NSNumberFormatter *nf = nil;
    if (!nf) {
        nf = [NSNumberFormatter new];
        nf.usesGroupingSeparator = YES;
        nf.groupingSize = 3;
    }

    return [nf stringFromNumber:[NSNumber numberWithInteger:number]];
}

+ (NSString *)hotelsCountDescriptionWithHotels:(NSInteger)count
{
	NSString * formattedCount = [StringUtils formattedNumberStringWithNumber:count];
	NSString * hotelWordString = NSLSP(@"HL_LOC_SEARCH_FORM_HOTEL", count);
	return [NSString stringWithFormat:@"%@ %@", formattedCount, hotelWordString];
}

+ (NSString *)filteredHotelsDescriptionWithFiltered:(NSInteger)filtered total:(NSInteger)total
{
    NSString *title = nil;
    if (filtered > 0) {
        NSString *countStr = [StringUtils formattedNumberStringWithNumber:filtered];
        NSString *totalStr = [StringUtils formattedNumberStringWithNumber:total];
        title = NSLSP(@"HL_LOC_FILTER_HOTELS_FOUND", filtered);
        title = [NSString stringWithFormat:title, countStr, totalStr];
    } else {
        title = NSLS(@"HL_FILTER_HOTELS_NOT_FOUND");
    }

    return title;
}

+ (NSString *)roomsAvailableStringWithCount:(NSInteger)count
{
    NSString *title = NSLSP(@"HL_HOTEL_DETAIL_AVAILABLE_ROOMS_COUNT_OPTION_BASED", count);
    title = [NSString stringWithFormat:title, count];

    return title;
}

+ (NSString *)photoCounterString:(NSInteger)count totalCount:(NSInteger)totalCount
{
    return [NSString stringWithFormat:@"%ld/%ld", (long)(count + 1), (long)totalCount];
}

+ (NSString *)shortRatingString:(NSInteger)rating
{
    return [self shortRatingString:rating locale:[NSLocale currentLocale]];
}

+ (NSString *)shortRatingString:(NSInteger)rating locale:(NSLocale *)locale
{
    return rating == 100 ? @"10" : [NSString stringWithFormat:@"%.1f", rating / 10.0];
}

#pragma mark - Price Formatting

+ (NSString *)priceStringWithVariant:(HLResultVariant *)variant;
{
    NSString *stringToReturn = nil;
    if (variant.rooms.count == 0) {
        stringToReturn = @"—";
    } else if (variant.searchInfo.currency) {
        stringToReturn = [[variant.searchInfo.currency.formatter stringFromNumber:@(variant.minPrice)] mutableCopy];
        BOOL shouldReplaceSpaceWithNonBreaking = variant.searchInfo.currency.symbol.length == 1;
        if (shouldReplaceSpaceWithNonBreaking) {
            stringToReturn = [stringToReturn stringByReplacingOccurrencesOfString:@" " withString:kNonBreakingSpaceString];
        }
    } else {
        stringToReturn = [self formattedNumberStringWithNumber:variant.minPrice];
    }

    return stringToReturn;
}

+ (NSString *)priceStringWithPrice:(float)price currency:(HDKCurrency *)currency
{
    return currency != nil
        ? [currency.formatter stringFromNumber:@(price)]
        : [self formattedNumberStringWithNumber:price];
}

+ (NSAttributedString *)attributedPriceStringWithVariant:(HLResultVariant *)variant currency:(HDKCurrency *)currency font:(UIFont *)font
{
    return [self attributedPriceStringWithVariant:variant currency:currency font:font noPriceColor:nil];
}

+ (NSAttributedString *)attributedPriceStringWithVariant:(HLResultVariant *)variant currency:(HDKCurrency *)currency font:(UIFont *)font noPriceColor:(UIColor * _Nullable)color
{
    if (variant.rooms.count > 0) {
        return [self attributedPriceStringWithPrice:variant.minPrice currency:currency font:font];
    } else {
        NSString *string = @"—";
        NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:string];
        [result addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, string.length)];
        if (color != nil) {
            [result addAttribute:NSForegroundColorAttributeName value:color range:(NSMakeRange(0, string.length))];
        }

        return result;
    }
}

+ (NSAttributedString *)attributedPriceStringWithPrice:(float)price currency:(HDKCurrency *)currency font:(UIFont *)font
{
    NSString *priceString = [self priceStringWithPrice:price currency:currency];
    NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:priceString];
    [result addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, priceString.length)];

    return result;
}

+ (NSAttributedString *)strikethroughAttributedString:(NSAttributedString *)attributedString
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
    [attributeString addAttribute:NSStrikethroughStyleAttributeName
                            value:@1
                            range:NSMakeRange(0, [attributeString length])];

    return attributeString;
}

+ (NSString *)discountStringForDiscount:(NSInteger)discount
{
    return [NSString stringWithFormat:@"%li%% %@", labs(discount), NSLS(@"HL_DISCOUNT")];
}

#pragma mark - URL handling

+ (NSDictionary *)paramsFromUrlAbsoluteString:(NSString *)urlString
{
    NSArray * params = [urlString componentsSeparatedByString:@"?"];
    urlString = [params lastObject];
    params = [urlString componentsSeparatedByString:@"://"];
    urlString = [params lastObject];

    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    NSArray *pairs = [urlString componentsSeparatedByString:@"&"];

    for (NSString *pair in pairs) {
        NSArray *elements = [pair componentsSeparatedByString:@"="];
        if(elements.count > 1){
            NSString *key = [[elements objectAtIndex:0] stringByRemovingPercentEncoding];
            NSString *val = [[elements objectAtIndex:1] stringByRemovingPercentEncoding];

            [dict setObject:val forKey:key];
        }
    }

    return dict;
}

+ (NSDictionary *)paramsFromAppsFlyerString:(NSString *)appsFlyerString
{
    NSArray *paramsArray = [appsFlyerString componentsSeparatedByString:@"-"];
    if (paramsArray.count < 5) {

        return @{};
    }

    NSDictionary *mapDict = @{kAppsFlyerHotelKey    : kAppsFlyerHolelIdKey,
                              kAppsFlyerLocationKey : kAppsFlyerLocationIdKey,
                              kAppsFlyerIataKey     : kAppsFlyerIataIdKey};

    NSString *type               = paramsArray[0];
    NSString *identifier         = paramsArray[1];
    NSString *checkInDateString  = paramsArray[2];
    NSString *checkOutDateString = paramsArray[3];
    NSString *adultsCount        = paramsArray[4];

    NSString *identifierName = mapDict[type];
    if (!identifierName) {
        return @{};
    }

    NSMutableDictionary *params = [NSMutableDictionary new];

    params[identifierName]          = identifier;
    params[kAppsFlyerCheckInKey]    = [self dateStringFromAppsFlyerString:checkInDateString];
    params[kAppsFlyerCheckOutKey]   = [self dateStringFromAppsFlyerString:checkOutDateString];
    params[kAppsFlyerAdultsKey]     = adultsCount;

    return [params copy];
}

+ (NSString *)dateStringFromAppsFlyerString:(NSString *)appsFlyerString
{
    NSString *result = nil;
    if (appsFlyerString.length == 8) {

        NSString *day = [appsFlyerString substringWithRange:NSMakeRange(0, 2)];
        NSString *month = [appsFlyerString substringWithRange:NSMakeRange(2, 2)];
        NSString *year = [appsFlyerString substringWithRange:NSMakeRange(4, 4)];

        result = [NSString stringWithFormat:@"%@-%@-%@", year, month, day];
    }

    return result;
}

#pragma mark - Distance formatting

+ (NSAttributedString *)attributedDistanceString:(CGFloat)meters
{
    return [self attributedDistanceString:meters
                                textColor:[JRColorScheme lightTextColor]
                              numberColor:[JRColorScheme darkTextColor]];
}

+ (NSAttributedString *)attributedDistanceString:(CGFloat)meters
                                       textColor:(UIColor *)textColor
                                     numberColor:(UIColor *)numberColor
{
    UIFont * textFont = [UIFont systemFontOfSize:12.0];
    UIFont * numberFont = [UIFont systemFontOfSize:12.0];

    NSString * valueString = [StringUtils roundedDistanceWithMeters:meters];
    NSAttributedString * attrValueString = [[NSAttributedString alloc] initWithString:valueString];
    NSString *str = [NSString stringWithFormat:@"%@ %@", NSLS(@"HL_LOC_FILTER_TO_STRING"), @"lowerValue"];
    NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:str];
    [result addAttribute:NSFontAttributeName value:textFont range:NSMakeRange(0, str.length)];
    [result addAttribute:NSForegroundColorAttributeName value:textColor range:NSMakeRange(0, str.length)];

    [result replaceCharactersInRange:[result.string rangeOfString:@"lowerValue"] withAttributedString:attrValueString];

    [result addAttribute:NSForegroundColorAttributeName value:numberColor range:[result.string rangeOfString:attrValueString.string]];
    [result addAttribute:NSFontAttributeName value:numberFont range:[result.string rangeOfString:attrValueString.string]];

    return result;
}

+ (NSString *)distanceUnitAbbreviation
{
    return [HLLocaleInspector shouldUseMetricSystem] ? NSLS(@"HL_LOC_KILOMETERS_ABBREVIATION") : NSLS(@"HL_LOC_MILES_ABBREVIATION");
}

+ (NSString *)shortDistanceStringWithKilometers:(CGFloat)distance
{
    NSString * unitAbbreviation = [self distanceUnitAbbreviation];
    if(![HLLocaleInspector shouldUseMetricSystem]){
        distance = [HLDistanceCalculator convertKilometersToMiles:distance];
    }
    NSString * result = [NSString stringWithFormat:@"%.1f %@", distance, unitAbbreviation];

    return result;
}

+ (NSString *)roundedDistanceWithMeters:(CGFloat)meters
{
    NSString * result = nil;
    if (![HLLocaleInspector shouldUseMetricSystem] || meters >= 1000) {
        result = [self shortDistanceStringWithKilometers:meters / 1000.0];
    } else {
        meters = 10 * round(meters / 10.0);
        result = [NSString stringWithFormat:@"%.f %@", meters, NSLS(@"HL_LOC_METERS_ABBREVIATION")];
    }
    return result;
}

#pragma mark - Points Name formatting

+ (NSString *)locationPointName:(nullable HDKLocationPoint *)point;
{
    if ([point isKindOfClass:[HLCityLocationPoint class]]) {
        NSString *cityCenterString = point.name;
        if (cityCenterString.length > 0) {
            cityCenterString = [cityCenterString hl_firstLetterCapitalizedString];
        }

        return [NSString stringWithFormat:@"%@ (%@)", cityCenterString, [(HLCityLocationPoint *)point cityName]];
    }

    return [self capitalizedFirstLetterString:point.name];
}

+ (NSString *)capitalizedFirstLetterString:(NSString *)string
{
    if (string.length == 0) {
        return string;
    }
    return [NSString stringWithFormat:@"%@%@",[[string substringToIndex:1] uppercaseString],[string substringFromIndex:1]];
}

#pragma mark - Hotels

+ (nonnull NSString *)hotelAddressForHotel:(nullable HDKHotel *)hotel
{
    NSString *addressString = hotel.address ?: @"";
    NSString *detailsString = [self hotelAddressDetails:hotel] ?: @"";
    NSMutableString *result = [[NSMutableString alloc] initWithString:addressString];
    if (result.length > 0 && detailsString.length > 0) {
        [result appendString:[NSString stringWithFormat:@", %@", detailsString]];
    } else {
        [result appendString:detailsString];
    }

    return [result copy];
}

+ (nullable NSString *)hotelAddressDetails:(nullable HDKHotel *)hotel
{
    NSString *districtName = hotel.firstDistrictName;
    if (districtName.length == 0) {
        return nil;
    }

    NSString *cityName = [self cityName:hotel.city];

    return cityName.length > 0
    ? [NSString stringWithFormat:@"%@, %@", districtName, cityName]
    : districtName;
}

+ (NSString *)adultGuestsDescriptionWithCount:(NSInteger)adultsCount
{
    if (adultsCount > 0) {
        NSString *adultLocString = NSLSP(@"HL_LOC_GUEST_ADULT", adultsCount);
        return [NSString stringWithFormat:@"%li %@", (long)adultsCount, adultLocString];
    } else {
        return @"";
    }
}

+ (NSString *)childGuestsDescriptionWithCount:(NSInteger)kidsCount
{
    if (kidsCount > 0) {
        NSString *kidsLocString = NSLSP(@"HL_LOC_GUEST_KID", kidsCount);
        return [NSString stringWithFormat:@"%li %@", (long)kidsCount, kidsLocString];
    } else {
        return @"";
    }
}

+ (NSString *)checkInTimeFromDate:(NSDate *)date
{
    return [NSString stringWithFormat:@"%@ %@", NSLS(@"HL_LOC_CHECKIN_AFTER"), [self timeStringFromDate:date]];
}

+ (NSString *)checkOutTimeFromDate:(NSDate *)date
{
    return [NSString stringWithFormat:@"%@ %@", NSLS(@"HL_LOC_CHECKOUT_BEFORE"), [self timeStringFromDate:date]];
}

+ (NSString *)timeStringFromDate:(NSDate *)date
{
    return [self timeStringFromDate:date locale:[NSLocale currentLocale]];
}

+ (NSString *)timeStringFromDate:(NSDate *)date locale:(NSLocale *)locale
{
    NSDateFormatter *timeFormatter = [HDKDateUtil standardFormatter];
    timeFormatter.timeStyle = NSDateFormatterShortStyle;
    timeFormatter.dateStyle = NSDateFormatterNoStyle;
    timeFormatter.locale = locale;
    return [timeFormatter stringFromDate:date];
}

+ (NSString *)accommodationSummaryCheckInStringForDate:(NSDate *)date shortMonth:(BOOL)shortMonth
{
    NSString *dateString = [self accommodationSummaryDateStringForDate:date shortMonth:shortMonth locale:[NSLocale currentLocale]];
    return [NSString stringWithFormat:@"%@ %@", NSLS(@"HL_HOTEL_DETAIL_INFORMATION_CHECKIN"), dateString];
}

+ (NSString *)accommodationSummaryCheckOutStringForDate:(NSDate *)date shortMonth:(BOOL)shortMonth
{
    NSString *dateString = [self accommodationSummaryDateStringForDate:date shortMonth:shortMonth locale:[NSLocale currentLocale]];
    return [NSString stringWithFormat:@"%@ %@", NSLS(@"HL_HOTEL_DETAIL_INFORMATION_CHECKOUT"), dateString];
}

+ (NSString *)accommodationSummaryDateStringForDate:(NSDate *)date shortMonth:(BOOL)shortMonth locale:(NSLocale *)locale
{
    NSDateFormatter *dateFormatter = [HDKDateUtil standardFormatter];
    dateFormatter.dateFormat = [NSString stringWithFormat:@"d %@, EE", shortMonth ? @"MMM" : @"MMMM"];
    dateFormatter.locale = locale;
    return [dateFormatter stringFromDate:date];
}

@end


text:
package de.bitbrain.mindmazer.graphics;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Disposable;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;
import de.bitbrain.braingdx.graphics.GameObjectRenderManager.GameObjectRenderer;
import de.bitbrain.braingdx.tweens.ColorTween;
import de.bitbrain.braingdx.tweens.SharedTweenManager;
import de.bitbrain.braingdx.tweens.SpriteTween;
import de.bitbrain.braingdx.tweens.VectorTween;
import de.bitbrain.braingdx.world.GameObject;
import de.bitbrain.mindmazer.Colors;
import de.bitbrain.mindmazer.Config;
import de.bitbrain.mindmazer.util.LogTags;

public class LevelStageRenderer implements GameObjectRenderer, Disposable {

   public interface LevelStageRenderListener {
      void afterSetStage();
   }

   private static final int CELL_OFFSET = (int) (Config.TILE_SIZE * 0.23f);
   private static final float CELL_ANIMATION_TIME = 0.65f;
   private static final float OLD_LEVEL_FADE_TIME = 0.9f;

   private byte[][] data;
   private Texture texture;
   private Texture blockA, blockB;
   private Sprite sprite;
   private Sprite oldSprite;
   private Texture oldTexture;
   private boolean renderRequest = true;

   private final Set<String> cellIds = new HashSet<String>();
   private final List<Cell> cells = new ArrayList<Cell>();
   private final TweenManager tweenManager = SharedTweenManager.getInstance();

   public LevelStageRenderer(byte[][] data) {
      this.data = data;
   }

   @Override
   public void init() {
      Gdx.app.debug(LogTags.INIT, "Initialising LevelStageRenderer...");
      Pixmap map = new Pixmap(Config.TILE_SIZE, Config.TILE_SIZE + CELL_OFFSET, Format.RGBA8888);
      map.setColor(Colors.CELL_A_DARK);
      map.fillRectangle(0, CELL_OFFSET, Config.TILE_SIZE, Config.TILE_SIZE);
      map.setColor(Colors.CELL_A);
      map.fillRectangle(0, 0, Config.TILE_SIZE, Config.TILE_SIZE);
      blockA = new Texture(map);
      map.setColor(Colors.CELL_B_DARK);
      map.fillRectangle(0, CELL_OFFSET, Config.TILE_SIZE, Config.TILE_SIZE);
      map.setColor(Colors.CELL_B);
      map.fillRectangle(0, 0, Config.TILE_SIZE, Config.TILE_SIZE);
      blockB = new Texture(map);
      map.dispose();
   }

   @Override
   public void dispose() {
      Gdx.app.log(LogTags.DISPOSE, "Disposing LevelStageRenderer...");
      if (data != null) {
         data = null;
         if (blockA != null) {
            blockA.dispose();
         }
         if (blockB != null) {
            blockB.dispose();
         }
         if (oldTexture != null) {
            oldTexture.dispose();
         }
         if (texture != null) {
            texture.dispose();
         }
      }
   }

   public void addCell(int x, int y) {
      if (!isCurrentlyProcessed(x, y)) {
         Gdx.app.debug(LogTags.RENDER, "Adding new cell to LevelStageRenderer at " + x + "," + y);
         Cell cell = new Cell(x, y);
         cellIds.add(cell.getId());
         cells.add(cell);
         animate(cell);
      }
   }

   public void reset() {
      Gdx.app.debug(LogTags.RENDER, "Resetting LevelStageRenderer...");
      renderRequest = true;
      cells.clear();
      cellIds.clear();
      if (oldTexture != null) {
         oldTexture.dispose();
         oldTexture = null;
      }
   }

   public void setStage(byte[][] data, boolean override) {
      this.setStage(data, override, null);
   }

   public void setStage(byte[][] data, boolean override, final LevelStageRenderListener callback) {
      this.data = data;
      if (texture != null && override) {
         Gdx.app.debug(LogTags.RENDER, "Overriding existing stage in LevelStageRenderer...");
         oldSprite = sprite;
         oldTexture = texture;
         renderRequest = true;
         cells.clear();
         cellIds.clear();
         tweenManager.killTarget(oldSprite);
         Tween.to(oldSprite, SpriteTween.ALPHA, OLD_LEVEL_FADE_TIME)
              .target(0f)
              .ease(TweenEquations.easeOutQuad)
              .setCallbackTriggers(TweenCallback.COMPLETE)
              .setCallback(new TweenCallback() {
                  @Override
                  public void onEvent(int arg0, BaseTween<?> arg1) {
                     if (callback != null) {
                        callback.afterSetStage();
                     }
                     if (oldTexture != null) {
                        oldTexture.dispose();
                        oldTexture = null;
                     }
                  }
               }).start(tweenManager);
      } else {
         Gdx.app.debug(LogTags.RENDER, "Resetting existing stage in LevelStageRenderer...");
         reset();
      }
   }

   @Override
   public void render(GameObject object, Batch batch, float delta) {
      if (renderRequest) {
         buildTextureBuffer(batch);
         renderRequest = false;
      }
      if (oldTexture != null) {
         oldSprite.setFlip(false, true);
         oldSprite.setPosition(object.getLeft(), object.getTop() - CELL_OFFSET * 2);
         oldSprite.draw(batch);
      }
      for (int i = cells.size() - 1; i >= 0; i--) {
         cells.get(i).draw(batch);
      }
      sprite.setFlip(false, true);
      sprite.setPosition(object.getLeft(), object.getTop() - CELL_OFFSET * 2);
      sprite.draw(batch);
   }

   private void animate(final Cell cell) {
      cell.getSprite().setScale(0.5f);
      Tween.to(cell.getColor(), ColorTween.A, CELL_ANIMATION_TIME * 1.2f)
           .target(1f)
           .ease(TweenEquations.easeInCubic)
           .setCallbackTriggers(TweenCallback.COMPLETE)
           .setCallback(new TweenCallback() {
            @Override
            public void onEvent(int arg0, BaseTween<?> arg1) {
               cellIds.remove(cell.getId());
               cells.remove(cell);
               renderRequest = true;
            }
           })
           .start(tweenManager);
      Tween.to(cell.getSprite(), SpriteTween.SCALE, CELL_ANIMATION_TIME).target(1f).ease(TweenEquations.easeInCubic)
            .start(tweenManager);
      cell.getOffset().y = -CELL_OFFSET * 10f;
      Tween.to(cell.getOffset(), VectorTween.POS_Y, CELL_ANIMATION_TIME / 1.5f)
      .target(0f)
      .ease(TweenEquations.easeInCubic)
      .start(tweenManager);
   }

   private void buildTextureBuffer(Batch batch) {
      Gdx.app.debug(LogTags.RENDER, "Building texture buffer for current LevelStage...");
      int textureWidth = Config.TILE_SIZE * data.length;
      int textureHeight = Config.TILE_SIZE * data[0].length + CELL_OFFSET;
      Pixmap map = new Pixmap(textureWidth, textureHeight, Format.RGBA8888);
      map.setColor(new Color(0f, 0f, 0f, 0f));
      for (int indexX = 0; indexX < data.length; ++indexX) {
         for (int indexY = data[indexX].length - 1; indexY >= 0; --indexY) {
            if (isCurrentlyProcessed(indexX, indexY)) {
               continue;
            }
            byte value = data[indexX][indexY];
            if (value == 1) {
               drawCellOntoPixmap(map, value, indexX, indexY, Colors.CELL_A, Colors.CELL_A_DARK, Colors.CELL_B,
                     Colors.CELL_B_DARK);
            }
            if (value == 2) {
               drawCellOntoPixmap(map, value, indexX, indexY, Color.RED, Color.RED, Color.RED, Color.RED);
            }

         }
      }
      texture = new Texture(map);
      sprite = new Sprite(texture);
      Gdx.app.debug(LogTags.RENDER, "Successfully built texture buffer!");
   }

   private void drawCellOntoPixmap(Pixmap map, byte value, int indexX, int indexY, Color colorA, Color colorADark,
         Color colorB, Color colorBDark) {
      float x = Config.TILE_SIZE * indexX;
      float y = Config.TILE_SIZE * indexY;
      if (indexX % 2 == 0) {
         if (indexY % 2 == 0) {
            map.setColor(colorBDark);
         } else {
            map.setColor(colorADark);
         }
      } else {
         if (indexY % 2 == 0) {
            map.setColor(colorADark);
         } else {
            map.setColor(colorBDark);
         }
      }
      map.fillRectangle((int) x, (int) y, Config.TILE_SIZE, Config.TILE_SIZE);
      if (indexX % 2 == 0) {
         if (indexY % 2 == 0) {
            map.setColor(colorB);
         } else {
            map.setColor(colorA);
         }
      } else {
         if (indexY % 2 == 0) {
            map.setColor(colorA);
         } else {
            map.setColor(colorB);
         }
      }
      map.fillRectangle((int) x, (int) y + CELL_OFFSET, Config.TILE_SIZE, Config.TILE_SIZE);
   }

   private boolean isCurrentlyProcessed(int x, int y) {
      return cellIds.contains(convertToId(x, y));
   }

   private String convertToId(int x, int y) {
      return x + "_" + y;
   }

   private Texture resolveBlockTexture(int x, int y) {
      if (x % 2 == 0) {
         if (y % 2 == 0) {
            return blockB;
         } else {
            return blockA;
         }
      } else {
         if (y % 2 == 0) {
            return blockA;
         } else {
            return blockB;
         }
      }
   }

   private class Cell {

      private final int x, y;

      private final String id;

      private final Color color;

      private final Sprite sprite;

      private final Vector2 offset;

      Cell(int x, int y) {
         this.x = x;
         this.y = y;
         this.id = convertToId(x, y);
         this.color = new Color(1f, 1f, 1f, 0f);
         sprite = new Sprite(resolveBlockTexture(x, y));
         offset = new Vector2(0, 0);

      }

      void draw(Batch batch) {
         float xPos = Config.TILE_SIZE * x;
         float yPos = Config.TILE_SIZE * y - CELL_OFFSET * 2;
         sprite.setPosition(xPos + offset.x, yPos + offset.y);
         sprite.setAlpha(color.a);
         sprite.draw(batch);
      }

      Vector2 getOffset() {
         return offset;
      }

      Sprite getSprite() {
         return sprite;
      }

      Color getColor() {
         return color;
      }

      String getId() {
         return id;
      }
   }

}

redpajama_set_name: RedPajamaGithub


text:
namespace dingo
{
    struct external {};

    template < typename Type, typename U > struct conversions< external, Type, U >
    {
        typedef type_list<> ValueTypes;
        typedef type_list< U& > LvalueReferenceTypes;
        typedef type_list<> RvalueReferenceTypes;
        typedef type_list< U* > PointerTypes;
    };

    template < typename Type, typename U > struct conversions< external, Type&, U >
        : public conversions< external, Type, U >
    {};

    template < typename Type, typename U > struct conversions< external, Type*, U >
        : public conversions< external, Type, U >
    {};

    template < typename Type, typename U > struct conversions< external, std::shared_ptr< Type >, U >
    {
        typedef type_list< std::shared_ptr< U > > ValueTypes;
        typedef type_list< U&, std::shared_ptr< U >& > LvalueReferenceTypes;
        typedef type_list<> RvalueReferenceTypes;
        typedef type_list< U*, std::shared_ptr< U >* > PointerTypes;
    };

    template < typename Type, typename U > struct conversions< external, std::shared_ptr< Type >&, U >
        : public conversions< external, std::shared_ptr< Type >, U >
    {};

    template < typename Type, typename U > struct conversions< external, std::unique_ptr< Type >, U >
    {
        typedef type_list<> ValueTypes;
        typedef type_list< U*, std::unique_ptr< U >* > PointerTypes;
        typedef type_list< U&, std::unique_ptr< U >& > LvalueReferenceTypes;
        typedef type_list<> RvalueReferenceTypes;
    };

    template < typename Type, typename U > struct conversions< external, std::unique_ptr< Type >&, U >
        : public conversions< external, std::unique_ptr< Type >, U >
    {};

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, Type, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(Type&& instance)
            : instance_(std::move(instance))
        {}

        ~storage()
        {}

        template < typename Container > Type& resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        Type instance_;
    };

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, Type&, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(Type& instance)
            : instance_(instance)
        {}

        ~storage()
        {}

        template < typename Container > Type& resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        Type& instance_;
    };

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, Type*, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(Type* instance)
            : instance_(instance)
        {}

        ~storage()
        {}

        template < typename Container > Type* resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        Type* instance_;
    };

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, std::shared_ptr< Type >, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(std::shared_ptr< Type > instance)
            : instance_(instance)
        {}

        ~storage()
        {}

        template < typename Container > std::shared_ptr< Type > resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        std::shared_ptr< Type > instance_;
    };

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, std::shared_ptr< Type >&, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(std::shared_ptr< Type >& instance)
            : instance_(instance)
        {}

        ~storage()
        {}

        template < typename Container > std::shared_ptr< Type > resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        std::shared_ptr< Type >& instance_;
    };

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, std::unique_ptr< Type >, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(std::unique_ptr< Type >&& instance)
            : instance_(std::move(instance))
        {}

        ~storage()
        {}

        template < typename Container > std::unique_ptr< Type >& resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        std::unique_ptr< Type > instance_;
    };

    template < typename Container, typename Type, typename Conversions > class storage< Container, external, std::unique_ptr< Type >&, Conversions >
        : public resettable_i
    {
    public:
        static const bool IsCaching = true;

        typedef Conversions Conversions;
        typedef Type Type;

        storage(std::unique_ptr< Type >& instance)
            : instance_(instance)
        {}

        ~storage()
        {}

        template < typename Container > std::unique_ptr< Type >& resolve(resolving_context< Container >& context)
        {
            return instance_;
        }

        bool is_resolved() const { return true; }

        void reset() override {}

    private:
        std::unique_ptr< Type >& instance_;
    };
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Foundation.ExtensionMethods;
using Foundation.Windows;

namespace Foundation.Build
{
    ///
    ///
The SrcTool (Srctool.exe) utility lists all files indexed within the .pdb file.
    /// For each file, it lists the full path, source control server, and version number of the file.
    /// You can use this information for reference.

    ///
You can also use SrcTool to list the raw source file information from the .pdb file.
    /// To do this, use the –s switch on the command line.

    ///
SrcTool has other options as well. Use the ? switch to see them.
    /// Of most interest is that this utility can be used to extract all of the source files from
    /// version control. This is done with the -x switch.

    ///
    /// <remarks>Previous versions of this program created a directory called src below the current directory
    /// when extracting files. This is no longer the case. If you want the src directory used, you must create
    /// it yourself and run the command from that directory.</remarks>
    public class SrcTool : ProcessWrapper
    {
        const string debuggingToolsForWindowsFolderName = "Debugging Tools for Windows";

        static readonly IEnumerable<string> searchPaths = new[]
        {
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), debuggingToolsForWindowsFolderName),
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), debuggingToolsForWindowsFolderName + " (x86)")
        };

        TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);

        public SrcTool() : base(GetSrcToolPath()) {}

        public SrcTool(string filename) : this()
        {
            Filename = filename;
        }

        static string GetSrcToolPath()
        {
            var directory = searchPaths.FirstOrDefault(Directory.Exists);

            if(directory == null) throw new FileNotFoundException("Couldn't find SrcTool.exe. Please install Debugging Tools for Windows.");

            return Path.Combine(directory, @"srcsrv\SrcTool.exe");
        }

        internal protected override void BuildArguments()
        {
            var sb = new StringBuilder();

            if (RawSourceData.HasValue && RawSourceData.Value) sb.Append("-r ");

            if( Filename.IsNullOrEmpty()) throw new FoundationException("The FileName argument for SrcTool is required");

            sb.AppendFormat("\"{0}\"", Filename);

            StartInfo.Arguments = sb.ToString();
        }

        ///
        /// Gets or sets the raw source data.
        ///
        /// <value>
        /// The raw source data options.
        /// </value>
        /// <remarks>When set to <c>true</c>, dumps raw source data from the pdb.</remarks>
        public bool? RawSourceData { get; set; }

        public string Filename { get; set; }

        ///
        /// Returns the list of source files used to build the binary that the debug symbols belong to.
        ///
        /// <returns></returns>
        public IEnumerable<string> GetSourceFiles()
        {
            RawSourceData = true;

            var lines = new List<string>();

            var errorStreamWaitHandle = new ManualResetEvent(false);
            var outputStreamWaitHandle = new ManualResetEvent(false);
            var processWaitHandle = new ManualResetEvent(false);

            ErrorDataReceived += delegate(object sender, DataReceivedEventArgs args)
            {
                if (args.Data == null) errorStreamWaitHandle.Set();
            };

            OutputDataReceived += delegate(object sender, DataReceivedEventArgs args)
            {
                if (args.Data == null)
                {
                    outputStreamWaitHandle.Set();
                    return;
                }

                if( args.Data.Trim().Length > 0) lines.Add(args.Data);
            };

            Exited += (o, eventArgs) => processWaitHandle.Set();

            EnableRaisingEvents = true;
            StartInfo.UseShellExecute = false;
            StartInfo.RedirectStandardOutput = true;
            StartInfo.RedirectStandardError = true;
            StartInfo.RedirectStandardInput = true;
            StartInfo.CreateNoWindow = true;

            Start();

            BeginErrorReadLine();
            BeginOutputReadLine();

            WaitHandle.WaitAll(new[]
            {
                errorStreamWaitHandle, outputStreamWaitHandle, processWaitHandle
            }, DefaultTimeout);

            return lines;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/open_action"
        android:title="@string/title_open_action"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/save_action"
        android:title="@string/title_save_action"
        app:showAsAction="ifRoom"/>
</menu>


text:
@interface NSHipsterViewController : UIViewController

@end


text:
<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Discount
 *
 * @author Ea Design
 */
class EaDesign_PdfGenerator_Model_Entity_Totals_Discount extends Mage_Core_Model_Abstract
{

    /**
     * Get the variables and values acording to tax rules
     * @return array
     */
    public function getTotalsForDisplay()
    {
        $amount = $this->getAmount();
        $amount = $this->getOrder()->formatPriceTxt($amount);

            $totals = array(array(
                'discountammount' => array(
                    'value' => $this->getAmountPrefix() . $amount,
                    'label' => Mage::helper('tax')->__('Subtotal (Excl. Tax)') . ':',
                    )));

        return $totals;
    }

    public function getAmount()
    {
        return $this->getSource()->getDataUsingMethod('discount_amount');
    }

}

?>


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Extension\Core\Type;

use Rollerworks\Component\Search\Extension\Core\DataTransformer\DateTimeToLocalizedStringTransformer;
use Rollerworks\Component\Search\Extension\Core\ValueComparator\DateValueComparator;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\Field\SearchFieldView;
use Rollerworks\Component\Search\Value\Compare;
use Rollerworks\Component\Search\Value\Range;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
final class DateType extends BaseDateTimeType
{
    public const DEFAULT_FORMAT = \IntlDateFormatter::MEDIUM;

    public const HTML5_FORMAT = 'yyyy-MM-dd';

    private $valueComparator;

    public function __construct()
    {
        $this->valueComparator = new DateValueComparator();
    }

    public function buildType(FieldConfig $config, array $options): void
    {
        $config->setValueComparator($this->valueComparator);
        $config->setValueTypeSupport(Range::class, true);
        $config->setValueTypeSupport(Compare::class, true);

        if ($options['pattern'] === null) {
            $this->validateFormat('format', $options['format']);
        } else {
            $this->validateDateFormat('pattern', $options['pattern']);
        }

        $config->setViewTransformer(
            new DateTimeToLocalizedStringTransformer(
                $options['model_timezone'],
                $options['view_timezone'],
                $options['format'],
                \IntlDateFormatter::NONE,
                \IntlDateFormatter::GREGORIAN,
                $options['pattern']
            )
        );

        $config->setNormTransformer(
            new DateTimeToLocalizedStringTransformer(
                $options['model_timezone'],
                $options['view_timezone'],
                $options['format'],
                \IntlDateFormatter::NONE,
                \IntlDateFormatter::GREGORIAN,
                self::HTML5_FORMAT
            )
        );
    }

    public function buildView(SearchFieldView $view, FieldConfig $config, array $options): void
    {
        $pattern = $options['pattern'];

        if ($pattern === null) {
            $pattern = \IntlDateFormatter::create(
                \Locale::getDefault(),
                $options['format'],
                \IntlDateFormatter::NONE,
                $options['view_timezone'],
                \IntlDateFormatter::GREGORIAN
            )->getPattern();
        }

        $view->vars['html5'] = $options['html5'];
        $view->vars['timezone'] = $options['view_timezone'] ?? date_default_timezone_get();
        $view->vars['pattern'] = $pattern;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'model_timezone' => null,
                'view_timezone' => null,
                'pattern' => null,
                'format' => self::DEFAULT_FORMAT,
                'html5' => true,
            ]
        );

        $resolver->setAllowedTypes('format', ['int']);
        $resolver->setAllowedTypes('pattern', ['string', 'null']);
    }

    public function getBlockPrefix(): string
    {
        return 'date';
    }
}


text:
/**
 * Created by cajetan on 7/14/17.
 */

public class Braking {
    private static final double G = 9.81;
    private static final double KM_TO_M = 1000.0 / 3600.0;
    private static final double M_TO_KM = 3600.0 / 1000.0;

    public static double dist(double v, double mu) {    // suppose reaction time is 1
        double brakingDistance = Math.pow(v*KM_TO_M, 2) / (2.0*mu*G);
        double reactionDistance = v*KM_TO_M;

        return brakingDistance + reactionDistance;
    }

    public static double speed(double d, double mu) {   // suppose reaction time is 1
        return (mu*G/2.0) * (Math.sqrt(4.0+8.0*d/mu/G) - 2.0) * M_TO_KM;
    }
}


text:
import hass from '../util/home-assistant-js-instance';

import Polymer from '../polymer';
import attributeClassNames from '../util/attribute-class-names';

const { serviceActions } = hass;
const ATTRIBUTE_CLASSES = ['volume_level'];

export default new Polymer({
  is: 'more-info-media_player',

  properties: {
    stateObj: {
      type: Object,
      observer: 'stateObjChanged',
    },

    isOff: {
      type: Boolean,
      value: false,
    },

    isPlaying: {
      type: Boolean,
      value: false,
    },

    isMuted: {
      type: Boolean,
      value: false,
    },

    volumeSliderValue: {
      type: Number,
      value: 0,
    },

    supportsPause: {
      type: Boolean,
      value: false,
    },

    supportsVolumeSet: {
      type: Boolean,
      value: false,
    },

    supportsVolumeMute: {
      type: Boolean,
      value: false,
    },

    supportsPreviousTrack: {
      type: Boolean,
      value: false,
    },

    supportsNextTrack: {
      type: Boolean,
      value: false,
    },

    supportsTurnOn: {
      type: Boolean,
      value: false,
    },

    supportsTurnOff: {
      type: Boolean,
      value: false,
    },

    supportsVolumeButtons: {
      type: Boolean,
      value: false,
    },

    hasMediaControl: {
      type: Boolean,
      value: false,
    },

  },

  stateObjChanged(newVal) {
    if (newVal) {
      const hasMediaStates = ['playing', 'paused', 'unknown'];

      this.isOff = newVal.state === 'off';
      this.isPlaying = newVal.state === 'playing';
      this.hasMediaControl = hasMediaStates.indexOf(newVal.state) !== -1;
      this.volumeSliderValue = newVal.attributes.volume_level * 100;
      this.isMuted = newVal.attributes.is_volume_muted;
      this.supportsPause = (newVal.attributes.supported_media_commands & 1) !== 0;
      this.supportsVolumeSet = (newVal.attributes.supported_media_commands & 4) !== 0;
      this.supportsVolumeMute = (newVal.attributes.supported_media_commands & 8) !== 0;
      this.supportsPreviousTrack = (newVal.attributes.supported_media_commands & 16) !== 0;
      this.supportsNextTrack = (newVal.attributes.supported_media_commands & 32) !== 0;
      this.supportsTurnOn = (newVal.attributes.supported_media_commands & 128) !== 0;
      this.supportsTurnOff = (newVal.attributes.supported_media_commands & 256) !== 0;
      this.supportsVolumeButtons = (newVal.attributes.supported_media_commands & 1024) !== 0;
    }

    this.async(() => this.fire('iron-resize'), 500);
  },

  computeClassNames(stateObj) {
    return attributeClassNames(stateObj, ATTRIBUTE_CLASSES);
  },

  computeIsOff(stateObj) {
    return stateObj.state === 'off';
  },

  computeMuteVolumeIcon(isMuted) {
    return isMuted ? 'mdi:volume-off' : 'mdi:volume-high';
  },

  computeHideVolumeButtons(isOff, supportsVolumeButtons) {
    return !supportsVolumeButtons || isOff;
  },

  computeShowPlaybackControls(isOff, hasMedia) {
    return !isOff && hasMedia;
  },

  computePlaybackControlIcon() {
    if (this.isPlaying) {
      return this.supportsPause ? 'mdi:pause' : 'mdi:stop';
    }
    return 'mdi:play';
  },

  computeHidePowerButton(isOff, supportsTurnOn, supportsTurnOff) {
    return isOff ? !supportsTurnOn : !supportsTurnOff;
  },

  handleTogglePower() {
    this.callService(this.isOff ? 'turn_on' : 'turn_off');
  },

  handlePrevious() {
    this.callService('media_previous_track');
  },

  handlePlaybackControl() {
    this.callService('media_play_pause');
  },

  handleNext() {
    this.callService('media_next_track');
  },

  handleVolumeTap() {
    if (!this.supportsVolumeMute) {
      return;
    }
    this.callService('volume_mute', { is_volume_muted: !this.isMuted });
  },

  handleVolumeUp() {
    const obj = this.$.volumeUp;
    this.handleVolumeWorker('volume_up', obj, true);
  },

  handleVolumeDown() {
    const obj = this.$.volumeDown;
    this.handleVolumeWorker('volume_down', obj, true);
  },

  handleVolumeWorker(service, obj, force) {
    if (force || (obj !== undefined && obj.pointerDown)) {
      this.callService(service);
      this.async(() => this.handleVolumeWorker(service, obj, false), 500);
    }
  },

  volumeSliderChanged(ev) {
    const volPercentage = parseFloat(ev.target.value);
    const vol = volPercentage > 0 ? volPercentage / 100 : 0;
    this.callService('volume_set', { volume_level: vol });
  },

  callService(service, data) {
    const serviceData = data || {};
    serviceData.entity_id = this.stateObj.entityId;
    serviceActions.callService('media_player', service, serviceData);
  },
});


text:
include_recipe "build-essential"
include_recipe "git"
include_recipe "erlang"

version = node['elixir']['elixir_git_ref']

cache_path = Chef::Config['file_cache_path']

git "elixir #{version}" do
  repository node['elixir']['elixir_git_url']
  destination "#{cache_path}/elixir"
  action :sync
end

bash "install #{version}" do
  code <<-EOS
cd #{cache_path}/elixir
git checkout #{version}
make && make install
EOS
  not_if { File.exists?("/usr/local/lib/elixir") }
end


text:
<refentry id="wordml.template">
<refmeta>
<refentrytitle>wordml.template</refentrytitle>
</refmeta>
<refnamediv>
<refname>wordml.template</refname>
<refpurpose>Specify the template WordML document</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment id='wordml.template.frag'>
<xsl:param name="wordml.template" select=""/>
</src:fragment>
</refsynopsisdiv>

<refsect1><title>Description</title>

<para>The <parameter>wordml.template</parameter> parameter specifies a WordML document to use as a template for the generated document.  The template document is used to define the (extensive) headers for the generated document, in particular the paragraph and character styles that are used to format the various elements.  Any content in the template document is ignored.</para>

<para>A template document is used in order to allow maintenance of the paragraph and character styles to be done using Word itself, rather than these XSL stylesheets.</para>

</refsect1>
</refentry>


text:
#ifndef ANDROID_IPOWERMANAGER_H
#define ANDROID_IPOWERMANAGER_H

#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <hardware/power.h>

namespace android {

// ----------------------------------------------------------------------------

class IPowerManager : public IInterface
{
public:
    // These transaction IDs must be kept in sync with the method order from
    // IPowerManager.aidl.
    enum {
        ACQUIRE_WAKE_LOCK            = IBinder::FIRST_CALL_TRANSACTION,
        ACQUIRE_WAKE_LOCK_UID        = IBinder::FIRST_CALL_TRANSACTION + 1,
        RELEASE_WAKE_LOCK            = IBinder::FIRST_CALL_TRANSACTION + 2,
        UPDATE_WAKE_LOCK_UIDS        = IBinder::FIRST_CALL_TRANSACTION + 3,
        POWER_HINT                   = IBinder::FIRST_CALL_TRANSACTION + 4,
        UPDATE_WAKE_LOCK_SOURCE      = IBinder::FIRST_CALL_TRANSACTION + 5,
        IS_WAKE_LOCK_LEVEL_SUPPORTED = IBinder::FIRST_CALL_TRANSACTION + 6,
        USER_ACTIVITY                = IBinder::FIRST_CALL_TRANSACTION + 7,
        WAKE_UP                      = IBinder::FIRST_CALL_TRANSACTION + 8,
        GO_TO_SLEEP                  = IBinder::FIRST_CALL_TRANSACTION + 9,
        NAP                          = IBinder::FIRST_CALL_TRANSACTION + 10,
        IS_INTERACTIVE               = IBinder::FIRST_CALL_TRANSACTION + 11,
        IS_POWER_SAVE_MODE           = IBinder::FIRST_CALL_TRANSACTION + 12,
        SET_POWER_SAVE_MODE          = IBinder::FIRST_CALL_TRANSACTION + 13,
        REBOOT                       = IBinder::FIRST_CALL_TRANSACTION + 14,
        SHUTDOWN                     = IBinder::FIRST_CALL_TRANSACTION + 15,
        CRASH                        = IBinder::FIRST_CALL_TRANSACTION + 16,
    };

    DECLARE_META_INTERFACE(PowerManager);

    // The parcels created by these methods must be kept in sync with the
    // corresponding methods from IPowerManager.aidl.
    // FIXME remove the bool isOneWay parameters as they are not oneway in the .aidl
    virtual status_t acquireWakeLock(int flags, const sp<IBinder>& lock, const String16& tag,
            const String16& packageName, bool isOneWay = false) = 0;
    virtual status_t acquireWakeLockWithUid(int flags, const sp<IBinder>& lock, const String16& tag,
            const String16& packageName, int uid, bool isOneWay = false) = 0;
    virtual status_t releaseWakeLock(const sp<IBinder>& lock, int flags, bool isOneWay = false) = 0;
    virtual status_t updateWakeLockUids(const sp<IBinder>& lock, int len, const int *uids,
            bool isOneWay = false) = 0;
    virtual status_t powerHint(int hintId, int data) = 0;
    virtual status_t goToSleep(int64_t event_time_ms, int reason, int flags) = 0;
    virtual status_t reboot(bool confirm, const String16& reason, bool wait) = 0;
    virtual status_t shutdown(bool confirm, const String16& reason, bool wait) = 0;
    virtual status_t crash(const String16& message) = 0;
};

// ----------------------------------------------------------------------------

}; // namespace android

#endif // ANDROID_IPOWERMANAGER_H


text:
using UnityEngine.Rendering;
using Unity.Collections;
using System.Collections.Generic;

namespace UnityEngine.Experimental.Rendering.HDPipeline
{
#if ENABLE_RAYTRACING
    public class RayCountManager
    {
        // Indices of the values that we can query
        public enum RayCountValues
        {
            AmbientOcclusion = 0,
            Reflection = 1,
            AreaShadow = 2,
            Total = 3
        }
        // Texture that keeps track of the ray count per pixel
        public RTHandleSystem.RTHandle rayCountTexture { get { return m_RayCountTexture; } }
        RTHandleSystem.RTHandle m_RayCountTexture = null;

        // Buffer that holds the reductions of the ray count
        ComputeBuffer m_ReducedRayCountBuffer0 = null;
        ComputeBuffer m_ReducedRayCountBuffer1 = null;
        ComputeBuffer m_ReducedRayCountBuffer2 = null;

        // CPU Buffer that holds the current values
        uint[] m_ReducedRayCountValues = new uint[4];

        // HDRP Resources
        DebugDisplaySettings m_DebugDisplaySettings;
        RenderPipelineResources m_PipelineResources;

        // Given that the requests are guaranteed to be executed in order we use a queue to store it
        Queue<AsyncGPUReadbackRequest> rayCountReadbacks = new Queue<AsyncGPUReadbackRequest>();

        public void Init(RenderPipelineResources renderPipelineResources, DebugDisplaySettings currentDebugDisplaySettings)
        {
            // Keep track of the external resources
            m_DebugDisplaySettings = currentDebugDisplaySettings;
            m_PipelineResources = renderPipelineResources;

            m_RayCountTexture = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: GraphicsFormat.R32G32B32A32_UInt, enableRandomWrite: true, useMipMap: false, name: "RayCountTexture");

            // We only require 3 buffers (this supports a maximal size of 8192x8192)
            m_ReducedRayCountBuffer0 = new ComputeBuffer(4 * 256 * 256, sizeof(uint));
            m_ReducedRayCountBuffer1 = new ComputeBuffer(4 * 32 * 32, sizeof(uint));
            m_ReducedRayCountBuffer2 = new ComputeBuffer(4, sizeof(uint));

            // Initialize the cpu ray count (Optional)
            for(int i = 0; i < 4; ++i)
            {
                m_ReducedRayCountValues[i] = 0;
            }
        }

        public void Release()
        {
            RTHandles.Release(m_RayCountTexture);
            CoreUtils.SafeRelease(m_ReducedRayCountBuffer0);
            CoreUtils.SafeRelease(m_ReducedRayCountBuffer1);
            CoreUtils.SafeRelease(m_ReducedRayCountBuffer2);
        }

        public void ClearRayCount(CommandBuffer cmd, HDCamera camera)
        {
            // We only want to do the clears only if the debug display is active
            if (m_DebugDisplaySettings.data.countRays)
            {
                // Get the compute shader to use
                ComputeShader countCompute = m_PipelineResources.shaders.countTracedRays;

                // Grab the kernel that we will be using for the clear
                int currentKenel = countCompute.FindKernel("ClearBuffer");

                // We only clear the 256x256 texture, the clear will then implicitly propagate to the lower resolutions
                cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer0);
                cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 256);
                int tileSize = 256 / 32;
                cmd.DispatchCompute(countCompute, currentKenel, tileSize, tileSize, 1);

                // Clear the ray count texture (that ensures that we don't have to check what we are reading while we reduce)
                HDUtils.SetRenderTarget(cmd, m_RayCountTexture, ClearFlag.Color);
            }
        }

        public int RayCountIsEnabled()
        {
            return m_DebugDisplaySettings.data.countRays ? 1 : 0;
        }

        public void EvaluateRayCount(CommandBuffer cmd, HDCamera camera)
        {
            if (m_DebugDisplaySettings.data.countRays)
            {
                using (new ProfilingSample(cmd, "Raytracing Debug Overlay", CustomSamplerId.RaytracingDebug.GetSampler()))
                {
                    // Get the size of the viewport to process
                    int currentWidth = camera.actualWidth;
                    int currentHeight = camera.actualHeight;

                    // Get the compute shader
                    ComputeShader countCompute = m_PipelineResources.shaders.countTracedRays;

                    // Grab the kernel that we will be using for the reduction
                    int currentKenel = countCompute.FindKernel("TextureReduction");

                    // Compute the dispatch dimensions
                    int areaTileSize = 32;
                    int dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                    int dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                    // Do we need three passes
                    if (dispatchHeight > 32  || dispatchWidth > 32)
                    {
                        // Bind the texture and the 256x256 buffer
                        cmd.SetComputeTextureParam(countCompute, currentKenel, HDShaderIDs._InputRayCountTexture, m_RayCountTexture);
                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer0);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 256);
                        cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);

                        // Let's move to the next reduction pass
                        currentWidth /= 32;
                        currentHeight /= 32;

                        // Grab the kernel that we will be using for the reduction
                        currentKenel = countCompute.FindKernel("BufferReduction");

                        // Compute the dispatch dimensions
                        dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                        dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer0);
                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._InputBufferDimension, 256);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 32);
                        cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);

                        // Let's move to the next reduction pass
                        currentWidth /= 32;
                        currentHeight /= 32;

                        // Compute the dispatch dimensions
                        dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                        dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer2);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._InputBufferDimension, 32);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 1);
                        cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
                    }
                    else
                    {
                        cmd.SetComputeTextureParam(countCompute, currentKenel, HDShaderIDs._InputRayCountTexture, m_RayCountTexture);
                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 32);
                        cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);

                        // Let's move to the next reduction pass
                        currentWidth /= 32;
                        currentHeight /= 32;

                        // Grab the kernel that we will be using for the reduction
                        currentKenel = countCompute.FindKernel("BufferReduction");

                        // Compute the dispatch dimensions
                        dispatchWidth = Mathf.Max(1, (currentWidth + (areaTileSize - 1)) / areaTileSize);
                        dispatchHeight = Mathf.Max(1, (currentHeight + (areaTileSize - 1)) / areaTileSize);

                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._InputRayCountBuffer, m_ReducedRayCountBuffer1);
                        cmd.SetComputeBufferParam(countCompute, currentKenel, HDShaderIDs._OutputRayCountBuffer, m_ReducedRayCountBuffer2);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._InputBufferDimension, 32);
                        cmd.SetComputeIntParam(countCompute, HDShaderIDs._OutputBufferDimension, 1);
                        cmd.DispatchCompute(countCompute, currentKenel, dispatchWidth, dispatchHeight, 1);
                    }

                    // Enqueue an Async read-back for the single value
                    AsyncGPUReadbackRequest singleReadBack = AsyncGPUReadback.Request(m_ReducedRayCountBuffer2, 4 * sizeof(uint), 0);
                    rayCountReadbacks.Enqueue(singleReadBack);

                }
            }
        }

        public float GetRaysPerFrame(RayCountValues rayCountValue)
        {
            if (!m_DebugDisplaySettings.data.countRays)
            {
                return 0.0f;
            }
            else
            {
                while(rayCountReadbacks.Peek().done || rayCountReadbacks.Peek().hasError ==  true)
                {
                    if (rayCountReadbacks.Peek().done)
                    {
                        // Grab the native array from this readback
                        NativeArray<uint> sampleCount = rayCountReadbacks.Peek().GetData<uint>();
                        for(int i = 0; i < 4; ++i)
                        {
                            m_ReducedRayCountValues[i] = sampleCount[i];
                        }
                    }
                    rayCountReadbacks.Dequeue();
                }

                return m_ReducedRayCountValues[(int)rayCountValue];
            }
        }

    }
#endif
}


text:
package store

import (
	"errors"
	"sync"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/volume"
	"github.com/docker/docker/volume/drivers"
)

var (
	// ErrVolumeInUse is a typed error returned when trying to remove a volume that is currently in use by a container
	ErrVolumeInUse = errors.New("volume is in use")
	// ErrNoSuchVolume is a typed error returned if the requested volume doesn't exist in the volume store
	ErrNoSuchVolume = errors.New("no such volume")
	// ErrInvalidName is a typed error returned when creating a volume with a name that is not valid on the platform
	ErrInvalidName = errors.New("volume name is not valid on this platform")
)

// New initializes a VolumeStore to keep
// reference counting of volumes in the system.
func New() *VolumeStore {
	return &VolumeStore{
		vols: make(map[string]*volumeCounter),
	}
}

// VolumeStore is a struct that stores the list of volumes available and keeps track of their usage counts
type VolumeStore struct {
	vols map[string]*volumeCounter
	mu   sync.Mutex
}

// volumeCounter keeps track of references to a volume
type volumeCounter struct {
	volume.Volume
	count uint
}

// AddAll adds a list of volumes to the store
func (s *VolumeStore) AddAll(vols []volume.Volume) {
	for _, v := range vols {
		s.vols[normaliseVolumeName(v.Name())] = &volumeCounter{v, 0}
	}
}

// Create tries to find an existing volume with the given name or create a new one from the passed in driver
func (s *VolumeStore) Create(name, driverName string, opts map[string]string) (volume.Volume, error) {
	s.mu.Lock()
	name = normaliseVolumeName(name)
	if vc, exists := s.vols[name]; exists {
		v := vc.Volume
		s.mu.Unlock()
		return v, nil
	}
	s.mu.Unlock()
	logrus.Debugf("Registering new volume reference: driver %s, name %s", driverName, name)

	vd, err := volumedrivers.GetDriver(driverName)
	if err != nil {
		return nil, err
	}

	// Validate the name in a platform-specific manner
	valid, err := volume.IsVolumeNameValid(name)
	if err != nil {
		return nil, err
	}
	if !valid {
		return nil, ErrInvalidName
	}

	v, err := vd.Create(name, opts)
	if err != nil {
		return nil, err
	}

	s.mu.Lock()
	s.vols[normaliseVolumeName(v.Name())] = &volumeCounter{v, 0}
	s.mu.Unlock()

	return v, nil
}

// Get looks if a volume with the given name exists and returns it if so
func (s *VolumeStore) Get(name string) (volume.Volume, error) {
	name = normaliseVolumeName(name)
	s.mu.Lock()
	defer s.mu.Unlock()
	vc, exists := s.vols[name]
	if !exists {
		return nil, ErrNoSuchVolume
	}
	return vc.Volume, nil
}

// Remove removes the requested volume. A volume is not removed if the usage count is > 0
func (s *VolumeStore) Remove(v volume.Volume) error {
	s.mu.Lock()
	defer s.mu.Unlock()
	name := normaliseVolumeName(v.Name())
	logrus.Debugf("Removing volume reference: driver %s, name %s", v.DriverName(), name)
	vc, exists := s.vols[name]
	if !exists {
		return ErrNoSuchVolume
	}

	if vc.count > 0 {
		return ErrVolumeInUse
	}

	vd, err := volumedrivers.GetDriver(vc.DriverName())
	if err != nil {
		return err
	}
	if err := vd.Remove(vc.Volume); err != nil {
		return err
	}
	delete(s.vols, name)
	return nil
}

// Increment increments the usage count of the passed in volume by 1
func (s *VolumeStore) Increment(v volume.Volume) {
	s.mu.Lock()
	defer s.mu.Unlock()
	name := normaliseVolumeName(v.Name())
	logrus.Debugf("Incrementing volume reference: driver %s, name %s", v.DriverName(), name)

	vc, exists := s.vols[name]
	if !exists {
		s.vols[name] = &volumeCounter{v, 1}
		return
	}
	vc.count++
}

// Decrement decrements the usage count of the passed in volume by 1
func (s *VolumeStore) Decrement(v volume.Volume) {
	s.mu.Lock()
	defer s.mu.Unlock()
	name := normaliseVolumeName(v.Name())
	logrus.Debugf("Decrementing volume reference: driver %s, name %s", v.DriverName(), name)

	vc, exists := s.vols[name]
	if !exists {
		return
	}
	if vc.count == 0 {
		return
	}
	vc.count--
}

// Count returns the usage count of the passed in volume
func (s *VolumeStore) Count(v volume.Volume) uint {
	s.mu.Lock()
	defer s.mu.Unlock()
	vc, exists := s.vols[normaliseVolumeName(v.Name())]
	if !exists {
		return 0
	}
	return vc.count
}

// List returns all the available volumes
func (s *VolumeStore) List() []volume.Volume {
	s.mu.Lock()
	defer s.mu.Unlock()
	var ls []volume.Volume
	for _, vc := range s.vols {
		ls = append(ls, vc.Volume)
	}
	return ls
}

// FilterByDriver returns the available volumes filtered by driver name
func (s *VolumeStore) FilterByDriver(name string) []volume.Volume {
	return s.filter(byDriver(name))
}

// filterFunc defines a function to allow filter volumes in the store
type filterFunc func(vol volume.Volume) bool

// byDriver generates a filterFunc to filter volumes by their driver name
func byDriver(name string) filterFunc {
	return func(vol volume.Volume) bool {
		return vol.DriverName() == name
	}
}

// filter returns the available volumes filtered by a filterFunc function
func (s *VolumeStore) filter(f filterFunc) []volume.Volume {
	s.mu.Lock()
	defer s.mu.Unlock()
	var ls []volume.Volume
	for _, vc := range s.vols {
		if f(vc.Volume) {
			ls = append(ls, vc.Volume)
		}
	}
	return ls
}


text:
#pragma once

#include <modules/json/jsonmoduledefine.h>
#include <inviwo/core/properties/property.h>
#include <nlohmann/json.hpp>

namespace inviwo {

using json = ::nlohmann::json;

/**
 * Interface for converting between JSON and Property.
 */
class IVW_MODULE_JSON_API PropertyJSONConverter {
public:
    PropertyJSONConverter() = default;
    virtual ~PropertyJSONConverter() = default;

    virtual std::string getPropClassIdentifier() const = 0;

    /**
     * Converts a Property to a JSON object.
     */
    virtual void toJSON(json& j, const Property& p) const = 0;
    /**
     * Converts a JSON object to a Property to a JSON object.
     */
    virtual void fromJSON(const json& j, Property& p) const = 0;
};
/**
 * Convert between JSON and Property.
 * A TemplatePropertyJSONConverter requires implementations of to_json(json& j,
 * const SrcProperty& p) and from_json(const json& j, SrcProperty& p).
 */
template <typename SrcProperty>
class TemplatePropertyJSONConverter : public PropertyJSONConverter {
public:
    TemplatePropertyJSONConverter() = default;
    virtual ~TemplatePropertyJSONConverter() = default;

    virtual std::string getPropClassIdentifier() const override {
        return PropertyTraits<SrcProperty>::classIdentifier();
    }
    /**
     * Converts a Property to a JSON object.
     * Requires that to_json(json& j, const SrcProperty& p) has been implemented.
     */
    virtual void toJSON(json& j, const Property& p) const override {
        to_json(j, static_cast<const SrcProperty&>(p));
    }
    /**
     * Converts a JSON object to a Property to a JSON object.
     * Requires that to_json(json& j, const SrcProperty& p) has been implemented.
     */
    virtual void fromJSON(const json& j, Property& p) const override {
        j.get_to(static_cast<SrcProperty&>(p));
    }
};

}  // namespace inviwo


text:
#ifndef ECMA_REFERENCE_H
#define ECMA_REFERENCE_H

#include "ecma-globals.h"

#include "jrt.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup references ECMA-Reference
 * @{
 */

ecma_object_t *ecma_op_resolve_reference_base (ecma_object_t *lex_env_p, ecma_string_t *name_p);
ecma_value_t ecma_op_resolve_reference_value (ecma_object_t *lex_env_p, ecma_string_t *name_p);
ecma_value_t ecma_op_object_bound_environment_resolve_reference_value (ecma_object_t *lex_env_p, ecma_string_t *name_p);
#if JERRY_ESNEXT
ecma_value_t ecma_op_resolve_super_base (ecma_object_t *lex_env_p);
#endif /* JERRY_ESNEXT */

/**
 * @}
 * @}
 */

#endif /* !ECMA_REFERENCE_H */