text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

// GTK headers
#include <gtk/gtk.h>

// Linux headers
#include <fcntl.h>
#include <unistd.h>
#include <dlfcn.h>

// Mozilla headers
#include "nsIFile.h"
#include "nsINIParser.h"
#include "nsXPCOMGlue.h"
#include "nsXPCOMPrivate.h"              // for MAXPATHLEN and XPCOM_DLL
#include "nsXULAppAPI.h"
#include "BinaryPath.h"

const char kAPP_INI[] = "application.ini";
const char kWEBAPP_INI[] = "webapp.ini";
const char kWEBAPP_JSON[] = "webapp.json";
const char kWEBAPPRT_INI[] = "webapprt.ini";
const char kWEBAPPRT_PATH[] = "webapprt";
const char kAPP_ENV_VAR[] = "XUL_APP_FILE";
const char kAPP_RT[] = "webapprt-stub";

int* pargc;
char*** pargv;
char profile[MAXPATHLEN];
bool isProfileOverridden = false;

XRE_GetFileFromPathType XRE_GetFileFromPath;
XRE_CreateAppDataType XRE_CreateAppData;
XRE_FreeAppDataType XRE_FreeAppData;
XRE_mainType XRE_main;

const nsDynamicFunctionLoad kXULFuncs[] = {
  { "XRE_GetFileFromPath", (NSFuncPtr*) &XRE_GetFileFromPath },
  { "XRE_CreateAppData", (NSFuncPtr*) &XRE_CreateAppData },
  { "XRE_FreeAppData", (NSFuncPtr*) &XRE_FreeAppData },
  { "XRE_main", (NSFuncPtr*) &XRE_main },
  { nullptr, nullptr }
};

class ScopedLogging
{
  public:
    ScopedLogging() { NS_LogInit(); }
    ~ScopedLogging() { NS_LogTerm(); }
};

// Copied from toolkit/xre/nsAppData.cpp.
void SetAllocatedString(const char *&str, const char *newvalue)
{
  NS_Free(const_cast<char*>(str));
  if (newvalue) {
    str = NS_strdup(newvalue);
  }
  else {
    str = nullptr;
  }
}

// Function to open a dialog box displaying the message provided
void ErrorDialog(const char* message)
{
  gtk_init(pargc, pargv);

  GtkWidget* dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", message);
  gtk_dialog_run(GTK_DIALOG(dialog));
  gtk_widget_destroy(dialog);
}

// Function to get the parent dir of a file
void GetDirFromPath(char* parentDir, char* filePath)
{
  char* base = strrchr(filePath, '/');

  if (!base) {
    strcpy(parentDir, ".");
  }
  else {
    while (base > filePath && *base == '/')
      base--;

    int len = 1 + base - filePath;
    strncpy(parentDir, filePath, len);
    parentDir[len] = '\0';
  }
}

bool CopyFile(const char* inputFile, const char* outputFile)
{
  // Open input file
  int inputFD = open(inputFile, O_RDONLY);
  if (!inputFD)
    return false;

  // Open output file
  int outputFD = creat(outputFile, S_IRWXU);
  if (!outputFD)
    return false;

  // Copy file
  char buf[BUFSIZ];
  ssize_t bytesRead;

  while ((bytesRead = read(inputFD, buf, BUFSIZ)) > 0) {
    ssize_t bytesWritten = write(outputFD, buf, bytesRead);
    if (bytesWritten < 0) {
      bytesRead = -1;
      break;
    }
  }

  // Close file descriptors
  close(inputFD);
  close(outputFD);

  return (bytesRead >= 0);
}

bool GRELoadAndLaunch(const char* firefoxDir)
{
  char xpcomDllPath[MAXPATHLEN];
  snprintf(xpcomDllPath, MAXPATHLEN, "%s/%s", firefoxDir, XPCOM_DLL);

  if (NS_FAILED(XPCOMGlueStartup(xpcomDllPath))) {
    ErrorDialog("Couldn't load the XPCOM library");
    return false;
  }

  if (NS_FAILED(XPCOMGlueLoadXULFunctions(kXULFuncs))) {
    ErrorDialog("Couldn't load libxul");
    return false;
  }

  // NOTE: The GRE has successfully loaded, so we can use XPCOM now
  { // Scope for any XPCOM stuff we create
    ScopedLogging log;

    // Get the path to the runtime
    char rtPath[MAXPATHLEN];
    snprintf(rtPath, MAXPATHLEN, "%s/%s", firefoxDir, kWEBAPPRT_PATH);

    // Get the path to the runtime's INI file
    char rtIniPath[MAXPATHLEN];
    snprintf(rtIniPath, MAXPATHLEN, "%s/%s", rtPath, kWEBAPPRT_INI);

    // Load the runtime's INI from its path
    nsCOMPtr<nsIFile> rtINI;
    if (NS_FAILED(XRE_GetFileFromPath(rtIniPath, getter_AddRefs(rtINI)))) {
      ErrorDialog("Couldn't load the runtime INI");
      return false;
    }

    bool exists;
    nsresult rv = rtINI->Exists(&exists);
    if (NS_FAILED(rv) || !exists) {
      ErrorDialog("The runtime INI doesn't exist");
      return false;
    }

    nsXREAppData *webShellAppData;
    if (NS_FAILED(XRE_CreateAppData(rtINI, &webShellAppData))) {
      ErrorDialog("Couldn't read WebappRT application.ini");
      return false;
    }

    if (!isProfileOverridden) {
      SetAllocatedString(webShellAppData->profile, profile);
      // nsXREAppData::name is used for the class name part of the WM_CLASS
      // property. Set it so that the DE can match our window to the correct
      // launcher.
      char programClass[MAXPATHLEN];
      snprintf(programClass, MAXPATHLEN, "owa-%s", profile);
      SetAllocatedString(webShellAppData->name, programClass);
    }

    nsCOMPtr<nsIFile> directory;
    if (NS_FAILED(XRE_GetFileFromPath(rtPath, getter_AddRefs(directory)))) {
      ErrorDialog("Couldn't open runtime directory");
      return false;
    }

    nsCOMPtr<nsIFile> xreDir;
    if (NS_FAILED(XRE_GetFileFromPath(firefoxDir, getter_AddRefs(xreDir)))) {
      ErrorDialog("Couldn't open XRE directory");
      return false;
    }

    xreDir.forget(&webShellAppData->xreDirectory);
    NS_IF_RELEASE(webShellAppData->directory);
    directory.forget(&webShellAppData->directory);

    XRE_main(*pargc, *pargv, webShellAppData, 0);

    XRE_FreeAppData(webShellAppData);
  }

  return true;
}

void CopyAndRelaunch(const char* firefoxDir, const char* curExePath)
{
  char newExePath[MAXPATHLEN];
  snprintf(newExePath, MAXPATHLEN, "%s/%s", firefoxDir, kAPP_RT);

  if (unlink(curExePath) == -1) {
    ErrorDialog("Couldn't remove the old webapprt-stub executable");
    return;
  }

  if (!CopyFile(newExePath, curExePath)) {
    ErrorDialog("Couldn't copy the new webapprt-stub executable");
    return;
  }

  execv(curExePath, *pargv);

  ErrorDialog("Couldn't execute the new webapprt-stub executable");
}

void RemoveApplication(nsINIParser& parser, const char* curExeDir, const char* profile)  {
  if (!isProfileOverridden) {
    // Remove the desktop entry file.
    char desktopEntryFilePath[MAXPATHLEN];

    char* dataDir = getenv("XDG_DATA_HOME");

    if (dataDir && *dataDir) {
      snprintf(desktopEntryFilePath, MAXPATHLEN, "%s/applications/owa-%s.desktop", dataDir, profile);
    } else {
      char* home = getenv("HOME");
      snprintf(desktopEntryFilePath, MAXPATHLEN, "%s/.local/share/applications/owa-%s.desktop", home, profile);
    }

    unlink(desktopEntryFilePath);
  }

  // Remove the files from the installation directory.
  char webAppIniPath[MAXPATHLEN];
  snprintf(webAppIniPath, MAXPATHLEN, "%s/%s", curExeDir, kWEBAPP_INI);
  unlink(webAppIniPath);

  char curExePath[MAXPATHLEN];
  snprintf(curExePath, MAXPATHLEN, "%s/%s", curExeDir, kAPP_RT);
  unlink(curExePath);

  char webAppJsonPath[MAXPATHLEN];
  snprintf(webAppJsonPath, MAXPATHLEN, "%s/%s", curExeDir, kWEBAPP_JSON);
  unlink(webAppJsonPath);

  char iconPath[MAXPATHLEN];
  snprintf(iconPath, MAXPATHLEN, "%s/icon.png", curExeDir);
  unlink(iconPath);

  char appName[MAXPATHLEN];
  if (NS_FAILED(parser.GetString("Webapp", "Name", appName, MAXPATHLEN))) {
    strcpy(appName, profile);
  }

  char uninstallMsg[MAXPATHLEN];
  if (NS_SUCCEEDED(parser.GetString("Webapp", "UninstallMsg", uninstallMsg, MAXPATHLEN))) {
    /**
     * The only difference between libnotify.so.4 and libnotify.so.1 for these symbols
     * is that notify_notification_new takes three arguments in libnotify.so.4 and
     * four in libnotify.so.1.
     * Passing the fourth argument as NULL is binary compatible.
     */
    typedef void  (*notify_init_t)(const char*);
    typedef void* (*notify_notification_new_t)(const char*, const char*, const char*, const char*);
    typedef void  (*notify_notification_show_t)(void*, void**);

    void *handle = dlopen("libnotify.so.4", RTLD_LAZY);
    if (!handle) {
      handle = dlopen("libnotify.so.1", RTLD_LAZY);
      if (!handle)
        return;
    }

    notify_init_t nn_init = (notify_init_t)(uintptr_t)dlsym(handle, "notify_init");
    notify_notification_new_t nn_new = (notify_notification_new_t)(uintptr_t)dlsym(handle, "notify_notification_new");
    notify_notification_show_t nn_show = (notify_notification_show_t)(uintptr_t)dlsym(handle, "notify_notification_show");
    if (!nn_init || !nn_new || !nn_show) {
      dlclose(handle);
      return;
    }

    nn_init(appName);

    void* n = nn_new(uninstallMsg, NULL, "dialog-information", NULL);

    nn_show(n, NULL);

    dlclose(handle);
  }
}

int main(int argc, char *argv[])
{
  pargc = &argc;
  pargv = &argv;

  // Get current executable path
  char curExePath[MAXPATHLEN];
  if (NS_FAILED(mozilla::BinaryPath::Get(argv[0], curExePath))) {
    ErrorDialog("Couldn't read current executable path");
    return 255;
  }
  char curExeDir[MAXPATHLEN];
  GetDirFromPath(curExeDir, curExePath);

  bool removeApp = false;
  for (int i = 1; i < argc; i++) {
    if (!strcmp(argv[i], "-profile")) {
      isProfileOverridden = true;
    }
    else if (!strcmp(argv[i], "-remove")) {
      removeApp = true;
    }
  }

  char firefoxDir[MAXPATHLEN];

  // Check if Firefox is in the ../../dist/bin directory (relative to the webapp runtime)
  // This is the case for webapprt chrome and content tests.
  snprintf(firefoxDir, MAXPATHLEN, "%s/../../dist/bin", curExeDir);
  if (access(firefoxDir, F_OK) != -1) {
    if (GRELoadAndLaunch(firefoxDir))
      return 0;

    return 255;
  }

  // Set up webAppIniPath with path to webapp.ini
  char webAppIniPath[MAXPATHLEN];
  snprintf(webAppIniPath, MAXPATHLEN, "%s/%s", curExeDir, kWEBAPP_INI);

  // Open webapp.ini as an INI file
  nsINIParser parser;
  if (NS_FAILED(parser.Init(webAppIniPath))) {
    ErrorDialog("Couldn't open webapp.ini");
    return 255;
  }

  // Set up our environment to know where webapp.ini was loaded from
  if (setenv(kAPP_ENV_VAR, webAppIniPath, 1) == -1) {
    ErrorDialog("Couldn't set up app environment");
    return 255;
  }

  // Get profile dir from webapp.ini
  if (NS_FAILED(parser.GetString("Webapp", "Profile", profile, MAXPATHLEN))) {
    ErrorDialog("Couldn't retrieve profile from web app INI file");
    return 255;
  }

  if (removeApp) {
    RemoveApplication(parser, curExeDir, profile);
    return 0;
  }

  // Get the location of Firefox from our webapp.ini
  if (NS_FAILED(parser.GetString("WebappRT", "InstallDir", firefoxDir, MAXPATHLEN))) {
    ErrorDialog("Couldn't find your Firefox install directory.");
    return 255;
  }

  // Set up appIniPath with path to application.ini.
  // This is in the Firefox installation directory.
  char appIniPath[MAXPATHLEN];
  snprintf(appIniPath, MAXPATHLEN, "%s/%s", firefoxDir, kAPP_INI);

  if (NS_FAILED(parser.Init(appIniPath))) {
    ErrorDialog("This app requires that Firefox version 16 or above is installed."
                " Firefox 16+ has not been detected.");
    return 255;
  }

  // Get buildid of Firefox we're trying to load (MAXPATHLEN only for convenience)
  char buildid[MAXPATHLEN];
  if (NS_FAILED(parser.GetString("App", "BuildID", buildid, MAXPATHLEN))) {
    ErrorDialog("Couldn't read BuildID from Firefox application.ini");
    return 255;
  }

  // If WebAppRT version == Firefox version, load XUL and execute the application
  if (!strcmp(buildid, NS_STRINGIFY(GRE_BUILDID))) {
    if (GRELoadAndLaunch(firefoxDir))
      return 0;
  }
  // Else, copy WebAppRT from Firefox installation and re-execute the process
  else
    CopyAndRelaunch(firefoxDir, curExePath);

  return 255;
}


text:
FOUNDATION_EXPORT double Pods_RealmCrustTestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_RealmCrustTestsVersionString[];

redpajama_set_name: RedPajamaGithub


text:
var collectContentPre = function(hook, context){
  var cls = context.cls;
  var tname = context.tname;
  var state = context.state;
  var lineAttributes = state.lineAttributes

  var tagIndex = cls.indexOf("tasklist-not-done");
  if(tagIndex === 0){
    lineAttributes['tasklist-not-done'] = tags[tagIndex];
  }

  var tagIndex = cls.indexOf("tasklist-done");
  if(tagIndex !== -1){
    lineAttributes['tasklist-done'] = 'tasklist-done';
  }

  if(tname === "div" || tname === "p"){
    delete lineAttributes['tasklist-done'];
    delete lineAttributes['tasklist-not-done'];
  }

};

var collectContentPost = function(hook, context){
  var cls = context.cls;
  var tname = context.tname;
  var state = context.state;
  var lineAttributes = state.lineAttributes

  var tagIndex = cls.indexOf("tasklist-not-done");
  if(tagIndex >= 0){
    delete lineAttributes['tasklist-not-done'];
  }

  var tagIndex = cls.indexOf("tasklist-done");
  if(tagIndex >= 0){
    delete lineAttributes['tasklist-done'];
  }
};

exports.collectContentPre = collectContentPre;
exports.collectContentPost = collectContentPost;


text:
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import plotly

# main database
db = create_engine('sqlite:///data/processed.db')

# make selections for datasets
def select(name, rule):
    # get the list of initial data datasets
    ns = db.table_names()
    ns = [n for n in ns if rule(n)]
    # make the selection dictionary
    selections = {}
    if name:
        selections['current_dataset'] = name
        selections['remaining_datasets'] = [n for n in ns if n != name]
    else:
        selections['current_dataset'] = ns[-1]
        selections['remaining_datasets'] = ns[:-1]
    return selections

def select_init_data(name):
    rule = lambda n: n[:4] == 'dat_' and not n[-7:] == '_result'
    return select(name, rule)

def select_time_series(name):
    rule = lambda n: 'discrete_time_series_' in n
    return select(name, rule)

# wrapper for plotly.offline.plot so that it plots to a div element
def plot_to_div(*args, **kwargs):
    kwargs['output_type'] = 'div'
    kwargs['include_plotlyjs'] = False,
    kwargs['show_link'] = False
    return plotly.offline.plot(*args, **kwargs)

# get list of experiments and time series measurements
def get_runs_n_cols():
    ns = db.table_names()
    runs = [n for n in ns if n[:2] == 'C1']
    cols = pd.read_sql_table('time_series_params', db, index_col = 'index')['0'].tolist()
    print(cols)
    return {'runs': runs, 'cols': cols}


text:
/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#include "QCameraCaptureBufferFormatControlSlots.h"

QCameraCaptureBufferFormatControlSlots::QCameraCaptureBufferFormatControlSlots( QObject *parent ) : QObject( parent )
{
}

QCameraCaptureBufferFormatControlSlots::~QCameraCaptureBufferFormatControlSlots()
{
}

void QCameraCaptureBufferFormatControlSlots::bufferFormatChanged( QVideoFrame::PixelFormat format )
{
  QObject *object = qobject_cast<QObject *>(sender());

  PHB_ITEM cb = Qt5xHb::Signals_return_codeblock( object, "bufferFormatChanged(QVideoFrame::PixelFormat)" );

  if( cb )
  {
    PHB_ITEM psender = Qt5xHb::Signals_return_qobject( (QObject *) object, "QCAMERACAPTUREBUFFERFORMATCONTROL" );
    PHB_ITEM pformat = hb_itemPutNI( NULL, (int) format );

    hb_vmEvalBlockV( cb, 2, psender, pformat );

    hb_itemRelease( psender );
    hb_itemRelease( pformat );
  }
}

void QCameraCaptureBufferFormatControlSlots_connect_signal( const QString & signal, const QString & slot )
{
  QCameraCaptureBufferFormatControl * obj = (QCameraCaptureBufferFormatControl *) Qt5xHb::itemGetPtrStackSelfItem();

  if( obj )
  {
    QCameraCaptureBufferFormatControlSlots * s = QCoreApplication::instance()->findChild<QCameraCaptureBufferFormatControlSlots *>();

    if( s == NULL )
    {
      s = new QCameraCaptureBufferFormatControlSlots();
      s->moveToThread( QCoreApplication::instance()->thread() );
      s->setParent( QCoreApplication::instance() );
    }

    hb_retl( Qt5xHb::Signals_connection_disconnection( s, signal, slot ) );
  }
  else
  {
    hb_retl( false );
  }
}


text:
/*
 * MinIO Cloud Storage, (C) 2018 MinIO, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package policy

import (
	"encoding/json"
)

// Effect - policy statement effect Allow or Deny.
type Effect string

const (
	// Allow - allow effect.
	Allow Effect = "Allow"

	// Deny - deny effect.
	Deny = "Deny"
)

// IsAllowed - returns if given check is allowed or not.
func (effect Effect) IsAllowed(b bool) bool {
	if effect == Allow {
		return b
	}

	return !b
}

// IsValid - checks if Effect is valid or not
func (effect Effect) IsValid() bool {
	switch effect {
	case Allow, Deny:
		return true
	}

	return false
}

// MarshalJSON - encodes Effect to JSON data.
func (effect Effect) MarshalJSON() ([]byte, error) {
	if !effect.IsValid() {
		return nil, Errorf("invalid effect '%v'", effect)
	}

	return json.Marshal(string(effect))
}

// UnmarshalJSON - decodes JSON data to Effect.
func (effect *Effect) UnmarshalJSON(data []byte) error {
	var s string
	if err := json.Unmarshal(data, &s); err != nil {
		return err
	}

	e := Effect(s)
	if !e.IsValid() {
		return Errorf("invalid effect '%v'", s)
	}

	*effect = e

	return nil
}


text:
package eu.bcvsolutions.idm.core.model.event;

import java.io.Serializable;
import java.util.Map;

import eu.bcvsolutions.idm.core.api.event.CoreEvent;
import eu.bcvsolutions.idm.core.api.event.EventType;
import eu.bcvsolutions.idm.core.notification.api.dto.IdmNotificationTemplateDto;

/**
 * Events for notification templates
 *
 * @author Ondrej Husnik
 *
 */
public class NotificationTemplateEvent extends CoreEvent<IdmNotificationTemplateDto> {

	private static final long serialVersionUID = 1L;

	/**
	 * Supported core notification template events
	 *
	 */
	public enum NotificationTemplateEventType implements EventType {
		CREATE, UPDATE, DELETE
	}

	public NotificationTemplateEvent(NotificationTemplateEventType operation, IdmNotificationTemplateDto content) {
		super(operation, content);
	}

	public NotificationTemplateEvent(NotificationTemplateEventType operation, IdmNotificationTemplateDto content,
			Map<String, Serializable> properties) {
		super(operation, content, properties);
	}
}


text:
package git4idea.merge;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.VcsKey;
import com.intellij.openapi.vcs.update.FileGroup;
import com.intellij.openapi.vcs.update.UpdatedFiles;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import git4idea.GitRevisionNumber;
import git4idea.GitUtil;
import git4idea.GitVcs;
import git4idea.commands.GitCommand;
import git4idea.commands.GitSimpleHandler;
import git4idea.repo.GitRepository;
import git4idea.util.StringScanner;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.intellij.util.ObjectUtils.assertNotNull;

/**
 * Collect change for merge or pull operations
 */
public class MergeChangeCollector {
  private final HashSet<String> myUnmergedPaths = new HashSet<>();
  private final Project myProject;
  private final VirtualFile myRoot;
  private final GitRevisionNumber myStart; // Revision number before update (used for diff)
  @NotNull private final GitRepository myRepository;

  public MergeChangeCollector(final Project project, final VirtualFile root, final GitRevisionNumber start) {
    myStart = start;
    myProject = project;
    myRoot = root;
    myRepository = assertNotNull(GitUtil.getRepositoryManager(project).getRepositoryForRoot(root));
  }

  /**
   * Collects changed files during or after merge operation to the supplied {@code updates} container.
   */
  public void collect(final UpdatedFiles updates, List<VcsException> exceptions) {
    try {
      // collect unmerged
      Set<String> paths = getUnmergedPaths();
      addAll(updates, FileGroup.MERGED_WITH_CONFLICT_ID, paths);

      // collect other changes (ignoring unmerged)
      TreeSet<String> updated = new TreeSet<>();
      TreeSet<String> created = new TreeSet<>();
      TreeSet<String> removed = new TreeSet<>();

      String revisionsForDiff = getRevisionsForDiff();
      if (revisionsForDiff ==  null) {
        return;
      }
      getChangedFilesExceptUnmerged(updated, created, removed, revisionsForDiff);
      addAll(updates, FileGroup.UPDATED_ID, updated);
      addAll(updates, FileGroup.CREATED_ID, created);
      addAll(updates, FileGroup.REMOVED_FROM_REPOSITORY_ID, removed);
    } catch (VcsException e) {
      exceptions.add(e);
    }
  }

  /**
   * Returns absolute paths to files which are currently unmerged, and also populates myUnmergedPaths with relative paths.
   */
  public @NotNull Set<String> getUnmergedPaths() throws VcsException {
    String root = myRoot.getPath();
    final GitSimpleHandler h = new GitSimpleHandler(myProject, myRoot, GitCommand.LS_FILES);
    h.setSilent(true);
    h.addParameters("--unmerged");
    final String result = h.run();

    final Set<String> paths = new HashSet<>();
    for (StringScanner s = new StringScanner(result); s.hasMoreData();) {
      if (s.isEol()) {
        s.nextLine();
        continue;
      }
      s.boundedToken('\t');
      final String relative = s.line();
      if (!myUnmergedPaths.add(relative)) {
        continue;
      }
      String path = root + "/" + GitUtil.unescapePath(relative);
      paths.add(path);
    }
    return paths;
  }

  /**
   * @return The revision range which will be used to find merge diff (merge may be just finished, or in progress)
   * or null in case of error or inconsistency.
   */
  @Nullable
  public String getRevisionsForDiff() throws VcsException {
    String root = myRoot.getPath();
    GitRevisionNumber currentHead = GitRevisionNumber.resolve(myProject, myRoot, "HEAD");
    if (currentHead.equals(myStart)) {
      // The head has not advanced. This means that this is a merge that did not commit.
      // This could be caused by --no-commit option or by failed two-head merge. The MERGE_HEAD
      // should be available. In case of --no-commit option, the MERGE_HEAD might contain
      // multiple heads separated by newline. The changes are collected separately for each head
      // and they are merged using TreeSet class (that also sorts the changes).
      File mergeHeadsFile = myRepository.getRepositoryFiles().getMergeHeadFile();
      try {
        if (mergeHeadsFile.exists()) {
          String mergeHeads = new String(FileUtil.loadFileText(mergeHeadsFile, CharsetToolkit.UTF8));
          for (StringScanner s = new StringScanner(mergeHeads); s.hasMoreData();) {
            String head = s.line();
            if (head.length() == 0) {
              continue;
            }
            // note that "..." cause the diff to start from common parent between head and merge head
            return myStart.getRev() + "..." + head;
          }
        }
      } catch (IOException e) {
        //noinspection ThrowableInstanceNeverThrown
        throw new VcsException("Unable to read the file " + mergeHeadsFile + ": " + e.getMessage(), e);
      }
    } else {
      // Otherwise this is a merge that did created a commit. And because of this the incoming changes
      // are diffs between old head and new head. The commit could have been multihead commit,
      // and the expression below considers it as well.
      return myStart.getRev() + "..HEAD";
    }
    return null;
  }

  /**
   * Populates the supplied collections of modified, created and removed files returned by 'git diff #revisions' command,
   * where revisions is the range of revisions to check.
   */
  public void getChangedFilesExceptUnmerged(Collection<String> updated, Collection<String> created, Collection<String> removed, String revisions)
    throws VcsException {
    if (revisions == null) {
      return;
    }
    String root = myRoot.getPath();
    GitSimpleHandler h = new GitSimpleHandler(myProject, myRoot, GitCommand.DIFF);
    h.setSilent(true);
    // note that moves are not detected here
    h.addParameters("--name-status", "--diff-filter=ADMRUX", "--no-renames", revisions);
    for (StringScanner s = new StringScanner(h.run()); s.hasMoreData();) {
      if (s.isEol()) {
        s.nextLine();
        continue;
      }
      char status = s.peek();
      s.boundedToken('\t');
      final String relative = s.line();
      // eliminate conflicts
      if (myUnmergedPaths.contains(relative)) {
        continue;
      }
      String path = root + "/" + GitUtil.unescapePath(relative);
      switch (status) {
        case 'M':
          updated.add(path);
          break;
        case 'A':
          created.add(path);
          break;
        case 'D':
          removed.add(path);
          break;
        default:
          throw new IllegalStateException("Unexpected status: " + status);
      }
    }
  }

  /**
   * Add all paths to the group
   */
  private static void addAll(final UpdatedFiles updates, String group_id, Set<String> paths) {
    FileGroup fileGroup = updates.getGroupById(group_id);
    final VcsKey vcsKey = GitVcs.getKey();
    for (String path : paths) {
      fileGroup.add(path, vcsKey, null);
    }
  }
}


text:
package org.apache.jackrabbit.oak.security.authorization.permission;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Root;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.plugins.tree.TreeUtil;
import org.apache.jackrabbit.oak.spi.security.authorization.permission.PermissionConstants;
import org.apache.jackrabbit.oak.spi.security.authorization.restriction.RestrictionProvider;
import org.apache.jackrabbit.oak.spi.security.privilege.JcrAllUtil;
import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeBits;
import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeBitsProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * {@code PermissionStoreImpl}...
 */
class PermissionStoreImpl implements PermissionStore, PermissionConstants {

    /**
     * default logger
     */
    private static final Logger log = LoggerFactory.getLogger(PermissionStoreImpl.class);

    private final String permissionRootName;

    private final RestrictionProvider restrictionProvider;

    private final Map<String, Tree> principalTreeMap = new HashMap<>();

    private Tree permissionsTree;
    private PrivilegeBitsProvider bitsProvider;

    PermissionStoreImpl(@NotNull Root root, @NotNull String permissionRootName, @NotNull RestrictionProvider restrictionProvider) {
        this.permissionRootName = permissionRootName;
        this.restrictionProvider = restrictionProvider;
        reset(root);
    }

    @Override
    public void flush(@NotNull Root root) {
        principalTreeMap.clear();
        reset(root);
    }

    private void reset(@NotNull Root root) {
        permissionsTree = PermissionUtil.getPermissionsRoot(root, permissionRootName);
        bitsProvider = new PrivilegeBitsProvider(root);
    }

    //----------------------------------------------------< PermissionStore >---
    @Nullable
    @Override
    public Collection<PermissionEntry> load(@NotNull String principalName, @NotNull String path) {
        Tree principalRoot = getPrincipalRoot(principalName);
        Collection<PermissionEntry> entries = null;
        if (principalRoot != null) {
            String name = PermissionUtil.getEntryName(path);
            if (principalRoot.hasChild(name)) {
                Tree child = principalRoot.getChild(name);
                if (PermissionUtil.checkACLPath(child, path)) {
                    entries = loadPermissionEntries(path, child);
                } else {
                    // check for child node : there may at most be one child for
                    // the given path.
                    for (Tree node : child.getChildren()) {
                        if (PermissionUtil.checkACLPath(node, path)) {
                            entries = loadPermissionEntries(path, node);
                            break;
                        }
                    }
                }
            }
        }
        return entries;
    }

    @NotNull
    @Override
    public NumEntries getNumEntries(@NotNull String principalName, long max) {
        Tree tree = getPrincipalRoot(principalName);
        if (tree == null) {
            return NumEntries.ZERO;
        } else {
            // if rep:numPermissions is present it contains the exact number of
            // access controlled nodes for the given principal name.
            // if this property is missing (backward compat) we use the old
            // mechanism and use child-cnt with a max value to get a rough idea
            // about the magnitude (note: this approximation ignores the hash-collisions)
            long l = TreeUtil.getLong(tree, REP_NUM_PERMISSIONS, -1);
            return (l >= 0) ? NumEntries.valueOf(l, true) : NumEntries.valueOf(tree.getChildrenCount(max), false);
        }
    }

    @Override
    @NotNull
    public PrincipalPermissionEntries load(@NotNull String principalName) {
        long t0 = System.nanoTime();
        PrincipalPermissionEntries ret = new PrincipalPermissionEntries();
        Tree principalRoot = getPrincipalRoot(principalName);
        if (principalRoot != null) {
            for (Tree entryTree : principalRoot.getChildren()) {
                loadPermissionEntries(entryTree, ret);
            }
        }
        ret.setFullyLoaded(true);
        long t1 = System.nanoTime();
        if (log.isDebugEnabled()) {
            log.debug(String.format("loaded %d entries in %.2fus for %s.%n", ret.getSize(), (t1 - t0) / 1000.0, principalName));
        }
        return ret;
    }

    //------------------------------------------------------------< private >---
    @Nullable
    private Tree getPrincipalRoot(@NotNull String principalName) {
        if (principalTreeMap.containsKey(principalName)) {
            return principalTreeMap.get(principalName);
        } else {
            Tree principalRoot = PermissionUtil.getPrincipalRoot(permissionsTree, principalName);
            if (!principalRoot.exists()) {
                principalRoot = null;
            }
            principalTreeMap.put(principalName, principalRoot);
            return principalRoot;
        }
    }

    private void loadPermissionEntries(@NotNull Tree tree,
                                       @NotNull PrincipalPermissionEntries principalPermissionEntries) {
        String path = TreeUtil.getString(tree, PermissionConstants.REP_ACCESS_CONTROLLED_PATH);
        if (path != null) {
            Collection<PermissionEntry> entries = principalPermissionEntries.getEntriesByPath(path);
            if (entries == null) {
                entries = new TreeSet<>();
                principalPermissionEntries.putEntriesByPath(path, entries);
            }
            for (Tree child : tree.getChildren()) {
                if (child.getName().charAt(0) == 'c') {
                    loadPermissionEntries(child, principalPermissionEntries);
                } else {
                    entries.add(createPermissionEntry(path, child));
                }
            }
        } else {
            log.error("Permission entry at '{}' without rep:accessControlledPath property.", tree.getPath());
        }
    }

    @NotNull
    private Collection<PermissionEntry> loadPermissionEntries(@NotNull String path,
                                                              @NotNull Tree tree) {
        Collection<PermissionEntry> ret = new TreeSet<>();
        for (Tree ace : tree.getChildren()) {
            if (ace.getName().charAt(0) != 'c') {
                ret.add(createPermissionEntry(path, ace));
            }
        }
        return ret;
    }

    @NotNull
    private PermissionEntry createPermissionEntry(@NotNull String path,
                                                  @NotNull Tree entryTree) {
        PropertyState ps = entryTree.getProperty(REP_PRIVILEGE_BITS);
        PrivilegeBits bits = JcrAllUtil.getPrivilegeBits(ps, bitsProvider);
        boolean isAllow = TreeUtil.getBoolean(entryTree, REP_IS_ALLOW);
        return new PermissionEntry(path,
                isAllow,
                Integer.parseInt(entryTree.getName()),
                bits,
                restrictionProvider.getPattern(path, entryTree));
    }
}


text:
import code
from typing import Dict

try:
    from IPython.terminal import embed
except ImportError:
    IPYTHON_SHELL_AVAILABLE = False
    embed = None
else:
    IPYTHON_SHELL_AVAILABLE = True

def start_shell(local_ns: Dict=None, banner: str=''):
    """Create and immediately drop into a Python shell.

    If IPython version 5 or greater is available it will be used instead
    of the built-in python shell.

    :param local_ns: An optional dict containing the global namespace of
                       the newly created shell.
    :param banner: An optional banner to render when terminal starts.
    """
    if IPYTHON_SHELL_AVAILABLE:
        # Don't try to stop IPython from displaying its banner, since
        # it's different in every major version
        terminal = embed.InteractiveShellEmbed(user_ns={})
        terminal.mainloop(local_ns=local_ns)
    else:
        code.interact(banner=banner, local=local_ns)


text:
namespace research_scann {
namespace asymmetric_hashing_internal {

void Avx512PlatformSpecificSwizzle(uint8_t* packed_dataset, int num_datapoints,
                                   int num_codes);

template <size_t kBatchSize, PrefetchStrategy kPrefetch>
class LUT16Avx512 {
 public:
  static SCANN_AVX512_OUTLINE void GetInt16Distances(LUT16Args<int16_t> args);
  static SCANN_AVX512_OUTLINE void GetInt32Distances(LUT16Args<int32_t> args);

  static SCANN_AVX512_OUTLINE void GetFloatDistances(
      LUT16Args<float> args, ConstSpan<float> inv_fp_multipliers);

  static void GetTopInt16Distances(LUT16ArgsTopN<int16_t> args);
  static void GetTopFloatDistances(LUT16ArgsTopN<float> args);
};

SCANN_INSTANTIATE_CLASS_FOR_LUT16_BATCH_SIZES(extern, LUT16Avx512);

}  // namespace asymmetric_hashing_internal
}  // namespace research_scann

#endif
#endif


text:
using System.Web.Mvc;

namespace ExampleWebApp.Controllers.Examples
{
    public class LoginController : Controller
    {
        // GET: Login
        public ActionResult Index()
        {
            return View("~/Views/Login.cshtml");
        }
    }
}


text:
package com.squarespace.less;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;

import org.testng.annotations.Test;

import com.squarespace.less.core.LessHarness;
import com.squarespace.less.core.LessTestBase;
import com.squarespace.less.model.BaseColor;
import com.squarespace.less.model.HSLColor;
import com.squarespace.less.model.RGBColor;
import com.squarespace.less.parse.Parselets;

public class ColorTest extends LessTestBase {

  @Test
  public void testColor() throws LessException {
    // Conversion of of certain keywords into colors during parse.
    LessHarness h = new LessHarness(Parselets.COLOR_KEYWORD);
    h.parseEquals("blue", rgb(0, 0, 255, 1.0, true));
    h.parseEquals("red", rgb(255, 0, 0, 1.0, true));
    h.parseEquals("black", rgb(0, 0, 0, 1.0, true));
    h.parseEquals("white", rgb(255, 255, 255, 1.0, true));

    h = new LessHarness(Parselets.COLOR);
    h.parseEquals("#fff", rgb(255, 255, 255));
    h.parseEquals("#000", rgb(0, 0, 0));
    h.parseEquals("#010203", rgb(1, 2, 3));
  }

  @Test
  public void testHex() {
    hexEquals("#48f", 0x44, 0x88, 0xff);
    hexEquals("#abc", 0xaa, 0xbb, 0xcc);
    hexEquals("#1278cd", 0x12, 0x78, 0xcd);
    hexEquals("#ff01fe", 0xff, 0x01, 0xfe);

    // bad hex chars
    hexEquals("#xyz", 0, 0, 0);
    hexEquals("#11zy22", 0x11, 0, 0x22);

    // varying number of leading '#' symbols, parse is tolerant
    hexEquals("010203", 0x01, 0x02, 0x03);
    hexEquals("###123", 0x11, 0x22, 0x33);
  }

  @Test
  public void testConversions() throws LessException {
    RGBColor rgb = rgb(200, 100, 50);
    HSLColor hsl = rgb.toHSL();
    assertEquals(hsl.toRGB(), rgb);

    rgb = rgb(32, 32, 32);
    hsl = rgb.toHSL();
    assertEquals(hsl.toRGB(), rgb);

    hsl = new HSLColor(.5, .5, .5);
    assertEquals(hsl.toRGB(), new RGBColor(64, 191, 191));
  }

  @Test
  public void testClamp() throws LessException {
    assertEquals(BaseColor.clamp(-1, 0, 1), 0.0);
    assertEquals(BaseColor.clamp(500, 0, 255), 255.0);
  }

  private void hexEquals(String hex, int red, int green, int blue) {
    RGBColor color = RGBColor.fromHex(hex);
    assertEquals(color.red(), red, "red component of " + hex);
    assertEquals(color.green(), green, "green component of " + hex);
    assertEquals(color.blue(), blue, "blue component of " + hex);
  }

  @Test
  public void testBadColors() {
    String[] badColors = new String[] {
      "@123", "", ".", "12", "1234", "12345"
    };
    for (String hex : badColors) {
      try {
        RGBColor.fromHex(hex);
        fail("Expected exception while parsing hex color '" + hex + "'");
      } catch (IllegalArgumentException e) {
        // fallthrough
      }
    }
  }

}


text:
import en from '../i18n/drs_en.json';
import it from '../i18n/drs_it.json';
import de from '../i18n/drs_de.json';
import fr from '../i18n/drs_fr.json';
import es from '../i18n/drs_es.json';
import ja from '../i18n/drs_ja.json';
import ptBr from '../i18n/drs_pt_BR.json';

function config($compileProvider, $locationProvider, $httpProvider, $translateProvider,
                $translateMessageFormatInterpolationProvider, localStorageServiceProvider, /* ngHttpRateLimiterConfigProvider */) {
  'ngInject';

  // Allow chrome-extension: URLs in ng-src
  $compileProvider.imgSrcSanitizationWhitelist(/^\s*((https?|chrome-extension):|data:image\/)/);

  $locationProvider.hashPrefix('');
  $locationProvider.html5Mode(true);

  $httpProvider.interceptors.push('ngHttpRateLimiterInterceptor');
  $httpProvider.useApplyAsync(true);

  // See https://angular-translate.github.io/docs/#/guide
  $translateProvider.useSanitizeValueStrategy('escape');
  $translateProvider.useMessageFormatInterpolation();
  $translateProvider.preferredLanguage('en');

  $translateMessageFormatInterpolationProvider.messageFormatConfigurer(function(mf) {
    mf.setIntlSupport(true);
  });

  $translateProvider
    .translations('en', en)
    .translations('it', it)
    .translations('de', de)
    .translations('fr', fr)
    .translations('es', es)
    .translations('ja', ja)
    .translations('pt-br', ptBr)
    .fallbackLanguage('en');

  localStorageServiceProvider.setPrefix('drs');

  // ngHttpRateLimiterConfigProvider.addLimiter(/www\.bungie\.net\/d1\/Platform\/Destiny\/Stats/, 1, 1100);
}

export default config;