text:
layout: post
disqus_identifier: #28
comments: true
categories:
  - GitHub Pages
  - SSL
---

Adding a certificate to your GitHub Pages site so that all of your traffic can
use HTTPS is easy... if you don't use a custom domain name.  If you do have a custom domain, then you need to do a little work and a (free) [Cloud Flare](https://www.cloudflare.com) account to get it going.

1. Create your free acount on https://www.cloudflare.com
1. Enter your site's address in the setup bar
1. Head over to your DNS provider and add the Clod Flare servers as your custom domain servers.  e.g. [On NameCheap](https://ap.www.namecheap.com/domains/domaincontrolpanel/quintussential.com/domain)
1. Optionally, you can head back to Cloud Flare and set up a page rule to redirect all HTTP pages to redirect to HTTPS. Just add a rule to match `http://*quintussential.com/*`
1. Wait.  DNS has to happen now.

Thanks to [Hacker Noon](https://hackernoon.com/set-up-ssl-on-github-pages-with-custom-domains-for-free-a576bdf51bc) for pointing this out.

redpajama_set_name: RedPajamaGithub


text:
EC2 MountPoint Property Type
============================

The EC2 MountPoint property is an embedded property of the [AWS::EC2::Instance](aws-properties-ec2-instance.html "AWS::EC2::Instance") type.

Syntax
------

``` {.programlisting}

{
   "Device" : String,
   "VolumeId" : String
}

```

Properties
----------

 `Device`
How the device is exposed to the instance (such as /dev/sdh, or xvdh).

*Required*: Yes

*Type*: String

 `VolumeId`
The ID of the Amazon EBS volume. The volume and instance must be within the same Availability Zone and the instance must be running.

*Required*: Yes

*Type*: String

Example
-------

This mount point (specified in the *`Volumes`* property in the EC2 instance) refers to a named EBS volume, "NewVolume".

``` {.programlisting}

"Ec2Instance" : {
   "Type" : "AWS::EC2::Instance",
   "Properties" : {
      "AvailabilityZone" : {
         "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "TestAz" ]
      },
      "SecurityGroups" : [ { "Ref" : "InstanceSecurityGroup" } ],
      "KeyName" : { "Ref" : "KeyName" },
      "ImageId" : {
         "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "AMI" ]
      },
      "Volumes" : [
         { "VolumeId" : { "Ref" : "NewVolume" }, "Device" : "/dev/sdk" }
      ]
   }
},
"NewVolume" : {
   "Type" : "AWS::EC2::Volume",
   "Properties" : {
      "Size" : "100",
      "AvailabilityZone" : {
         "Fn::FindInMap" : [ "RegionMap", { "Ref" : "AWS::Region" }, "TestAz" ]
      }
   }
}

```

See Also
--------

-   [AWS::EC2::Instance](aws-properties-ec2-instance.html "AWS::EC2::Instance")
-   [AWS::EC2::Volume](aws-properties-ec2-ebs-volume.html "AWS::EC2::Volume")


text:
import os
import shutil
import numpy as np
from osgeo import gdal, osr

# Set this variable to your osgeopy-data directory so that the following
# examples will work without editing. We'll use the os.path.join() function
# to combine this directory and the filenames to make a complete path. Of
# course, you can type the full path to the file for each example if you'd
# prefer.
data_dir = r'D:\osgeopy-data'
# data_dir =

##############################  10.1 Ground control points  ####################

# See listing10_1.py, since the example reuses some code from that listing.

#############  10.2 Converting pixel coordinates to another image  #############

# Create a function to get the extent of a raster and try it out on the
# raster just created in listing 10.1. This function is in
def get_extent(fn):
    '''Returns min_x, max_y, max_x, min_y'''
    ds = gdal.Open(fn)
    gt = ds.GetGeoTransform()
    return (gt[0], gt[3], gt[0] + gt[1] * ds.RasterXSize,
        gt[3] + gt[5] * ds.RasterYSize)

# The raster with GCPs doesn't have a geotransform so this extent isn't
# correct.
os.chdir(os.path.join(data_dir, 'Utah'))
print(get_extent('cache.tif'))

# But this one is.
print(get_extent('cache2.tif'))

# Extra examples...
# Remember the vashon.tif file created in the last chapter? Let's use it
# for a transformer example.
os.chdir(os.path.join(data_dir, 'Landsat', 'Washington'))
vashon_ds = gdal.Open('vashon.tif')
full_ds = gdal.Open('nat_color.tif')

# Create a transformer that will map pixel coordinates from the Vashon
# dataset into the full one.
trans = gdal.Transformer(vashon_ds, full_ds, [])

# Use the transformer to figure out the pixel offsets in the full image
# that correspond with the upper left corner of the vashon one.
success, xyz = trans.TransformPoint(False, 0, 0)
print(success, xyz)

# If we use the output from that and go the reverse direction, we'll get the
# upper left corner for vashon.
success, xyz = trans.TransformPoint(True, 6606, 3753)
print(success, xyz)

##############################  10.3 Color tables  #############################

# Make a copy of the raster we just created in listing 10.3.
os.chdir(os.path.join(data_dir, 'Switzerland'))
original_ds = gdal.Open('dem_class2.tif')
ds = original_ds.GetDriver().CreateCopy('dem_class3.tif', original_ds)

# Get the existing color table from the band.
band = ds.GetRasterBand(1)
colors = band.GetRasterColorTable()

# Change the entry for 5.
colors.SetColorEntry(5, (250, 250, 250))

# Set the modified color table back on the raster.
band.SetRasterColorTable(colors)
del band, ds

#############################  10.3.1 Transparency  ############################

# Let's take the output from listing 10.3 and add some transparency. We have
# to make a copy of the dataset, though, so we can add the alpha band.
os.chdir(os.path.join(data_dir, 'Switzerland'))
original_ds = gdal.Open('dem_class2.tif')
driver = gdal.GetDriverByName('gtiff')

# This is the only line shown in the text. The rest of the copy code is
# left out for space reasons (and because you know all about it by now).
ds = driver.Create('dem_class4.tif', original_ds.RasterXSize,
    original_ds.RasterYSize, 2, gdal.GDT_Byte, ['ALPHA=YES'])

# Add the projection and and geotransform info to the copy.
ds.SetProjection(original_ds.GetProjection())
ds.SetGeoTransform(original_ds.GetGeoTransform())

# Read the data in from dem_class2.
original_band1 = original_ds.GetRasterBand(1)
data = original_band1.ReadAsArray()

# Write the data to band 1 of the new raster and copy the color table over.
band1 = ds.GetRasterBand(1)
band1.WriteArray(data)
band1.SetRasterColorTable(original_band1.GetRasterColorTable())
band1.SetRasterColorInterpretation(gdal.GCI_PaletteIndex)
band1.SetNoDataValue(original_band1.GetNoDataValue())

ds.FlushCache()

# Now that we're finally done copying, go back to the text and find
# everywhere in the data array that the pixel value is 5 and set
# the value to 65 instead. Set everything else to 255.
import numpy as np
data = band1.ReadAsArray()
data = np.where(data == 5, 65, 255)

# Now write the modified data array to the second (alpha) band in the new
# raster.
band2 = ds.GetRasterBand(2)
band2.WriteArray(data)
band2.SetRasterColorInterpretation(gdal.GCI_AlphaBand)

del ds, original_ds

# To get this output to render correctly in QGIS, you might have to change
# the symbology. Open up the Layer Properties dialog, go to the Style tab,
# and choose Pletted for the Render type. Try putting the swiss_dem raster
# under it so you can see the transparency.

###############################  10.4 Histograms  ##############################

# Look at approximate vs exact histogram values.
os.chdir(os.path.join(data_dir, 'Switzerland'))
ds = gdal.Open('dem_class2.tif')
band = ds.GetRasterBand(1)
approximate_hist = band.GetHistogram()
exact_hist = band.GetHistogram(approx_ok=False)
print('Approximate:', approximate_hist[:7], sum(approximate_hist))
print('Exact:', exact_hist[:7], sum(exact_hist))

# Look at the current default histogram.
print(band.GetDefaultHistogram())

# Change the default histogram so that it lumps 1 & 2, 3 & 4, and leaves 5
# by itself.
hist = band.GetHistogram(0.5, 6.5, 3, approx_ok=False)
band.SetDefaultHistogram(1, 6, hist)

# Look at what the default histogram is now.
print(band.GetDefaultHistogram())

# Get the individual bits of data from the default histogram.
min_val, max_val, n, hist = band.GetDefaultHistogram()
print(min_val, max_val, n)
print(hist)

##################################  10.6 VRTs  #################################

# XML defining a VRT band. It uses the first band in whatever dataset it's
# pointed to with the SourceFilename tag.
xml = '''
<SimpleSource>
  <SourceFilename>{0}</SourceFilename>
  <SourceBand>1</SourceBand>
</SimpleSource>
'''

# Create a 3-band VRT with the same dimensions as one of the Landsat bands.
os.chdir(os.path.join(data_dir, 'Landsat', 'Washington'))
tmp_ds = gdal.Open('p047r027_7t20000730_z10_nn30.tif')
driver = gdal.GetDriverByName('vrt')
ds = driver.Create('nat_color.vrt', tmp_ds.RasterXSize,
    tmp_ds.RasterYSize, 3)
ds.SetProjection(tmp_ds.GetProjection())
ds.SetGeoTransform(tmp_ds.GetGeoTransform())

# Point the VRT to the 3 individual GeoTIFFs holding the Landsat bands.
# The bands are stored in the VRT in the order you add them, so we add
# them in 3,2,1 order so that we get RGB.
metadata = {'source_0': xml.format('p047r027_7t20000730_z10_nn30.tif')}
ds.GetRasterBand(1).SetMetadata(metadata, 'vrt_sources')

metadata = {'source_0': xml.format('p047r027_7t20000730_z10_nn20.tif')}
ds.GetRasterBand(2).SetMetadata(metadata, 'vrt_sources')

metadata = {'source_0': xml.format('p047r027_7t20000730_z10_nn10.tif')}
ds.GetRasterBand(3).SetMetadata(metadata, 'vrt_sources')

del ds, tmp_ds

##########################  10.6.2 Troublesome formats  ########################

# Use the VRT created in listing 9.5 to create a jpeg of Vashon Island.
os.chdir(os.path.join(data_dir, 'Landsat', 'Washington'))
ds = gdal.Open('vashon.vrt')
gdal.GetDriverByName('jpeg').CreateCopy('vashon.jpg', ds)

##########################  10.6.3 Reprojecting images  ########################

# Reproject the nat_color.tif from UTM to unprojected lat/lon. First create
# the output SRS.
srs = osr.SpatialReference()
srs.SetWellKnownGeogCS('WGS84')

# Open the nat_color file.
os.chdir(os.path.join(data_dir, 'Landsat', 'Washington'))
old_ds = gdal.Open('nat_color.tif')

# Create a VRT in memory that does the reproject.
vrt_ds = gdal.AutoCreateWarpedVRT(old_ds, None, srs.ExportToWkt(),
    gdal.GRA_Bilinear)

# Copy the VRT to a GeoTIFF so we have a file on disk.
gdal.GetDriverByName('gtiff').CreateCopy('nat_color_wgs84.tif', vrt_ds)

###########################  10.7 Callback functions  ##########################

# Let's calculate statistics on the natural color Landsat image and show
# progress while it does it (this image probably already has stats, so this
# will go really fast). Watch your output window to see what happens.
os.chdir(os.path.join(data_dir, 'Landsat', 'Washington'))
ds = gdal.Open('nat_color.tif')
for i in range(ds.RasterCount):
    ds.GetRasterBand(i + 1).ComputeStatistics(False, gdal.TermProgress_nocb)

# How about using the gdal callback function with my own stuff? Let's just
# list all of the files in the current diretory and pretend to do something
# with them.
def process_file(fn):
    # Slow things down a bit by counting to 1,000,000 for each file.
    for i in range(1000000):
        pass # do nothing

list_of_files = os.listdir('.')
for i in range(len(list_of_files)):
    process_file(list_of_files[i])
    gdal.TermProgress_nocb(i / float(len(list_of_files)))
gdal.TermProgress_nocb(100)

######################  10.8 Exceptions and error handlers  ####################

os.chdir(os.path.join(data_dir, 'Switzerland'))

# This will fail because the second filename has an extra f at the end. The
# first one is the only one that will get statistics calculated.
file_list = ['dem_class.tif', 'dem_class2.tiff', 'dem_class3.tif']
for fn in file_list:
    ds = gdal.Open(fn)
    ds.GetRasterBand(1).ComputeStatistics(False)

# You could check to see if the file could be opened and skip it if not.
for fn in file_list:
    ds = gdal.Open(fn)
    if ds is None:
        print('Could not compute stats for ' + fn)
    else:
        print('Computing stats for ' + fn)
        ds.GetRasterBand(1).ComputeStatistics(False)

# Or you could use exceptions and a try/except block.
gdal.UseExceptions()
for fn in file_list:
    try:
        ds = gdal.Open(fn)
        ds.GetRasterBand(1).ComputeStatistics(False)
    except:
        print('Could not compute stats for ' + fn)
        # Uncomment this if you also want it to print the gdal error message.
        # print(gdal.GetLastErrorMsg())

# Turn exceptions off.
gdal.DontUseExceptions()

# How about the second example, but without the gdal error message?
gdal.PushErrorHandler('CPLQuietErrorHandler')
for fn in file_list:
    ds = gdal.Open(fn)
    if ds is None:
        print('Could not compute stats for ' + fn)
    else:
        print('Computing stats for ' + fn)
        ds.GetRasterBand(1).ComputeStatistics(False)

# Get the default error handler back.
gdal.PopErrorHandler()

# Call the error function yourself.
def do_something(ds1, ds2):
    if ds1.GetProjection() != ds2.GetProjection():
        gdal.Error(gdal.CE_Failure, gdal.CPLE_AppDefined,
            'Datasets must have the same SRS')
        return False
    # now do your stuff
ds1 = gdal.Open(os.path.join(data_dir, 'Switzerland', 'dem_class.tif'))
ds2 = gdal.Open(os.path.join(data_dir, 'Landsat', 'Washington', 'nat_color.tif'))
do_something(ds1, ds2)
del ds1, ds2

# Create your own error handler.
import ospybook as pb
def log_error_handler(err_class, err_no, msg):
    logging.error('{} - {}: {}'.format(
        pb.get_gdal_constant_name('CE', err_class),
        pb.get_gdal_constant_name('CPLE', err_no),
        msg))

# Use your custom error handler to print messages to the screen.
import logging
gdal.PushErrorHandler(log_error_handler)
ds1 = gdal.Open(os.path.join(data_dir, 'Switzerland', 'dem_class.tif'))
ds2 = gdal.Open(os.path.join(data_dir, 'Landsat', 'Washington', 'nat_color.tif'))
do_something(ds1, ds2)
del ds1, ds2

# Or use it to write to a file (change to file path!).
import logging
logging.basicConfig(filename='d:/temp/log.txt')
gdal.PushErrorHandler(log_error_handler)
ds1 = gdal.Open(os.path.join(data_dir, 'Switzerland', 'dem_class.tif'))
ds2 = gdal.Open(os.path.join(data_dir, 'Landsat', 'Washington', 'nat_color.tif'))
do_something(ds1, ds2)
del ds1, ds2

######################  Get constant names with ospybook  #####################

import ospybook as pb

# Get the GDT constant that has a value of 5.
print(pb.get_gdal_constant_name('GDT', 5))


text:
@implementation BZTestController {
    VSSpeechSynthesizer *synthesizer;
}

#define addKIFScenario(name) [self addScenario:[KIFTestScenario name]]

- (void)initializeScenarios {
    synthesizer = [VSSpeechSynthesizer new];
    [synthesizer setVolume:0.3];
}

- (NSString *)logsFolder {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Logs"];
}

- (NSString *)logFile {
    NSString *logsFolder = [self logsFolder];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *fileName = nil;
    for (NSString *file in [fileManager enumeratorAtPath:logsFolder]) {
        NSLog(@"found log file: %@", file);
        fileName = file;
    }
    NSParameterAssert(fileName);
    return [logsFolder stringByAppendingPathComponent:fileName];
}

- (NSString *)completeTestLog {
    NSError *error = nil;
    NSString *completeTestLog = [NSString stringWithContentsOfFile:[self logFile]
                                                          encoding:NSUTF8StringEncoding
                                                             error:&error];
    NSParameterAssert(!error);
    return completeTestLog;
}

- (void)showLog:(NSString *)log {
    NSString *title = failureCount ? [NSString stringWithFormat:@"%d failures", failureCount] : @"All Tests Passed";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                    message:log
                                                   delegate:self
                                          cancelButtonTitle:@"Close"
                                          otherButtonTitles:@"Feedback", nil];
    [alert show];
}

- (void)completeInteractiveTesting {
    NSString *testLog = [self completeTestLog];
    [self performSelectorOnMainThread:@selector(showLog:) withObject:testLog waitUntilDone:NO];
    [TestFlight submitFeedback:testLog];
}

- (BOOL)shouldExitTests {
#if TARGET_IPHONE_SIMULATOR
    NSNumber *maxFailureCountToExit = [[[NSProcessInfo processInfo] environment]
                                       objectForKey:@"KIF_MAX_FAILURE_COUNT_TO_EXIT"];
    BOOL shouldExit = !maxFailureCountToExit || (failureCount <= [maxFailureCountToExit intValue]);
    return shouldExit;
#else
    return NO;
#endif
}

- (void)exitTests {
    [UIApplication sharedApplication].delegate = nil;
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    exit(failureCount);
}

- (void)sayStepFailed {
    [self say:[self.currentStep description]];
}

- (void)sayResultsAndThankYou {
    NSString *message = nil;
    if (!failureCount) {
        message = [NSString stringWithFormat:@"All %d Tests Passed!", [self.scenarios count]];
    } else {
        NSUInteger firstFailure = [failedScenarioIndexes firstIndex];
        KIFTestScenario *firstFailedScenario = [scenarios objectAtIndex:firstFailure];
        NSString *failures = failureCount > 1 ? [NSString stringWithFormat:@"There were %d failures!", failureCount] : @"There was only 1 failure!";
        message = [NSString stringWithFormat:@"%@ First Failure is in %@", failures, [firstFailedScenario description]];
    }
    NSString *announcement = [NSString stringWithFormat:@"%@ Thank you for using automated tests.", message];
    [self say:announcement];
}

- (void)say:(NSString *)what {
    [synthesizer startSpeakingString:what];
}

- (void)endOfTestsCheckpoint {
    [TestFlight passCheckpoint:@"tests finished"];
    [self sayResultsAndThankYou];
    if (!failureCount) {
        [TestFlight passCheckpoint:@"tests succeeded"];
    }
}

- (void)clearPreviousLogs {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSString *logsFolder = [self logsFolder];
    BOOL isDirectory = NO;
    if ([fileManager fileExistsAtPath:logsFolder isDirectory:&isDirectory]) {
        NSParameterAssert(isDirectory);
        [fileManager removeItemAtPath:logsFolder error:&error];
    }
    NSParameterAssert(!error);
}

- (void)startTesting {
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    [self clearPreviousLogs];
    [self say:[NSString stringWithFormat:@"Starting %d test scenarios", [self.scenarios count]]];
    __block BZTestController *controller = self;
    [self startTestingWithCompletionBlock:^{
        [controller endOfTestsCheckpoint];
        if ([controller shouldExitTests]) {
            // Exit after the tests complete so that CI knows we're done
            [controller exitTests];
        } else {
            [controller completeInteractiveTesting];
        }
        controller = nil;
    }];
}

- (void)dealloc {
    synthesizer = nil;
}

#pragma mark - UIAlertViewDelegate

- (void)alertViewCancel:(UIAlertView *)alertView {
    [self exitTests];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ([@"Feedback" isEqualToString:[alertView buttonTitleAtIndex:buttonIndex]]) {
        [TestFlight openFeedbackView];
    } else {
        [self exitTests];
    }
}
@end


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ttp="http://stix.mitre.org/TTP-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/TTP-1 http://stix.mitre.org/XMLSchema/ttp/1.1.1/ttp.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-7c28e6ae-e0e8-4bca-9aef-283740dc119b" version="1.1.1" timestamp="2013-09-10T20:13:32+00:00">
    <stix:TTPs>
        <stix:TTP id="example:ttp-facaa5ed-62c1-49b5-a607-0cbc5527f1dc" timestamp="2014-12-22T16:30:12.702000+00:00" xsi:type='ttp:TTPType'>
            <ttp:Behavior>
                <ttp:Malware>
                    <ttp:Malware_Instance>
                        <ttp:Type>Unknown</ttp:Type>
                    </ttp:Malware_Instance>
                </ttp:Malware>
            </ttp:Behavior>
        </stix:TTP>
    </stix:TTPs>
    <stix:Incidents>
        <stix:Incident id="example:incident-08c89a32-2c94-44ec-b7f5-3839a025d105" timestamp="2014-04-27T19:37:02+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>Facebook discovered that hackers had exploited a vulnerability and accessed unspecified data.  Facebook found no evidence that Facebook user data was compromised.  Malware was installed on a number of employee laptops after a small number of them visited a mobile developer website that turned out to be unsafe. Microsoft, Twitter, and Apple were affected by the same issue around the same time.</incident:Title>
            <incident:External_ID source="VERIS">795F0CF0-31A1-4636-B39C-2E5D9D01B168</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="year">2013-01-01T00:00:00</incident:Initial_Compromise>
            </incident:Time>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Facebook</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>US</xal:NameElement>
      </xal:Country>
      <xal:AdministrativeArea xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>CA</xal:NameElement>
      </xal:AdministrativeArea>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Laptop</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Confidentiality</incident:Property>
                        </incident:Property_Affected>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Software installation</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Leveraged_TTPs>
                <incident:Leveraged_TTP>
                    <stixCommon:TTP idref="example:ttp-facaa5ed-62c1-49b5-a607-0cbc5527f1dc" xsi:type='ttp:TTPType'/>
                </incident:Leveraged_TTP>
            </incident:Leveraged_TTPs>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-871d74b6-854a-49e0-b3cf-d0c35580f842" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://news.cnet.com/8301-1009_3-57573720-83/apple-facebook-hackers-hit-car-and-candy-companies-too/, http://www.reuters.com/article/2013/02/19/us-apple-hackers-idUSBRE91I10920130219?goback=%2Egde_36573_member_215647969</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-871d74b6-854a-49e0-b3cf-d0c35580f842" timestamp="2014-12-22T16:30:12.702000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>Unknown</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Type timestamp="2014-12-22T16:30:12.702000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:30:12.702000+00:00">
                <stixCommon:Value>Unknown</stixCommon:Value>
            </ta:Motivation>
            <ta:Observed_TTPs>
                <ta:Observed_TTP>
                    <stixCommon:TTP idref="example:ttp-facaa5ed-62c1-49b5-a607-0cbc5527f1dc" xsi:type='ttp:TTPType'/>
                </ta:Observed_TTP>
            </ta:Observed_TTPs>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
package com.github.eventsource.client;

public interface EventSourceHandler {
    void onConnect() throws Exception;
    void onMessage(String event, MessageEvent message) throws Exception;
    void onError(Throwable t);
}


text:
package com.groupon.sparklint.data

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

/**
  *
  * @param dataRange       The time range that this sink represents
  * @param numBuckets      When output, the numberOfBucket
  * @param origin          the actual time for time0 in this data structure
  * @param losslessStorage the storage data strucutre
  * @author rxue
  * @since 8/16/16.
  */
class LosslessMetricsSink(val dataRange: Option[Interval],
                          val numBuckets: Int,
                          private[sparklint] val origin: Long,
                          private[sparklint] val losslessStorage: Map[Interval, Int]) extends MetricsSink {

  override lazy val resolution: Long = {
    var _resolution = 1L
    if (dataRange.nonEmpty) {
      val desiredRange = dataRange.get.merge(Interval(origin, origin)).length
      if (desiredRange > 0) {
        while ((desiredRange / _resolution + 1) >= numBuckets) {
          _resolution *= CompressedMetricsSink.getCompactRatio(_resolution)
        }
      }
    }
    _resolution
  }

  override private[sparklint] lazy val storage: Array[Long] = {
    val _storage = ArrayBuffer.fill(numBuckets)(0L)
    losslessStorage.foreach({ case (interval, weight) =>
      val startBucket = getBucketIndexWithNewResolution(interval.minimum, resolution)
      val endBucket = getBucketIndexWithNewResolution(interval.maximum, resolution)
      if (startBucket == endBucket) {
        _storage(startBucket) += interval.length * weight
      } else {
        _storage(startBucket) += (resolution - interval.minimum % resolution) * weight
        Range(startBucket + 1, endBucket).foreach(bucket => {
          _storage(bucket) += resolution * weight
        })
        _storage(endBucket) += (interval.maximum % resolution) * weight
      }
    })
    _storage.toArray
  }

  override def changeResolution(toResolution: Long): MetricsSink = {
    val numBucketsNeeded = if (dataRange.nonEmpty) {
      val desiredRange = dataRange.get.merge(Interval(origin, origin)).length
      (desiredRange / toResolution + 1).toInt
    } else {
      1
    }
    new LosslessMetricsSink(dataRange, numBucketsNeeded, origin, losslessStorage)
  }

  override def addUsage(startTime: Long, endTime: Long, weight: Int = 1): LosslessMetricsSink =
    batchAddUsage(Seq(startTime -> endTime), weight)

  override def batchAddUsage(pairs: Seq[(Long, Long)], weight: Int): LosslessMetricsSink = {
    val inputInterval = Interval(pairs.map(_._1).min, pairs.map(_._2).max)
    val newDataRange = Some(dataRange.fold(inputInterval)(_.merge(inputInterval)))
    val newStorage = mutable.Map(losslessStorage.toSeq: _*)
    pairs.foreach({ case (startTime, endTime) =>
      val interval = Interval(startTime, endTime)
      newStorage.get(interval) match {
        case None => newStorage(interval) = weight
        case Some(x) if x + weight == 0 => newStorage.remove(interval)
        case Some(x) => newStorage(interval) = x + weight
      }
    })
    new LosslessMetricsSink(newDataRange, numBuckets, origin, newStorage.toMap)
  }

  override def removeUsage(startTime: Long, endTime: Long, weight: Int = 1): LosslessMetricsSink =
    batchAddUsage(Seq(startTime -> endTime), -weight)

  private[data] def getBucketIndexWithNewResolution(time: Long, resolutionToUse: Long): Int = {
    ((time - bucketStart) / resolutionToUse).toInt
  }
}

object LosslessMetricsSink {
  def empty(originTime: Long, numBuckets: Int): LosslessMetricsSink = new LosslessMetricsSink(None, numBuckets, originTime, Map.empty)
}


text:
<?php

namespace App\Console\Commands\Permissions;

use Doctrine\ORM\EntityManagerInterface;
use HMS\Repositories\PermissionRepository;
use HMS\Repositories\RoleRepository;
use HMS\User\Permissions\RoleManager;
use Illuminate\Console\Command;
use LaravelDoctrine\ACL\Permissions\Permission;

class SyncCommand extends BaseCommand
{
    /**
     * @var PermissionRepository
     */
    protected $permissionRepository;

    /**
     * @var RoleManager
     */
    protected $roleManager;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'permissions:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync permissions and roles to match the default config';

    /**
     * @var array
     */
    private $permissions = [];

    /**
     * @var array
     */
    private $roles = [];

    public function __construct(
        EntityManagerInterface $entityManager,
        RoleRepository $roleRepository,
        PermissionRepository $permissionRepository,
        RoleManager $roleManager
    ) {
        parent::__construct($entityManager, $roleRepository);
        $this->permissionRepository = $permissionRepository;
        $this->roleManager = $roleManager;

        $permissions = config('roles.permissions');

        foreach ($permissions as $permission) {
            $this->permissions[$permission] = null;
        }

        $this->roles = config('roles.roles');
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->createPermissionEntities();
        $this->info('Permissions synced');

        $this->syncRoles();
        $this->info('Roles synced');

        $this->entityManager->flush();
    }

    /**
     * Creates permissions based on array.
     *
     * @return void
     */
    private function createPermissionEntities()
    {
        foreach ($this->permissions as $permission => &$entity) {
            if (! $entity = $this->permissionRepository->findOneByName($permission)) {
                $entity = new Permission($permission);
                $this->entityManager->persist($entity);
                $this->info('Created permission: ' . $permission);
            }
        }
    }

    /**
     * For existing roles, strip and rebuild their permissions.
     * Create any new roles.
     *
     * @return void
     */
    private function syncRoles()
    {
        foreach ($this->roles as $roleName => $role) {
            if ($roleEntity = $this->roleRepository->findOneByName($roleName)) {
                $roleEntity->stripPermissions();
                if (count($role['permissions']) == 1 && $role['permissions'][0] == '*') {
                    foreach ($this->permissions as $permission) {
                        $roleEntity->addPermission($permission);
                    }
                } else {
                    foreach ($role['permissions'] as $permission) {
                        if (array_key_exists($permission, $this->permissions)
                            && $this->permissions[$permission]) {
                            $roleEntity->addPermission($this->permissions[$permission]);
                        } else {
                            $this->warning($roleName . ' has unknown permission: ' . $permission);
                        }
                    }
                }
                $this->info('Updated role: ' . $roleName);
            } else {
                $this->createRole($roleName, $role);
            }
        }
    }

    /**
     * Creates roles and assigns permissions.
     *
     * @param string $roleName
     * @param array $role
     */
    private function createRole(string $roleName, array $role)
    {
        $this->roleManager->createRoleFromTemplate($roleName, $role, $this->permissions);
        $this->info('Created role: ' . $roleName);
    }
}


text:
<?php

namespace Zend\ProgressBar\Adapter;

use Traversable;
use Zend\Stdlib\ArrayUtils;

/**
 * Abstract class for Zend\ProgressBar Adapters
 */
abstract class AbstractAdapter
{
    /**
     * Option keys to skip when calling setOptions()
     *
     * @var array
     */
    protected $skipOptions = array(
        'options',
        'config',
    );

    /**
     * Create a new adapter
     *
     * $options may be either be an array or a Zend\Config object which
     * specifies adapter related options.
     *
     * @param  array|Traversable $options
     */
    public function __construct($options = null)
    {
        if ($options instanceof Traversable) {
            $options = ArrayUtils::iteratorToArray($options);
        }
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

    /**
     * Set options via an array
     *
     * @param  array $options
     * @return AbstractAdapter
     */
    public function setOptions(array $options)
    {
        foreach ($options as $key => $value) {
            if (in_array(strtolower($key), $this->skipOptions)) {
                continue;
            }

            $method = 'set' . ucfirst($key);
            if (method_exists($this, $method)) {
                $this->$method($value);
            }
        }

        return $this;
    }

    /**
     * Notify the adapter about an update
     *
     * @param  float   $current       Current progress value
     * @param  float   $max           Max progress value
     * @param  float   $percent       Current percent value
     * @param  int $timeTaken     Taken time in seconds
     * @param  int $timeRemaining Remaining time in seconds
     * @param  string  $text          Status text
     * @return void
     */
    abstract public function notify($current, $max, $percent, $timeTaken, $timeRemaining, $text);

    /**
     * Called when the progress is explicitly finished
     *
     * @return void
     */
    abstract public function finish();
}


text:
require "google/cloud/apigee_registry/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::ApigeeRegistry::V1::Registry::Client#rollback_api_spec
#
def rollback_api_spec
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::ApigeeRegistry::V1::Registry::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::ApigeeRegistry::V1::RollbackApiSpecRequest.new

  # Call the rollback_api_spec method.
  result = client.rollback_api_spec request

  # The returned object is of type Google::Cloud::ApigeeRegistry::V1::ApiSpec.
  p result
end
# [END apigeeregistry_v1_generated_Registry_RollbackApiSpec_sync]


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

/*

DROP TABLE IF EXISTS `pw_windid_admin_custom`;
CREATE TABLE `pw_windid_admin_custom` (
  `username` varchar(15) NOT NULL,
  `custom` text COMMENT '常用菜单项',
  PRIMARY KEY (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='后台常用菜单表';

 */

class PwWindidAdminCustomTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function run()
    {
        Schema::create('pw_windid_admin_custom', function (Blueprint $table) {
            if (env('DB_CONNECTION', false) === 'mysql') {
                $table->engine = 'InnoDB';
            }
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pw_windid_admin_custom');
    }
}


text:
package com.veridu.idos.endpoints;

import java.util.HashMap;

import com.google.gson.JsonObject;
import com.veridu.idos.exceptions.SDKException;
import com.veridu.idos.utils.Filter;
import com.veridu.idos.utils.IdOSAuthType;

/**
 * ProfileSources Endpoint class
 */
public class ProfileSources extends AbstractEndpoint {
    /**
     * Constructor Class
     *
     * @param credentials
     * @param baseURL
     * @param doNotCheckSSL
     */
    public ProfileSources(HashMap<String, String> credentials, String baseURL, boolean doNotCheckSSL) {
        super(credentials, IdOSAuthType.USER, baseURL, doNotCheckSSL);
    }

    /**
     * Lists all sources related to the given user
     *
     * @param username
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject listAll(String username) throws SDKException {
        return this.fetch("GET", "profiles/" + username + "/sources");
    }

    /**
     * Lists all sources related to the given user with filtering
     *
     * @param username
     * @param filter
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject listAll(String username, Filter filter) throws SDKException {
        return this.fetch("GET", "profiles/" + username + "/sources", null, filter);
    }

    /**
     * Retrieves a source given its source id
     *
     * @param username
     * @param sourceId
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject getOne(String username, int sourceId) throws SDKException {
        return this.fetch("GET", "profiles/" + username + "/sources/" + sourceId);
    }

    /**
     * Creates a source for the given username
     *
     * @param username
     * @param name
     * @param tags
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject create(String username, String name, HashMap<String, String> tags) throws SDKException {
        JsonObject jsonTags = new JsonObject();
        for (String key : tags.keySet())
            jsonTags.addProperty(key, tags.get(key));
        JsonObject data = new JsonObject();
        data.addProperty("name", name);
        data.add("tags", jsonTags);
        return this.fetch("POST", "profiles/" + username + "/sources", data);
    }

    /**
     * Updates a source giving its sourceId
     *
     * @param username
     * @param tags
     * @param sourceId
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject update(String username, int sourceId, HashMap<String, String> tags) throws SDKException {
        JsonObject jsonTags = new JsonObject();
        for (String key : tags.keySet())
            jsonTags.addProperty(key, tags.get(key));
        JsonObject data = new JsonObject();
        data.add("tags", jsonTags);
        return this.fetch("PATCH", "profiles/" + username + "/sources/" + sourceId, data);
    }

    /**
     * Deletes a source given its source id
     *
     * @param username
     * @param sourceId
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject delete(String username, int sourceId) throws SDKException {
        return this.fetch("DELETE", "profiles/" + username + "/sources/" + sourceId);
    }

    /**
     * Deletes all sources related to the given user
     *
     * @param username
     * @return JsonObject response
     * @throws SDKException
     */
    public JsonObject deleteAll(String username) throws SDKException {
        return this.fetch("DELETE", "profiles/" + username + "/sources");
    }
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/pubsublite/v1/common.proto

package com.google.cloud.pubsublite.proto;

public interface AttributeValuesOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.pubsublite.v1.AttributeValues)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The list of values associated with a key.
   *

   *
   * repeated bytes values = 1;
   *
   * @return A list containing the values.
   */
  java.util.List<com.google.protobuf.ByteString> getValuesList();
  /**
   *
   *
   *

   * The list of values associated with a key.
   *

   *
   * repeated bytes values = 1;
   *
   * @return The count of values.
   */
  int getValuesCount();
  /**
   *
   *
   *

   * The list of values associated with a key.
   *

   *
   * repeated bytes values = 1;
   *
   * @param index The index of the element to return.
   * @return The values at the given index.
   */
  com.google.protobuf.ByteString getValues(int index);
}


text:
package org.apache.camel.http.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.concurrent.TimeoutException;

import javax.activation.DataHandler;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.Message;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.StreamCache;
import org.apache.camel.attachment.AttachmentMessage;
import org.apache.camel.attachment.CamelFileDataSource;
import org.apache.camel.converter.stream.CachedOutputStream;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.GZIPHelper;
import org.apache.camel.support.MessageHelper;
import org.apache.camel.support.ObjectHelper;
import org.apache.camel.util.FileUtil;
import org.apache.camel.util.IOHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Binding between {@link HttpMessage} and {@link HttpServletResponse}.
 * <p/>
 * Uses by default the {@link org.apache.camel.http.common.HttpHeaderFilterStrategy}
 */
public class DefaultHttpBinding implements HttpBinding {

    /**
     * Whether Date/Locale should be converted to String types (enabled by default)
     */
    public static final String DATE_LOCALE_CONVERSION = "CamelHttpBindingDateLocaleConversion";

    /**
     * The data format used for storing java.util.Date instances as a String value.
     */
    public static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";

    private static final Logger LOG = LoggerFactory.getLogger(DefaultHttpBinding.class);
    private static final TimeZone TIME_ZONE_GMT = TimeZone.getTimeZone("GMT");

    private boolean useReaderForPayload;
    private boolean eagerCheckContentAvailable;
    private boolean transferException;
    private boolean muteException;
    private boolean allowJavaSerializedObject;
    private boolean mapHttpMessageBody = true;
    private boolean mapHttpMessageHeaders = true;
    private boolean mapHttpMessageFormUrlEncodedBody = true;
    private HeaderFilterStrategy headerFilterStrategy = new HttpHeaderFilterStrategy();
    private String fileNameExtWhitelist;

    public DefaultHttpBinding() {
    }

    @Deprecated
    public DefaultHttpBinding(HeaderFilterStrategy headerFilterStrategy) {
        this.headerFilterStrategy = headerFilterStrategy;
    }

    @Deprecated
    public DefaultHttpBinding(HttpCommonEndpoint endpoint) {
        this.headerFilterStrategy = endpoint.getHeaderFilterStrategy();
        this.transferException = endpoint.isTransferException();
        this.muteException = endpoint.isMuteException();
        if (endpoint.getComponent() != null) {
            this.allowJavaSerializedObject = endpoint.getComponent().isAllowJavaSerializedObject();
        }
    }

    @Override
    public void readRequest(HttpServletRequest request, HttpMessage message) {
        LOG.trace("readRequest {}", request);

        // must read body before headers
        if (mapHttpMessageBody) {
            readBody(request, message);
        }
        if (mapHttpMessageHeaders) {
            readHeaders(request, message);
        }
        if (mapHttpMessageFormUrlEncodedBody) {
            try {
                readFormUrlEncodedBody(request, message);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeCamelException("Cannot read Form URL encoded body due " + e.getMessage(), e);
            }
        }

        // populate the headers from the request
        Map<String, Object> headers = message.getHeaders();

        // always store these standard headers
        // store the method and query and other info in headers as String types
        String rawPath = getRawPath(request);
        headers.put(Exchange.HTTP_METHOD, request.getMethod());
        headers.put(Exchange.HTTP_QUERY, request.getQueryString());
        headers.put(Exchange.HTTP_URL, request.getRequestURL().toString());
        headers.put(Exchange.HTTP_URI, request.getRequestURI());
        headers.put(Exchange.HTTP_PATH, rawPath);
        // only set content type if not already extracted
        if (!headers.containsKey(Exchange.CONTENT_TYPE)) {
            headers.put(Exchange.CONTENT_TYPE, request.getContentType());
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("HTTP method {}", request.getMethod());
            LOG.trace("HTTP query {}", request.getQueryString());
            LOG.trace("HTTP url {}", request.getRequestURL());
            LOG.trace("HTTP uri {}", request.getRequestURI());
            LOG.trace("HTTP path {}", rawPath);
            LOG.trace("HTTP content-type {}", headers.get(Exchange.CONTENT_TYPE));
        }
    }

    protected void readHeaders(HttpServletRequest request, HttpMessage message) {
        LOG.trace("readHeaders {}", request);

        Map<String, Object> headers = message.getHeaders();

        //apply the headerFilterStrategy
        Enumeration<?> names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = request.getHeader(name);
            // use http helper to extract parameter value as it may contain multiple values
            Object extracted = HttpHelper.extractHttpParameterValue(value);
            // mapping the content-type
            if (name.equalsIgnoreCase("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            if (headerFilterStrategy != null
                    && !headerFilterStrategy.applyFilterToExternalHeaders(name, extracted, message.getExchange())) {
                HttpHelper.appendHeader(headers, name, extracted);
            }
        }

        if (request.getCharacterEncoding() != null) {
            headers.put(Exchange.HTTP_CHARACTER_ENCODING, request.getCharacterEncoding());
            message.getExchange().setProperty(Exchange.CHARSET_NAME, request.getCharacterEncoding());
        }

        try {
            populateRequestParameters(request, message);
        } catch (Exception e) {
            throw new RuntimeCamelException("Cannot read request parameters due " + e.getMessage(), e);
        }
    }

    protected void readBody(HttpServletRequest request, HttpMessage message) {
        LOG.trace("readBody {}", request);

        // lets parse the body
        Object body = message.getBody();
        // reset the stream cache if the body is the instance of StreamCache
        if (body instanceof StreamCache) {
            ((StreamCache) body).reset();
        }

        // if content type is serialized java object, then de-serialize it to a Java object
        if (request.getContentType() != null
                && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(request.getContentType())) {
            // only deserialize java if allowed
            if (allowJavaSerializedObject || isTransferException()) {
                try {
                    InputStream is
                            = message.getExchange().getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, body);
                    Object object = HttpHelper.deserializeJavaObjectFromStream(is, message.getExchange().getContext());
                    if (object != null) {
                        message.setBody(object);
                    }
                } catch (Exception e) {
                    throw new RuntimeCamelException("Cannot deserialize body to Java object", e);
                }
            } else {
                // set empty body
                message.setBody(null);
            }
        }

        populateAttachments(request, message);
    }

    protected void populateRequestParameters(HttpServletRequest request, HttpMessage message) throws Exception {
        //we populate the http request parameters without checking the request method
        Map<String, Object> headers = message.getHeaders();
        Enumeration<?> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            // there may be multiple values for the same name
            String[] values = request.getParameterValues(name);
            LOG.trace("HTTP parameter {} = {}", name, values);

            if (values != null) {
                for (String value : values) {
                    if (headerFilterStrategy != null
                            && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
                        HttpHelper.appendHeader(headers, name, value);
                    }
                }
            }
        }
    }

    protected void readFormUrlEncodedBody(HttpServletRequest request, HttpMessage message) throws UnsupportedEncodingException {
        LOG.trace("readFormUrlEncodedBody {}", request);
        // should we extract key=value pairs from form bodies (application/x-www-form-urlencoded)
        // and map those to Camel headers
        if (mapHttpMessageBody && mapHttpMessageHeaders) {
            LOG.trace("HTTP method {} with Content-Type {}", request.getMethod(), request.getContentType());
            Map<String, Object> headers = message.getHeaders();
            Boolean flag = message.getHeader(Exchange.SKIP_WWW_FORM_URLENCODED, Boolean.class);
            boolean skipWwwFormUrlEncoding = flag != null ? flag : false;
            if (request.getMethod().equals("POST") && request.getContentType() != null
                    && request.getContentType().startsWith(HttpConstants.CONTENT_TYPE_WWW_FORM_URLENCODED)
                    && !skipWwwFormUrlEncoding) {
                String charset = request.getCharacterEncoding();
                if (charset == null) {
                    charset = "UTF-8";
                }

                // lets parse the body
                Object body = message.getBody();
                // reset the stream cache if the body is the instance of StreamCache
                if (body instanceof StreamCache) {
                    ((StreamCache) body).reset();
                }

                // Push POST form params into the headers to retain compatibility with DefaultHttpBinding
                String text = message.getBody(String.class);
                if (org.apache.camel.util.ObjectHelper.isNotEmpty(text)) {
                    for (String param : text.split("&")) {
                        String[] pair = param.split("=", 2);
                        if (pair.length == 2) {
                            String name = URLDecoder.decode(pair[0], charset);
                            String value = URLDecoder.decode(pair[1], charset);
                            if (headerFilterStrategy != null
                                    && !headerFilterStrategy.applyFilterToExternalHeaders(name, value, message.getExchange())) {
                                HttpHelper.appendHeader(headers, name, value);
                            }
                        } else {
                            throw new IllegalArgumentException("Invalid parameter, expected to be a pair but was " + param);
                        }
                    }
                }

                // reset the stream cache if the body is the instance of StreamCache
                if (body instanceof StreamCache) {
                    ((StreamCache) body).reset();
                }
            }
        }
    }

    private String getRawPath(HttpServletRequest request) {
        String uri = request.getRequestURI();
        /**
         * In async case, it seems that request.getContextPath() can return null
         *
         * @see https://dev.eclipse.org/mhonarc/lists/jetty-users/msg04669.html
         */
        String contextPath = request.getContextPath() == null ? "" : request.getContextPath();
        String servletPath = request.getServletPath() == null ? "" : request.getServletPath();
        return uri.substring(contextPath.length() + servletPath.length());
    }

    protected void populateAttachments(HttpServletRequest request, HttpMessage message) {
        // check if there is multipart files, if so will put it into DataHandler
        Enumeration<?> names = request.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            Object object = request.getAttribute(name);
            LOG.trace("HTTP attachment {} = {}", name, object);
            if (object instanceof File) {
                String fileName = request.getParameter(name);
                // is the file name accepted
                boolean accepted = true;
                if (fileNameExtWhitelist != null) {
                    String ext = FileUtil.onlyExt(fileName);
                    if (ext != null) {
                        ext = ext.toLowerCase(Locale.US);
                        fileNameExtWhitelist = fileNameExtWhitelist.toLowerCase(Locale.US);
                        if (!fileNameExtWhitelist.equals("*") && !fileNameExtWhitelist.contains(ext)) {
                            accepted = false;
                        }
                    }
                }
                if (accepted) {
                    AttachmentMessage am = message.getExchange().getMessage(AttachmentMessage.class);
                    am.addAttachment(fileName, new DataHandler(new CamelFileDataSource((File) object, fileName)));
                } else {
                    LOG.debug(
                            "Cannot add file as attachment: {} because the file is not accepted according to fileNameExtWhitelist: {}",
                            fileName, fileNameExtWhitelist);
                }
            }
        }
    }

    @Override
    public void writeResponse(Exchange exchange, HttpServletResponse response) throws IOException {
        Message target = exchange.getMessage();
        if (exchange.isFailed()) {
            if (exchange.getException() != null) {
                doWriteExceptionResponse(exchange.getException(), response);
            } else {
                // it must be a fault, no need to check for the fault flag on the message
                doWriteFaultResponse(target, response, exchange);
            }
        } else {
            if (exchange.hasOut()) {
                // just copy the protocol relates header if we do not have them
                copyProtocolHeaders(exchange.getIn(), exchange.getOut());
            }
            doWriteResponse(target, response, exchange);
        }
    }

    private void copyProtocolHeaders(Message request, Message response) {
        if (request.getHeader(Exchange.CONTENT_ENCODING) != null) {
            String contentEncoding = request.getHeader(Exchange.CONTENT_ENCODING, String.class);
            response.setHeader(Exchange.CONTENT_ENCODING, contentEncoding);
        }
        if (checkChunked(response, response.getExchange())) {
            response.setHeader(Exchange.TRANSFER_ENCODING, "chunked");
        }
    }

    @Override
    public void doWriteExceptionResponse(Throwable exception, HttpServletResponse response) throws IOException {
        if (exception instanceof TimeoutException) {
            response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
            response.setContentType("text/plain");
            response.getWriter().write("Timeout error");
        } else if (isMuteException()) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("text/plain");
            response.getWriter().write("Exception");
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

            if (isTransferException()) {
                // transfer the exception as a serialized java object
                HttpHelper.writeObjectToServletResponse(response, exception);
            } else {
                // write stacktrace as plain text
                response.setContentType("text/plain");
                PrintWriter pw = response.getWriter();
                exception.printStackTrace(pw);
                pw.flush();
            }
        }
    }

    @Override
    public void doWriteFaultResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
        doWriteResponse(message, response, exchange);
    }

    @Override
    public void doWriteResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
        int statusCode = determineResponseCode(exchange, exchange.getMessage().getBody());
        response.setStatus(statusCode);

        // set the content type in the response.
        String contentType = MessageHelper.getContentType(message);
        if (contentType != null) {
            response.setContentType(contentType);
        }

        // append headers
        // must use entrySet to ensure case of keys is preserved
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null, true);
            while (it.hasNext()) {
                String headerValue = convertHeaderValueToString(exchange, it.next());
                if (headerValue != null && headerFilterStrategy != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
                    response.addHeader(key, headerValue);
                }
            }
        }

        // write the body.
        if (message.getBody() != null) {
            if (GZIPHelper.isGzip(message)) {
                doWriteGZIPResponse(message, response, exchange);
            } else {
                doWriteDirectResponse(message, response, exchange);
            }
        }
    }

    /*
     * set the HTTP status code
     * NOTE: this is similar to the Netty-Http and Undertow approach
     * TODO: we may want to refactor this class so that
     * the status code is determined in one place
     */
    private int determineResponseCode(Exchange camelExchange, Object body) {
        boolean failed = camelExchange.isFailed();
        int defaultCode = failed ? 500 : 200;

        Message message = camelExchange.getMessage();
        Integer currentCode = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
        int codeToUse = currentCode == null ? defaultCode : currentCode;

        if (codeToUse != 500) {
            if ((body == null) || (body instanceof String && ((String) body).trim().isEmpty())) {
                // no content
                codeToUse = currentCode == null ? 204 : currentCode;
            }
        }

        return codeToUse;
    }

    protected String convertHeaderValueToString(Exchange exchange, Object headerValue) {
        if ((headerValue instanceof Date || headerValue instanceof Locale)
                && convertDateAndLocaleLocally(exchange)) {
            if (headerValue instanceof Date) {
                return toHttpDate((Date) headerValue);
            } else {
                return toHttpLanguage((Locale) headerValue);
            }
        } else {
            return exchange.getContext().getTypeConverter().convertTo(String.class, headerValue);
        }
    }

    protected boolean convertDateAndLocaleLocally(Exchange exchange) {
        // This check is done only if a given header value is Date or Locale
        return exchange.getProperty(DATE_LOCALE_CONVERSION, Boolean.TRUE, Boolean.class);
    }

    protected boolean isText(String contentType) {
        if (contentType != null) {
            String temp = contentType.toLowerCase();
            if (temp.contains("text") || temp.contains("html")) {
                return true;
            }
        }
        return false;
    }

    protected int copyStream(InputStream is, OutputStream os, int bufferSize) throws IOException {
        try {
            // copy stream, and must flush on each write as etc Jetty has better performance when
            // flushing after writing to its servlet output stream
            return IOHelper.copy(is, os, bufferSize, true);
        } finally {
            IOHelper.close(os, is);
        }
    }

    protected void doWriteDirectResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
        // if content type is serialized Java object, then serialize and write it to the response
        String contentType = message.getHeader(Exchange.CONTENT_TYPE, String.class);
        if (HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
            if (allowJavaSerializedObject || isTransferException()) {
                try {
                    Object object = message.getMandatoryBody(Serializable.class);
                    HttpHelper.writeObjectToServletResponse(response, object);
                    // object is written so return
                    return;
                } catch (InvalidPayloadException e) {
                    throw new IOException(e);
                }
            } else {
                throw new RuntimeCamelException(
                        "Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed");
            }
        }

        // prefer streaming
        InputStream is = null;
        if (checkChunked(message, exchange)) {
            is = message.getBody(InputStream.class);
        } else {
            // try to use input stream first, so we can copy directly
            if (!isText(contentType)) {
                is = exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, message.getBody());
            }
        }

        if (is != null) {
            ServletOutputStream os = response.getOutputStream();
            if (!checkChunked(message, exchange)) {
                CachedOutputStream stream = new CachedOutputStream(exchange);
                try {
                    // copy directly from input stream to the cached output stream to get the content length
                    int len = copyStream(is, stream, response.getBufferSize());
                    // we need to setup the length if message is not chucked
                    response.setContentLength(len);
                    OutputStream current = stream.getCurrentStream();
                    if (current instanceof ByteArrayOutputStream) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Streaming (direct) response in non-chunked mode with content-length {}", len);
                        }
                        ByteArrayOutputStream bos = (ByteArrayOutputStream) current;
                        bos.writeTo(os);
                    } else {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Streaming response in non-chunked mode with content-length {} and buffer size: {}", len,
                                    len);
                        }
                        copyStream(stream.getInputStream(), os, len);
                    }
                } finally {
                    IOHelper.close(is, os);
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Streaming response in chunked mode with buffer size {}", response.getBufferSize());
                }
                copyStream(is, os, response.getBufferSize());
            }
        } else {
            // not convertable as a stream so fallback as a String
            String data = message.getBody(String.class);
            if (data != null) {
                // set content length and encoding before we write data
                String charset = ExchangeHelper.getCharsetName(exchange, true);
                final int dataByteLength = data.getBytes(charset).length;
                response.setCharacterEncoding(charset);
                response.setContentLength(dataByteLength);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Writing response in non-chunked mode as plain text with content-length {} and buffer size: {}",
                            dataByteLength, response.getBufferSize());
                }
                try {
                    response.getWriter().print(data);
                } finally {
                    response.getWriter().flush();
                }
            }
        }
    }

    protected boolean checkChunked(Message message, Exchange exchange) {
        boolean answer = true;
        if (message.getHeader(Exchange.HTTP_CHUNKED) == null) {
            // check the endpoint option
            Endpoint endpoint = exchange.getFromEndpoint();
            if (endpoint instanceof HttpCommonEndpoint) {
                answer = ((HttpCommonEndpoint) endpoint).isChunked();
            }
        } else {
            answer = message.getHeader(Exchange.HTTP_CHUNKED, boolean.class);
        }
        return answer;
    }

    protected void doWriteGZIPResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
        byte[] bytes;
        try {
            bytes = message.getMandatoryBody(byte[].class);
        } catch (InvalidPayloadException e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }

        byte[] data = GZIPHelper.compressGZIP(bytes);
        ServletOutputStream os = response.getOutputStream();
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Streaming response as GZIP in non-chunked mode with content-length {} and buffer size: {}",
                        data.length, response.getBufferSize());
            }
            response.setContentLength(data.length);
            os.write(data);
            os.flush();
        } finally {
            IOHelper.close(os);
        }
    }

    @Override
    public Object parseBody(HttpMessage httpMessage) throws IOException {
        // lets assume the body is a reader
        HttpServletRequest request = httpMessage.getRequest();
        // there is only a body if we have a content length, or its -1 to indicate unknown length
        int len = request.getContentLength();
        LOG.trace("HttpServletRequest content-length: {}", len);
        if (len == 0) {
            return null;
        }
        if (isUseReaderForPayload()) {
            // use reader to read the response body
            return request.getReader();
        } else {
            // if we do not know if there is any data at all, then make sure to check the stream first
            if (len < 0 && isEagerCheckContentAvailable()) {
                InputStream is = request.getInputStream();
                if (is.available() == 0) {
                    // no data so return null
                    return null;
                }
            }
            // read the response body from servlet request
            return HttpHelper.readRequestBodyFromServletRequest(request, httpMessage.getExchange());
        }
    }

    @Override
    public boolean isUseReaderForPayload() {
        return useReaderForPayload;
    }

    @Override
    public void setUseReaderForPayload(boolean useReaderForPayload) {
        this.useReaderForPayload = useReaderForPayload;
    }

    @Override
    public boolean isEagerCheckContentAvailable() {
        return eagerCheckContentAvailable;
    }

    @Override
    public void setEagerCheckContentAvailable(boolean eagerCheckContentAvailable) {
        this.eagerCheckContentAvailable = eagerCheckContentAvailable;
    }

    @Override
    public boolean isTransferException() {
        return transferException;
    }

    @Override
    public void setTransferException(boolean transferException) {
        this.transferException = transferException;
    }

    @Override
    public boolean isMuteException() {
        return muteException;
    }

    @Override
    public void setMuteException(boolean muteException) {
        this.muteException = muteException;
    }

    @Override
    public boolean isAllowJavaSerializedObject() {
        return allowJavaSerializedObject;
    }

    @Override
    public void setAllowJavaSerializedObject(boolean allowJavaSerializedObject) {
        this.allowJavaSerializedObject = allowJavaSerializedObject;
    }

    @Override
    public HeaderFilterStrategy getHeaderFilterStrategy() {
        return headerFilterStrategy;
    }

    @Override
    public void setHeaderFilterStrategy(HeaderFilterStrategy headerFilterStrategy) {
        this.headerFilterStrategy = headerFilterStrategy;
    }

    @Override
    public boolean isMapHttpMessageBody() {
        return mapHttpMessageBody;
    }

    @Override
    public void setMapHttpMessageBody(boolean mapHttpMessageBody) {
        this.mapHttpMessageBody = mapHttpMessageBody;
    }

    @Override
    public boolean isMapHttpMessageHeaders() {
        return mapHttpMessageHeaders;
    }

    @Override
    public void setMapHttpMessageHeaders(boolean mapHttpMessageHeaders) {
        this.mapHttpMessageHeaders = mapHttpMessageHeaders;
    }

    @Override
    public boolean isMapHttpMessageFormUrlEncodedBody() {
        return mapHttpMessageFormUrlEncodedBody;
    }

    @Override
    public void setMapHttpMessageFormUrlEncodedBody(boolean mapHttpMessageFormUrlEncodedBody) {
        this.mapHttpMessageFormUrlEncodedBody = mapHttpMessageFormUrlEncodedBody;
    }

    @Override
    public String getFileNameExtWhitelist() {
        return fileNameExtWhitelist;
    }

    @Override
    public void setFileNameExtWhitelist(String fileNameExtWhitelist) {
        this.fileNameExtWhitelist = fileNameExtWhitelist;
    }

    protected static SimpleDateFormat getHttpDateFormat() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
        dateFormat.setTimeZone(TIME_ZONE_GMT);
        return dateFormat;
    }

    protected static String toHttpDate(Date date) {
        SimpleDateFormat format = getHttpDateFormat();
        return format.format(date);
    }

    protected static String toHttpLanguage(Locale locale) {
        StringBuilder sb = new StringBuilder();
        sb.append(locale.getLanguage());
        if (locale.getCountry() != null) {
            // Locale.toString() will use a "_" separator instead,
            // while '-' is expected in headers such as Content-Language, etc:
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.10
            sb.append('-').append(locale.getCountry());
        }
        return sb.toString();
    }
}


text:
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = require("@firebase/util");
var errors_1 = require("../models/errors");
var token_manager_1 = require("../models/token-manager");
var notification_permission_1 = require("../models/notification-permission");
var SENDER_ID_OPTION_NAME = 'messagingSenderId';
var ControllerInterface = /** @class */ (function () {
    /**
     * An interface of the Messaging Service API
     * @param {!firebase.app.App} app
     */
    function ControllerInterface(app) {
        var _this = this;
        this.errorFactory_ = new util_1.ErrorFactory('messaging', 'Messaging', errors_1.default.map);
        if (!app.options[SENDER_ID_OPTION_NAME] ||
            typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {
            throw this.errorFactory_.create(errors_1.default.codes.BAD_SENDER_ID);
        }
        this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];
        this.tokenManager_ = new token_manager_1.default();
        this.app = app;
        this.INTERNAL = {};
        this.INTERNAL.delete = function () { return _this.delete; };
    }
    /**
     * @export
     * @return {Promise<string> | Promise<null>} Returns a promise that
     * resolves to an FCM token.
     */
    ControllerInterface.prototype.getToken = function () {
        var _this = this;
        // Check with permissions
        var currentPermission = this.getNotificationPermission_();
        if (currentPermission !== notification_permission_1.default.granted) {
            if (currentPermission === notification_permission_1.default.denied) {
                return Promise.reject(this.errorFactory_.create(errors_1.default.codes.NOTIFICATIONS_BLOCKED));
            }
            // We must wait for permission to be granted
            return Promise.resolve(null);
        }
        return this.getSWRegistration_().then(function (registration) {
            return _this.tokenManager_
                .getSavedToken(_this.messagingSenderId_, registration)
                .then(function (token) {
                if (token) {
                    return token;
                }
                return _this.tokenManager_.createToken(_this.messagingSenderId_, registration);
            });
        });
    };
    /**
     * This method deletes tokens that the token manager looks after and then
     * unregisters the push subscription if it exists.
     * @export
     * @param {string} token
     * @return {Promise<void>}
     */
    ControllerInterface.prototype.deleteToken = function (token) {
        var _this = this;
        return this.tokenManager_.deleteToken(token).then(function () {
            return _this.getSWRegistration_()
                .then(function (registration) {
                if (registration) {
                    return registration.pushManager.getSubscription();
                }
            })
                .then(function (subscription) {
                if (subscription) {
                    return subscription.unsubscribe();
                }
            });
        });
    };
    ControllerInterface.prototype.getSWRegistration_ = function () {
        throw this.errorFactory_.create(errors_1.default.codes.SHOULD_BE_INHERITED);
    };
    //
    // The following methods should only be available in the window.
    //
    ControllerInterface.prototype.requestPermission = function () {
        throw this.errorFactory_.create(errors_1.default.codes.AVAILABLE_IN_WINDOW);
    };
    /**
     * @export
     * @param {!ServiceWorkerRegistration} registration
     */
    ControllerInterface.prototype.useServiceWorker = function (registration) {
        throw this.errorFactory_.create(errors_1.default.codes.AVAILABLE_IN_WINDOW);
    };
    /**
     * @export
     * @param {!firebase.Observer|function(*)} nextOrObserver
     * @param {function(!Error)=} optError
     * @param {function()=} optCompleted
     * @return {!function()}
     */
    ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {
        throw this.errorFactory_.create(errors_1.default.codes.AVAILABLE_IN_WINDOW);
    };
    /**
     * @export
     * @param {!firebase.Observer|function()} nextOrObserver An observer object
     * or a function triggered on token refresh.
     * @param {function(!Error)=} optError Optional A function
     * triggered on token refresh error.
     * @param {function()=} optCompleted Optional function triggered when the
     * observer is removed.
     * @return {!function()} The unsubscribe function for the observer.
     */
    ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {
        throw this.errorFactory_.create(errors_1.default.codes.AVAILABLE_IN_WINDOW);
    };
    //
    // The following methods are used by the service worker only.
    //
    /**
     * @export
     * @param {function(Object)} callback
     */
    ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {
        throw this.errorFactory_.create(errors_1.default.codes.AVAILABLE_IN_SW);
    };
    //
    // The following methods are used by the service themselves and not exposed
    // publicly or not expected to be used by developers.
    //
    /**
     * This method is required to adhere to the Firebase interface.
     * It closes any currently open indexdb database connections.
     */
    ControllerInterface.prototype.delete = function () {
        return this.tokenManager_.closeDatabase();
    };
    /**
     * Returns the current Notification Permission state.
     * @private
     * @return {string} The currenct permission state.
     */
    ControllerInterface.prototype.getNotificationPermission_ = function () {
        return Notification.permission;
    };
    /**
     * @protected
     * @returns {TokenManager}
     */
    ControllerInterface.prototype.getTokenManager = function () {
        return this.tokenManager_;
    };
    return ControllerInterface;
}());
exports.default = ControllerInterface;

//# sourceMappingURL=controller-interface.js.map


text:
<?php namespace Altenia\Ecofy\CoreService;

/**
 * Service class that provides file
 */
class FileService extends BaseService {

	const ROOT_FOLDER =  'uploads/';

    /**
     * Constructor
     */
    public function __construct($name = 'file')
    {
        parent::__construct($name);
    }

	/**
	 * @param $model    {Mode}   The model object that contains the file parameter
	 * @param $filePropNames {array} The array of property names that are file
	 *
	 * @return Returns a assoc-array: [{ name, type, size, location, description}]
	 */
	public function saveUploads($filePropNames, &$model, $subFolder = "")
	{
		if (!empty($subFolder) && !ends_with($subFolder, "/")) {
			$subFolder .= "/";
		}

		$fileInfos = array();

		foreach ($filePropNames as $filePropName)
		{
			$uploadedFile = \Input::file($filePropName);

			if (!empty($uploadedFile))
			{
				$subPath = self::ROOT_FOLDER . $model->getTable() . '/' . $subFolder;
				// @todo - Change public_path() to base_path() once MediaController is implemented
				$uploadRootPath = public_path();
				$destinationPath =  $uploadRootPath . '/' . $subPath;

				self::createDir($destinationPath);

				$filename = $model->sid . '_' . $uploadedFile->getClientOriginalName();
				$extension = $uploadedFile->getClientOriginalExtension();
				$size = $uploadedFile->getSize();;
				$type = $uploadedFile->getMimeType();;

				//self::deleteFile($uploadRootPath . $model->$filePropName);
				// Will be set to something like: 'users/1_myprofile.jpg'
				//$model->$filePropName = $subPath . $filename;

//print_r($destinationPath . ' : ' . $filename);
				$uploadSuccess = $uploadedFile->move($destinationPath, $filename);

				if ($uploadSuccess) {
					$fileInfos[] = array(
							'name' => $uploadedFile->getClientOriginalName(),
							'type' => $type, 'size' => $size,
							'uri' =>  $subPath . $filename
						);
				}
			}
			//die();
		}

		return $fileInfos;
	}

	public static function createDir($dir)
	{
		if (!file_exists($dir))
		{
			mkdir($dir, 0777, true);
		}
	}

	public static function deleteFile($path)
	{
		if (!file_exists($path))
		{
			return unlink($dir);
		}
		return false;
	}
}


text:
export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) {
  if (parentModule) {
    throw new Error(`${moduleName} has already been loaded. Import Core modules in the AppModule only.`);
  }
}


text:
package org.apache.syncope.core.init;

import java.util.Locale;
import java.util.Set;
import org.apache.commons.lang.SerializationUtils;
import org.apache.syncope.common.types.ConnConfProperty;
import org.apache.syncope.core.persistence.beans.ConnInstance;
import org.apache.syncope.core.persistence.beans.ExternalResource;
import org.apache.syncope.core.persistence.dao.ConnectorRegistry;
import org.apache.syncope.core.persistence.dao.ResourceDAO;
import org.apache.syncope.core.propagation.Connector;
import org.apache.syncope.core.propagation.ConnectorFactory;
import org.apache.syncope.core.propagation.impl.ConnectorFacadeProxy;
import org.apache.syncope.core.rest.data.ResourceDataBinder;
import org.apache.syncope.core.util.ApplicationContextProvider;
import org.apache.syncope.core.util.ConnIdBundleManager;
import org.identityconnectors.common.l10n.CurrentLocale;
import org.identityconnectors.framework.api.ConnectorFacadeFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * Load ConnId connector instances.
 */
@Component
class ConnectorManager implements ConnectorRegistry, ConnectorFactory {

    private static final Logger LOG = LoggerFactory.getLogger(ConnectorManager.class);

    @Autowired
    private ResourceDAO resourceDAO;

    @Autowired
    private ResourceDataBinder resourceDataBinder;

    private String getBeanName(final ExternalResource resource) {
        return String.format("connInstance-%d-%s", resource.getConnector().getId(), resource.getName());
    }

    @Override
    public Connector getConnector(final ExternalResource resource) {
        // Try to re-create connector bean from underlying resource (useful for managing failover scenarios)
        if (!ApplicationContextProvider.getBeanFactory().containsBean(getBeanName(resource))) {
            registerConnector(resource);
        }

        return (Connector) ApplicationContextProvider.getBeanFactory().getBean(getBeanName(resource));
    }

    @Override
    public Connector createConnector(final ConnInstance connInstance, final Set<ConnConfProperty> configuration) {
        final ConnInstance connInstanceClone = (ConnInstance) SerializationUtils.clone(connInstance);

        connInstanceClone.setConfiguration(configuration);

        Connector connector = new ConnectorFacadeProxy(connInstanceClone);
        ApplicationContextProvider.getBeanFactory().autowireBean(connector);

        return connector;
    }

    @Override
    public void registerConnector(final ExternalResource resource) {
        final ConnInstance connInstance = resourceDataBinder.getConnInstance(resource);
        final Connector connector = createConnector(resource.getConnector(), connInstance.getConfiguration());
        LOG.debug("Connector to be registered: {}", connector);

        final String beanName = getBeanName(resource);

        if (ApplicationContextProvider.getBeanFactory().containsSingleton(beanName)) {
            unregisterConnector(beanName);
        }

        ApplicationContextProvider.getBeanFactory().registerSingleton(beanName, connector);
        LOG.debug("Successfully registered bean {}", beanName);
    }

    @Override
    public void unregisterConnector(final String id) {
        ApplicationContextProvider.getBeanFactory().destroySingleton(id);
    }

    @Transactional(readOnly = true)
    @Override
    public void load() {
        // This is needed in order to avoid encoding problems when sending error messages via REST
        CurrentLocale.set(Locale.ENGLISH);

        // Load all connector bundles
        ConnIdBundleManager.getConnManagers();

        // Load all resource-specific connectors
        int connectors = 0;
        for (ExternalResource resource : resourceDAO.findAll()) {
            LOG.info("Registering resource-connector pair {}-{}", resource, resource.getConnector());
            try {
                registerConnector(resource);
                connectors++;
            } catch (Exception e) {
                LOG.error("While registering resource-connector pair {}-{}", resource, resource.getConnector(), e);
            }
        }

        LOG.info("Done loading {} connectors", connectors);
    }

    @Transactional(readOnly = true)
    @Override
    public void unload() {
        int connectors = 0;
        for (ExternalResource resource : resourceDAO.findAll()) {
            final String beanName = getBeanName(resource);
            if (ApplicationContextProvider.getBeanFactory().containsSingleton(beanName)) {
                LOG.info("Unegistering resource-connector pair {}-{}", resource, resource.getConnector());
                unregisterConnector(beanName);
                connectors++;
            }
        }

        LOG.info("Done unloading {} connectors", connectors);

        ConnectorFacadeFactory.getInstance().dispose();
        ConnIdBundleManager.resetConnManagers();
        LOG.info("All connector resources disposed");
    }
}


text:
extern bool loadFileToBuffer(std::string filePath, std::vector<unsigned char>& outBytes);

extern bool saveFileFromBuffer(std::string filePath, const std::vector<unsigned char>& inBytes);


text:
.example {
    box-sizing: padding-box;
}


text:
<?php

namespace SeekAsia\Timezones;

use Illuminate\Support\ServiceProvider;

class TimezonesServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->loadViewsFrom(__DIR__.'/views', 'timezones');
        $this->publishes([
            __DIR__.'/views' => base_path('resources/views/seekasia/timezones'),
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        include __DIR__.'/routes.php';
        $this->app->make('SeekAsia\Timezones\TimezonesController');
    }
}


text:
import React from 'react';
import {
  GestureResponderEvent,
  ImageProps,
  StyleProp,
  StyleSheet,
  TouchableOpacityProps,
  View,
  ViewProps,
  ViewStyle,
} from 'react-native';
import {
  EvaInputSize,
  EvaStatus,
  FalsyFC,
  FalsyText,
  RenderProp,
  TouchableWithoutFeedback,
} from '../../devsupport';
import {
  Interaction,
  StyledComponentProps,
  StyleType,
} from '../../theme';
import { BaseCalendarProps } from '../calendar/baseCalendar.component';
import { CalendarElement } from '../calendar/calendar.component';
import { RangeCalendarElement } from '../calendar/rangeCalendar.component';
import { NativeDateService } from '../calendar/service/nativeDate.service';
import { Popover } from '../popover/popover.component';
import {
  PopoverPlacement,
  PopoverPlacements,
} from '../popover/type';
import { TextProps } from '../text/text.component';

export interface BaseDatepickerProps<D = Date> extends StyledComponentProps,
  TouchableOpacityProps,
  BaseCalendarProps<D> {

  controlStyle?: StyleProp<ViewStyle>;
  label?: RenderProp<TextProps> | React.ReactText;
  caption?: RenderProp<TextProps> | React.ReactText;
  accessoryLeft?: RenderProp<Partial<ImageProps>>;
  accessoryRight?: RenderProp<Partial<ImageProps>>;
  status?: EvaStatus;
  size?: EvaInputSize;
  placeholder?: RenderProp<TextProps> | React.ReactText;
  placement?: PopoverPlacement | string;
  backdropStyle?: StyleProp<ViewStyle>;
  onFocus?: () => void;
  onBlur?: () => void;
}

interface State {
  visible: boolean;
}

export abstract class BaseDatepickerComponent<P, D = Date> extends React.Component<BaseDatepickerProps<D> & P, State> {

  static defaultProps: Partial<BaseDatepickerProps> = {
    dateService: new NativeDateService(),
    placeholder: 'dd/mm/yyyy',
    placement: PopoverPlacements.BOTTOM_START,
  };

  public state: State = {
    visible: false,
  };

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  protected calendarRef = React.createRef<any>();

  public scrollToToday = (): void => {
    this.calendarRef.current?.scrollToToday();
  };

  public scrollToDate = (date: Date): void => {
    this.calendarRef.current?.scrollToDate(date);
  };

  private popoverRef = React.createRef<Popover>();

  public show = (): void => {
    this.popoverRef.current?.show();
  };

  public hide = (): void => {
    this.popoverRef.current?.hide();
  };

  public focus = (): void => {
    this.setState({ visible: true }, this.onPickerVisible);
  };

  public blur = (): void => {
    this.setState({ visible: false }, this.onPickerInvisible);
  };

  public isFocused = (): boolean => {
    return this.state.visible;
  };

  public abstract clear(): void;

  protected abstract getComponentTitle(): RenderProp<TextProps> | React.ReactText;

  protected abstract renderCalendar(): CalendarElement<D> | RangeCalendarElement<D>;

  private getComponentStyle = (style: StyleType): StyleType => {
    const {
      textMarginHorizontal,
      textFontFamily,
      textFontSize,
      textFontWeight,
      textColor,
      placeholderColor,
      iconWidth,
      iconHeight,
      iconMarginHorizontal,
      iconTintColor,
      labelColor,
      labelFontSize,
      labelMarginBottom,
      labelFontWeight,
      labelFontFamily,
      captionMarginTop,
      captionColor,
      captionFontSize,
      captionFontWeight,
      captionFontFamily,
      popoverWidth,
      ...controlParameters
    } = style;

    return {
      control: controlParameters,
      text: {
        marginHorizontal: textMarginHorizontal,
        fontFamily: textFontFamily,
        fontSize: textFontSize,
        fontWeight: textFontWeight,
        color: textColor,
      },
      placeholder: {
        marginHorizontal: textMarginHorizontal,
        color: placeholderColor,
      },
      icon: {
        width: iconWidth,
        height: iconHeight,
        marginHorizontal: iconMarginHorizontal,
        tintColor: iconTintColor,
      },
      label: {
        color: labelColor,
        fontSize: labelFontSize,
        fontFamily: labelFontFamily,
        marginBottom: labelMarginBottom,
        fontWeight: labelFontWeight,
      },
      captionLabel: {
        fontSize: captionFontSize,
        fontWeight: captionFontWeight,
        fontFamily: captionFontFamily,
        color: captionColor,
      },
      popover: {
        width: popoverWidth,
        marginBottom: captionMarginTop,
      },
    };
  };

  private onPress = (event: GestureResponderEvent): void => {
    this.setPickerVisible();
    this.props.onPress?.(event);
  };

  private onPressIn = (event: GestureResponderEvent): void => {
    this.props.eva.dispatch([Interaction.ACTIVE]);
    this.props.onPressIn?.(event);
  };

  private onPressOut = (event: GestureResponderEvent): void => {
    this.props.eva.dispatch([]);
    this.props.onPressOut?.(event);
  };

  private onPickerVisible = (): void => {
    this.props.eva.dispatch([Interaction.ACTIVE]);
    this.props.onFocus?.();
  };

  private onPickerInvisible = (): void => {
    this.props.eva.dispatch([]);
    this.props.onBlur?.();
  };

  private setPickerVisible = (): void => {
    this.setState({ visible: true }, this.onPickerVisible);
  };

  private setPickerInvisible = (): void => {
    this.setState({ visible: false }, this.onPickerInvisible);
  };

  private renderInputElement = (props, evaStyle): React.ReactElement => {
    return (
      <TouchableWithoutFeedback
        {...props}
        style={[evaStyle.control, styles.control, this.props.controlStyle]}
        onPress={this.onPress}
        onPressIn={this.onPressIn}
        onPressOut={this.onPressOut}
      >
        <FalsyFC
          style={evaStyle.icon}
          component={this.props.accessoryLeft}
        />
        <FalsyText
          style={evaStyle.text}
          numberOfLines={1}
          ellipsizeMode='tail'
          component={this.getComponentTitle()}
        />
        <FalsyFC
          style={evaStyle.icon}
          component={this.props.accessoryRight}
        />
      </TouchableWithoutFeedback>
    );
  };

  public render(): React.ReactElement<ViewProps> {
    const {
      eva,
      style,
      testID,
      backdropStyle,
      controlStyle,
      placement,
      label,
      accessoryLeft,
      accessoryRight,
      caption,
      ...touchableProps
    } = this.props;

    const evaStyle = this.getComponentStyle(eva.style);

    return (
      <View
        style={style}
        testID={testID}
      >
        <FalsyText
          style={[evaStyle.label, styles.label]}
          component={label}
        />
        <Popover
          ref={this.popoverRef}
          style={[evaStyle.popover, styles.popover]}
          backdropStyle={backdropStyle}
          placement={placement}
          visible={this.state.visible}
          anchor={() => this.renderInputElement(touchableProps, evaStyle)}
          onBackdropPress={this.setPickerInvisible}
        >
          {this.renderCalendar()}
        </Popover>
        <FalsyText
          style={[evaStyle.captionLabel, styles.captionLabel]}
          component={caption}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  popover: {
    borderWidth: 0,
  },
  control: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  label: {
    textAlign: 'left',
  },
  captionLabel: {
    textAlign: 'left',
  },
});