text:
namespace v8_inspector {

namespace {

void clearContext(const v8::WeakCallbackInfo<v8::Global<v8::Context>>& data) {
  // Inspected context is created in V8InspectorImpl::contextCreated method
  // and destroyed in V8InspectorImpl::contextDestroyed.
  // Both methods takes valid v8::Local<v8::Context> handle to the same context,
  // it means that context is created before InspectedContext constructor and is
  // always destroyed after InspectedContext destructor therefore this callback
  // should be never called.
  // It's possible only if inspector client doesn't call contextDestroyed which
  // is considered an error.
  CHECK(false);
  data.GetParameter()->Reset();
}

}  // namespace

InspectedContext::InspectedContext(V8InspectorImpl* inspector,
                                   const V8ContextInfo& info, int contextId)
    : m_inspector(inspector),
      m_context(info.context->GetIsolate(), info.context),
      m_contextId(contextId),
      m_contextGroupId(info.contextGroupId),
      m_origin(toString16(info.origin)),
      m_humanReadableName(toString16(info.humanReadableName)),
      m_auxData(toString16(info.auxData)),
      m_reported(false) {
  v8::Isolate* isolate = m_inspector->isolate();
  info.context->SetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex),
                                v8::Int32::New(isolate, contextId));
  m_context.SetWeak(&m_context, &clearContext,
                    v8::WeakCallbackType::kParameter);

  v8::Local<v8::Object> global = info.context->Global();
  v8::Local<v8::Object> console =
      V8Console::createConsole(this, info.hasMemoryOnConsole);
  if (!global
           ->Set(info.context, toV8StringInternalized(isolate, "console"),
                 console)
           .FromMaybe(false))
    return;
  m_console.Reset(isolate, console);
  m_console.SetWeak();
}

InspectedContext::~InspectedContext() {
  if (!m_console.IsEmpty()) {
    v8::HandleScope scope(isolate());
    V8Console::clearInspectedContextIfNeeded(context(),
                                             m_console.Get(isolate()));
  }
}

// static
int InspectedContext::contextId(v8::Local<v8::Context> context) {
  v8::Local<v8::Value> data =
      context->GetEmbedderData(static_cast<int>(v8::Context::kDebugIdIndex));
  if (data.IsEmpty() || !data->IsInt32()) return 0;
  return static_cast<int>(data.As<v8::Int32>()->Value());
}

v8::Local<v8::Context> InspectedContext::context() const {
  return m_context.Get(isolate());
}

v8::Isolate* InspectedContext::isolate() const {
  return m_inspector->isolate();
}

bool InspectedContext::createInjectedScript() {
  DCHECK(!m_injectedScript);
  std::unique_ptr<InjectedScript> injectedScript = InjectedScript::create(this);
  // InjectedScript::create can destroy |this|.
  if (!injectedScript) return false;
  m_injectedScript = std::move(injectedScript);
  return true;
}

void InspectedContext::discardInjectedScript() { m_injectedScript.reset(); }

}  // namespace v8_inspector


text:
package org.md2k.datakit.cerebralcortex;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;

import org.md2k.datakit.R;

/**
 * Settings activity for CerebralCortex.
 */
public class ActivityCerebralCortexSettings extends AppCompatActivity {

    /**
     * Creates the activity.
     *
     * @param savedInstanceState Previous state of this activity, if it existed.
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        getFragmentManager().beginTransaction().replace(R.id.layout_preference_fragment,
                new PrefsFragmentCerebralCortexSettings()).commit();

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(true);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
     * Finishes the activity if the home button is pressed on the device.
     *
     * @param item Menu item that was selected.
     * @return Whether home or back was pressed.
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'ruby-prof/profile/exclude_common_methods'
require 'ruby-prof/profile/legacy_method_elimination'

module RubyProf
  class Profile
    include LegacyMethodElimination

    # Hides methods that, when represented as a call graph, have
    # extremely large in and out degrees and make navigation impossible.
    def exclude_common_methods!
      ExcludeCommonMethods.apply!(self)
    end

    def exclude_methods!(mod, *method_or_methods)
      [method_or_methods].flatten.each do |name|
        exclude_method!(mod, name)
      end
    end

    def exclude_singleton_methods!(mod, *method_or_methods)
      exclude_methods!(mod.singleton_class, *method_or_methods)
    end
  end
end


text:
import java.util.*;
import cards.*;
import cards.Hand.*;

class Player {
    private List<Card> hand = new ArrayList<Card>();
    private String name;
    private Hand handRank;

    public Player(String n) {
        name = n;
    }

    public void drawTwo(Deck d) {
        for (int i = 0; i < 2; i++) {
            hand.add(d.draw());
        }
    }

    public List<Card> getHand() {
        return hand;
    }

    public String getName() {
        return name;
    }

    public Hand getHandRank() {
        return handRank;
    }

    public void setHandRank(Hand h) {
        handRank = h;
    }

    public String toString() {
        return hand.toString();
    }
}

public class HoldEm {

    public static void main(String[] args) {
        Deck deck = new Deck();
        deck.shuffle();

        final int PLAYER_COUNT = 2;

        List<Card> community = new ArrayList<Card>();

        List<Player> players = new ArrayList<Player>();

        for (int i = 0; i < PLAYER_COUNT; i++) {
            players.add(new Player("Player " + (i + 1)));
        }

        for (int i = 0; i < PLAYER_COUNT; i++) {
            players.get(i).drawTwo(deck);
        }

        deck.draw();

        for (int i = 0; i < 3; i++) {
            community.add(deck.draw());
        }

        deck.draw();

        for (int i = 0; i < 1; i++) {
            community.add(deck.draw());
        }

        deck.draw();

        for (int i = 0; i < 1; i++) {
            community.add(deck.draw());
        }

        RankHand rankHand = new RankHand();

        for (int i = 0; i < PLAYER_COUNT; i++) {
            Player player = players.get(i);
            player.setHandRank(rankHand.rank(player.getHand(), community));
            System.out.println(player.getName() + ": " + player.getHandRank());
        }

        int winnerIndex = 0;
        Hand tempHand = players.get(0).getHandRank();
        for (int i = 1; i < PLAYER_COUNT; i++) {
            Hand playerHandRank = players.get(i).getHandRank();
            if (tempHand.compareTo(playerHandRank) > 0) {
                tempHand = playerHandRank;
                winnerIndex = i;
            }
        }

        System.out.println("Winner is " + players.get(winnerIndex).getName());

    }
}


text:
* Regenerated from discovery document revision 20221027

### v0.9.0 (2022-10-20)

* Regenerated using generator version 0.11.0

### v0.8.0 (2022-09-28)

* Regenerated using generator version 0.10.0

### v0.7.0 (2022-08-21)

* Regenerated from discovery document revision 20220811
* Regenerated using generator version 0.9.0

### v0.6.0 (2022-06-30)

* Regenerated using generator version 0.8.0

### v0.5.0 (2022-06-21)

* Regenerated from discovery document revision 20220609
* Regenerated using generator version 0.7.0

### v0.4.0 (2022-06-11)

* Regenerated from discovery document revision 20220602
* Regenerated using generator version 0.5.0

### v0.3.0 (2022-04-06)

* Regenerated from discovery document revision 20220323

### v0.2.0 (2022-02-01)

* Regenerated from discovery document revision 20220131
* Regenerated using generator version 0.4.1

### v0.1.0 (2021-12-14)

* Regenerated from discovery document revision 20211108
* Regenerated using generator version 0.4.0


text:
using System;
using System.Windows.Forms;

namespace Warframe_Alerts
{
    public partial class SecondaryForm : Form
    {
        private readonly MainWindow _mainForm;

        private readonly bool _phaseShift;
        private readonly bool _initialR;
        private readonly bool _initialM;
        private readonly bool _initialB;
        private readonly bool _initialC;
        private readonly bool _initialD;

        public SecondaryForm(MainWindow mw, bool resourceFlag, bool modFlag, bool creditFlag, bool blueprintFlag, bool detectionFlag)
        {
            _mainForm = mw;
            InitializeComponent();
            textBoxInterval.Text = (_mainForm.UpdateInterval / (60 * 1000)).ToString();

            _initialR = resourceFlag;
            _initialM = modFlag;
            _initialC = creditFlag;
            _initialB = blueprintFlag;
            _initialD = detectionFlag;

            _phaseShift = true;

            if (resourceFlag)
            {
                checkBoxResource.Checked = true;
            }

            if (modFlag)
            {
                checkBoxMod.Checked = true;
            }

            if (creditFlag)
            {
                checkBoxCredit.Checked = true;
            }

            if (blueprintFlag)
            {
                checkBoxBlueprint.Checked = true;
            }

            if (detectionFlag)
            {
                checkBoxDetection.Checked = true;
            }

            _phaseShift = false;
        }

        private void buttonSet_Click(object sender, EventArgs e)
        {
            var input = textBoxInterval.Text;

            if (!Int32.TryParse(input, out var inputToInt))
            {
                var message = "Please insert a valid input";
                var caption = "Invalid Input";
                var buttons = MessageBoxButtons.OK;
                MessageBox.Show(message, caption, buttons);
            }

            _mainForm.UpdateInterval = inputToInt * 60 * 1000;

            _mainForm.Update_Settings_XML();

            Action update = _mainForm.WF_Update;
            update.BeginInvoke(ar => update.EndInvoke(ar), null);

            Close();
        }

        private void CheckBoxResource_Changed(object sender, EventArgs e)
        {
            if (!_phaseShift)
            {
                _mainForm.ResourceFilter = checkBoxResource.Checked;
            }
        }

        private void CheckBoxCredit_Changed(object sender, EventArgs e)
        {
            if (!_phaseShift)
            {
                _mainForm.CreditFilter = checkBoxCredit.Checked;
            }
        }

        private void CheckBoxMod_Changed(object sender, EventArgs e)
        {
            if (!_phaseShift)
            {
                _mainForm.ModFilter = checkBoxMod.Checked;
            }
        }

        private void CheckBoxBlueprint_Changed(object sender, EventArgs e)
        {
            if (!_phaseShift)
            {
                _mainForm.BlueprintFilter = checkBoxBlueprint.Checked;
            }
        }

        private void CheckBoxDetection_CheckedChanged(object sender, EventArgs e)
        {
            if (!_phaseShift)
            {
                _mainForm.GameDetection = checkBoxDetection.Checked;
            }
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            _mainForm.BlueprintFilter = _initialB;
            _mainForm.ResourceFilter = _initialR;
            _mainForm.CreditFilter = _initialC;
            _mainForm.ModFilter = _initialM;
            _mainForm.GameDetection = _initialD;

            Close();
        }
    }
}


text:
Then(/^I should see a page of validation results$/) do
  page.body.should include("Validation Results")
end

Then(/^I should see my URL$/) do
  page.body.should include(@url)
end

Then(/^I should see the number of rows processed/) do
  page.body.should include("Total Rows Processed")
  # TODO - decide how to incorporate the number returned
  end

Then(/^the number of rows processed should equal (\d+)/) do | row_count|
  page.body.should include("Total Rows Processed = #{row_count}")
  # TODO - decide how to incorporate the number returned
end

Then(/^my file should be persisted in the database$/) do
  Validation.count.should == 1
  Validation.first.filename.should =~ /#{File.basename(@file)}/
end

Then(/^"(.*?)" should be persisted in the database$/) do |filename|
  Validation.count.should == 1
  Validation.first.filename.should =~ /#{filename}/
end

Then(/^my file should not be saved in the database$/) do
  Validation.count.should == 0
end

Then(/^my url should be persisted in the database$/) do
  Validation.count.should == 1
  Validation.first.url.should == @url
  filename = File.basename(URI.parse(@url).path)
  Validation.first.filename.should == filename
end

Then(/^the database record should have a "(.*?)" of the type "(.*?)"$/) do |category, type|
  result = Marshal.load(Validation.first.result)
  result.send(category.pluralize).first.type.should == type.to_sym
end

Then(/^the validation should be updated$/) do
  Validation.any_instance.should_receive(:update_attributes).once
end

Then(/^the validation should not be updated$/) do
  Validation.any_instance.should_not_receive(:update_attributes)
end

Then(/^I should be given the option to revalidate using a different dialect$/) do
  page.should have_css('#revalidate')
end


text:
module Fastlane
  module Actions
    module SharedValues
      PODSPEC_VERSION_NUMBER ||= :PODSPEC_VERSION_NUMBER
    end

    class VersionBumpPodspecAction < Action
      def self.run(params)
        podspec_path = params[:path]

        UI.user_error!("Could not find podspec file at path #{podspec_path}") unless File.exist?(podspec_path)

        version_podspec_file = Helper::PodspecHelper.new(podspec_path, params[:require_variable_prefix])

        if params[:version_number]
          new_version = params[:version_number]
        elsif params[:version_appendix]
          new_version = version_podspec_file.update_version_appendix(params[:version_appendix])
        else
          new_version = version_podspec_file.bump_version(params[:bump_type])
        end

        version_podspec_file.update_podspec(new_version)

        Actions.lane_context[SharedValues::PODSPEC_VERSION_NUMBER] = new_version
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Increment or set the version in a podspec file"
      end

      def self.details
        [
          "You can use this action to manipulate any 'version' variable contained in a ruby file.",
          "For example, you can use it to bump the version of a CocoaPods' podspec file.",
          "It also supports versions that are not semantic: `1.4.14.4.1`.",
          "For such versions, there is an option to change the appendix (e.g. `4.1`)."
        ].join("\n")
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(key: :path,
                                       env_name: "FL_VERSION_BUMP_PODSPEC_PATH",
                                       description: "You must specify the path to the podspec file to update",
                                       code_gen_sensitive: true,
                                       default_value: Dir["*.podspec"].last,
                                       default_value_dynamic: true,
                                       verify_block: proc do |value|
                                         UI.user_error!("Please pass a path to the `version_bump_podspec` action") if value.length == 0
                                       end),
          FastlaneCore::ConfigItem.new(key: :bump_type,
                                       env_name: "FL_VERSION_BUMP_PODSPEC_BUMP_TYPE",
                                       description: "The type of this version bump. Available: patch, minor, major",
                                       default_value: "patch",
                                       verify_block: proc do |value|
                                         UI.user_error!("Available values are 'patch', 'minor' and 'major'") unless ['patch', 'minor', 'major'].include?(value)
                                       end),
          FastlaneCore::ConfigItem.new(key: :version_number,
                                       env_name: "FL_VERSION_BUMP_PODSPEC_VERSION_NUMBER",
                                       description: "Change to a specific version. This will replace the bump type value",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :version_appendix,
                                       env_name: "FL_VERSION_BUMP_PODSPEC_VERSION_APPENDIX",
                                       description: "Change version appendix to a specific value. For example 1.4.14.4.1 -> 1.4.14.5",
                                       optional: true),
          FastlaneCore::ConfigItem.new(key: :require_variable_prefix,
                                       env_name: "FL_VERSION_BUMP_PODSPEC_VERSION_REQUIRE_VARIABLE_PREFIX",
                                       description: "true by default, this is used for non CocoaPods version bumps only",
                                       type: Boolean,
                                       default_value: true)
        ]
      end

      def self.output
        [
          ['PODSPEC_VERSION_NUMBER', 'The new podspec version number']
        ]
      end

      def self.authors
        ["Liquidsoul", "KrauseFx"]
      end

      def self.is_supported?(platform)
        [:ios, :mac].include?(platform)
      end

      def self.example_code
        [
          'version = version_bump_podspec(path: "TSMessages.podspec", bump_type: "patch")',
          'version = version_bump_podspec(path: "TSMessages.podspec", version_number: "1.4")'
        ]
      end

      def self.category
        :misc
      end
    end
  end
end


text:
MyWeather
=========

An Android Weather App


text:
#include <aws/transcribe/model/ListCallAnalyticsCategoriesResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::TranscribeService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

ListCallAnalyticsCategoriesResult::ListCallAnalyticsCategoriesResult()
{
}

ListCallAnalyticsCategoriesResult::ListCallAnalyticsCategoriesResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

ListCallAnalyticsCategoriesResult& ListCallAnalyticsCategoriesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("NextToken"))
  {
    m_nextToken = jsonValue.GetString("NextToken");

  }

  if(jsonValue.ValueExists("Categories"))
  {
    Aws::Utils::Array<JsonView> categoriesJsonList = jsonValue.GetArray("Categories");
    for(unsigned categoriesIndex = 0; categoriesIndex < categoriesJsonList.GetLength(); ++categoriesIndex)
    {
      m_categories.push_back(categoriesJsonList[categoriesIndex].AsObject());
    }
  }

  return *this;
}


text:
package com.torquescript.symbols;

import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.search.FileTypeIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.torquescript.TSFile;
import com.torquescript.TSFileType;
import com.torquescript.psi.TSFnDeclStmt;
import com.torquescript.psi.TSPackageDecl;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class TSFunctionCachedListGenerator extends TSCachedListGenerator<TSFnDeclStmt> {
    @Override
    public Set<TSFnDeclStmt> generate(Project project) {
        Set<TSFnDeclStmt> items = new HashSet<>();
        //Search every file in the project
        Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME, TSFileType.INSTANCE, GlobalSearchScope.projectScope(project));
        for (VirtualFile virtualFile : virtualFiles) {
            TSFile tsFile = (TSFile) PsiManager.getInstance(project).findFile(virtualFile);
            if (tsFile != null) {
                TSFnDeclStmt[] functions = PsiTreeUtil.getChildrenOfType(tsFile, TSFnDeclStmt.class);
                if (functions != null) {
                    Collections.addAll(items, functions);
                }

                TSPackageDecl[] packages = PsiTreeUtil.getChildrenOfType(tsFile, TSPackageDecl.class);
                if (packages != null) {
                    for (TSPackageDecl pack : packages) {
                        functions = PsiTreeUtil.getChildrenOfType(pack, TSFnDeclStmt.class);
                        if (functions != null) {
                            Collections.addAll(items, functions);
                        }
                    }
                }
                ProgressManager.progress("Loading Symbols");
            }
        }
        return items;
    }
}


text:
<?php
/**
 * Automatically generated
 *
 * @author: Viskov Sergey
 * @date: 07.05.15
 */

namespace LTDBeget\apacheConfigurator\directives\available;

use LTDBeget\apacheConfigurator\ConfigurationFile;
use LTDBeget\apacheConfigurator\directives\Directive;

class SessionHeader extends Directive
{
    /**
     * Return link to full description of apache directive
     * @return String
     */
    public static function getApacheDocLink()
    {
        return Directive::$apacheSite."/docs/2.4/mod/mod_session.html#sessionheader";
    }

    /**
     * the source module which defines the directive
     * @return String
     */
    public static function getModule()
    {
        return "mod_session";
    }

    /**
     * Return text description of apache directive
     * @return String
     */
    public static function getDescription()
    {
        return "Import session updates from a given HTTP response header";
    }

    /**
     * Return Apache directive Syntax
     * @return String
     */
    public static function getSyntax()
    {
        return 'SessionHeader header';
    }

    /**
     * is this directive can include inner directives
     * @return boolean
     */
    public function isSection()
    {
        return false;
    }

    /**
     * Set allowed context of concrete directive
     */
    protected function setAllowedContext()
    {
        $this->allowedContext = [
            ConfigurationFile::SERVER_CONFIG,
            VirtualHost::getFullName(),
            Directory::getFullName(),
            ConfigurationFile::HTACCESS,
        ];
    }

}


text:
Scheduler that when triggered runs a project until it stabilizes, then stops. The service runs on port 5000.

[![Build Status](https://travis-ci.org/sesam-community/scheduler.svg?branch=master)](https://travis-ci.org/sesam-community/scheduler)

## API

GET / returns scheduler state (se example-state.json)
```
{
  "state" : "init|running|stopped|failed|success"
}
```

POST /start starts the scheduler when not in state ``running``.

The /start endpoint takes three request parameters:

* reset_pipes=true - will reset all pipes before starting
* delete_datasets=true - will delete all internal datasets associated with the pipes before running (only if
  reset_pipes is set
* skip_input_sources=true - will skip all input sources when running the first pass
* reload_and_wipe_microservices=true - will attempt to reload and wipe the data for all running microservices (except
  ourselves)
* compact_execution_datasets=true - will schedule compaction jobs for the pipe execution datasets to keep them from
  growing too large

All of these are off by default. Note that this means that the mere inclusion of a parameter means that the corresponding
flag is "on", the actual value of the parameter is ignored.

In addition you can change the amount of logging using:
* log_level=INFO - sets the log level when running

## Microservice configuration

```
    {
        "_id": "bootstrap-scheduler-microservice",
        "name": "Name of microservice",
        "type": "system:microservice",
        "docker": {
            "image": "sesamcommunity/scheduler:latest",
            "port": 5000,
            "memory": 128,
            "environment": {
                "MASTER_NODE": "https://m1.sesam.cloud",
                "JWT_TOKEN" : "fklrl464nimsnfskfklrl464nimskfklrl464nimsnfskfkfklrl464nimsnfskf4nimsnfskfklrl464n",
                "LOGLEVEL": "INFO"
            }
        }
    }
```

You can reach the running microservice API using the built-in proxy function. See details here:
https://docs.sesam.io/api.html#get--systems-system_id-proxy--path-relative_path-


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <title>Presentation</title>

    <link rel="stylesheet" href="css/reveal.css">
    <link rel="stylesheet" href="css/theme/blood.css">

    <link rel="stylesheet" href="lib/css/gruvbox-dark.css">

Conan

En beviseditor för predikatlogik

Editorn

Funktionaliteter

Syntax checking

Verifikation

Generering

Export till LaTeX

Genvägar

Spara/ladda

Felmeddelanden


text:
//===--- ModuleLoadingTests.cpp -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "swift/AST/ASTContext.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/ModuleInterfaceLoader.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/Serialization/Validation.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/VirtualFileSystem.h"

using namespace swift;

static std::string createFilename(StringRef base, StringRef name) {
  SmallString<256> path = base;
  llvm::sys::path::append(path, name);
  return llvm::Twine(path).str();
}

static bool emitFileWithContents(StringRef path, StringRef contents,
                                 std::string *pathOut = nullptr) {
  int fd;
  if (llvm::sys::fs::openFileForWrite(path, fd))
    return true;
  if (pathOut)
    *pathOut = path;
  llvm::raw_fd_ostream file(fd, /*shouldClose=*/true);
  file << contents;
  return false;
}

static bool emitFileWithContents(StringRef base, StringRef name,
                                 StringRef contents,
                                 std::string *pathOut = nullptr) {
  return emitFileWithContents(createFilename(base, name), contents, pathOut);
}

namespace unittest {

class OpenTrackingFileSystem : public llvm::vfs::ProxyFileSystem {
  llvm::StringMap<unsigned> numberOfOpensPerFile;
public:
  OpenTrackingFileSystem(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs)
    : llvm::vfs::ProxyFileSystem(fs) {}

  llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
  openFileForRead(const Twine &Path) override {
    numberOfOpensPerFile[Path.str()] += 1;
    return ProxyFileSystem::openFileForRead(Path);
  }

  unsigned numberOfOpens(StringRef path) {
    return numberOfOpensPerFile[path];
  }
};

class ModuleInterfaceLoaderTest : public testing::Test {
protected:
  void setupAndLoadModuleInterface() {
    SmallString<256> tempDir;
    ASSERT_FALSE(llvm::sys::fs::createUniqueDirectory(
        "ModuleInterfaceBufferTests.emitModuleInMemory", tempDir));
    SWIFT_DEFER { llvm::sys::fs::remove_directories(tempDir); };

    auto cacheDir = createFilename(tempDir, "ModuleCache");
    ASSERT_FALSE(llvm::sys::fs::create_directory(cacheDir));

    auto prebuiltCacheDir = createFilename(tempDir, "PrebuiltModuleCache");
    ASSERT_FALSE(llvm::sys::fs::create_directory(prebuiltCacheDir));

    // Emit an interface file that we can attempt to compile.
    ASSERT_FALSE(emitFileWithContents(tempDir, "Library.swiftinterface",
        "// swift-interface-format-version: 1.0\n"
        "// swift-module-flags: -module-name TestModule -parse-stdlib\n"
        "public func foo()\n"));

    SourceManager sourceMgr;

    // Create a file system that tracks how many times a file has been opened.
    llvm::IntrusiveRefCntPtr<OpenTrackingFileSystem> fs(
      new OpenTrackingFileSystem(sourceMgr.getFileSystem()));

    sourceMgr.setFileSystem(fs);
    PrintingDiagnosticConsumer printingConsumer;
    DiagnosticEngine diags(sourceMgr);
    diags.addConsumer(printingConsumer);
    TypeCheckerOptions typeckOpts;
    LangOptions langOpts;
    langOpts.Target = llvm::Triple(llvm::sys::getDefaultTargetTriple());
    SearchPathOptions searchPathOpts;
    auto ctx =
        ASTContext::get(langOpts, typeckOpts, searchPathOpts, sourceMgr, diags);

    auto loader = ModuleInterfaceLoader::create(
        *ctx, cacheDir, prebuiltCacheDir,
        /*dependencyTracker*/nullptr,
        ModuleLoadingMode::PreferSerialized);

    Identifier moduleName = ctx->getIdentifier("TestModule");

    std::unique_ptr<llvm::MemoryBuffer> moduleBuffer;
    std::unique_ptr<llvm::MemoryBuffer> moduleDocBuffer;
    std::unique_ptr<llvm::MemoryBuffer> moduleSourceInfoBuffer;

    auto error =
      loader->findModuleFilesInDirectory({moduleName, SourceLoc()},
        SerializedModuleBaseName(tempDir, SerializedModuleBaseName("Library")),
        /*ModuleInterfacePath*/nullptr,
        &moduleBuffer, &moduleDocBuffer, &moduleSourceInfoBuffer);
    ASSERT_FALSE(error);
    ASSERT_FALSE(diags.hadAnyError());

    ASSERT_NE(nullptr, moduleBuffer);

    // We should not have written a module doc file.
    ASSERT_EQ(nullptr, moduleDocBuffer);

    // Make sure the buffer identifier points to the written module.
    StringRef cachedModulePath = moduleBuffer->getBufferIdentifier();
    ASSERT_TRUE(fs->exists(cachedModulePath));

    // Assert that we've only opened this file once, to write it.
    ASSERT_EQ((unsigned)1, fs->numberOfOpens(cachedModulePath));

    auto bufOrErr = fs->getBufferForFile(cachedModulePath);
    ASSERT_TRUE(bufOrErr);

    auto bufData = (*bufOrErr)->getBuffer();
    auto validationInfo = serialization::validateSerializedAST(bufData);
    ASSERT_EQ(serialization::Status::Valid, validationInfo.status);
    ASSERT_EQ(bufData, moduleBuffer->getBuffer());
  }
};

TEST_F(ModuleInterfaceLoaderTest, LoadModuleFromBuffer) {
  setupAndLoadModuleInterface();
}

} // end namespace unittest


text:
#ifndef itkMINCTransformIOFactory_h
#define itkMINCTransformIOFactory_h

#include "itkObjectFactoryBase.h"
#include "itkTransformIOBase.h"

namespace itk
{
/** \class MINCTransformIOFactory
   * \brief Create instances of MincTransformIO objects using an object factory.
   *
   * \ingroup ITKIOTransformMINC
   */
  class MINCTransformIOFactory:public ObjectFactoryBase
  {
  public:
    /** Standard class typedefs. */
    typedef MINCTransformIOFactory     Self;
    typedef ObjectFactoryBase          Superclass;
    typedef SmartPointer< Self >       Pointer;
    typedef SmartPointer< const Self > ConstPointer;

    /** Class methods used to interface with the registered factories. */
    virtual const char * GetITKSourceVersion() const ITK_OVERRIDE;

    virtual const char * GetDescription() const ITK_OVERRIDE;

    /** Method for class instantiation. */
    itkFactorylessNewMacro(Self);

    /** Run-time type information (and related methods). */
    itkTypeMacro(MINCTransformIOFactory, ObjectFactoryBase);

    /** Register one factory of this type  */
    static void RegisterOneFactory(void)
    {
      MINCTransformIOFactory::Pointer metaFactory = MINCTransformIOFactory::New();

      ObjectFactoryBase::RegisterFactory(metaFactory);
    }

  protected:
    MINCTransformIOFactory();
    ~MINCTransformIOFactory();
    virtual void PrintSelf(std::ostream & os, Indent indent) const ITK_OVERRIDE;

  private:
    MINCTransformIOFactory(const Self &); //purposely not implemented
    void operator=(const Self &);        //purposely not implemented
  };
} // end namespace itk

#endif //itkMINCTransformIOFactory_h


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Examine;
using Examine.Lucene.Directories;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Runtime;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Services.Implement;
using Umbraco.Cms.Core.Sync;
using Umbraco.Cms.Core.WebAssets;
using Umbraco.Cms.Infrastructure.Examine;
using Umbraco.Cms.Infrastructure.HostedServices;
using Umbraco.Cms.Infrastructure.PublishedCache;
using Umbraco.Cms.Tests.Common.TestHelpers.Stubs;
using Umbraco.Cms.Tests.Integration.Implementations;
using Umbraco.Extensions;

namespace Umbraco.Cms.Tests.Integration.DependencyInjection
{
    /// <summary>
    /// This is used to replace certain services that are normally registered from our Core / Infrastructure that
    /// we do not want active within integration tests
    /// </summary>
    public static class UmbracoBuilderExtensions
    {
        /// <summary>
        /// Uses/Replaces services with testing services
        /// </summary>
        public static IUmbracoBuilder AddTestServices(this IUmbracoBuilder builder, TestHelper testHelper, AppCaches appCaches = null)
        {
            builder.Services.AddUnique(appCaches ?? AppCaches.NoCache);
            builder.Services.AddUnique(Mock.Of<IUmbracoBootPermissionChecker>());
            builder.Services.AddUnique(testHelper.MainDom);

            builder.Services.AddUnique<ExamineIndexRebuilder, TestBackgroundIndexRebuilder>();
            builder.Services.AddUnique(factory => Mock.Of<IRuntimeMinifier>());

            // we don't want persisted nucache files in tests
            builder.Services.AddTransient(factory => new PublishedSnapshotServiceOptions { IgnoreLocalDb = true });

#if IS_WINDOWS
            // ensure all lucene indexes are using RAM directory (no file system)
            builder.Services.AddUnique<IDirectoryFactory, LuceneRAMDirectoryFactory>();
#endif

            // replace this service so that it can lookup the correct file locations
            builder.Services.AddUnique(GetLocalizedTextService);

            builder.Services.AddUnique<IServerMessenger, NoopServerMessenger>();
            builder.Services.AddUnique<IProfiler, TestProfiler>();

            return builder;
        }

        /// <summary>
        /// Used to register a replacement for <see cref="ILocalizedTextService"/> where the file sources are the ones within the netcore project so
        /// we don't need to copy files
        /// </summary>
        private static ILocalizedTextService GetLocalizedTextService(IServiceProvider factory)
        {
            IOptions<GlobalSettings> globalSettings = factory.GetRequiredService<IOptions<GlobalSettings>>();
            ILoggerFactory loggerFactory = factory.GetRequiredService<ILoggerFactory>();
            AppCaches appCaches = factory.GetRequiredService<AppCaches>();

            var localizedTextService = new LocalizedTextService(
                new Lazy<LocalizedTextServiceFileSources>(() =>
                {
                    // get the src folder
                    var root = TestContext.CurrentContext.TestDirectory.Split("tests")[0];
                    var srcFolder = Path.Combine(root, "src");

                    var currFolder = new DirectoryInfo(srcFolder);

                    DirectoryInfo uiProject = currFolder.GetDirectories("Umbraco.Web.UI", SearchOption.TopDirectoryOnly).First();
                    var mainLangFolder = new DirectoryInfo(Path.Combine(uiProject.FullName, globalSettings.Value.UmbracoPath.TrimStart("~/"), "config", "lang"));

                    return new LocalizedTextServiceFileSources(
                        loggerFactory.CreateLogger<LocalizedTextServiceFileSources>(),
                        appCaches,
                        mainLangFolder);
                }),
                loggerFactory.CreateLogger<LocalizedTextService>());

            return localizedTextService;
        }

        // replace the default so there is no background index rebuilder
        private class TestBackgroundIndexRebuilder : ExamineIndexRebuilder
        {
            public TestBackgroundIndexRebuilder(IMainDom mainDom, IRuntimeState runtimeState, ILogger<ExamineIndexRebuilder> logger, IExamineManager examineManager, IEnumerable<IIndexPopulator> populators, IBackgroundTaskQueue backgroundTaskQueue) : base(mainDom, runtimeState, logger, examineManager, populators, backgroundTaskQueue)
            {
            }

            public override void RebuildIndex(string indexName, TimeSpan? delay = null, bool useBackgroundThread = true)
            {
                // noop
            }

            public override void RebuildIndexes(bool onlyEmptyIndexes, TimeSpan? delay = null, bool useBackgroundThread = true)
            {
                // noop
            }
        }

        private class NoopServerMessenger : IServerMessenger
        {
            public NoopServerMessenger()
            {
            }

            public void QueueRefresh<TPayload>(ICacheRefresher refresher, TPayload[] payload)
            {
            }

            public void QueueRefresh<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
            {
            }

            public void QueueRefresh<T>(ICacheRefresher refresher, Func<T, Guid> getGuidId, params T[] instances)
            {
            }

            public void QueueRemove<T>(ICacheRefresher refresher, Func<T, int> getNumericId, params T[] instances)
            {
            }

            public void QueueRemove(ICacheRefresher refresher, params int[] numericIds)
            {
            }

            public void QueueRefresh(ICacheRefresher refresher, params int[] numericIds)
            {
            }

            public void QueueRefresh(ICacheRefresher refresher, params Guid[] guidIds)
            {
            }

            public void QueueRefreshAll(ICacheRefresher refresher)
            {
            }

            public void Sync() { }

            public void SendMessages() { }
        }
    }
}


text:
package org.apache.jena.sdb.core;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.jena.sparql.core.Var ;

public class Scope2 implements Scope
{
    Scope left ;
    Scope right ;
    //ScopeStatus scopeStatus ;

    public Scope2(Scope left, Scope right)
    {
        this.left = left ;
        this.right = right ;
        //this.scopeStatus = status ;
    }

    @Override
    public boolean hasColumnForVar(Var var)
    {
        if ( left != null && left.hasColumnForVar(var) )
            return true ;
        if ( right != null && right.hasColumnForVar(var) )
            return true ;
        return false ;
    }

    @Override
    public Set<Var> getVars()
    {
        // Better - implement Iterable
        Set<Var> acc = new LinkedHashSet<Var>() ;
        if ( left != null ) acc.addAll(left.getVars()) ;
        if ( right != null ) acc.addAll(right.getVars()) ;
        return acc ;
    }

    @Override
    public boolean isEmpty()
    { return left.isEmpty() && right.isEmpty() ; }

    @Override
    public Set<ScopeEntry> findScopes()
    {
        Set<ScopeEntry> x = new HashSet<ScopeEntry>() ;
        for ( Var v : getVars() )
        {
            ScopeEntry e = findScopeForVar(v) ;
            x.add(e) ;
        }
        return x ;
    }

    @Override
    public ScopeEntry findScopeForVar(Var var)
    {
        // Return a fixed ScopeEntry in preference to an optional one.
        // Return a more rightward optional (c.f. coalesce) if both optional
        ScopeEntry c1 = null ;

        if ( left != null )
            c1 = left.findScopeForVar(var) ;

        if ( c1 != null && c1.getStatus() == ScopeStatus.FIXED )
            return c1 ;

        // Got no Scope or one that's optional.
        ScopeEntry c2 = null ;

        if ( right != null )
            c2 = right.findScopeForVar(var) ;
        if ( c2 != null && c2.getStatus() == ScopeStatus.FIXED )
            return c2 ;

        // No fixed out - return an optional if present.
        // Prefer the rigth to the left

        if ( c2 != null )
            return c2 ;
        if ( c1 != null )
            return c1 ;

        return null ;
    }

    @Override
    public String toString()
    {
        String x = "" ;
        if ( ! left.isEmpty() )
            x = left.toString() ;
        if ( !left.isEmpty() && !right.isEmpty() )
            x = x + " " ;
        if ( ! right.isEmpty() )
            x = x + right.toString();
        return x ;
    }
}


text:
using System;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Weapsy.Domain.Languages;
using Weapsy.Domain.Pages;
using Weapsy.Reporting.Pages;
using Weapsy.Reporting.Pages.Queries;
using System.Linq;
using Weapsy.Reporting.Roles.Queries;
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
using Weapsy.Cqrs;
using Weapsy.Data.Entities;
using Weapsy.Data.TempIdentity;
using Weapsy.Domain.Roles.DefaultRoles;
using Weapsy.Cqrs.Queries;

namespace Weapsy.Data.Reporting.Pages
{
    public class GetForAdminHandler : IQueryHandlerAsync<GetForAdmin, PageAdminModel>
    {
        private readonly IContextFactory _contextFactory;
        private readonly IDispatcher _queryDispatcher;

        public GetForAdminHandler(IContextFactory contextFactory, IDispatcher queryDispatcher)
        {
            _contextFactory = contextFactory;
            _queryDispatcher = queryDispatcher;
        }

        public async Task<PageAdminModel> RetrieveAsync(GetForAdmin query)
        {
            using (var context = _contextFactory.Create())
            {
                var page = await context.Pages
                    .Include(x => x.PageLocalisations)
                    .Include(x => x.PagePermissions)
                    .FirstOrDefaultAsync(x => x.SiteId == query.SiteId && x.Id == query.Id && x.Status != PageStatus.Deleted);

                if (page == null)
                    return null;

                var result = new PageAdminModel
                {
                    Id = page.Id,
                    Name = page.Name,
                    Status = page.Status,
                    Url = page.Url,
                    Title = page.Title,
                    MetaDescription = page.MetaDescription,
                    MetaKeywords = page.MetaKeywords
                };

                var languages = await context.Languages
                    .Where(x => x.SiteId == query.SiteId && x.Status != LanguageStatus.Deleted)
                    .OrderBy(x => x.SortOrder)
                    .ToListAsync();

                foreach (var language in languages)
                {
                    var url = string.Empty;
                    var title = string.Empty;
                    var metaDescription = string.Empty;
                    var metaKeywords = string.Empty;

                    var existingLocalisation = page
                        .PageLocalisations
                        .FirstOrDefault(x => x.LanguageId == language.Id);

                    if (existingLocalisation != null)
                    {
                        url = existingLocalisation.Url;
                        title = existingLocalisation.Title;
                        metaDescription = existingLocalisation.MetaDescription;
                        metaKeywords = existingLocalisation.MetaKeywords;
                    }

                    result.PageLocalisations.Add(new PageLocalisationAdminModel
                    {
                        PageId = page.Id,
                        LanguageId = language.Id,
                        LanguageName = language.Name,
                        LanguageStatus = language.Status,
                        Url = url,
                        Title = title,
                        MetaDescription = metaDescription,
                        MetaKeywords = metaKeywords
                    });
                }

                foreach (var role in await _queryDispatcher.GetResultAsync<GetAllRoles, IEnumerable<ApplicationRole>>(new GetAllRoles()))
                {
                    var pagePermission = new PagePermissionModel
                    {
                        RoleId = role.Id,
                        RoleName = role.Name,
                        Disabled = role.Name == Administrator.Name
                    };

                    foreach (PermissionType permisisonType in Enum.GetValues(typeof(PermissionType)))
                    {
                        bool selected = page.PagePermissions
                            .FirstOrDefault(x => x.RoleId == role.Id && x.Type == permisisonType) != null;

                        pagePermission.PagePermissionTypes.Add(new PagePermissionTypeModel
                        {
                            Type = permisisonType,
                            Selected = selected || role.Name == Administrator.Name
                        });
                    }

                    result.PagePermissions.Add(pagePermission);
                }

                return result;
            }
        }
    }
}


text:
package test.javassist.bytecode.analysis;

import java.io.BufferedReader;
import java.io.FileReader;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.bytecode.analysis.Analyzer;

/**
 * Simple testing tool that verifies class files can be analyzed.
 *
 * @author Jason T. Greene
 */
public class ErrorFinder {

    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();

        String className = args[0];
        if (!className.equals("-file")) {
            analyzeClass(pool, className);
            return;
        }

        FileReader reader = new FileReader(args[1]);
        BufferedReader lineReader = new BufferedReader(reader);

        String line = lineReader.readLine();
        while (line != null) {
            analyzeClass(pool, line);
            line = lineReader.readLine();
        }
    }

    private static void analyzeClass(ClassPool pool, String className) {
        try {

            CtClass clazz = pool.get(className);
            CtMethod[] methods = clazz.getDeclaredMethods();
            for (int i = 0; i < methods.length; i++)
                analyzeMethod(clazz, methods[i]);
        } catch (Throwable e) {
            System.out.println("FAIL: CLASS: " + className + " " + e.getClass() + ":" + e.getMessage());
        }
    }

    private static void analyzeMethod(CtClass clazz, CtMethod method) {
        String methodName = clazz.getName() + "." + method.getName() + method.getSignature();
        System.out.println("START: " + methodName);
        Analyzer analyzer = new Analyzer();

        long time = System.currentTimeMillis();
        try {
            analyzer.analyze(clazz, method.getMethodInfo2());
            System.out.println("SUCCESS: " + methodName + " - " + (System.currentTimeMillis() - time));
        } catch (Exception e) {
            System.out.println("FAIL: " + methodName + " - " + (e.getMessage() == null ? e.getClass().getName() : e.getMessage()));
        }
    }
}


text:
package com.northernwall.hadrian.workItem.action;

import com.northernwall.hadrian.config.Const;
import com.northernwall.hadrian.domain.Host;
import com.northernwall.hadrian.domain.Vip;
import com.northernwall.hadrian.domain.WorkItem;
import com.northernwall.hadrian.workItem.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HostVipDisableAction extends HostVipBaseAction {

    private final static Logger LOGGER = LoggerFactory.getLogger(HostVipDisableAction.class);

    @Override
    public void updateStatus(WorkItem workItem) {
        Host host = dataAccess.getHost(workItem.getService().serviceId, workItem.getHost().hostId);
        if (host == null) {
            LOGGER.warn("Could not find host {} who's VIP is being disabled", workItem.getHost().hostId);
            return;
        }
        dataAccess.updateStatus(
                workItem.getHost().hostId,
                true,
                "Disabling in VIP...",
                Const.STATUS_WIP);
    }

    @Override
    public Result process(WorkItem workItem) {
        return processVips(workItem);
    }

    @Override
    protected Result processVip(WorkItem workItem, Vip vip) {
        LOGGER.info("Disabling vip {} for {} {}", vip.getDns(), workItem.getHost().hostName, workItem.getService().serviceName);
        return Result.success;
    }

    @Override
    protected String getVerb() {
        return "disable";
    }

    @Override
    protected String getVerbPastTense() {
        return "disabled";
    }

    @Override
    protected String getPreposition() {
        return "in";
    }

}


text:
package armcompute

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// CommunityGalleryImageVersionsClient contains the methods for the CommunityGalleryImageVersions group.
// Don't use this type directly, use NewCommunityGalleryImageVersionsClient() instead.
type CommunityGalleryImageVersionsClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewCommunityGalleryImageVersionsClient creates a new instance of CommunityGalleryImageVersionsClient with the specified values.
// subscriptionID - Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms
// part of the URI for every service call.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewCommunityGalleryImageVersionsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*CommunityGalleryImageVersionsClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &CommunityGalleryImageVersionsClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// Get - Get a community gallery image version.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-03-03
// location - Resource location.
// publicGalleryName - The public name of the community gallery.
// galleryImageName - The name of the community gallery image definition.
// galleryImageVersionName - The name of the community gallery image version. Needs to follow semantic version name pattern:
// The allowed characters are digit and period. Digits must be within the range of a 32-bit integer.
// Format: ..
// options - CommunityGalleryImageVersionsClientGetOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.Get
// method.
func (client *CommunityGalleryImageVersionsClient) Get(ctx context.Context, location string, publicGalleryName string, galleryImageName string, galleryImageVersionName string, options *CommunityGalleryImageVersionsClientGetOptions) (CommunityGalleryImageVersionsClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, location, publicGalleryName, galleryImageName, galleryImageVersionName, options)
	if err != nil {
		return CommunityGalleryImageVersionsClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return CommunityGalleryImageVersionsClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return CommunityGalleryImageVersionsClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *CommunityGalleryImageVersionsClient) getCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, galleryImageVersionName string, options *CommunityGalleryImageVersionsClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}/versions/{galleryImageVersionName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if location == "" {
		return nil, errors.New("parameter location cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
	if publicGalleryName == "" {
		return nil, errors.New("parameter publicGalleryName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
	if galleryImageName == "" {
		return nil, errors.New("parameter galleryImageName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
	if galleryImageVersionName == "" {
		return nil, errors.New("parameter galleryImageVersionName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{galleryImageVersionName}", url.PathEscape(galleryImageVersionName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-03")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *CommunityGalleryImageVersionsClient) getHandleResponse(resp *http.Response) (CommunityGalleryImageVersionsClientGetResponse, error) {
	result := CommunityGalleryImageVersionsClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageVersion); err != nil {
		return CommunityGalleryImageVersionsClientGetResponse{}, err
	}
	return result, nil
}

// NewListPager - List community gallery image versions inside an image.
// Generated from API version 2022-03-03
// location - Resource location.
// publicGalleryName - The public name of the community gallery.
// galleryImageName - The name of the community gallery image definition.
// options - CommunityGalleryImageVersionsClientListOptions contains the optional parameters for the CommunityGalleryImageVersionsClient.List
// method.
func (client *CommunityGalleryImageVersionsClient) NewListPager(location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImageVersionsClientListOptions) *runtime.Pager[CommunityGalleryImageVersionsClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[CommunityGalleryImageVersionsClientListResponse]{
		More: func(page CommunityGalleryImageVersionsClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *CommunityGalleryImageVersionsClientListResponse) (CommunityGalleryImageVersionsClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, location, publicGalleryName, galleryImageName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return CommunityGalleryImageVersionsClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return CommunityGalleryImageVersionsClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return CommunityGalleryImageVersionsClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *CommunityGalleryImageVersionsClient) listCreateRequest(ctx context.Context, location string, publicGalleryName string, galleryImageName string, options *CommunityGalleryImageVersionsClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/communityGalleries/{publicGalleryName}/images/{galleryImageName}/versions"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if location == "" {
		return nil, errors.New("parameter location cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
	if publicGalleryName == "" {
		return nil, errors.New("parameter publicGalleryName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{publicGalleryName}", url.PathEscape(publicGalleryName))
	if galleryImageName == "" {
		return nil, errors.New("parameter galleryImageName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{galleryImageName}", url.PathEscape(galleryImageName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-03")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *CommunityGalleryImageVersionsClient) listHandleResponse(resp *http.Response) (CommunityGalleryImageVersionsClientListResponse, error) {
	result := CommunityGalleryImageVersionsClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.CommunityGalleryImageVersionList); err != nil {
		return CommunityGalleryImageVersionsClientListResponse{}, err
	}
	return result, nil
}


text:
#ifndef OCFS2_AOPS_H
#define OCFS2_AOPS_H

int ocfs2_prepare_write_nolock(struct inode *inode, struct page *page,
			       unsigned from, unsigned to);

handle_t *ocfs2_start_walk_page_trans(struct inode *inode,
							 struct page *page,
							 unsigned from,
							 unsigned to);

int ocfs2_map_page_blocks(struct page *page, u64 *p_blkno,
			  struct inode *inode, unsigned int from,
			  unsigned int to, int new);

int walk_page_buffers(	handle_t *handle,
			struct buffer_head *head,
			unsigned from,
			unsigned to,
			int *partial,
			int (*fn)(	handle_t *handle,
					struct buffer_head *bh));

struct ocfs2_write_ctxt;
typedef int (ocfs2_page_writer)(struct inode *, struct ocfs2_write_ctxt *,
				u64 *, unsigned int *, unsigned int *);

ssize_t ocfs2_buffered_write_cluster(struct file *file, loff_t pos,
				     size_t count, ocfs2_page_writer *actor,
				     void *priv);

struct ocfs2_write_ctxt {
	size_t				w_count;
	loff_t				w_pos;
	u32				w_cpos;
	unsigned int			w_finished_copy;

	/* This is true if page_size > cluster_size */
	unsigned int			w_large_pages;

	/* Filler callback and private data */
	ocfs2_page_writer		*w_write_data_page;
	void				*w_private;

	/* Only valid for the filler callback */
	struct page			*w_this_page;
	unsigned int			w_this_page_new;
};

struct ocfs2_buffered_write_priv {
	char				*b_src_buf;
	const struct iovec		*b_cur_iov; /* Current iovec */
	size_t				b_cur_off; /* Offset in the
						    * current iovec */
};
int ocfs2_map_and_write_user_data(struct inode *inode,
				  struct ocfs2_write_ctxt *wc,
				  u64 *p_blkno,
				  unsigned int *ret_from,
				  unsigned int *ret_to);

struct ocfs2_splice_write_priv {
	struct splice_desc		*s_sd;
	struct pipe_buffer		*s_buf;
	struct pipe_inode_info		*s_pipe;
	/* Neither offset value is ever larger than one page */
	unsigned int			s_offset;
	unsigned int			s_buf_offset;
};
int ocfs2_map_and_write_splice_data(struct inode *inode,
				    struct ocfs2_write_ctxt *wc,
				    u64 *p_blkno,
				    unsigned int *ret_from,
				    unsigned int *ret_to);

/* all ocfs2_dio_end_io()'s fault */
#define ocfs2_iocb_is_rw_locked(iocb) \
	test_bit(0, (unsigned long *)&iocb->private)
static inline void ocfs2_iocb_set_rw_locked(struct kiocb *iocb, int level)
{
	set_bit(0, (unsigned long *)&iocb->private);
	if (level)
		set_bit(1, (unsigned long *)&iocb->private);
	else
		clear_bit(1, (unsigned long *)&iocb->private);
}
#define ocfs2_iocb_clear_rw_locked(iocb) \
	clear_bit(0, (unsigned long *)&iocb->private)
#define ocfs2_iocb_rw_locked_level(iocb) \
	test_bit(1, (unsigned long *)&iocb->private)
#endif /* OCFS2_FILE_H */


text:
#ifndef __r3__
#define __r3__

#include "sys.h"   //for using system implementation
#include <ctype.h> //implicit declaration of isspace

#define MAX_ARG 1024

/**
 * Contains data associated with a command to be executed
 */
typedef struct _CmdData
{
  char* args[MAX_LEN], *pth, *inf, *outf; //args, path to exec io redirect
  int argc , plen;                        //num args
  char* strcmd;
} CmdData;

#endif


text:
from pygame import *

def roundedRectangle(rect, colour, radius = 0.2):
    rect = Rect(rect)
    colour = Color(*colour)
    alpha = colour.a
    colour.a = 0
    pos = rect.topleft
    rect.topleft = 0,0
    rectangle = Surface(rect.size,SRCALPHA)
    circle = Surface([min(rect.size)*3]*2,SRCALPHA)
    draw.ellipse(circle,(0,0,0),circle.get_rect(),0)
    circle = transform.smoothscale(circle,[int(min(rect.size)*radius)]*2)

    radius = rectangle.blit(circle,(0,0))
    radius.bottomright = rect.bottomright
    rectangle.blit(circle,radius)
    radius.topright = rect.topright
    rectangle.blit(circle,radius)
    radius.bottomleft = rect.bottomleft
    rectangle.blit(circle,radius)

    rectangle.fill((0,0,0),rect.inflate(-radius.w,0))
    rectangle.fill((0,0,0),rect.inflate(0,-radius.h))

    rectangle.fill(colour,special_flags=BLEND_RGBA_MAX)
    rectangle.fill((255,255,255,alpha),special_flags=BLEND_RGBA_MIN)
    return rectangle


text:
module Trainyard
  module PortletControl
    def is_portlet?(klass = nil)
      !!current_portal(klass)
    end

    def current_portal(klass = nil)
      load_current_portal unless defined?(@current_portal)
      return (klass.nil? || @current_portal.is_a?(klass)) ? @current_portal : nil
    end

    def current_portal=(portal)
      @current_portal = portal
      if @current_portal
        session[:portal_id] = @current_portal.id
        session[:portal_type] = @current_portal.class.to_s
      end
    end

    def load_current_portal
      @current_portal = nil
      if session[:portal_id] && session[:portal_type]
        begin
          @current_portal = session[:portal_type].classify.constantize.find(session[:portal_id])
        rescue
        end
      end
      logger.debug("Application portal: #{@current_portal.inspect}") unless @current_portal.nil?
      @current_portal
    end

    def parse_portal(params = {})
      session[:portal_id] = params[:portal_id]
      session[:portal_type] = params[:portal_type]
      load_current_portal
    end

    def reset_portal
      session[:portal_id] = nil
      session[:portal_type] = nil
      load_current_portal
    end

    def default_portal
      default_portal? ? Configuration.default_portal_type.to_class.find(Configuration.default_portal_id) : nil
    end

    def default_portal?
      Configuration.default_portal_type && Configuration.default_portal_id
    end

    def set_default_portal
      self.current_portal=(default_portal) if self.current_portal.nil?
    end

    def self.included(base)
      base.send :helper_method, :is_portlet?, :current_portal, :default_portal, :default_portal? if base.respond_to?(:helper_method)
      base.send :before_filter, :set_default_portal if base.respond_to?(:before_filter)
      # FIXME - what is this?...
      base.send :persistent_session_variables, :portal_type, :portal_id if base.respond_to?(:persistent_session_variables)
    end
  end
end

ActionController::Base.send(:include, Trainyard::PortletControl) if defined?(ActionController::Base)


text:
<?php

declare(strict_types=1);

namespace Webthink\GuzzleJwt\Test\Unit\Token\TokenFactory;

use PHPUnit\Framework\TestCase;
use Webthink\GuzzleJwt\Token\DummyToken;
use Webthink\GuzzleJwt\Token\TokenFactory\DummyTokenFactory;

final class DummyTokenFactoryUnitTest extends TestCase
{
    public function testCreateDummyToken()
    {
        $factory = new DummyTokenFactory(['payload'], ['header'], 'signature');
        $token = $factory->create('token');

        $this->assertInstanceOf(DummyToken::class, $token);
    }

    public function testValuesOfCreatedDummyToken()
    {
        $factory = new DummyTokenFactory(['payload'], ['header'], 'signature');
        $token = $factory->create('token');

        $this->assertSame('token', $token->getTokenString());
        $this->assertSame(['payload'], $token->getPayload());
        $this->assertSame(['header'], $token->getHeader());
        $this->assertSame('signature', $token->getSignature());
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Fab
 * Date: 26/10/17
 * Time: 11:31
 */

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class StageController extends Controller
{
    /**
     * AFFICHE LA PAGE D'UN STAGE
     *
     * @Route("stage/{slug}", name="show_stage")
     */
    public function showStage($slug){

        $doctrine = $this->getDoctrine();
        $repo = $doctrine->getRepository('AppBundle:Stage');
        $stage = $repo->stageWhithProvider($slug);

        return $this->render('stages/stage.html.twig',['stage'=>$stage]);

    }

    /**
     *
     * AFFICHE LA LISTE DES STAGES
     *
     * @Route("stages/list", name="list_stages")
     */
    public function listStages()
    {

        $doctrine = $this->getDoctrine();
        $repo = $doctrine->getRepository('AppBundle:Stage');
        $stages = $repo->findAll();

        return $this->render('stages/stages.html.twig',['stages'=>$stages]);

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<version branch='master'>1.1</version>


text:
description: This guide has troubleshooting tips for each authentication step and for things like getting user profile information.
toc: true
topics:
  - troubleshooting
  - errors
contentType:
  - how-to
useCase:
  - troubleshooting
---

# Troubleshooting Issues With ...

In this guide you'll find tips for troubleshooting each authentication step and for things like getting user profile information. If these tips don't outright solve your issue, they can at least narrow down a possible cause and help Auth0 support resolve your issue faster.

## Login issues

Here are things to check to help you narrow down where issues are occurring during login.

### Is the user prompted for login credentials?

* Does the HAR file show a call to the authorization server (`/authorize` endpoint)?
* Is the connection enabled for the application?
* Is the remote authorization service available?
* If using the [Auth0 Universal Login Page](/hosted-pages/login), try turning off customization and see if authentication works. If login works without your customizations, review your Universal Login Page customization code.

### Is an error message shown after entering credentials?

* Can you test login another way to ensure credentials are correct?
* If password expiration is a possibility, check if password has expired.
* Check your browser's developer tools or web inspector console for errors in the flow before returning to Auth0.
* Check the HAR file - does it show a return to Auth0 (`/login/callback`endpoint)?
    - If not, check that the identity provider has the correct callback URL for Auth0.

### Is a login session established for the user at the authorization server?

* To test this, open a second tab in the same browser and go to the same URL. Are you prompted to log in again?
    - If you're not prompted to log in, a session is there.

### Is a log entry created in your Auth0 Logs?

* If no log entry was created the authentication transaction did not complete or return to Auth0.
* Check the response from the authorization server for error messages.
* Check authorization server logs (if possible) for errors.

### Is an entry created in Auth0 user's screen with all correct profile info?

* If not, check the response from authorization server in the HAR file. It may not be returning information about the user
* If you're using rules, check your rules scripts for issues.
* If you're using a custom database connection, check your database action scripts for issues.
* If you're using LDAP, check the profile mapper script (`profileMapper.js`) for issues.
* Check your social connection configurations for what profile information is requested.

### Does the HAR file show a token or assertion returned to application?

* Look in the HAR file for the call to your application callback URL.
* Find the ID Token (`id_token`) and check if it has the information needed by the application.

### If you decode the token or assertion does it have information you expect?

* JSON Web Tokens (JWT) can be viewed with [JWT.io](http://jwt.io)
* <dfn data-key="security-assertion-markup-language">SAML</dfn> assertions can be viewed with [SAMLTool.io](http://samltool.io)

### Check your application logs

* Do your application logs show any errors?
* Did the application receive all the information it needs, such as groups or user profile attributes?

## Single Sign-on issues

Here's some things to check if the user logged in to one application, but cannot access a second application through <dfn data-key="single-sign-on">Single Sign-on (SSO)</dfn>.

### If the logged in user cannot access another application with Single Sign-on

* Is the user trying to login to the second application from the same browser as their initial login?
* Go to your [Tenant Settings > Advanced Settings](${manage_url}/#/tenant/advanced) and check the **Log In Session Management** settings.
    - Was the second login attempt within the timeout periods?
* Check the value passed as the `prompt` parameter in `/authorize` call.
* Is the connection used to log in to the first application enabled for the second application?
* Did the second application receive all the necessary user profile information?
* If using a mobile device, you'll need to use a browser-based flow. For more information, check out [Browser-Based vs. Native Login Flows on Mobile Devices](/design/browser-based-vs-native-experience-on-mobile).

## Issues with getting user profile information

* Is user profile information correct at the source (authorization server)?
* Check the HTTP Archive, look for an `id_token`.
* Decode the `id_token` at [JWT.io](https://jwt.io) to see if it has the correct information.
* Check any custom database scripts or rule logic.
* Check if you called `/tokeninfo` endpoint and have a custom domain configured within Auth0. If so, you need to use `/userinfo` endpoint instead
* Check if you called `/userinfo` endpoint properly. You should pass an access token.
* Check if you specified the correct [scope](/scopes) to get an Access Token?

## Issues with checking session state

* Are you using the correct domain?
    - The domain should be the same as that used during authentication.
* If using an Auth0 [Custom Domain](/custom-domains), it is important to use the same domain as used in the application to invoke authentication.

## Logout issues

* Did you whitelist your logout redirect URLs? If you are using a redirect URL in a logout call it must be registered in either the tenant or application settings.
* If you need federated logout, did you append the `?federated` parameter to the logout call?
* Make sure that the logout redirect URL is different from the login callback URL.
* Make the logout redirect URL an anonymous page (not protected by login) so that redirects to the logout redirect URL do not immediately trigger a login, which may confuse users.

## Issues with calling the Management API

* Do you have a [Management API Access Token](/api/management/v2/tokens)?
* Did the Access Token expire?
* Did the Access Token contain the scopes needed for the call you made?
* If a rule adjusts the scopes in the Access Token or checks whether specific users are allowed to have the scopes, have you checked the rule to make sure it is executing correctly?
* Get the Access Token from [a HAR file](/troubleshoot/har) and test it in the [Auth0 Management API Explorer](/api/management/v2/) to see if it works there
* If you are calling the Auth0 Management API from an application that authenticates with Client Credentials flow, note that rules are not executed in this context. The Client Credentials Exchange Hook can be used in this context instead, for functionality similar to a rule.

## Issues with calling your API

* Check in the [HAR file](/troubleshoot/har) if the Access Token contains correct scopes to call the API.
* Check if the response to the `/authorize` endpoint call contains a scopes object. If so, check if the returned scopes are different from the requested scopes.
* Make sure your [API can validate the Access Token](/api-auth/tutorials/verify-access-token).  It should validate the audience, issuer, client (if any), signature algorithm, signature, claims and permissions.
* If you experience errors with Access Token expiration, they could be caused by [clock skew differences manifested across different systems](/connector/troubleshooting#clock-skew) or even different language libraries, such as Java and Node.js.  This can be handled by running NTP on servers and configuring a clock skew tolerance in libraries used to validate tokens such as [jwt.verify](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback).

## Issues that affect only one or a few users

* Check the user's profile, browser, or device for any issues.
* Check to see if it happens in all browsers for the affected users (indicating a data issue) or just certain types of browsers (indicating a browser-specific issue).
* Check to see if the browser has enabled JavaScript and cookies.
* Check that the caps lock key is disabled.
* If the user is using a mobile device, check to see if there's any software that might impact authentication and/or authorization (such as not running some type of required software).
* Check to see if the user can access some of the application's key URLs, such as the identity provider's <dfn data-key="single-sign-on">Single Sign-on (SSO)</dfn> URL (indicating a network connectivity issue).

## Issues that occur after go-live (worked before, then stopped working)

* Check if any recent changes to your application or any APIs you call?
* Check if any recent network changes (load balancer, firewall, proxy config changes).
* Check if any recent infrastructure changes (e.g. credentials for LDAP or DB servers?)
* Check for any patches or updates to applications, infrastructure, or technology stacks.
* Check that all your servers are running NTP and have accurate time sync
* Check if any of your certificates have expired.
* Check with owners of any remote identity providers if anything changed.
    - Check network connectivity to any remote identity providers.
* Check notifications in Auth0 dashboard/migrations - any changes you overlooked?
* Check Auth0 change log - any recent configuration changes related to your issue?
* Check if any component in the technology stack has been updated or patched recently?


text:
package org.typemeta.funcj.control;

import org.typemeta.funcj.algebra.Monoid;
import org.typemeta.funcj.functions.Functions;

public interface WriterM<W, A> {
    class Base<W, A> implements WriterM<W, A> {
        final Monoid<W> monoid;
        final A value;
        final W written;

        public Base(Monoid<W> monoid, A value, W written) {
            this.monoid = monoid;
            this.value = value;
            this.written = written;
        }

        @Override
        public Monoid<W> monoid() {
            return monoid;
        }

        @Override
        public A value() {
            return value;
        }

        @Override
        public W written() {
            return written;
        }
    }

    static <W, A> WriterM<W, A> of(Monoid<W> monoid, A value, W written) {
        return new Base<>(monoid, value, written);
    }

    static <W, A> WriterM<W, A> pure(Monoid<W> monoid, A value) {
        return new Base<>(monoid, value, monoid.zero());
    }

    Monoid<W> monoid();

    A value();

    W written();

    default <B> WriterM<W, B> writer(B value, W written) {
        return new Base<>(monoid(), value, written);
    }

    default <B> WriterM<W, B> flatMap(Functions.F<A, WriterM<W, B>> fb) {
        final WriterM<W, B> wb = fb.apply(value());
        return writer(wb.value(), monoid().combine(written(), wb.written()));
    }

    default <B> WriterM<W, B> app(WriterM<W, Functions.F<A, B>> wtrF) {
        final B b = wtrF.value().apply(this.value());
        final W w = wtrF.monoid().combine(wtrF.written(), this.written());
        return writer(b, w);
    }

    default <B> WriterM<W, B> map(Functions.F<A, B> f) {
        return writer(f.apply(value()), written());
    }
}


text:
enum FdoLongTransactionFreezeOperations
{
    /// Freeze the long transaction for exclusive update.
    FdoLongTransactionFreezeOperations_Freeze,

    /// Thaw the long transaction.
    FdoLongTransactionFreezeOperations_Thaw
};
#endif


text:
package keeper

import (
	"github.com/cosmos/cosmos-sdk/store/prefix"
	sdk "github.com/cosmos/cosmos-sdk/types"
	"github.com/zigbee-alliance/distributed-compliance-ledger/x/dclauth/types"
)

// SetRejectedAccount set a specific rejectedAccount in the store from its index.
func (k Keeper) SetRejectedAccount(ctx sdk.Context, rejectedAccount types.RejectedAccount) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RejectedAccountKeyPrefix))
	b := k.cdc.MustMarshal(&rejectedAccount)
	store.Set(types.RejectedAccountKey(
		rejectedAccount.GetAddress(),
	), b)
}

// GetRejectedAccount returns a rejectedAccount from its index.
func (k Keeper) GetRejectedAccount(
	ctx sdk.Context,
	address sdk.AccAddress,
) (val types.RejectedAccount, found bool) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RejectedAccountKeyPrefix))

	b := store.Get(types.RejectedAccountKey(
		address,
	))
	if b == nil {
		return val, false
	}

	k.cdc.MustUnmarshal(b, &val)

	return val, true
}

// RemoveRejectedAccount removes a rejectedAccount from the store.
func (k Keeper) RemoveRejectedAccount(
	ctx sdk.Context,
	address sdk.AccAddress,
) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RejectedAccountKeyPrefix))
	store.Delete(types.RejectedAccountKey(
		address,
	))
}

// GetAllRejectedAccount returns all rejectedAccount.
func (k Keeper) GetAllRejectedAccount(ctx sdk.Context) (list []types.RejectedAccount) {
	store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.RejectedAccountKeyPrefix))
	iterator := sdk.KVStorePrefixIterator(store, []byte{})

	defer iterator.Close()

	for ; iterator.Valid(); iterator.Next() {
		var val types.RejectedAccount
		k.cdc.MustUnmarshal(iterator.Value(), &val)
		list = append(list, val)
	}

	return
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
GwtIncompatible (Google Collections Library 1.0 (FINAL))
</TITLE>

<META NAME="date" CONTENT="2009-12-30">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: REQUIRED | OPTIONAL

DETAIL: ELEMENT

com.google.common.annotations

Annotation Type GwtIncompatible

@Retention(value=CLASS)
@Target(value=METHOD)
public @interface GwtIncompatible

The presence of this annotation on a method indicates that the method may
 not be used with the
 Google Web Toolkit (GWT),
 even though its type is annotated as GwtCompatible and accessible in
 GWT.  They can cause GWT compilation errors or simply unexpected exceptions
 when used in GWT.

Note that this annotation should only be applied to methods of types which
 are annotated as GwtCompatible.

Author:

Charles Fry

Required Element Summary

 String
value

          Describes why the annotated element is incompatible with GWT.

Element Detail

value

public abstract String value

Describes why the annotated element is incompatible with GWT. Since this is
 generally due to a dependence on a type/method which GWT doesn't support,
 it is sufficient to simply reference the unsupported type/method. E.g.
 "Class.isInstance".

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: REQUIRED | OPTIONAL

DETAIL: ELEMENT


text:
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;

namespace Soothsharp.Translation.Trees.Silver
{
    class CallSilvernode : ExpressionSilvernode
    {
        private List<Silvernode> expressions;
        private Identifier identifier;

        public CallSilvernode(
            Identifier identifier,
            List<Silvernode> expressions,
            SilverType returnType,
            SyntaxNode originalNode) : base(originalNode, returnType)
        {
            this.identifier = identifier;
            this.expressions = expressions;
        }

        public override string ToString()
        {
            return this.identifier + " (" + String.Join(", ", this.expressions) + ")";
        }
    }
}


text:
'use strict';

module.exports = addressOrComponents => {

  const components = Array.isArray(addressOrComponents) ? addressOrComponents
    : (addressOrComponents || {}).address_components || [];

  function get(type) {
    for (let ac of components) {
      const cmpnt = ac || {};
      const types = cmpnt.types || [];
      for (let ct of types) {
        if (ct === type) {
          return cmpnt;
        }
      }
    }
  }

  function getName(type) {
    const cmpnt = get(type);
    return (cmpnt) ? cmpnt.short_name : undefined;
  }

  return { get, getName };
};


text:
import logging
import os

from cookiecutter.hooks import _HOOKS

_HOOKS_EXT = ['.py', '.sh']

def find_hooks():
    """
    Must be called with the project template as the current working directory.
    Returns a dict of all hook scripts provided.
    Dict's key will be the hook/script's name, without extension, while
    values will be the absolute path to the script.
    Missing scripts will not be included in the returned dict.
    """
    hooks_dir = 'hooks'
    r = {}
    logging.debug('hooks_dir is {0}'.format(hooks_dir))
    if not os.path.isdir(hooks_dir):
        logging.debug('No hooks/ dir in template_dir')
        return r
    for f in os.listdir(hooks_dir):
        basename, ext = os.path.splitext(os.path.basename(f))
        if basename in _HOOKS and ext in _HOOKS_EXT:
            r[basename] = os.path.abspath(os.path.join(hooks_dir, f))
    return r

def patch():
    from cookiecutter import hooks
    hooks.find_hooks = find_hooks


text:
#include <list>
#include <string>

#include "gtest/gtest.h"
#include "gmock/gmock.h"

#include "protocolrecords/GetApplicationsRequest.h"

using std::list;
using std::string;
using namespace libyarn;
using namespace testing;

class TestGetApplicationsRequest: public ::testing::Test {
protected:
	GetApplicationsRequest getRequest;
};

TEST_F(TestGetApplicationsRequest, TestGetApplicationRequest)
{
	GetApplicationsRequestProto getRequestProto;
	getRequest = GetApplicationsRequestProto(getRequestProto);

	SUCCEED();
}

TEST_F(TestGetApplicationsRequest, TestGetApplicationTypes)
{
	list<string> applicationTypes;
	list<string> retApplicationTypes;
	string type("type");
	applicationTypes.push_back(type);

	getRequest.setApplicationTypes(applicationTypes);
	retApplicationTypes = getRequest.getApplicationTypes();

	EXPECT_TRUE(applicationTypes == retApplicationTypes);
}

TEST_F(TestGetApplicationsRequest, TestGetApplicationStatus)
{
	list<YarnApplicationState> applicationStates;
	list<YarnApplicationState> retApplicationStates;
	YarnApplicationState state;
	applicationStates.push_back(state);

	getRequest.setApplicationStates(applicationStates);
	retApplicationStates = getRequest.getApplicationStates();

	EXPECT_TRUE(applicationStates == retApplicationStates);
}


text:
/**
 * @file tgBasicContactCableInfo.h
 * @brief Definition of class tgBasicContactCableInfo
 * @author Brian Mirletz and Ryan Adams
 * @date October 2014
 * $Id$
 */

#ifndef SRC_TGCREATOR_TG_BASIC_CONTACT_CABLE_INFO_H
#define SRC_TGCREATOR_TG_BASIC_CONTACT_CABLE_INFO_H

#include "tgcreator/tgConnectorInfo.h"

#include "tgcreator/tgRigidInfo.h"

#include <string>

#include "core/tgBasicActuator.h"
#include "core/tgTags.h"

class tgBulletContactSpringCable;

class tgBasicContactCableInfo : public tgConnectorInfo
{
public:

    /**
     * Construct a tgBasicContactCableInfo with just a config. The pair must be filled in
     * later, or factory methods can be used to create instances with
     * pairs.
     */
    tgBasicContactCableInfo(const tgBasicActuator::Config& config);

    /**
     * Construct a tgBasicContactCableInfo with just a config and tags. The pair must
     * be filled in later, or factory methods can be used to create instances
     * with pairs.
     */
    tgBasicContactCableInfo(const tgBasicActuator::Config& config, tgTags tags);

    /**
     * Construct a tgBasicContactCableInfo from its endpoints, radius and density.
     * @param[in] from one endpoint
     * @param[in] to the other endpoint
     * @param[in] config contains the radius and density
     * @todo: make sure that tgPairs returns references to the vectors...
     */
    tgBasicContactCableInfo(const tgBasicActuator::Config& config, const tgPair& pair);

    virtual ~tgBasicContactCableInfo() {}

    /**
     * Create a tgConnectorInfo* from a tgPair
     */
    virtual tgConnectorInfo* createConnectorInfo(const tgPair& pair);

    void initConnector(tgWorld& world);

    virtual tgModel* createModel(tgWorld& world);

    double getMass();

protected:
    tgBulletContactSpringCable* m_bulletContactSpringCable;

private:

    tgBulletContactSpringCable* createTgBulletContactSpringCable(tgWorld& world);

private:

    tgBasicActuator::Config m_config;

};

#endif // SRC_TGCREATOR_TG_BASIC_CONTACT_CABLE_INFO_H


text:
using System.Collections.Generic;

namespace Tup.Cobar4Net.Parser.Ast.Expression.Primary.Function.Arithmetic
{
    /// <author>
    ///     QIU Shuo
    /// </author>
    public class Rand : FunctionExpression
    {
        public Rand(IList<IExpression> arguments)
            : base("RAND", arguments)
        {
        }

        public override FunctionExpression ConstructFunction(IList<IExpression> arguments)
        {
            return new Rand(arguments);
        }
    }
}


text:
============
Release 0.75
============

Hive Changes
------------

* The Hive S3 file system has a new configuration option,
  ``hive.s3.max-connections``, which sets the maximum number of
  connections to S3. The default has been increased from ``50`` to ``500``.

* The Hive connector now supports renaming tables. By default, this feature
  is not enabled. To enable it, set ``hive.allow-rename-table=true`` in
  your Hive catalog properties file.

General Changes
---------------

* Optimize :func:`count` with a constant to execute as the much faster ``count(*)``
* Add support for binary types to the JDBC driver
* The legacy byte code compiler has been removed
* New aggregation framework (~10% faster)
* Added :func:`max_by` aggregation function
* The ``approx_avg()`` function has been removed. Use :func:`avg` instead.
* Fixed parsing of ``UNION`` queries that use both ``DISTINCT`` and ``ALL``
* Fixed cross join planning error for certain query shapes
* Added hex and base64 conversion functions for varbinary
* Fix the ``LIKE`` operator to correctly match against values that contain
  multiple lines. Previously, it would stop matching at the first newline.
* Add support for renaming tables using the :doc:`/sql/alter-table` statement.
* Add basic support for inserting data using the :doc:`/sql/insert` statement.
  This is currently only supported for the Raptor connector.

JSON Function Changes
---------------------

The :func:`json_extract` and :func:`json_extract_scalar` functions now support
the square bracket syntax::

    SELECT json_extract(json, '$.store[book]');
    SELECT json_extract(json, '$.store["book name"]');

As part of this change, the set of characters allowed in a non-bracketed
path segment has been restricted to alphanumeric, underscores and colons.
Additionally, colons cannot be used in a un-quoted bracketed path segment.
Use the new bracket syntax with quotes to match elements that contain
special characters.

Scheduler Changes
-----------------

The scheduler now assigns splits to a node based on the current load on the node across all queries.
Previously, the scheduler load balanced splits across nodes on a per query level. Every node can have
``node-scheduler.max-splits-per-node`` splits scheduled on it. To avoid starvation of small queries,
when the node already has the maximum allowable splits, every task can schedule at most
``node-scheduler.max-pending-splits-per-node-per-task`` splits on the node.

Row Number Optimizations
------------------------

Queries that use the :func:`row_number` function are substantially faster
and can run on larger result sets for two types of queries.

Performing a partitioned limit that choses ``N`` arbitrary rows per
partition is a streaming operation. The following query selects
five arbitrary rows from ``orders`` for each ``orderstatus``::

    SELECT * FROM (
        SELECT row_number() OVER (PARTITION BY orderstatus) AS rn,
            custkey, orderdate, orderstatus
        FROM orders
    ) WHERE rn <= 5;

Performing a partitioned top-N that chooses the maximum or minimum
``N`` rows from each partition now uses significantly less memory.
The following query selects the five oldest rows based on ``orderdate``
from ``orders`` for each ``orderstatus``::

    SELECT * FROM (
        SELECT row_number() OVER (PARTITION BY orderstatus ORDER BY orderdate) AS rn,
            custkey, orderdate, orderstatus
        FROM orders
    ) WHERE rn <= 5;

Use the :doc:`/sql/explain` statement to see if any of these optimizations
have been applied to your query.

SPI Changes
-----------

The core Presto engine no longer automatically adds a column for ``count(*)``
queries. Instead, the ``RecordCursorProvider`` will receive an empty list of
column handles.

The ``Type`` and ``Block`` APIs have gone through a major refactoring in this
release. The main focus of the refactoring was to consolidate all type specific
encoding logic in the type itself, which makes types much easier to implement.
You should consider ``Type`` and ``Block`` to be a beta API as we expect
further changes in the near future.

To simplify the API, ``ConnectorOutputHandleResolver`` has been merged into
``ConnectorHandleResolver``. Additionally, ``ConnectorHandleResolver``,
``ConnectorRecordSinkProvider`` and ``ConnectorMetadata`` were modified to
support inserts.

.. note::
    This is a backwards incompatible change with the previous connector and
    type SPI, so if you have written a connector or type, you will need to update
    your code before deploying this release. In particular, make sure your
    connector can handle an empty column handles list (this can be verified
    by running ``SELECT count(*)`` on a table from your connector).


text:
package me.lucasmenendez.myrecipesapp.presenters;

import android.app.Activity;

import me.lucasmenendez.myrecipesapp.activities.LoginActivity;
import me.lucasmenendez.myrecipesapp.interactors.AuthInteractor;

/**
 * Created by kazzzweb on 11/6/16.
 */

public class LoginPresenter implements Presenter {
	private LoginActivity loginActivity;
	private AuthInteractor authInteractor;

	public LoginPresenter(LoginActivity loginActivity) {
		this.loginActivity = loginActivity;
		this.authInteractor = new AuthInteractor();

		if (this.authInteractor.authorized()) {
			this.authInteractor.restoreSession();
		}
	}

	public void doLogin(String username, String password) {
		this.authInteractor.doLogin(username, password);
	}

	public void successLogin() {
		this.loginActivity.successLogin();
	}
}


text:
require 'dm-core'
require 'dm-aggregates'
require 'will_paginate/per_page'
require 'will_paginate/page_number'
require 'will_paginate/collection'

module WillPaginate
  module DataMapper
    module Pagination
      def page(num)
        pagenum = ::WillPaginate::PageNumber(num.nil? ? 1 : num)
        per_page = query.limit || self.per_page
        options = {:offset => pagenum.to_offset(per_page).to_i}
        options[:limit] = per_page unless query.limit
        col = new_collection(query.merge(options))
        col.current_page = pagenum
        col
      end

      def paginate(options)
        options  = options.dup
        pagenum  = options.fetch(:page) { raise ArgumentError, ":page parameter required" }
        per_page = options.delete(:per_page) || self.per_page

        options.delete(:page)
        options[:limit] = per_page.to_i

        all(options).page(pagenum)
      end
    end

    module CollectionMethods
      include WillPaginate::CollectionMethods

      attr_accessor :current_page

      def paginated?
        !current_page.nil?
      end

      def per_page
        query.limit || model.per_page
      end

      def offset
        query.offset
      end

      def total_entries
        @total_entries ||= begin
          if loaded? and @array.size < per_page and (current_page == 1 or @array.size > 0)
            offset + @array.size
          else
            # :reload prevents Collection.filter from being run, which
            # would cause a stack overflow
            clean_query = query.merge(:reload => true)
            # seems like the only way
            clean_query.instance_variable_set('@limit', nil)
            clean_query.instance_variable_set('@offset', 0)
            new_collection(clean_query).count
          end
        end
      end

      def to_a
        if paginated?
          ::WillPaginate::Collection.create(current_page, per_page) do |col|
            col.replace super
            col.total_entries ||= total_entries
          end
        else
          super
        end
      end

      private

      def new_collection(query, resources = nil)
        col = super
        col.current_page = self.current_page
        col
      end

      def initialize_copy(original)
        super
        @total_entries = nil
      end
    end

    ::DataMapper::Model.append_extensions PerPage
    ::DataMapper::Model.append_extensions Pagination
    ::DataMapper::Collection.send(:include, Pagination)
    ::DataMapper::Collection.send(:include, CollectionMethods)
  end
end


text:
call _collect.bat
cd ..\_compile\_collectedForCompile
cmd /K dasm.exe demopart.asm -v3  -I..\..\..\Framework\trackmo\framework\ -l..\..\StartPicture\assembly.lst -s..\..\StartPicture\symbols.txt -o..\..\StartPicture\check.prg
cd ..\..\StartPicture