text:
namespace switches {

// -----------------------------------------------------------------------------
// Can't find the switch you are looking for? Try looking in
// media/base/media_switches.cc or ui/gl/gl_switches.cc or one of the
// .cc files corresponding to the *_switches.h files included above
// instead.
// -----------------------------------------------------------------------------

// All switches in alphabetical order. The switches should be documented
// alongside the definition of their values in the .cc file.
extern const char kAllowCreateExistingManagedUsers[];
extern const char kAllowCrossOriginAuthPrompt[];
extern const char kAllowFileAccess[];
extern const char kAllowHttpScreenCapture[];
extern const char kAllowNaClCrxFsAPI[];
extern const char kAllowNaClFileHandleAPI[];
extern const char kAllowNaClSocketAPI[];
extern const char kAllowOutdatedPlugins[];
extern const char kAllowRunningInsecureContent[];
extern const char kAlwaysAuthorizePlugins[];
extern const char kAppId[];
extern const char kApp[];
extern const char kAppListStartPageURL[];
extern const char kAppWindowSize[];
extern const char kAppsCheckoutURL[];
extern const char kAppsGalleryDownloadURL[];
extern const char kAppsGalleryInstallAutoConfirmForTests[];
extern const char kAppsGalleryURL[];
extern const char kAppsGalleryUpdateURL[];
extern const char kAppModeAuthCode[];
extern const char kAppModeOAuth2Token[];
extern const char kAppsNewInstallBubble[];
extern const char kAppsUseNativeFrame[];
extern const char kAuthExtensionPath[];
extern const char kAuthNegotiateDelegateWhitelist[];
extern const char kAuthSchemes[];
extern const char kAuthServerWhitelist[];
extern const char kAutoLaunchAtStartup[];
extern const char kAutomationClientChannelID[];
extern const char kAutomationReinitializeOnChannelError[];
extern const char kCancelFirstRun[];
extern const char kCertificateTransparencyLog[];
extern const char kCheckForUpdateIntervalSec[];
extern const char kCheckCloudPrintConnectorPolicy[];
extern const char kCipherSuiteBlacklist[];
extern const char kClearTokenService[];
extern const char kCloudPrintDeleteFile[];
extern const char kCloudPrintFile[];
extern const char kCloudPrintJobTitle[];
extern const char kCloudPrintFileType[];
extern const char kCloudPrintPrintTicket[];
extern const char kCloudPrintSetupProxy[];
extern const char kCloudPrintServiceURL[];
extern const char kComponentUpdater[];
extern const char kConflictingModulesCheck[];
extern const char kContentSettings2[];
extern const char kCountry[];
extern const char kCrashOnHangThreads[];
extern const char kCreateBrowserOnStartupForTests[];
#if defined(OS_ANDROID) || defined(OS_IOS)
extern const char kDataReductionProxyProbeURL[];
#endif
extern const char kDebugEnableFrameToggle[];
extern const char kDebugPackedApps[];
extern const char kDiagnostics[];
extern const char kDiagnosticsFormat[];
extern const char kDiagnosticsRecovery[];
extern const char kDisableAsyncDns[];
extern const char kDisableAuthNegotiateCnameLookup[];
extern const char kDisableAutofillAddressI18n[];
extern const char kDisableBackgroundMode[];
extern const char kDisableBackgroundNetworking[];
extern const char kDisableBundledPpapiFlash[];
extern const char kDisableBookmarkAutocompleteProvider[];
extern const char kDisableClientSidePhishingDetection[];
extern const char kDisableComponentExtensionsWithBackgroundPages[];
extern const char kDisableComponentUpdate[];
extern const char kDisableCRLSets[];
extern const char kDisableCreateExistingManagedUsers[];
extern const char kDisableCustomJumpList[];
extern const char kDisableDefaultApps[];
extern const char kDisableDeviceDiscovery[];
extern const char kDisableDeviceDiscoveryNotifications[];
extern const char kDisableDhcpWpad[];
extern const char kDisableDnsProbes[];
extern const char kDisableExtensionsFileAccessCheck[];
extern const char kDisableExtensionsHttpThrottling[];
extern const char kDisableExtensionsResourceWhitelist[];
extern const char kDisableExtensions[];
extern const char kDisableGoogleNowIntegration[];
extern const char kDisableImprovedDownloadProtection[];
extern const char kDisableIPv6[];
extern const char kDisableIPPooling[];
extern const char kDisableMinimizeOnSecondLauncherItemClick[];
extern const char kDisableNTPOtherSessionsMenu[];
extern const char kDisableOmniboxAutoCompletionForIme[];
extern const char kDisableOriginChip[];
extern const char kDisableOriginChipV2[];
extern const char kDisablePasswordManagerReauthentication[];
extern const char kDisablePeopleSearch[];
extern const char kDisablePnacl[];
extern const char kDisablePopupBlocking[];
extern const char kDisablePreconnect[];
extern const char kDisablePrerenderLocalPredictor[];
extern const char kDisablePrivetLocalPrinting[];
extern const char kDisablePromptOnRepost[];
extern const char kDisableQuic[];
extern const char kDisableQuicHttps[];
extern const char kDisableQuicPortSelection[];
extern const char kDisableRestoreBackgroundContents[];
extern const char kDisableRestoreSessionState[];
extern const char kDisableSearchButtonInOmnibox[];
extern const char kDisableScriptedPrintThrottling[];
extern const char kDisableSpdy31[];
extern const char kDisableSync[];
extern const char kDisableSyncAppSettings[];
extern const char kDisableSyncApps[];
extern const char kDisableSyncAutofill[];
extern const char kDisableSyncAutofillProfile[];
extern const char kDisableSyncBookmarks[];
extern const char kDisableSyncDictionary[];
extern const char kDisableSyncExtensionSettings[];
extern const char kDisableSyncExtensions[];
extern const char kDisableSyncFavicons[];
extern const char kDisableSyncPasswords[];
extern const char kDisableSyncPreferences[];
extern const char kDisableSyncPriorityPreferences[];
extern const char kDisableSyncSearchEngines[];
extern const char kDisableSyncSessionsV2[];
extern const char kDisableSyncSyncedNotifications[];
extern const char kDisableSyncTabs[];
extern const char kDisableSyncThemes[];
extern const char kDisableSyncTypedUrls[];
extern const char kDisableTLSChannelID[];
extern const char kDisableUserMediaSecurity[];
extern const char kDisableWebResources[];
extern const char kDisableZeroBrowsersOpenForTests[];
extern const char kDiskCacheDir[];
extern const char kDiskCacheSize[];
extern const char kDnsLogDetails[];
extern const char kDnsPrefetchDisable[];
extern const char kDumpBrowserHistograms[];
extern const char kEmbedFlashFullscreen[];
extern const char kEnableAdview[];
extern const char kEnableAppList[];
extern const char kEnableAppWindowControls[];
extern const char kEnableAppsShowOnFirstPaint[];
extern const char kEnableAsyncDns[];
extern const char kEnableAuthNegotiatePort[];
extern const char kEnableAutologin[];
extern const char kEnableBenchmarking[];
extern const char kEnableClientHints[];
extern const char kEnableBookmarkUndo[];
extern const char kEnableCloudPrintProxy[];
extern const char kEnableContacts[];
extern const char kEnableDevToolsExperiments[];
extern const char kEnableDeviceDiscoveryNotifications[];
extern const char kEnableDomDistiller[];
extern const char kEnableEnhancedBookmarks[];
extern const char kEnableEphemeralApps[];
extern const char kEnableExtensionActivityLogging[];
extern const char kEnableExtensionActivityLogTesting[];
extern const char kEnableFastUnload[];
extern const char kEnableGoogleNowIntegration[];
extern const char kEnableHttp2Draft04[];
extern const char kEnableWebBasedSignin[];
extern const char kEnableIPPooling[];
extern const char kEnableIPv6[];
extern const char kEnableLinkableEphemeralApps[];
extern const char kEnableLocalFirstLoadNTP[];
extern const char kEnableManagedStorage[];
extern const char kEnableMemoryInfo[];
extern const char kEnableMetricsReportingForTesting[];
extern const char kEnableNaCl[];
extern const char kEnableNetBenchmarking[];
extern const char kEnableNetworkTime[];
extern const char kEnableNpnHttpOnly[];
extern const char kEnableOfflineAutoReload[];
extern const char kEnableOmniboxAutoCompletionForIme[];
extern const char kEnableOriginChip[];
extern const char kEnableOriginChipLeadingLocationBar[];
extern const char kEnableOriginChipTrailingLocationBar[];
extern const char kEnableOriginChipLeadingMenuButton[];
extern const char kEnableOriginChipV2[];
extern const char kEnableOriginChipV2HideOnMouseRelease[];
extern const char kEnableOriginChipV2HideOnUserInput[];
extern const char kEnablePanels[];
extern const char kEnablePasswordAutofillPublicSuffixDomainMatching[];
extern const char kEnablePermissionsBubbles[];
extern const char kEnableQueryExtraction[];
extern const char kEnablePrivetStorage[];
extern const char kEnableProfiling[];
extern const char kEnableQuic[];
extern const char kEnableQuicHttps[];
extern const char kEnableQuicPortSelection[];
extern const char kEnableResourceContentSettings[];
extern const char kEnableSavePasswordBubble[];
extern const char kEnableSdch[];
extern const char kEnableSearchButtonInOmniboxAlways[];
extern const char kEnableSearchButtonInOmniboxForStr[];
extern const char kEnableSearchButtonInOmniboxForStrOrIip[];
extern const char kEnableSignedCertificateTimestampsViewer[];
extern const char kEnableSpdy2[];
extern const char kEnableSpdy4a2[];
extern const char kEnableSpellingAutoCorrect[];
extern const char kEnableSpellingFeedbackFieldTrial[];
extern const char kEnableStackedTabStrip[];
extern const char kEnableStreamlinedHostedApps[];
extern const char kEnableSuggestionsTabPage[];
extern const char kEnableSyncAppList[];
extern const char kEnableSyncArticles[];
extern const char kEnableSyncSyncedNotifications[];
extern const char kEnableTabGroupsContextMenu[];
extern const char kEnableThumbnailRetargeting[];
extern const char kEnableTranslateNewUX[];
extern const char kEnableUnrestrictedSSL3Fallback[];
extern const char kEnableUserAlternateProtocolPorts[];
extern const char kEnableWatchdog[];
extern const char kEnableWebSocketOverSpdy[];
extern const char kExplicitlyAllowedPorts[];
extern const char kExtensionsInstallVerification[];
extern const char kExtensionsNotWebstore[];
extern const char kExtensionsUpdateFrequency[];
extern const char kExtraSearchQueryParams[];
extern const char kFakeVariationsChannel[];
extern const char kFastStart[];
extern const char kFlagSwitchesBegin[];
extern const char kFlagSwitchesEnd[];
extern const char kFeedbackServer[];
extern const char kFileDescriptorLimit[];
extern const char kForceAppMode[];
extern const char kForceFirstRun[];
extern const char kForceVariationIds[];
extern const char kGoogleBaseURL[];
extern const char kGoogleProfileInfo[];
extern const char kGoogleSearchDomainCheckURL[];
extern const char kGSSAPILibraryName[];
extern const char kHelp[];
extern const char kHelpShort[];
extern const char kHideIcons[];
extern const char kHistoryDisableFullHistorySync[];
extern const char kHistoryEnableGroupByDomain[];
extern const char kHistoryWebHistoryUrl[];
extern const char kHomePage[];
extern const char kHostRules[];
extern const char kHostResolverParallelism[];
extern const char kHostResolverRetryAttempts[];
extern const char kIgnoreUrlFetcherCertRequests[];
extern const char kIncognito[];
extern const char kInstallFromWebstore[];
extern const char kInstantProcess[];
extern const char kIpcFuzzerTestcase[];
extern const char kKeepAliveForTest[];
extern const char kKioskMode[];
extern const char kKioskModePrinting[];
extern const char kLimitedInstallFromWebstore[];
extern const char kLoadComponentExtension[];
extern const char kLoadExtension[];
extern const char kMakeDefaultBrowser[];
extern const char kManagedUserId[];
extern const char kManagedUserSyncToken[];
extern const char kManualEnhancedBookmarks[];
extern const char kMediaCacheSize[];
extern const char kMemoryProfiling[];
extern const char kMessageLoopHistogrammer[];
extern const char kMetricsRecordingOnly[];
extern const char kMultiProfiles[];
extern const char kNativeMessagingHosts[];
extern const char kNetLogLevel[];
extern const char kNewProfileManagement[];
extern const char kNoDefaultBrowserCheck[];
extern const char kNoDisplayingInsecureContent[];
extern const char kNoEvents[];
extern const char kNoExperiments[];
extern const char kNoFirstRun[];
extern const char kNoJsRandomness[];
extern const char kNoNetworkProfileWarning[];
extern const char kNoProxyServer[];
extern const char kNoPings[];
extern const char kNoServiceAutorun[];
extern const char kNoStartupWindow[];
extern const char kNoManagedUserAcknowledgmentCheck[];
extern const char kNtpAppInstallHint[];
extern const char kNumPacThreads[];
extern const char kOnlyBlockSettingThirdPartyCookies[];
extern const char kOpenInNewWindow[];
extern const char kOrganicInstall[];
extern const char kOriginToForceQuicOn[];
extern const char kOriginalProcessStartTime[];
extern const char kOutOfProcessPdf[];
extern const char kPackExtension[];
extern const char kPackExtensionKey[];
extern const char kParentProfile[];
extern const char kPerformanceMonitorGathering[];
extern const char kPlaybackMode[];
extern const char kPnaclDir[];
extern const char kPpapiFlashPath[];
extern const char kPpapiFlashVersion[];
extern const char kPrefetchSearchResults[];
extern const char kPrerenderFromOmnibox[];
extern const char kPrerenderFromOmniboxSwitchValueAuto[];
extern const char kPrerenderFromOmniboxSwitchValueDisabled[];
extern const char kPrerenderFromOmniboxSwitchValueEnabled[];
extern const char kPrerenderMode[];
extern const char kPrerenderModeSwitchValueAuto[];
extern const char kPrerenderModeSwitchValueDisabled[];
extern const char kPrerenderModeSwitchValueEnabled[];
extern const char kPrerenderModeSwitchValuePrefetchOnly[];
extern const char kPrivetIPv6Only[];
extern const char kProductVersion[];
extern const char kProfileDirectory[];
extern const char kProfilingAtStart[];
extern const char kProfilingFile[];
extern const char kProfilingFlush[];
extern const char kProfilingOutputFile[];
extern const char kPromoServerURL[];
extern const char kProxyAutoDetect[];
extern const char kProxyBypassList[];
extern const char kProxyPacUrl[];
extern const char kProxyServer[];
extern const char kPurgeMemoryButton[];
extern const char kQuicMaxPacketLength[];
extern const char kQuicVersion[];
extern const char kRecordMode[];
extern const char kRemoteDebuggingFrontend[];
extern const char kRendererPrintPreview[];
extern const char kResetAppListInstallState[];
extern const char kResetVariationState[];
extern const char kRestoreLastSession[];
extern const char kSavePageAsMHTML[];
extern const char kSbURLPrefix[];
extern const char kSbDisableAutoUpdate[];
extern const char kSbDisableDownloadProtection[];
extern const char kSbDisableExtensionBlacklist[];
extern const char kSbDisableSideEffectFreeWhitelist[];
extern const char kSbDownloadFeedbackURL[];
extern const char kServiceProcess[];
extern const char kSilentDebuggerExtensionAPI[];
extern const char kSilentLaunch[];
extern const char kSetToken[];
extern const char kShowAppList[];
extern const char kShowAppListStartPage[];
extern const char kShowIcons[];
extern const char kSigninProcess[];
extern const char kSilentDumpOnDCHECK[];
extern const char kSimulateUpgrade[];
extern const char kSimulateCriticalUpdate[];
extern const char kSimulateOutdated[];
extern const char kSpdyProxyAuthFallback[];
extern const char kSpdyProxyAuthOrigin[];
extern const char kSpdyProxyAuthValue[];
extern const char kSpdyProxyDevAuthOrigin[];
extern const char kSpellingServiceFeedbackUrl[];
extern const char kSpellingServiceFeedbackIntervalSeconds[];
extern const char kSSLVersionMax[];
extern const char kSSLVersionMin[];
extern const char kStartMaximized[];
extern const char kSuggestionNtpFilterWidth[];
extern const char kSuggestionNtpGaussianFilter[];
extern const char kSuggestionNtpLinearFilter[];
extern const char kSyncAllowInsecureXmppConnection[];
extern const char kSyncInvalidateXmppLogin[];
extern const char kSyncShortInitialRetryOverride[];
extern const char kSyncNotificationHostPort[];
extern const char kSyncServiceURL[];
extern const char kSyncThrowUnrecoverableError[];
extern const char kSyncTrySsltcpFirstForXmpp[];
extern const char kSyncEnableDeferredStartup[];
extern const char kSyncEnableGetUpdateAvoidance[];
extern const char kSyncfsEnableDirectoryOperation[];
extern const char kTabCapture[];
extern const char kTestName[];
extern const char kTestType[];
extern const char kTestingChannelID[];
extern const char kTrustedSpdyProxy[];
extern const char kTryChromeAgain[];
extern const char kUninstallExtension[];
extern const char kUninstall[];
extern const char kUnlimitedStorage[];
extern const char kUseSimpleCacheBackend[];
extern const char kUseSpdy[];
extern const char kUseSpellingSuggestions[];
extern const char kMaxSpdyConcurrentStreams[];
extern const char kUserDataDir[];
extern const char kValidateCrx[];
extern const char kVariationsServerURL[];
extern const char kVersion[];
extern const char kWhitelistedExtensionID[];
extern const char kWindowPosition[];
extern const char kWindowSize[];
extern const char kWinHttpProxyResolver[];

#if defined(ENABLE_PLUGIN_INSTALLATION)
extern const char kPluginsMetadataServerURL[];
#endif

#if defined(OS_ANDROID) || defined(OS_IOS)
extern const char kEnableSpdyProxyAuth[];
#endif  // defined(OS_ANDROID) || defined(OS_IOS)

#if defined(OS_ANDROID)
extern const char kDisableAppBanners[];
extern const char kDisableNewNTP[];
extern const char kDisableZeroSuggest[];
extern const char kEnableAccessibilityTabSwitcher[];
extern const char kEnableCast[];
extern const char kEnableContextualSearch[];
extern const char kEnableNewNTP[];
extern const char kEnableTranslate[];
extern const char kEnableZeroSuggestEtherSerp[];
extern const char kEnableZeroSuggestEtherNoSerp[];
extern const char kEnableZeroSuggestMostVisited[];
#endif

#if defined(USE_ASH)
extern const char kOpenAsh[];
#endif

#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_CHROMEOS)
extern const char kPasswordStore[];
#endif

#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
extern const char kMigrateDataDirForSxS[];
#endif

#if defined(OS_MACOSX)
extern const char kDisableAppShims[];
extern const char kDisableCoreAnimationLayerSquashing[];
extern const char kDisableSystemFullscreenForTesting[];
extern const char kEnableSimplifiedFullscreen[];
extern const char kKeychainReauthorize[];
extern const char kRelauncherProcess[];
extern const char kUseMockKeychain[];
#endif

#if defined(OS_WIN)
extern const char kDebugPrint[];
extern const char kEnableProfileShortcutManager[];
extern const char kForceImmersive[];
extern const char kForceDesktop[];
extern const char kPrintRaster[];
extern const char kRelaunchShortcut[];
extern const char kViewerConnect[];
extern const char kViewerLaunchViaAppId[];
extern const char kWaitForMutex[];
extern const char kWindows8Search[];
#endif

#ifndef NDEBUG
extern const char kFileManagerExtensionPath[];
extern const char kImageLoaderExtensionPath[];
#endif

#if defined(GOOGLE_CHROME_BUILD)
extern const char kDisablePrintPreview[];
#else
extern const char kEnablePrintPreview[];
#endif

// DON'T ADD RANDOM STUFF HERE. Put it in the main section above in
// alphabetical order, or in one of the ifdefs (also in order in each section).

}  // namespace switches

#endif  // CHROME_COMMON_CHROME_SWITCHES_H_


text:
package gowebserver

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"net/http"
	"path/filepath"
	"strings"

	"github.com/bodgit/sevenzip"
	archiver "github.com/mholt/archiver/v4"
	"go.opentelemetry.io/otel/trace"
)

var (
	archives = []string{".tar", ".tar.gz", ".tar.bz2", ".tar.xz", ".tar.lz4", ".tar.br", ".tar.zst", ".rar", ".zip"}
)

func splitNestedFSPath(path string) []string {
	parts := strings.Split(path, "/")
	segments := []string{}
	archiveDir := false

	cur := []string{}
	for _, part := range parts {
		cur = append(cur, part)
		if strings.HasSuffix(part, nestedDirSuffix) {
			undelimitedPart := strings.TrimSuffix(part, nestedDirSuffix)
			if isSupportedArchive(undelimitedPart) || isSupportedSevenZip(undelimitedPart) {
				segments = append(segments, strings.Join(cur, "/"))
				cur = []string{}
				archiveDir = true
			} else {
				archiveDir = false
			}
		}
	}
	if len(cur) > 0 {
		segments = append(segments, strings.Join(cur, "/"))
	} else if archiveDir {
		segments = append(segments, ".")
	}
	return segments
}

func joinNestedFSPath(paths []string) string {
	return strings.Join(paths, "/")
}

func newHandlerFromFS(path string, tp trace.TracerProvider, enhancedList bool) (http.Handler, func() error, error) {
	if !isSupportedGit(path) && isSupportedHTTP(path) {
		handler, err := newHTTPReverseProxy(path)
		return handler, nilFuncWithError, err
	}
	vFS, err := newRawFSFromURI(path)
	if err != nil {
		return nil, nilFuncWithError, err
	}
	nFS := newNestedFS(vFS)

	return newCustomIndex(http.FileServer(http.FS(nFS)), nFS, tp, enhancedList), nFS.Close, nil
}

func newRawFSFromURI(path string) (FileSystem, error) {
	if isSupportedSevenZip(path) {
		return newSevenZipFS(path)
	} else if isSupportedArchive(path) {
		return newArchiveFSFromLocalPath(path)
	} else if isSupportedGit(path) {
		return newGitFS(path)
	}
	return newLocalFS(path, func() error { return nil })
}

func isSupportedArchive(filePath string) bool {
	for _, suffix := range archives {
		if strings.HasSuffix(strings.ToLower(filePath), suffix) {
			return true
		}
	}
	return false
}

func isSupportedSevenZip(filePath string) bool {
	return strings.HasSuffix(strings.ToLower(filePath), ".7z")
}

func writeFileFromArchiveEntry(f opener, filePath string) error {
	zf, err := f.Open()
	if err != nil {
		return fmt.Errorf("cannot open input file: %w", err)
	}
	defer zf.Close()
	return copyFile(zf, filePath)
}

type opener interface {
	Open() (io.ReadCloser, error)
}

func newSevenZipFS(filePath string) (*localFS, error) {
	tmpDir, localFilePath, cleanup, err := stageRemoteFile(filePath)
	if err != nil {
		return nil, err
	}

	// Extract archive
	r, err := sevenzip.OpenReader(localFilePath)
	if err != nil {
		logError(cleanup())
		return nil, err
	}
	defer r.Close()

	// Iterate through the files in the archive,
	// printing some of their contents.
	for _, f := range r.File {
		name := sanitizeFileName(f.Name)
		filePath := filepath.Join(tmpDir, name)
		if f.FileInfo().IsDir() {
			err = createDirectory(filePath)
			if err != nil {
				logError(cleanup())
				return nil, fmt.Errorf("cannot create directory: %s, %w", filePath, err)
			}
		} else {
			dirPath := filepath.Dir(filePath)
			err = createDirectory(dirPath)
			if err != nil {
				logError(cleanup())
				return nil, fmt.Errorf("cannot create directory: %s, %w", dirPath, err)
			}

			err := writeFileFromArchiveEntry(f, filePath)
			if err != nil {
				logError(cleanup())
				return nil, fmt.Errorf("cannot write zip file entry: %s, %w", name, err)
			}
		}
	}

	return newLocalFS(tmpDir, cleanup)
}

func coerceToReaderAt(file fs.File) (io.ReaderAt, error) {
	readerAt, ok := file.(io.ReaderAt)
	if ok {
		return readerAt, nil
	} else {
		// TODO: This is super inefficient because it's reading a nested zip file into memory.
		data, err := io.ReadAll(file)
		if err != nil {
			return nil, err
		}
		return bytes.NewReader(data), err
	}
}

func archiverFileSystemFromArchive(file fs.File) (fs.FS, error) {
	stat, err := file.Stat()
	if err != nil {
		return nil, err
	}

	readerAt, err := coerceToReaderAt(file)
	if err != nil {
		return nil, err
	}

	format, _, err := archiver.Identify(stat.Name(), file)
	if err != nil && !errors.Is(err, archiver.ErrNoMatch) {
		return nil, err
	}
	if format != nil {
		// TODO: we only really need Extractor and Decompressor here, not the combined interfaces...
		if af, ok := format.(archiver.Archival); ok {
			r := io.NewSectionReader(readerAt, 0, stat.Size())
			return archiver.ArchiveFS{Stream: r, Format: af}, nil
		}
	}
	return nil, fmt.Errorf("archive not recognized")
}

redpajama_set_name: RedPajamaGithub


text:
package im.AfriChat.messenger.app.fragment.group.view;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.TextView;

import im.AfriChat.messenger.R;
import im.AfriChat.messenger.app.util.Screen;
import im.AfriChat.messenger.app.view.AvatarView;
import im.AfriChat.core.entity.PublicGroup;

/**
 * Created by korka on 30.06.15.
 */
public class PublicGroupCardView extends LinearLayout {
    public static final int COUNTER_TYPE_FRIENDS = 0;
    public static final int COUNTER_TYPE_MEMBERS = 1;
    AvatarView avatarView;
    TextView title;
    TextView counter;

    public PublicGroupCardView(Context context) {
        super(context);
    }

    public PublicGroupCardView(Context context, PublicGroup data, int counterType) {
        super(context);
        setPadding(Screen.dp(8), 0, Screen.dp(8), 0);
        setOrientation(VERTICAL);
        setGravity(Gravity.CENTER_HORIZONTAL);
        avatarView = new AvatarView(context);
        avatarView.init(Screen.dp(52), 24);
        avatarView.bind(data);
        addView(avatarView, new LinearLayout.LayoutParams(Screen.dp(58), Screen.dp(58)));

        title = new TextView(context);
        title.setText(data.getTitle());
        title.setGravity(Gravity.CENTER);
        title.setTextColor(context.getResources().getColor(R.color.text_secondary));
        title.setTextSize(15);
        title.setMaxLines(2);
        title.setEllipsize(TextUtils.TruncateAt.END);
        title.setMaxWidth(Screen.dp(100));
        addView(title, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        counter = new TextView(context);
        counter.setGravity(Gravity.CENTER);
        counter.setSingleLine();
        counter.setTextColor(context.getResources().getColor(R.color.text_secondary));
        counter.setTextSize(13);
        counter.setMaxWidth(Screen.dp(100));
        counter.setEllipsize(TextUtils.TruncateAt.END);
        String counterString;
        switch (counterType) {
            case COUNTER_TYPE_FRIENDS:
                counterString = context.getString(R.string.join_public_group_friends_count).concat(Integer.toString(data.getFriends()));
                break;

            case COUNTER_TYPE_MEMBERS:
                counterString = context.getString(R.string.join_public_group_members_count).concat(Integer.toString(data.getMembers()));
                break;

            default:
                counterString = "";
                break;
        }
        counter.setText(counterString);
        addView(counter, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
    }

}


text:
require 'spec_helper'

describe Sunrise::Locales::InstallGenerator do
  include GeneratorSpec::TestCase
  destination File.expand_path("../../tmp", __FILE__)
#  arguments %w(something)

  before(:all) do
    prepare_destination
    run_generator
  end

  it "should create codemirror js and css" do
    assert_file "public/javascripts/codemirror.js"
    assert_file "public/javascripts/yaml.js"
    assert_file "public/stylesheets/codemirror.css"
  end
end


text:
set -ex
pgcont_server_start_local
psql -c "ALTER USER \"user\" CREATEDB;"
pgcont_server_stop


text:
#if !defined(BOOST_SPIRIT_KARMA_SIMPLE_TRACE_APR_21_2010_0155PM)
#define BOOST_SPIRIT_KARMA_SIMPLE_TRACE_APR_21_2010_0155PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/karma/nonterminal/debug_handler_state.hpp>
#include <boost/fusion/include/out.hpp>
#include <iostream>

//  The stream to use for debug output
#if !defined(BOOST_SPIRIT_DEBUG_OUT)
#define BOOST_SPIRIT_DEBUG_OUT std::cerr
#endif

//  number of tokens to print while debugging
#if !defined(BOOST_SPIRIT_DEBUG_PRINT_SOME)
#define BOOST_SPIRIT_DEBUG_PRINT_SOME 20
#endif

//  number of spaces to indent
#if !defined(BOOST_SPIRIT_DEBUG_INDENT)
#define BOOST_SPIRIT_DEBUG_INDENT 2
#endif

namespace boost { namespace spirit { namespace karma
{
    struct simple_trace
    {
        int& get_indent() const
        {
            static int indent = 0;
            return indent;
        }

        void print_indent() const
        {
            int n = get_indent();
            n *= BOOST_SPIRIT_DEBUG_INDENT;
            for (int i = 0; i != n; ++i)
                BOOST_SPIRIT_DEBUG_OUT << ' ';
        }

        template <typename Buffer>
        void print_some(char const* tag, Buffer const& buffer) const
        {
            print_indent();
            BOOST_SPIRIT_DEBUG_OUT << '<' << tag << '>' << std::flush;
            {
                std::ostreambuf_iterator<char> out(BOOST_SPIRIT_DEBUG_OUT);
                buffer.buffer_copy_to(out, BOOST_SPIRIT_DEBUG_PRINT_SOME);
            }
            BOOST_SPIRIT_DEBUG_OUT << "</" << tag << '>' << std::endl;
        }

        template <typename OutputIterator, typename Context, typename State
          , typename Buffer>
        void operator()(
            OutputIterator& sink, Context const& context
          , State state, std::string const& rule_name
          , Buffer const& buffer) const
        {
            switch (state)
            {
                case pre_generate:
                    print_indent();
                    ++get_indent();
                    BOOST_SPIRIT_DEBUG_OUT
                        << '<' << rule_name << '>' << std::endl;
                    print_indent();
                    ++get_indent();
                    BOOST_SPIRIT_DEBUG_OUT << "<try>" << std::endl;;
                    print_indent();
                    BOOST_SPIRIT_DEBUG_OUT << "<attributes>";
                    traits::print_attribute(
                        BOOST_SPIRIT_DEBUG_OUT,
                        context.attributes
                    );
                    BOOST_SPIRIT_DEBUG_OUT << "</attributes>" << std::endl;
                    if (!fusion::empty(context.locals))
                    {
                        print_indent();
                        BOOST_SPIRIT_DEBUG_OUT
                            << "<locals>" << context.locals << "</locals>"
                            << std::endl;
                    }
                    --get_indent();
                    print_indent();
                    BOOST_SPIRIT_DEBUG_OUT << "</try>" << std::endl;;
                    break;

                case successful_generate:
                    print_indent();
                    ++get_indent();
                    BOOST_SPIRIT_DEBUG_OUT << "<success>" << std::endl;
                    print_some("result", buffer);
                    if (!fusion::empty(context.locals))
                    {
                        print_indent();
                        BOOST_SPIRIT_DEBUG_OUT
                            << "<locals>" << context.locals << "</locals>"
                            << std::endl;
                    }
                    --get_indent();
                    print_indent();
                    BOOST_SPIRIT_DEBUG_OUT << "</success>" << std::endl;
                    --get_indent();
                    print_indent();
                    BOOST_SPIRIT_DEBUG_OUT
                        << "</" << rule_name << '>' << std::endl;
                    break;

                case failed_generate:
                    print_indent();
                    BOOST_SPIRIT_DEBUG_OUT << "<fail/>" << std::endl;
                    --get_indent();
                    print_indent();
                    BOOST_SPIRIT_DEBUG_OUT
                        << "</" << rule_name << '>' << std::endl;
                    break;
            }
        }
    };
}}}

#endif


text:
using System;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
    internal struct VirtualTreePoint : IComparable<VirtualTreePoint>, IEquatable<VirtualTreePoint>
    {
        private readonly SyntaxTree _tree;
        private readonly SourceText _text;
        private readonly int _position;
        private readonly int _virtualSpaces;

        public VirtualTreePoint(SyntaxTree tree, SourceText text, int position, int virtualSpaces = 0)
        {
            Contract.ThrowIfNull(tree);
            Contract.ThrowIfFalse(position >= 0 && position <= tree.Length);
            Contract.ThrowIfFalse(virtualSpaces >= 0);

            _tree = tree;
            _text = text;
            _position = position;
            _virtualSpaces = virtualSpaces;
        }

        public static bool operator !=(VirtualTreePoint left, VirtualTreePoint right)
        {
            return !(left == right);
        }

        public static bool operator <(VirtualTreePoint left, VirtualTreePoint right)
        {
            return left.CompareTo(right) < 0;
        }

        public static bool operator <=(VirtualTreePoint left, VirtualTreePoint right)
        {
            return left.CompareTo(right) <= 0;
        }

        public static bool operator ==(VirtualTreePoint left, VirtualTreePoint right)
        {
            return object.Equals(left, right);
        }

        public static bool operator >(VirtualTreePoint left, VirtualTreePoint right)
        {
            return left.CompareTo(right) > 0;
        }

        public static bool operator >=(VirtualTreePoint left, VirtualTreePoint right)
        {
            return left.CompareTo(right) >= 0;
        }

        public bool IsInVirtualSpace
        {
            get { return _virtualSpaces != 0; }
        }

        public int Position
        {
            get { return _position; }
        }

        public int VirtualSpaces
        {
            get { return _virtualSpaces; }
        }

        public SourceText Text
        {
            get { return _text; }
        }

        public SyntaxTree Tree
        {
            get { return _tree; }
        }

        public int CompareTo(VirtualTreePoint other)
        {
            if (Text != other.Text)
            {
                throw new InvalidOperationException(EditorFeaturesResources.CantComparePositionsFromDiffSnapshots);
            }

            if (Position < other.Position)
            {
                return -1;
            }
            else if (Position > other.Position)
            {
                return 1;
            }

            if (VirtualSpaces < other.VirtualSpaces)
            {
                return -1;
            }
            else if (VirtualSpaces > other.VirtualSpaces)
            {
                return 1;
            }

            return 0;
        }

        public bool Equals(VirtualTreePoint other)
        {
            return CompareTo(other) == 0;
        }

        public override bool Equals(object obj)
        {
            return (obj is VirtualTreePoint) && Equals((VirtualTreePoint)obj);
        }

        public override int GetHashCode()
        {
            return Text.GetHashCode() ^ Position.GetHashCode() ^ VirtualSpaces.GetHashCode();
        }

        public override string ToString()
        {
            return $"VirtualTreePoint {{ Tree: '{Tree}', Text: '{Text}', Position: '{Position}', VirtualSpaces '{VirtualSpaces}' }}";
        }

        public TextLine GetContainingLine()
        {
            return Text.Lines.GetLineFromPosition(Position);
        }
    }
}


text:
CREATE DATABASE  IF NOT EXISTS `regatta` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `regatta`;
-- MySQL dump 10.13  Distrib 5.6.17, for Win32 (x86)
--
-- Host: 127.0.0.1    Database: regatta
-- ------------------------------------------------------
-- Server version	5.6.22-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `boat`
--

DROP TABLE IF EXISTS `boat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `boat` (
  `idBoat` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `photo` varchar(90) DEFAULT NULL,
  PRIMARY KEY (`idBoat`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `boat`
--

LOCK TABLES `boat` WRITE;
/*!40000 ALTER TABLE `boat` DISABLE KEYS */;
INSERT INTO `boat` VALUES (1,'Jumacabi',''),(2,'Goldfinger',NULL);
/*!40000 ALTER TABLE `boat` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `inscription`
--

DROP TABLE IF EXISTS `inscription`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inscription` (
  `Regatta_idRegatta` int(11) NOT NULL,
  `Team_idTeam` int(11) NOT NULL,
  PRIMARY KEY (`Regatta_idRegatta`,`Team_idTeam`),
  KEY `fk_Inscription_Team1_idx` (`Team_idTeam`),
  CONSTRAINT `fk_Inscription_Regatta1` FOREIGN KEY (`Regatta_idRegatta`) REFERENCES `regatta` (`idRegatta`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_Inscription_Team1` FOREIGN KEY (`Team_idTeam`) REFERENCES `team` (`idTeam`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `inscription`
--

LOCK TABLES `inscription` WRITE;
/*!40000 ALTER TABLE `inscription` DISABLE KEYS */;
INSERT INTO `inscription` VALUES (1,1),(2,1),(3,1),(1,2),(2,2),(4,2);
/*!40000 ALTER TABLE `inscription` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `regatta`
--

DROP TABLE IF EXISTS `regatta`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `regatta` (
  `idRegatta` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `active` boolean NOT NULL,
  PRIMARY KEY (`idRegatta`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `regatta`
--

LOCK TABLES `regatta` WRITE;
/*!40000 ALTER TABLE `regatta` DISABLE KEYS */;
INSERT INTO `regatta` VALUES (1,'Coupe Du Trimaran', true),(2,'Trophée Luc Liardet', false),(3,'Coupe des Tas de Pois', true),(4,'La Solitaire', true);
/*!40000 ALTER TABLE `regatta` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `team`
--

DROP TABLE IF EXISTS `team`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `team` (
  `idTeam` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `description` varchar(255),
  `Boat_idBoat` int(11) NOT NULL,
  PRIMARY KEY (`idTeam`,`Boat_idBoat`),
  KEY `fk_Team_Boat_idx` (`Boat_idBoat`),
  CONSTRAINT `fk_Team_Boat` FOREIGN KEY (`Boat_idBoat`) REFERENCES `boat` (`idBoat`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `team`
--

LOCK TABLES `team` WRITE;
/*!40000 ALTER TABLE `team` DISABLE KEYS */;
INSERT INTO `team` VALUES (1,'Team Rocket','',1),(2,'Team Burton',NULL,2);
/*!40000 ALTER TABLE `team` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `teamcomposition`
--

DROP TABLE IF EXISTS `teamcomposition`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `teamcomposition` (
  `Teammate_idTeammate` int(11) NOT NULL,
  `Team_idTeam` int(11) NOT NULL,
  PRIMARY KEY (`Teammate_idTeammate`,`Team_idTeam`),
  KEY `fk_TeamComposition_Teammate1_idx` (`Teammate_idTeammate`),
  KEY `fk_TeamComposition_Team1_idx` (`Team_idTeam`),
  CONSTRAINT `fk_TeamComposition_Team1` FOREIGN KEY (`Team_idTeam`) REFERENCES `team` (`idTeam`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `fk_TeamComposition_Teammate1` FOREIGN KEY (`Teammate_idTeammate`) REFERENCES `teammate` (`idTeammate`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `teamcomposition`
--

LOCK TABLES `teamcomposition` WRITE;
/*!40000 ALTER TABLE `teamcomposition` DISABLE KEYS */;
INSERT INTO `teamcomposition` VALUES (1,1),(2,1),(3,1),(4,1),(5,2),(6,2),(7,2);
/*!40000 ALTER TABLE `teamcomposition` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `teammate`
--
CREATE TABLE `user` (
	`idUser` int(11) NOT NULL AUTO_INCREMENT,
    `password` varchar(45),
    `username` varchar(45),
    PRIMARY KEY(`idUser`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `teammate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `teammate` (
  `idTeammate` int(11) NOT NULL AUTO_INCREMENT,
  `lastname` varchar(45) DEFAULT NULL,
  `firstname` varchar(45) DEFAULT NULL,
  `description` varchar(255),
  PRIMARY KEY (`idTeammate`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `teammate`
--

LOCK TABLES `teammate` WRITE;
/*!40000 ALTER TABLE `teammate` DISABLE KEYS */;
INSERT INTO `teammate` VALUES (1,'Guillou','Goulven',''),(2,'Hamon','Jean-Baptiste',''),(3,'Petesch','Nicolas',NULL),(4,'Guillermou','Jeremie',NULL),(5,'Le Formal','Marc',NULL),(6,'Cabillic','Erwan',NULL),(7,'Gaveriaux','Marie',NULL);
/*!40000 ALTER TABLE `teammate` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2015-02-18 17:47:35


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Case__c</name>
    <help>El cas que representa l'esdeveniment denunciat.</help>
    <relationshipLabel>Implicacions de comportament</relationshipLabel>
    <label>Cas</label>
</CustomFieldTranslation>


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

  function find (selector) {
      return document.querySelector(selector);
  }

  function add_class (node, name) {
      node.classList.add(name);
  }

  function remove_class (node, name) {
      node.classList.remove(name);
  }

  var schedule_data = [
    {
      "weekday": "Monday",
      "time": "6:00 PM",
      "duration": undefined,
      "canceled": false
    },
    {
      "weekday": "Tuesday",
      "time": "6:00 PM",
      "duration": undefined,
      "canceled": false
    },
    {
      "weekday": "Wednesday",
      "time": "5:00 PM",
      "duration": undefined,
      "canceled": false
    },
    {
      "weekday": "Thursday",
      "time": "9:30 PM",
      "duration": undefined,
      "canceled": false
    },
    {
      "weekday": "Friday",
      "time": "5:00 PM",
      "duration": undefined,
      "canceled": false
    },
    {
      "weekday": "Saturday",
      "time": "3:00 PM",
      "duration": undefined,
      "canceled": false
    },
    {
      "weekday": "Sunday",
      "time": "4:00 PM",
      "duration": undefined,
      "canceled": false
    }
  ];

  // shared constants

  var an_hour = 3600;
  var a_week = 604800;
  // is the streamer observing DST?
  var streamer_dst = moment().tz("america/vancouver").isDST();
  var visitor_timezone_offset = (new Date()).getTimezoneOffset();
  var weekday_names = ["monday", "tuesday", "wednesday", "thursday",
                              "friday", "saturday", "sunday"];

  function Stream(start_time, duration, canceled) {
      this.start = start_time.clone().zone(visitor_timezone_offset);
      this.end = this.start.clone();
      this.end.add('hours', duration);
      this.duration = duration;
      var week_when_stream_starts = this.start.clone().startOf("isoWeek").unix();
      this.start_normalized = this.start.unix() - week_when_stream_starts;
      this.end_normalized = this.end.unix() - week_when_stream_starts;
      this.dom_elements = [];
      this.canceled = canceled;
  }

  Stream.prototype.toString = function() {
      var start = this.start;
      var end = this.end;
      var start_suffix = start.format("a");
      var end_suffix = end.format("a");

      var start_format = base_format(this.start);
      if (!this.duration) {
          return format_stream(start, start_format);
      }
      var end_format = base_format(this.end);

      // assume duration > 0. This is for making time like 10 to 12 am
      // less ambiguous
      if (start.isoWeekday() !== end.isoWeekday()) {
          return format_stream(start, start_format) + " for " +
              this.duration + " hours";
      }

      if (start_suffix === end_suffix) {
          start_format.pop();  // make "3pm to 5pm" "3 to 5pm"
      }
      return format_stream(start, start_format) + " to " +
          format_stream(end, end_format);

      function format_stream (time, format_arr) {
          var hour = time.hours();
          var minutes = time.minutes();
          if (minutes === 0) {
              if (hour === 12) {
                  return 'Noon';
              } else if (hour === 0) {
                  return 'Beginning of day';
              }
          }
          return time.format(format_arr.join(" "));
      }
  };

  Stream.prototype.is_live = function(since_week_start) {
      if (!this.duration) {
          return false;
      }
      // in seconds
      return since_week_start >= this.start_normalized &&
          since_week_start <= this.end_normalized;
  };

  Stream.prototype.same_stream_next_week = function () {
      var clone = new Stream(this.start, this.duration);
      var one_week = moment.duration(1, 'week').asSeconds();
      clone.start_normalized += one_week;
      clone.end_normalized += one_week;
      return clone;
  }

  function base_format (moment_instance) {
      return moment_instance.minutes() > 0 ? ["h:m", "a"] : ["h", "a"];
  }

  function eng_to_iso (name) {
      var lowered = name.toLowerCase();
      var index = weekday_names.indexOf(lowered);
      if (index === -1) {
          throw new Error("Invalid weekday name");
      }
      return index + 1;
  }

  // Make an array of Stream objects given an array of time slots
  function make_streams (schedule) {
      var timezone_suffix = streamer_dst ? "-0700" : "-0800";
      var format = "h:m a Z E WW YYYY";

      function make_stream (slot) {
          return new Stream(moment(
                  slot.time + " " + timezone_suffix + " " +
                  eng_to_iso(slot.weekday) + " " + "1" + " 1970", format),
              slot.duration, slot.canceled);
      }

      if (window.export_internals) {
          window.streamer_dst = streamer_dst;
          window.visitor_timezone_offset = visitor_timezone_offset;
          window.make_stream = make_stream;
          window.Stream = Stream;
      }

      return schedule.map(make_stream).sort(function (a, b) {
          return a.start_normalized - b.start_normalized;
      });
  }

  // populate the dom tree with schedule info
  function display_schedule (grouped, max_same_day) {
      var i, j;

      var head_tr = find('tr');
      for (i = 0; i < grouped.length; i++) {
          var first_stream = grouped[i][0];
          var th = document.createElement("th");
          th.textContent = first_stream.start.format("dddd");
          // save reference to elements for highlighting later
          first_stream.dom_elements.push(th);
          head_tr.appendChild(th);
      }

      var body = find("tbody");
      for (i = 0; i < max_same_day; i++) {
          var tr = filled_tr(grouped.length);
          if (i !== 0) {
              tr.className = "auxiliary-slots";
          }
          body.appendChild(tr);
      }

      for (i = 0; i < grouped.length; i++) {
          for (j = 0; j < grouped[i].length; j++) {
              var target_stream = grouped[i][j];
              var target_element = body.children[j].children[i];

              target_element.appendChild(gen_schedule_node(target_stream));
              // save reference to elements for highlighting later
              target_stream.dom_elements.push(target_element);
              if (j >= 1) {
                  // this is for the mobile view, thus body.children[0]
                  body.children[0].children[i]
                      .appendChild(gen_schedule_node(target_stream, true));
              }
          }
      }

      function filled_tr (num_columns) {
          var tr = document.createElement("tr");
          while (tr.children.length < num_columns) {
              tr.appendChild(document.createElement("td"));
          }
          return tr;
      }
  }

  function gen_schedule_node (stream, same_line) {
      var node = document.createElement("span");
      var node_text = stream.toString();
      if (same_line) {
          node_text = ", " + node_text;
          add_class(node, "same-line-slots");
      }
      node.textContent = node_text;
      if (stream.canceled) {
          add_class(node, "canceled");
      }
      return node;
  }

  function pluralize (integer, string) {
      var base = integer + " " + string;
      if (integer > 1) {
          return base + 's';
      }
      return base;
  }

  function format_countdown (in_seconds) {
      var duration = moment.duration(in_seconds * 1000);
      var days = duration.days();
      var hours = duration.hours();
      var minutes = duration.minutes();
      var seconds = duration.seconds();
      var result = [];
      if (days) {
          result.push(pluralize(days, 'day'));
      }
      if (hours) {
          result.push(pluralize(hours, 'hour'));
      }
      if (minutes) {
          result.push(pluralize(minutes, 'minute'));
      }
      if (seconds) {
          result.push(pluralize(seconds, 'second'));
      }
      return result.join(", ");
  }

  function get_countdown (now, target) {
      // in seconds
      if (now === target) {  // this should never happen. See tick()
          throw new Error(
              "get_countdown() called with invalid arguments");
      }
      var delta = target - now;
      if (delta < 0) {
          delta += a_week;
      }
      return format_countdown(delta);
  }

  // Return a Stream that is currently live. If no such Stream exists,
  // return the Stream with the closest start time that is in the future.
  // Canceled streams are ignored
  function find_next_stream (streams, since_week_start) {
      streams = streams.filter(function (stream) {
          return !stream.canceled;
      });
      var found;
      for (var i = 0; i < streams.length; i++) {
          var stream = streams[i];
          if (since_week_start > stream.end_normalized) {
              continue;
          }
          found = stream;
          break;
      }
      if (!found) {
          return streams[0].same_stream_next_week();
      }
      return found;
  }

  var prefix = find("h3");
  var countdown = find("h1").children[0];
  var hide_class = "hidden";
  var clock = "disguise";

  function update_countdown (live, countdown_string) {
      // second argument is ignored if live is true
      if (live) {
          add_class(prefix, hide_class);
          remove_class(countdown, clock);
          countdown.textContent =
              "Kate is live right now! Click to watch";
          countdown.href = "http://www.twitch.tv/lovelymomo";
          return;
      }
      remove_class(prefix, hide_class);
      add_class(countdown, clock);
      countdown.textContent = countdown_string;
      countdown.href = "#";
  }

  var BLACK = "#333";
  var GREY = "grey";

  // highlight all the streams that starts on `today`. `today` is a day from
  // moment. If no stream is happening on `today` highlight all streams
  // that starts on the same day of `next_stream`
  function highlight_today(streams, today, next_stream) {
      var found = false;
      var i, j;

      for (i = 0; i < streams.length; i++) {
          for (j = 0; j < streams[i].dom_elements.length; j++) {
              if (streams[i].start.day() === today) {
                  streams[i].dom_elements[j].style.color = BLACK;
                  found = true;
              } else {
                  streams[i].dom_elements[j].style.color = GREY;
              }
          }
      }
      if (!found) {
          var target_day = next_stream.start.day();
          for (i = 0; i < streams.length; i++) {
              if (streams[i].start.day() === target_day) {
                  for (j = 0; j < streams[i].dom_elements.length; j++) {
                      streams[i].dom_elements[j].style.color = BLACK;
                  }
              }
          }
      }
  }

  // Return [[Stream]]. The streams that are in the same array start on the
  // same day
  function group_streams (streams) {
      var i, j;

      var grouped = [];
      var processed = {};

      for (i = 0; i < streams.length; i++) {
          if (i in processed) {
              continue;
          }
          processed[i] = 0;
          var current = streams[i];
          var same_day = [current];
          var day = current.start.isoWeekday();
          for (j = 0; j < streams.length; j++) {
              if (j in processed) {
                  continue;
              }
              if (streams[j].start.isoWeekday() === day) {
                  same_day.push(streams[j]);
                  processed[j] = 0;
              }
          }
          grouped.push(same_day);
      }
      return grouped;
  }

  // now :: Moment
  function calc_since_week_start (now) {
      var now_unix = now.unix();
      var since_week_start = now_unix -
                             now.clone().startOf("isoWeek").unix();
      var since_day_start = now_unix - now.clone().startOf("day").unix();
      // This is non-zero on the day of DST adjustment.
      // On the day DST ends, the elapsed time at the end of the day is 25 hours.
      // On the day DST starts, it's 23 hours.
      var observed_difference = now.hour() - Math.floor(since_day_start / an_hour);
      since_week_start += observed_difference * an_hour;
      return since_week_start;
  }

  var countdown_block = find("#countdown");
  var loading_message_node = find("#loading-message");

  var streams = make_streams(schedule_data);
  var grouped_streams = group_streams(streams);
  var max_same_day = Math.max.apply(null, grouped_streams.map(function (e) {
      return e.length;
  }));
  display_schedule(grouped_streams, max_same_day);

  function tick() {
      var now = moment();
      var since_week_start = calc_since_week_start(now);
      var stream = find_next_stream(streams, since_week_start);
      highlight_today(streams, now.day(), stream);

      if (stream.is_live(since_week_start)) {
          update_countdown(true);
      } else {
          update_countdown(false, get_countdown(since_week_start,
                                                stream.start_normalized));
      }
  }

  add_class(loading_message_node, "hidden");
  remove_class(countdown_block, "hidden");
  tick();
  setInterval(tick, 1000);

  if (window.export_internals) {
      window.calc_since_week_start = calc_since_week_start;
      window.find_next_stream = find_next_stream;
      window.get_countdown = get_countdown;
      window.group_streams = group_streams;
      window.tick = tick;
      window.streams = streams;
  }

})();


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Core\Exception;

use PhpSpec\ObjectBehavior;

final class MissingChannelConfigurationExceptionSpec extends ObjectBehavior
{
    function let(): void
    {
        $this->beConstructedWith('Message');
    }

    function it_is_a_runtime_exception(): void
    {
        $this->shouldHaveType(\RuntimeException::class);
    }
}


text:
                {{trans('cms::config.cache.memcached.host')}}
                @tooltip('cms::config.cache.memcached.host-info')

            <input type="text" v-model="cache.stores.memcached.servers[0].host" class="form-control">

                {{trans('cms::config.cache.memcached.port')}}
                @tooltip('cms::config.cache.memcached.port-info')

            <input type="text" v-model="cache.stores.memcached.servers[0].port" class="form-control">

        {{trans('cms::config.cache.memcached.weight')}}
        @tooltip('cms::config.cache.memcached.weight-info')

    <input type="text" v-model="cache.stores.memcached.servers[0].weight" class="form-control">


text:
package com.spotify.scio.avro.types

import org.apache.avro.Schema
import org.apache.avro.generic.GenericRecord

import scala.annotation.{compileTimeOnly, nowarn, StaticAnnotation}
import scala.reflect.runtime.universe._

/**
 * Macro annotations and converter generators for Avro types.
 *
 * The following table lists Avro types and their Scala counterparts.
 * {{{
 * Avro type      Scala type
 * BOOLEAN        Boolean
 * LONG           Long
 * INT            Int
 * DOUBLE         Double
 * FLOAT          Float
 * STRING, ENUM   String
 * BYTES          com.google.protobuf.ByteString
 * ARRAY          List[T]
 * MAP            Map[String, T]
 * UNION          Option[T]
 * RECORD         Nested case class
 * }}}
 *
 * @groupname trait
 * Traits for annotated types
 * @groupname annotation
 * Type annotations
 * @groupname converters
 * Converters
 * @groupname Ungrouped
 * Other Members
 */
object AvroType {

  /**
   * Macro annotation for an Avro schema.
   *
   * Generate case classes for an Avro schema. Note that `schema` must be a single string literal of
   * the JSON schema with optional `.stripMargin` at the end. For example:
   *
   * {{{
   *   @AvroType.fromSchema(
   *       """
   *         |{
   *         |  "type": "record",
   *         |  "namespace": "com.spotify.namespace",
   *         |  "name": "RecordName",
   *         |  "fields": [
   *         |    { "name": "boolF", "type": "boolean"},
   *         |    { "name": "intF", "type": "int"},
   *         |    { "name": "longF", "type": "long"},
   *         |    { "name": "floatF", "type": "float"},
   *         |    { "name": "doubleF", "type": "double"},
   *         |    { "name": "stringF", "type": "string"},
   *         |    { "name": "byteStringF", "type": "bytes"}
   *         |  ]
   *         |}
   *       """.stripMargin)
   *   class MyRecord
   * }}}
   *
   * Also generate a companion object with convenience methods.
   * @group annotation
   */
  @nowarn
  @compileTimeOnly(
    "enable macro paradise (2.12) or -Ymacro-annotations (2.13) to expand macro annotations"
  )
  class fromSchema(schema: String) extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro TypeProvider.schemaImpl
  }

  /**
   * Macro annotation for a path containing Avro files.
   *
   * Generates case classes from a path which contains Avro files. Path needs to represent a folder,
   * hence it always needs to end with `/`. Inside of the folder needs to exist at least one file
   * matching `*.avro` glob.
   *
   * Note that path must be a single string literal with optional `.stripMargin` at the end. For
   * example:
   *
   * {{{
   * @AvroType.fromPath("gs://myBucket/myFolder/")
   * class MyRecord
   * }}}
   *
   * or
   *
   * {{{
   * @AvroType.fromPath(
   *     """
   *     | gs://myBucket/myFolder/
   *     | myLooooooooooooooooongPath/
   *     """.stripMargin)
   * class MyRecord
   * }}}
   *
   * Globs are supported as a part of the path. For example:
   *
   * {{{
   * @AvroType.fromPath("gs://myBucket{@literal /}*{@literal /}*{@literal /}*{@literal /}")
   * class MyRecord
   * }}}
   *
   * Also generate a companion object with convenience methods.
   * @group annotation
   */
  @nowarn
  @compileTimeOnly(
    "enable macro paradise (2.12) or -Ymacro-annotations (2.13) to expand macro annotations"
  )
  class fromPath(folderGlob: String) extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro TypeProvider.pathImpl
  }

  /**
   * Macro annotation for a file which contains Avro schema.
   *
   * Generate case classes for an Avro schema. File can be either local or remote files. For example
   * file can be located on Google Cloud Storage (GCS):
   *
   * {{{
   *   @AvroType.fromSchemaFile("gs://myBucket/myFolder/schema-file.avsc")
   *   class MyRecord
   * }}}
   *
   * For local files, you need to either provide absolute path, or path relative to project root
   * directory. For example:
   *
   * {{{
   *   @AvroType.fromSchemaFile("sub-project/src/main/avro/schema-file.avsc")
   *   class MyRecord
   * }}}
   *
   * Also generate a companion object with convenience methods.
   * @group annotation
   */
  @nowarn
  @compileTimeOnly(
    "enable macro paradise (2.12) or -Ymacro-annotations (2.13) to expand macro annotations"
  )
  class fromSchemaFile(schemaFile: String) extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro TypeProvider.schemaFileImpl
  }

  /**
   * Macro annotation for case classes to be saved to Avro files.
   *
   * Note that this annotation does not generate case classes, only a companion object with
   * convenience methods. You need to define a complete case class for as output record. For
   * example:
   *
   * {{{
   * @AvroType.toSchema
   * case class Result(name: Option[String] = None, score: Option[Double] = None)
   * }}}
   *
   * It is recommended that you define all of your fields as Option. This way you could stop
   * populating them in the future if you notice that you don't need them.
   *
   * This macro doesn't help you with schema evolution. It's up to you to follow the best practices
   * on how to do evolution of your Avro schemas. Rule of thumb is to only add new fields, without
   * removing the old ones.
   * @group annotation
   */
  @compileTimeOnly(
    "enable macro paradise (2.12) or -Ymacro-annotations (2.13) to expand macro annotations"
  )
  class toSchema extends StaticAnnotation {
    def macroTransform(annottees: Any*): Any = macro TypeProvider.toSchemaImpl
  }

  /**
   * Trait for generated companion objects of case classes.
   * @group trait
   */
  trait HasAvroSchema[T] {
    def schema: Schema

    def fromGenericRecord: GenericRecord => T

    def toGenericRecord: T => GenericRecord

    def toPrettyString(indent: Int = 0): String
  }

  /**
   * Trait for companion objects of case classes generated with docs.
   * @group trait
   */
  trait HasAvroDoc {
    def doc: String
  }

  /**
   * Trait for case classes with generated companion objects.
   * @group trait
   */
  trait HasAvroAnnotation

  /** Generate [[org.apache.avro.Schema Schema]] for a case class. */
  def schemaOf[T: TypeTag]: Schema = SchemaProvider.schemaOf[T]

  /**
   * Generate a converter function from [[org.apache.avro.generic.GenericRecord GenericRecord]] to
   * the given case class `T`.
   * @group converters
   */
  def fromGenericRecord[T]: GenericRecord => T =
    macro ConverterProvider.fromGenericRecordImpl[T]

  /**
   * Generate a converter function from the given case class `T` to
   * [[org.apache.avro.generic.GenericRecord GenericRecord]].
   * @group converters
   */
  def toGenericRecord[T]: T => GenericRecord =
    macro ConverterProvider.toGenericRecordImpl[T]

  /** Create a new AvroType instance. */
  def apply[T: TypeTag]: AvroType[T] = new AvroType[T]
}

/**
 * Type class for case class `T` annotated for Avro IO.
 *
 * This decouples generated fields and methods from macro expansion to keep core macro free.
 */
class AvroType[T: TypeTag] extends Serializable {
  private val instance = runtimeMirror(getClass.getClassLoader)
    .reflectModule(typeOf[T].typeSymbol.companion.asModule)
    .instance

  private def getField(key: String) =
    instance.getClass.getMethod(key).invoke(instance)

  /** GenericRecord to `T` converter. */
  def fromGenericRecord: GenericRecord => T =
    getField("fromGenericRecord").asInstanceOf[GenericRecord => T]

  /** `T` to GenericRecord converter. */
  def toGenericRecord: T => GenericRecord =
    getField("toGenericRecord").asInstanceOf[T => GenericRecord]

  /** Schema of `T`. */
  def schema: Schema =
    getField("schema").asInstanceOf[Schema]
}


text:
from nova.objects import base
from nova.objects import fields

# TODO(berrange): Remove NovaObjectDictCompat
@base.NovaObjectRegistry.register
class HVSpec(base.NovaObject,
             base.NovaObjectDictCompat):
    # Version 1.0: Initial version
    VERSION = '1.0'

    fields = {
        'arch': fields.ArchitectureField(),
        'hv_type': fields.HVTypeField(),
        'vm_mode': fields.VMModeField(),
        }

    # NOTE(pmurray): for backward compatibility, the supported instance
    # data is stored in the database as a list.
    @classmethod
    def from_list(cls, data):
        return cls(arch=data[0],
                   hv_type=data[1],
                   vm_mode=data[2])

    def to_list(self):
        return [self.arch, self.hv_type, self.vm_mode]


text:
<?php

declare(strict_types=1);

namespace Bluz\EventManager;

/**
 * Representation of an event
 *
 * @package  Bluz\EventManager
 */
class Event
{
    /**
     * @var string event name
     */
    protected $name;

    /**
     * @var string|object the event target
     */
    protected $target;

    /**
     * @var array|object the event parameters
     */
    protected $params = [];

    /**
     * Constructor
     *
     * Accept a target and its parameters.
     *
     * @param  string $name Event name
     * @param  string|object $target
     * @param  array|object  $params
     *
     * @throws EventException
     */
    public function __construct(string $name, $target = null, $params = null)
    {
        $this->setName($name);

        if (null !== $target) {
            $this->setTarget($target);
        }

        if (null !== $params) {
            $this->setParams($params);
        }
    }

    /**
     * Get event name
     *
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * Get the event target
     *
     * This may be either an object, or the name of a static method.
     *
     * @return string|object
     */
    public function getTarget()
    {
        return $this->target;
    }

    /**
     * Overwrites parameters
     *
     * @param  array|object $params
     *
     * @return void
     * @throws EventException
     */
    public function setParams($params): void
    {
        if (!is_array($params) && !is_object($params)) {
            throw new EventException(
                'Event parameters must be an array or object; received `' . gettype($params) . '`'
            );
        }

        $this->params = $params;
    }

    /**
     * Get all parameters
     *
     * @return array|object
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * Get an individual parameter
     *
     * If the parameter does not exist, the $default value will be returned.
     *
     * @param  string|int $name
     * @param  mixed      $default
     *
     * @return mixed
     */
    public function getParam($name, $default = null)
    {
        if (is_array($this->params)) {
            // Check in params that are arrays or implement array access
            return $this->params[$name] ?? $default;
        } elseif (is_object($this->params)) {
            // Check in normal objects
            return $this->params->{$name} ?? $default;
        } else {
            // Wrong type, return default value
            return $default;
        }
    }

    /**
     * Set the event name
     *
     * @param string $name
     *
     * @return void
     */
    public function setName(string $name): void
    {
        $this->name = $name;
    }

    /**
     * Set the event target/context
     *
     * @param  null|string|object $target
     *
     * @return void
     */
    public function setTarget($target): void
    {
        $this->target = $target;
    }

    /**
     * Set an individual parameter to a value
     *
     * @param  string|int $name
     * @param  mixed      $value
     *
     * @return void
     */
    public function setParam($name, $value): void
    {
        if (is_array($this->params)) {
            // Arrays or objects implementing array access
            $this->params[$name] = $value;
        } else {
            // Objects
            $this->params->{$name} = $value;
        }
    }
}


text:
<?php

namespace Zenify\CodingStandard\Tests\Exception;

use Exception;

final class StandardRulesetNotFoundException extends Exception
{

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/DynamoDBBatchWriteItemResponseUnmarshaller.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/DynamoDBBatchWriteItemResponseUnmarshaller</TokenIdentifier>
			<Abstract type="html">Batch Write Item Result Unmarshaller</Abstract>
			<DeclaredIn>DynamoDBBatchWriteItemResponseUnmarshaller.h</DeclaredIn>

			<NodeRef refid="265"/>
		</Token>

	</File>
</Tokens>


text:
/* @internal */
namespace ts.codefix {
    const fixId = "fixAwaitInSyncFunction";
    const errorCodes = [
        Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
        Diagnostics.for_await_loops_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules.code,
    ];
    registerCodeFix({
        errorCodes,
        getCodeActions(context) {
            const { sourceFile, span } = context;
            const nodes = getNodes(sourceFile, span.start);
            if (!nodes) return undefined;
            const changes = textChanges.ChangeTracker.with(context, t => doChange(t, sourceFile, nodes));
            return [createCodeFixAction(fixId, changes, Diagnostics.Add_async_modifier_to_containing_function, fixId, Diagnostics.Add_all_missing_async_modifiers)];
        },
        fixIds: [fixId],
        getAllCodeActions: context => {
            const seen = new Map<number, true>();
            return codeFixAll(context, errorCodes, (changes, diag) => {
                const nodes = getNodes(diag.file, diag.start);
                if (!nodes || !addToSeen(seen, getNodeId(nodes.insertBefore))) return;
                doChange(changes, context.sourceFile, nodes);
            });
        },
    });

    function getReturnType(expr: FunctionDeclaration | MethodDeclaration | FunctionExpression | ArrowFunction) {
        if (expr.type) {
            return expr.type;
        }
        if (isVariableDeclaration(expr.parent) &&
            expr.parent.type &&
            isFunctionTypeNode(expr.parent.type)) {
            return expr.parent.type.type;
        }
    }

    function getNodes(sourceFile: SourceFile, start: number): { insertBefore: Node, returnType: TypeNode | undefined } | undefined {
        const token = getTokenAtPosition(sourceFile, start);
        const containingFunction = getContainingFunction(token);
        if (!containingFunction) {
            return;
        }

        let insertBefore: Node | undefined;
        switch (containingFunction.kind) {
            case SyntaxKind.MethodDeclaration:
                insertBefore = containingFunction.name;
                break;
            case SyntaxKind.FunctionDeclaration:
            case SyntaxKind.FunctionExpression:
                insertBefore = findChildOfKind(containingFunction, SyntaxKind.FunctionKeyword, sourceFile);
                break;
            case SyntaxKind.ArrowFunction:
                insertBefore = findChildOfKind(containingFunction, SyntaxKind.OpenParenToken, sourceFile) || first(containingFunction.parameters);
                break;
            default:
                return;
        }

        return insertBefore && {
            insertBefore,
            returnType: getReturnType(containingFunction)
        };
    }

    function doChange(
        changes: textChanges.ChangeTracker,
        sourceFile: SourceFile,
        { insertBefore, returnType }: { insertBefore: Node, returnType: TypeNode | undefined }): void {

        if (returnType) {
            const entityName = getEntityNameFromTypeNode(returnType);
            if (!entityName || entityName.kind !== SyntaxKind.Identifier || entityName.text !== "Promise") {
                changes.replaceNode(sourceFile, returnType, factory.createTypeReferenceNode("Promise", factory.createNodeArray([returnType])));
            }
        }
        changes.insertModifierBefore(sourceFile, SyntaxKind.AsyncKeyword, insertBefore);
    }
}


text:
package com.cezarykluczynski.stapi.etl.template.species.processor;

import com.cezarykluczynski.stapi.etl.common.dto.EnrichablePair;
import com.cezarykluczynski.stapi.etl.common.service.PageBindingService;
import com.cezarykluczynski.stapi.etl.species.creation.service.SpeciesPageFilter;
import com.cezarykluczynski.stapi.etl.template.service.TemplateFinder;
import com.cezarykluczynski.stapi.etl.template.species.dto.SpeciesTemplate;
import com.cezarykluczynski.stapi.etl.util.TitleUtil;
import com.cezarykluczynski.stapi.sources.mediawiki.dto.Page;
import com.cezarykluczynski.stapi.sources.mediawiki.dto.Template;
import com.cezarykluczynski.stapi.util.constant.TemplateTitle;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class SpeciesTemplatePageProcessor implements ItemProcessor<Page, SpeciesTemplate> {

	private final SpeciesPageFilter speciesPageFilter;

	private final PageBindingService pageBindingService;

	private final TemplateFinder templateFinder;

	private final SpeciesTemplatePartsEnrichingProcessor speciesTemplatePartsEnrichingProcessor;

	private final SpeciesTemplateTypeEnrichingProcessor speciesTemplateTypeEnrichingProcessor;

	public SpeciesTemplatePageProcessor(SpeciesPageFilter speciesPageFilter, PageBindingService pageBindingService,
			TemplateFinder templateFinder, SpeciesTemplatePartsEnrichingProcessor speciesTemplatePartsEnrichingProcessor,
			SpeciesTemplateTypeEnrichingProcessor speciesTemplateTypeEnrichingProcessor) {
		this.speciesPageFilter = speciesPageFilter;
		this.pageBindingService = pageBindingService;
		this.templateFinder = templateFinder;
		this.speciesTemplatePartsEnrichingProcessor = speciesTemplatePartsEnrichingProcessor;
		this.speciesTemplateTypeEnrichingProcessor = speciesTemplateTypeEnrichingProcessor;
	}

	@Override
	public SpeciesTemplate process(Page item) throws Exception {
		if (speciesPageFilter.shouldBeFilteredOut(item)) {
			return null;
		}

		SpeciesTemplate speciesTemplate = new SpeciesTemplate();

		speciesTemplate.setName(TitleUtil.getNameFromTitle(item.getTitle()));
		speciesTemplate.setPage(pageBindingService.fromPageToPageEntity(item));

		speciesTemplateTypeEnrichingProcessor.enrich(EnrichablePair.of(item, speciesTemplate));

		Optional<Template> templateOptional = templateFinder.findTemplate(item, TemplateTitle.SIDEBAR_SPECIES);

		if (templateOptional.isPresent()) {
			speciesTemplatePartsEnrichingProcessor.enrich(EnrichablePair.of(templateOptional.get().getParts(), speciesTemplate));
		}

		return speciesTemplate;
	}

}


text:
namespace instance_id {
class InstanceIDDriver;
}

namespace device {
namespace cablev2 {
namespace authenticator {

// Registration represents a subscription to events from the tunnel service.
class Registration {
 public:
  // Type enumerates the types of registrations that are maintained.
  enum class Type : uint8_t {
    // LINKING is for link information shared with desktops after scanning a QR
    // code. If the user chooses to unlink devices then this registration can be
    // rotated by calling |RotateContactID|. That will cause the server to
    // inform clients that the registration is no longer valid and that they
    // should forget about it.
    LINKING = 0,
    // SYNC is for information shared via the Sync service. This is separate so
    // that unlinking devices doesn't break sync peers.
    SYNC = 1,
  };

  // An Event contains the information sent by the tunnel service when a peer is
  // trying to connect.
  struct Event {
    Event();
    ~Event();
    Event(const Event&) = delete;
    Event& operator=(const Event&) = delete;

    // Serialize returns a serialized form of the |Event|. This format is
    // not stable and is suitable only for transient storage.
    absl::optional<std::vector<uint8_t>> Serialize();

    // FromSerialized parses the bytes produced by |Serialize|. It assumes that
    // the input is well formed. It returns |nullptr| on error.
    static std::unique_ptr<Event> FromSerialized(base::span<const uint8_t> in);

    Type source;
    FidoRequestType request_type;
    std::array<uint8_t, kTunnelIdSize> tunnel_id;
    std::array<uint8_t, kRoutingIdSize> routing_id;
    std::array<uint8_t, kPairingIDSize> pairing_id;
    std::array<uint8_t, kClientNonceSize> client_nonce;
    absl::optional<std::vector<uint8_t>> contact_id;

    // protocol_revision can be optionally asserted while we transition from
    // revision zero to revision one. This might be removed in the future.
    unsigned protocol_revision = 0;
  };

  virtual ~Registration();

  // PrepareContactID indicates that |contact_id| will soon be called. In order
  // to save resources for the case when |contact_id| is never used,
  // registration will be deferred until this is called.
  virtual void PrepareContactID() = 0;

  // RotateContactID invalidates the current contact ID and prepares a fresh
  // one.
  virtual void RotateContactID() = 0;

  // contact_id returns an opaque token that may be placed in pairing data for
  // desktops to later connect to. |nullopt| will be returned if the value is
  // not yet ready.
  virtual absl::optional<std::vector<uint8_t>> contact_id() const = 0;
};

// Register subscribes to the tunnel service and returns a |Registration|. This
// should only be called once in an address space. Subsequent calls may CHECK.
// The |event_callback| is called, on the same thread, whenever a paired device
// requests a tunnel.
std::unique_ptr<Registration> Register(
    instance_id::InstanceIDDriver* instance_id_driver,
    Registration::Type type,
    base::OnceCallback<void()> on_ready,
    base::RepeatingCallback<void(std::unique_ptr<Registration::Event>)>
        event_callback);

}  // namespace authenticator
}  // namespace cablev2
}  // namespace device

#endif  // DEVICE_FIDO_CABLE_V2_REGISTRATION_H_


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" href="../../favicon.ico">

    <title>30 Days of programming Challenge</title>

	<link rel="stylesheet" href="{{site.baseurl}}/css/reset.css">

	<link href="{{site.baseurl}}/css/bootstrap.min.css" rel="stylesheet">

	<link href="{{site.baseurl}}/css/main.css" rel="stylesheet">

	{% include nav.html navclass='top' %}

    	{{ content }}

© Renato Francia 2017


text:
Write-Host "Running health_check hook: {{pkg.ident}}"
Start-Sleep 2
Write-Host "health_check finished!"


text:
<?php

final class Lisphp_Runtime_List_SetAt extends Lisphp_Runtime_BuiltinFunction
{
    protected function execute(array $arguments)
    {
        list($list, $offset) = $arguments;
        $list = array_shift($arguments);
        if (count($arguments) < 2) {
            $list[] = $value = array_shift($arguments);
        } else {
            list($key, $value) = $arguments;
            $list[$key] = $value;
        }

        return $value;
    }
}


text:
import json
import csv
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(base_dir)

def read_csv(file_name):
    data = []
    with open(file_name, 'r') as input_file:
        reader = csv.reader(input_file)
        for i, row in enumerate(reader):
            if(i != 1 and i != 2):
                data.append(row)
    return data[0] if len(data) == 1 else data

def write_json(file_name, content):
    with open(file_name, 'w') as output_file:
        json.dump(content, output_file)

import sys

output = {}
data = read_csv(sys.argv[1])
for i in range(1, len(data)):
    output[data[i][4]] = {}
    for j in range(0, len(data[i])):
        output[data[i][4]][data[0][j]] = data[i][j]
write_json('./data/river.json', output)


text:
<?php

namespace Urodoz\Bundle\CacheBundle\Service\Store;

class MemcacheConfigurationStore extends AbstractConfigurationStore
{

}


text:
"use strict";Object.defineProperty(exports, "__esModule", { value: true });

class ExpectationFailed extends Error {}exports.default = ExpectationFailed;


text:
class CreateMares < ActiveRecord::Migration
  def change
    create_table :mares do |t|
      t.string :name
      t.text :description
      t.string :image

      t.timestamps null: false
    end
  end
end