text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QualifyMemberAccess
{
    public partial class QualifyMemberAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
    {
        [Fact]
        [Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)]
        [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
        public async Task TestFixAllInSolution_QualifyMemberAccess()
        {
            var input = @"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document>
using System;

class C
{
    int Property { get; set; }
    int OtherProperty { get; set; }

    void M()
    {
        {|FixAllInSolution:Property|} = 1;
        var x = OtherProperty;
    }
}
        </Document>
        <Document>
using System;

class D
{
    string StringProperty { get; set; }
    int field;

    void N()
    {
        StringProperty = string.Empty;
        field = 0; // ensure this doesn't get qualified
    }
}
        </Document>
    </Project>
</Workspace>";

            var expected = @"
<Workspace>
    <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
        <Document>
using System;

class C
{
    int Property { get; set; }
    int OtherProperty { get; set; }

    void M()
    {
        this.Property = 1;
        var x = this.OtherProperty;
    }
}
        </Document>
        <Document>
using System;

class D
{
    string StringProperty { get; set; }
    int field;

    void N()
    {
        this.StringProperty = string.Empty;
        field = 0; // ensure this doesn't get qualified
    }
}
        </Document>
    </Project>
</Workspace>";

            await TestInRegularAndScriptAsync(
                initialMarkup: input,
                expectedMarkup: expected,
                options: Option(CodeStyleOptions2.QualifyPropertyAccess, true, NotificationOption2.Suggestion));
        }
    }
}


text:
#ifndef TRC_STREAMING_PORT_H
#define TRC_STREAMING_PORT_H

#ifdef __cplusplus
extern "C" {
#endif

int32_t itm_write(void* ptrData, uint32_t size, int32_t* ptrBytesWritten);
int32_t read_from_host(void* ptrData, uint32_t size, int32_t* ptrBytesRead);

/*******************************************************************************
 * TRC_CFG_ITM_PORT
 *
 * Possible values: 0 - 31
 *
 * What ITM port to use for the ITM software events. Make sure the IDE is
 * configured for the same channel.
 *
 * Default: 1 (0 is typically terminal output and 31 is used by Keil)
 *
 ******************************************************************************/
#define TRC_CFG_ITM_PORT 1

#if (TRC_CFG_ITM_PORT < 0) || (TRC_CFG_ITM_PORT > 31)
#error "Bad ITM port selected."
#endif

// Not used for ITM - no RAM buffer...
#define TRC_STREAM_PORT_ALLOCATE_FIELDS()

// Not used for ITM - assume the IDE configures the ITM setup
#define TRC_STREAM_PORT_INIT()

/* Important for the ITM port - no RAM buffer, direct writes. In most other ports this can be skipped (default is 1) */
#define TRC_STREAM_PORT_USE_INTERNAL_BUFFER 0

#define TRC_STREAM_PORT_WRITE_DATA(_ptrData, _size, _ptrBytesWritten) itm_write(_ptrData, _size, _ptrBytesWritten)

#define TRC_STREAM_PORT_READ_DATA(_ptrData, _size, _ptrBytesRead) read_from_host(_ptrData, _size, _ptrBytesRead)

#ifdef __cplusplus
}
#endif

#endif /* TRC_STREAMING_PORT_H */

redpajama_set_name: RedPajamaGithub


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

<title>All Classes</title>
<meta name="date" content="2015-04-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

AdmRecoOnlyPreferences

AudioCompressionType

AudioStream

Confidence

Contract

ConversationBase

DataRecognitionClient

DataRecognitionClientWithIntent

Intent

ISpeechRecognitionServerEvents

MicrophoneRecognitionClient

MicrophoneRecognitionClientWithIntent

RecognitionResult

RecognitionStatus

RecognizedPhrase

SpeechAudioFormat

SpeechRecognitionMode

SpeechRecognitionServiceFactory


text:
package jp.gr.java_conf.daisy.ajax_mutator.mutation_generator;

import org.mozilla.javascript.ast.AstNode;

import java.io.InputStream;
import java.util.List;

public class UnifiedDiffGeneratorForTest extends UnifiedDiffGenerator {
    public UnifiedDiffGeneratorForTest(InputStream inputStream) {
        super("fake.js", 100000000L, inputStream);
    }

    @Override
    public String generateUnifiedDiff(
            AstNode mutatedNode, List<String> mutatingContent) {
        return super.generateUnifiedDiff(mutatedNode, mutatingContent);
    }
}


text:
package uk.ac.ebi.eva.commons.beacon.models;

import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;

import com.fasterxml.jackson.annotation.JsonCreator;

/**
 * Gets or Sets SharingMode
 */
public enum SharingMode {
  UNKNOWN("UNKNOWN"),
    DISCOVERY("DISCOVERY"),
    ACCESS("ACCESS"),
    DISCOVERY_AND_ACCESS("DISCOVERY_AND_ACCESS");

  private String value;

  SharingMode(String value) {
    this.value = value;
  }

  @Override
  @JsonValue
  public String toString() {
    return String.valueOf(value);
  }

  @JsonCreator
  public static SharingMode fromValue(String text) {
    for (SharingMode b : SharingMode.values()) {
      if (String.valueOf(b.value).equals(text)) {
        return b;
      }
    }
    return null;
  }
}


text:
package com.sector91.wit.log;

import java.io.IOException;
import java.io.PrintStream;

import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class ConsoleLogger implements Logger {

  private static final DateTimeFormatter format = DateTimeFormat.mediumTime();

  private final PrintStream out;

  public ConsoleLogger() {
    this(System.out);
  }

  public ConsoleLogger(PrintStream stream) {
    out = stream;
  }

  @Override public void log(LogEntry entry) throws IOException {
    switch (entry.level()) {
      case ERROR:
        out.print("[ERR] ");
        break;
      case WARN:
        out.print("[WRN] ");
        break;
      case INFO:
        out.print("[INF] ");
        break;
      case DEBUG:
        out.print("[DBG] ");
        break;
      case TRACE:
        out.print("[TRC] ");
        break;
    }
    out.print(' ');
    out.print(entry.time().toString(format));
    out.print(" | ");
    out.print(entry.category());
    out.print(": ");
    out.print(entry.message());
    out.println();
    if (entry.hasException()) {
      entry.exception().printStackTrace(out);
    }
  }
}


text:
package main

import (
	"os/exec"
	"strings"
	"time"

	"github.com/go-check/check"
)

func (s *DockerSuite) TestCliStatsNoStream(c *check.C) {
	out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-d", "busybox", "top"))
	if err != nil {
		c.Fatalf("Error on container creation: %v, output: %s", err, out)
	}
	id := strings.TrimSpace(out)
	if err := waitRun(id); err != nil {
		c.Fatalf("error waiting for container to start: %v", err)
	}

	statsCmd := exec.Command(dockerBinary, "stats", "--no-stream", id)
	chErr := make(chan error)
	go func() {
		chErr <- statsCmd.Run()
	}()

	select {
	case err := <-chErr:
		if err != nil {
			c.Fatalf("Error running stats: %v", err)
		}
	case <-time.After(2 * time.Second):
		statsCmd.Process.Kill()
		c.Fatalf("stats did not return immediately when not streaming")
	}
}


text:
/**
 * THIS FILE IS AUTO-GENERATED
 * DON'T MAKE CHANGES HERE
 */
import { typedDependencies } from './dependenciesTyped.generated'
import { createSech } from '../../factoriesNumber.js'

export const sechDependencies = {
  typedDependencies,
  createSech
}


text:
<?php

/**
 * Gearman Monitor configuration file
 *
 * The following server fields are available:
 *  - address: Gearman server address, hostname and port
 *  - name: Gearman server name to display in Gearman Monitor interface
 *
 * Example:
 * $cfgServers[$i]['address'] = '192.168.0.10:4730';
 * $cfgServers[$i]['name'] = 'Gearman server 1';
 * ++ $i;
 *
 * $cfgServers[$i]['address'] = '192.168.1.1:7003';
 * $cfgServers[$i]['name'] = 'Gearman server 2';
 * ++ $i;
 */

$i = 0;
$cfgServers = array();

$cfgServers[$i]['address'] = '';
$cfgServers[$i]['name'] = '';
++ $i;

?>


text:
package org.apache.http.nio.reactor;

/**
 * IOEventDispatch interface is used by I/O reactors to notify clients of I/O
 * events pending for a particular session. All methods of this interface are
 * executed on a dispatch thread of the I/O reactor. Therefore, it is important
 * that processing that takes place in the event methods will not block the
 * dispatch thread for too long, as the I/O reactor will be unable to react to
 * other events.
 *
 * @since 4.0
 */
public interface IOEventDispatch {

    /**
     * Attribute name of an object that represents a non-blocking connection.
     */
    public static final String CONNECTION_KEY = "http.connection";

    /**
     * Triggered after the given session has been just created.
     *
     * @param session the I/O session.
     */
    void connected(IOSession session);

    /**
     * Triggered when the given session has input pending.
     *
     * @param session the I/O session.
     */
    void inputReady(IOSession session);

    /**
     * Triggered when the given session is ready for output.
     *
     * @param session the I/O session.
     */
    void outputReady(IOSession session);

    /**
     * Triggered when the given session as timed out.
     *
     * @param session the I/O session.
     */
    void timeout(IOSession session);

    /**
     * Triggered when the given session has been terminated.
     *
     * @param session the I/O session.
     */
    void disconnected(IOSession session);

}


text:
using System;

namespace VirtFunc
{
    public class CDerived12
    {
        public override int GetHashCode() { return 12; }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='main.css') }}">
    <link id="favicon" rel="shortcut icon" type="image/png" href="static/images/favicon.png" />

        USS Qualifier Host
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">

        </button>

            {% if session['user_id'] %}
              {{session['name']}}
              Logout
            {% else %}
              Login
            {% endif %}

    {% block head %}{% endblock %}

        <title>USS Qualifier host</title>

                {% with messages = get_flashed_messages(with_categories=true) %}
                  {% if messages %}
                    {% for category, message in messages %}

                        {{ message }}

                    {% endfor %}
                  {% endif %}
                {% endwith %}
                {% block body %}{% endblock %}


text:
package com.google.inject.example;

import static com.google.inject.example.JndiProvider.fromJndi;

import com.google.inject.AbstractModule;
import com.google.inject.CreationException;
import com.google.inject.Guice;
import com.google.inject.Injector;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

class JndiProviderClient {

    public static void main(String[] args) throws CreationException {
        Injector injector = Guice.createInjector(new AbstractModule() {
            protected void configure() {
                // Bind Context to the default InitialContext.
                bind(Context.class).to(InitialContext.class);

                // Bind to DataSource from JNDI.
                bind(DataSource.class)
                        .toProvider(fromJndi(DataSource.class, "..."));
            }
        });
    }
}


text:
package com.lohool.ola.wedgit;

import org.w3c.dom.*;

import com.lohool.ola.UIFactory;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Gravity;
import android.widget.RelativeLayout;

//Layout
@SuppressLint("NewApi")
public class IRelativeLayout extends Layout
{

	String layout="RelativeLayout";

	public IRelativeLayout(Context context) {
		//super(context);
		super(null,context,null,null);
		RelativeLayout t=new RelativeLayout(context);
		v=t;
		super.initiate();
		t.setGravity(css.getGravity());
		parseChildren(this,root);

	}

	public IRelativeLayout(IView parent,Context context,Node root,UIFactory ui) {
		super(parent, context,  root,ui);

		RelativeLayout t=new RelativeLayout(context);
		v=t;

		super.initiate();
		t.setGravity(css.getGravity());
		parseChildren(this,root);

	}

}


text:
class ExtensionService;

namespace extensions {

class ExtensionSystem;
class ManagementPolicy;

namespace api {

class EntryPicker;
class EntryPickerClient;

namespace developer_private {

struct ItemInfo;
struct ItemInspectView;
struct ProjectInfo;

}

}  // namespace api

}  // namespace extensions

namespace developer = extensions::api::developer_private;

typedef std::vector<linked_ptr<developer::ItemInfo> > ItemInfoList;
typedef std::vector<linked_ptr<developer::ProjectInfo> > ProjectInfoList;
typedef std::vector<linked_ptr<developer::ItemInspectView> >
    ItemInspectViewList;

namespace extensions {

// The profile-keyed service that manages the DeveloperPrivate API.
class DeveloperPrivateAPI : public ProfileKeyedService,
                            public content::NotificationObserver {
 public:
  // Convenience method to get the DeveloperPrivateAPI for a profile.
  static DeveloperPrivateAPI* Get(Profile* profile);

  explicit DeveloperPrivateAPI(Profile* profile);
  virtual ~DeveloperPrivateAPI();

  void SetLastUnpackedDirectory(const base::FilePath& path);

  base::FilePath& GetLastUnpackedDirectory() {
    return last_unpacked_directory_;
  }

  // ProfileKeyedService implementation
  virtual void Shutdown() OVERRIDE;

  // content::NotificationObserver implementation.
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

 private:
  void RegisterNotifications();

  // Used to start the load |load_extension_dialog_| in the last directory that
  // was loaded.
  base::FilePath last_unpacked_directory_;

  content::NotificationRegistrar registrar_;

};

namespace api {

class DeveloperPrivateAutoUpdateFunction : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.autoUpdate",
                             DEVELOPERPRIVATE_AUTOUPDATE)

 protected:
  virtual ~DeveloperPrivateAutoUpdateFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateGetItemsInfoFunction : public AsyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.getItemsInfo",
                             DEVELOPERPRIVATE_GETITEMSINFO)

 protected:
  virtual ~DeveloperPrivateGetItemsInfoFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;

 private:

  scoped_ptr<developer::ItemInfo> CreateItemInfo(
      const extensions::Extension& item,
      bool item_is_enabled);

  void GetIconsOnFileThread(
      ItemInfoList item_list,
      std::map<std::string, ExtensionResource> itemIdToIconResourceMap);

  // Helper that lists the current inspectable html pages for the extension.
  void GetInspectablePagesForExtensionProcess(
      const std::set<content::RenderViewHost*>& views,
      ItemInspectViewList* result);

  ItemInspectViewList GetInspectablePagesForExtension(
      const extensions::Extension* extension,
      bool extension_is_enabled);

  void GetShellWindowPagesForExtensionProfile(
      const extensions::Extension* extension,
      ItemInspectViewList* result);

  linked_ptr<developer::ItemInspectView> constructInspectView(
      const GURL& url,
      int render_process_id,
      int render_view_id,
      bool incognito);
};

class DeveloperPrivateInspectFunction : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.inspect",
                             DEVELOPERPRIVATE_INSPECT)

 protected:
  virtual ~DeveloperPrivateInspectFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateAllowFileAccessFunction : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.allowFileAccess",
                             DEVELOPERPRIVATE_ALLOWFILEACCESS);

 protected:
  virtual ~DeveloperPrivateAllowFileAccessFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateAllowIncognitoFunction : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.allowIncognito",
                             DEVELOPERPRIVATE_ALLOWINCOGNITO);

 protected:
  virtual ~DeveloperPrivateAllowIncognitoFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateReloadFunction : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.reload",
                             DEVELOPERPRIVATE_RELOAD);

 protected:
  virtual ~DeveloperPrivateReloadFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateShowPermissionsDialogFunction
    : public SyncExtensionFunction,
      public ExtensionInstallPrompt::Delegate {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.showPermissionsDialog",
                             DEVELOPERPRIVATE_PERMISSIONS);

  DeveloperPrivateShowPermissionsDialogFunction();
 protected:
  virtual ~DeveloperPrivateShowPermissionsDialogFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;

  // Overridden from ExtensionInstallPrompt::Delegate
  virtual void InstallUIProceed() OVERRIDE;
  virtual void InstallUIAbort(bool user_initiated) OVERRIDE;

  scoped_ptr<ExtensionInstallPrompt> prompt_;

};

class DeveloperPrivateRestartFunction : public SyncExtensionFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.restart",
                             DEVELOPERPRIVATE_RESTART);

 protected:
  virtual ~DeveloperPrivateRestartFunction();

  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateEnableFunction
    : public SyncExtensionFunction,
      public base::SupportsWeakPtr<DeveloperPrivateEnableFunction> {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.enable",
                             DEVELOPERPRIVATE_ENABLE);

  DeveloperPrivateEnableFunction();

 protected:
  virtual ~DeveloperPrivateEnableFunction();

  // Callback for requirements checker.
  void OnRequirementsChecked(std::string extension_id,
                             std::vector<std::string> requirements_errors);
  // ExtensionFunction:
  virtual bool RunImpl() OVERRIDE;

 private:
  scoped_ptr<extensions::RequirementsChecker> requirements_checker_;
};

class DeveloperPrivateChooseEntryFunction : public AsyncExtensionFunction,
                                            public EntryPickerClient {
 protected:
  virtual ~DeveloperPrivateChooseEntryFunction();
  virtual bool RunImpl() OVERRIDE;
  bool ShowPicker(ui::SelectFileDialog::Type picker_type,
                  const base::FilePath& last_directory,
                  const string16& select_title,
                  const ui::SelectFileDialog::FileTypeInfo& info,
                  int file_type_index);

  // EntryPickerClient functions.
  virtual void FileSelected(const base::FilePath& path) = 0;
  virtual void FileSelectionCanceled() = 0;
};

class DeveloperPrivateLoadUnpackedFunction
    : public DeveloperPrivateChooseEntryFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.loadUnpacked",
                             DEVELOPERPRIVATE_LOADUNPACKED);

 protected:
  virtual ~DeveloperPrivateLoadUnpackedFunction();
  virtual bool RunImpl() OVERRIDE;

  // EntryPickerCLient implementation.
  virtual void FileSelected(const base::FilePath& path) OVERRIDE;
  virtual void FileSelectionCanceled() OVERRIDE;
};

class DeveloperPrivateChoosePathFunction
    : public DeveloperPrivateChooseEntryFunction {
 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.choosePath",
                             DEVELOPERPRIVATE_CHOOSEPATH);

 protected:
  virtual ~DeveloperPrivateChoosePathFunction();
  virtual bool RunImpl() OVERRIDE;

  // EntryPickerClient functions.
  virtual void FileSelected(const base::FilePath& path) OVERRIDE;
  virtual void FileSelectionCanceled() OVERRIDE;
};

class DeveloperPrivatePackDirectoryFunction
    : public AsyncExtensionFunction,
      public extensions::PackExtensionJob::Client {

 public:
  DECLARE_EXTENSION_FUNCTION("developerPrivate.packDirectory",
                             DEVELOPERPRIVATE_PACKDIRECTORY);

  DeveloperPrivatePackDirectoryFunction();

  // ExtensionPackJob::Client implementation.
  virtual void OnPackSuccess(const base::FilePath& crx_file,
                             const base::FilePath& key_file) OVERRIDE;
  virtual void OnPackFailure(
      const std::string& error,
      extensions::ExtensionCreator::ErrorType error_type) OVERRIDE;

 protected:
  virtual ~DeveloperPrivatePackDirectoryFunction();
  virtual bool RunImpl() OVERRIDE;

 private:
  scoped_refptr<extensions::PackExtensionJob> pack_job_;
  std::string item_path_str_;
  std::string key_path_str_;
};

class DeveloperPrivateGetStringsFunction : public SyncExtensionFunction {
  public:
   DECLARE_EXTENSION_FUNCTION("developerPrivate.getStrings",
                              DEVELOPERPRIVATE_GETSTRINGS);

  protected:
   virtual ~DeveloperPrivateGetStringsFunction();

   // ExtensionFunction
   virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateExportSyncfsFolderToLocalfsFunction
    : public AsyncExtensionFunction {
  public:
   DECLARE_EXTENSION_FUNCTION("developerPrivate.exportSyncfsFolderToLocalfs",
                              DEVELOPERPRIVATE_LOADUNPACKEDCROS);

   DeveloperPrivateExportSyncfsFolderToLocalfsFunction();

  protected:
   virtual ~DeveloperPrivateExportSyncfsFolderToLocalfsFunction();

   // ExtensionFunction
   virtual bool RunImpl() OVERRIDE;

   void ClearPrexistingDirectoryContent(const base::FilePath& project_path);

   void ReadSyncFileSystemDirectory(const base::FilePath& project_path);

   void ReadSyncFileSystemDirectoryCb(
       const base::FilePath& project_path,
       base::PlatformFileError result,
       const fileapi::FileSystemOperation::FileEntryList& file_list,
       bool has_more);

   void CreateFolderAndSendResponse(const base::FilePath& project_path);

   void SnapshotFileCallback(
       const base::FilePath& target_path,
       base::PlatformFileError result,
       const base::PlatformFileInfo& file_info,
       const base::FilePath& platform_path,
       const scoped_refptr<webkit_blob::ShareableFileReference>& file_ref);

   void CopyFile(const base::FilePath& src_path,
                 const base::FilePath& dest_path);

   scoped_refptr<fileapi::FileSystemContext> context_;

  private:
   int pendingCallbacksCount_;

   // This is set to false if any of the copyFile operations fail on
   // call of the API. It is returned as a response of the API call.
   bool success_;
};

class DeveloperPrivateLoadProjectToSyncfsFunction
    : public AsyncExtensionFunction {
  public:
   DECLARE_EXTENSION_FUNCTION("developerPrivate.loadProjectToSyncfs",
                              DEVELOPERPRIVATE_LOADPROJECTTOSYNCFS);

   DeveloperPrivateLoadProjectToSyncfsFunction();

  protected:
   virtual ~DeveloperPrivateLoadProjectToSyncfsFunction();

   // ExtensionFunction
   virtual bool RunImpl() OVERRIDE;

   void CopyFolder(const base::FilePath::StringType& project_name);

   void CopyFiles(const std::vector<base::FilePath>& paths);

   void CopyFilesCallback(const base::PlatformFileError result);

  private:
   // Number of pending copy files callbacks.
   // It should only be modified on the IO Thread.
   int pendingCallbacksCount_;

   // True only when all the copyFiles job are successful.
   // It should only be modified on the IO thread.
   bool success_;

   scoped_refptr<fileapi::FileSystemContext> context_;
};

class DeveloperPrivateGetProjectsInfoFunction : public AsyncExtensionFunction {
  public:
   DECLARE_EXTENSION_FUNCTION("developerPrivate.getProjectsInfo",
                              DEVELOPERPRIVATE_GETPROJECTSINFO);

   DeveloperPrivateGetProjectsInfoFunction();

  protected:
   virtual ~DeveloperPrivateGetProjectsInfoFunction();

   void ReadFolder();

   // ExtensionFunction
   virtual bool RunImpl() OVERRIDE;
};

class DeveloperPrivateLoadProjectFunction : public AsyncExtensionFunction {
  public:
   DECLARE_EXTENSION_FUNCTION("developerPrivate.loadProject",
                              DEVELOPERPRIVATE_LOADPROJECT);

   DeveloperPrivateLoadProjectFunction();

  protected:
   virtual ~DeveloperPrivateLoadProjectFunction();

   // ExtensionFunction
   virtual bool RunImpl() OVERRIDE;

   void GetUnpackedExtension(const base::FilePath& path,
                             const ExtensionSet* extensions);
};

}  // namespace api

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_DEVELOPER_PRIVATE_DEVELOPER_PRIVATE_API_H_


text:
![image](https://cdn.images.express.co.uk/img/dynamic/80/590x/Monster-635042.jpg)
# Objectif
Créer une application qui selon une liste d'aliment donne le nombre de calories du repas.
Même si on est pas des desiigners, le design doit être soigné.

# Stories
* En tant que consommateur je souhaite pouvoir entrer ma taille, mon poids, mon âge et si je suis un homme ou une femme pour calculer le nombre de calories nécessaires par jour (kcal)
* En tant que consommateur je souhaite pouvoir concevoir mon menu habituel (boisson, plats) et la quantité en grammes
* En tant que consommateur je souhaite pouvoir voir le nombre de calories que comporte mon repas
* En tant que consommateur je souhaite pouvoir enregistré mon menu

# Note
Utiliser la formule de de Harris et Benedict pour calculer les besoins caloriques quotidiens moyens estimés: https://fr.wikipedia.org/wiki/Métabolisme_de_base

# Contraintes
* Utiliser typescript
* Faire une application one page sans utiliser de framework telles que Angular, React, Backbone, etc.
* La liste des aliments doit être stocké dans un fichier json
* Héberger sur github
* Ajouter la phrase suivante en rouge en bas du site :
"ATTENTION : ces pages n'ont PAS été faites sous le contrôle d'un diététicien ou d'un nutritionniste. Ce site ne peut pas, ne doit pas servir dans le cadre d'un régime, ou pire, dans un cadre médical. Il s'agit uniquement d'un outil destiné à sensibiliser les élèves. En cas de doutes sur vos pratiques alimentaires, consultez un médecin ou un diététicien."

# Bonus
* Afficher le l'IMC du consommateur
* Afficher le nombre de calories nécessaires par jour en utilisant la formule de formule de Black et al.
* Stocker les choix du consommateur dans une base de données MongoDB

# Mode hardcore
* Ne pas utiliser de framework javascript (jquery etc.)


text:
function Test-SqlAgent {
    <#
    .SYNOPSIS
        Internal function. Checks to see if SQL Server Agent is running on a server.
    #>
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential
    )

    if ($SqlInstance.GetType() -ne [Microsoft.SqlServer.Management.Smo.Server]) {
        $SqlInstance = Connect-DbaInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    }

    if ($null -eq $SqlInstance.JobServer) { return $false }
    try { $null = $SqlInstance.JobServer.script(); return $true }
    catch { return $false }
}


text:
#region Using Directives

using System;

#endregion Using Directives

namespace ScintillaNET
{
    /// <summary>
    ///     Style of smart indent
    /// </summary>
    public enum SmartIndent
    {
        /// <summary>
        ///     No smart indent
        /// </summary>
        None = 0,

        /// <summary>
        ///     C++ style indenting
        /// </summary>
        CPP = 1,

        /// <summary>
        ///     Alternate C++ style indenting
        /// </summary>
        CPP2 = 4,

        /// <summary>
        ///     Block indenting, the last indentation is retained in new lines
        /// </summary>
        Simple = 2
    }
}


text:
package org.ovirt.engine.ui.webadmin.section.main.view.tab.virtualMachine;

import org.ovirt.engine.core.common.businessentities.AuditLog;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.system.ClientStorage;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.uicommonweb.models.vms.VmEventListModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.VmListModel;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.virtualMachine.SubTabVirtualMachineEventPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabEventView;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;

public class SubTabVirtualMachineEventView extends AbstractSubTabEventView<VM, VmListModel, VmEventListModel>
        implements SubTabVirtualMachineEventPresenter.ViewDef {

    interface ViewIdHandler extends ElementIdHandler<SubTabVirtualMachineEventView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @Inject
    public SubTabVirtualMachineEventView(SearchableDetailModelProvider<AuditLog, VmListModel, VmEventListModel> modelProvider,
            EventBus eventBus,
            ClientStorage clientStorage) {
        super(modelProvider, eventBus, clientStorage);
    }

    @Override
    protected void generateIds() {
        ViewIdHandler.idHandler.generateAndSetIds(this);
    }

}


text:
.class public final Landroid/R$raw;
.super Ljava/lang/Object;
.source "R.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/R;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "raw"
.end annotation

# static fields
.field public static final accessibility_gestures:I = 0x1100000

.field public static final fallbackring:I = 0x1100001

.field public static final incognito_mode_start_page:I = 0x1100002

.field public static final loaderror:I = 0x1100003

.field public static final nodomain:I = 0x1100004

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 22553
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method


text:
START_ATF_NAMESPACE
    typedef _PROVIDOR_INFO_2A *LPPROVIDOR_INFO_2A;
END_ATF_NAMESPACE


text:
//
//  UIView+XMGExtension.h
//  2期-百思不得姐
//
//  Created by apple on 15/8/15.
//  Copyright (c) 2015年 小码哥. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (XMGExtension)
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@property (nonatomic, assign) CGFloat centerX;
@property (nonatomic, assign) CGFloat centerY;
@end

/**
 1.@property如果不是写在分类中, 会自动生成
 1> 属性的setter\getter声明和实现
 2> _下划线开头的成员变量

 2.@property如果是写在分类中, 仅仅会自动生成
 1> 属性的setter\getter声明
 */


text:
#import <Foundation/Foundation.h>
#import "SNSListEndpointsByPlatformApplicationResponse.h"
#import "SNSResponseUnmarshaller.h"
#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonValueUnmarshaller.h>
#import <AWSRuntime/AmazonBoolValueUnmarshaller.h>
#else
#import "AmazonValueUnmarshaller.h"
#import "AmazonBoolValueUnmarshaller.h"
#endif

#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonListUnmarshaller.h>
#else
#import "AmazonListUnmarshaller.h"
#endif
#import "SNSEndpointUnmarshaller.h"

/**
 * List Endpoints By Platform Application Result Unmarshaller
 */
@interface SNSListEndpointsByPlatformApplicationResponseUnmarshaller:SNSResponseUnmarshaller {
    SNSListEndpointsByPlatformApplicationResponse *response;
}

@property (nonatomic, readonly) SNSListEndpointsByPlatformApplicationResponse *response;

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;

@end


text:
class AP_API apHostSourceCodeBreakpoint : public apBreakPoint
{
public:
    /////////////////////////////////////////////////////////////////////////////
    /// \brief Default constructor
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    apHostSourceCodeBreakpoint() {}

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Additional constructor
    /// \param filePath a path for targen breakpoint file
    /// \param lineNum a breakpoint line number
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    apHostSourceCodeBreakpoint(const osFilePath& filePath, int lineNum = -1);

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Destructor
    /// \author Vadim Entov
    /// \date 12/09/2015
    ~apHostSourceCodeBreakpoint();

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Other breakpoint compare.
    ///
    /// \param otherBreakpoint a reference to comaparing breakpoint class instance
    ///
    /// \return In case self and target the same - true
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    virtual bool compareToOther(const apBreakPoint& otherBreakpoint) const; // override;

    // Overrides osTransferableObject:

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Get current class instance type
    ///
    /// \return instance type
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    virtual osTransferableObjectType type() const override;

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Serialization to channel
    ///
    /// \param ipcChannel a reference to ICP channel instance
    ///
    /// \return true on function call succedes or false
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    virtual bool writeSelfIntoChannel(osChannel& ipcChannel) const override;

    /////////////////////////////////////////////////////////////////////////////
    /// \brief DeSerialization from channel
    ///
    /// \param ipcChannel a reference to ICP channel instance
    ///
    /// \return true on function call succedes or false
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    virtual bool readSelfFromChannel(osChannel& ipcChannel) override;

    // Accessors:

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Set breakpoint line number
    ///
    /// \param lineNum a breakpoint line number
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    void setLineNumber(int lineNum) { m_lineNumber = lineNum; };

    /////////////////////////////////////////////////////////////////////////////
    /// \brief Get breakpoint line number
    ///
    /// \return breakpoint line number
    ///
    /// \author Vadim Entov
    /// \date 12/09/2015
    int lineNumber() const { return m_lineNumber; }

    // Breakpoint resolution:
    void setFilePath(const osFilePath& path) { m_FilePath = path; }

    const osFilePath& filePath() const { return m_FilePath; }

private:
    osFilePath m_FilePath; ///< breakpoint file path
    int        m_lineNumber;                 ///< breakpoiint line number
};

#endif //__APKERNELSOURCECODEBREAKPOINT_H


text:
package com.alibaba.json.bvt.issue_2200;

import com.alibaba.fastjson.JSON;
import junit.framework.TestCase;

import java.time.LocalDateTime;

public class Issue2206 extends TestCase {
    public void test_for_issue() throws Exception {
        JSON.parseObject("{\"date\":\"20181229162849\"}", Model.class);
    }

    public static class Model {
        public LocalDateTime date;
    }
}


text:
#include "perf_precomp.hpp"

#ifdef HAVE_OPENCV_OCL

using namespace cv;
using namespace cv::ocl;
using namespace std;

typedef perf::TestBaseWithParam<std::string> OCL_SURF;

#define SURF_IMAGES \
    "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\
    "stitching/a3.png"

#define OCL_TEST_CYCLE() for( ; startTimer(), next(); cv::ocl::finish(), stopTimer())

PERF_TEST_P(OCL_SURF, DISABLED_with_data_transfer, testing::Values(SURF_IMAGES))
{
    string filename = getDataPath(GetParam());
    Mat src = imread(filename, IMREAD_GRAYSCALE);
    ASSERT_FALSE(src.empty());

    Mat cpu_kp, cpu_dp;
    declare.time(60);

    if (getSelectedImpl() == "ocl")
    {
        SURF_OCL d_surf;
        oclMat d_keypoints, d_descriptors;

        OCL_TEST_CYCLE()
        {
            oclMat d_src(src);

            d_surf(d_src, oclMat(), d_keypoints, d_descriptors);

            d_keypoints.download(cpu_kp);
            d_descriptors.download(cpu_dp);
        }
    }
    else if (getSelectedImpl() == "plain")
    {
        cv::SURF surf;
        std::vector<cv::KeyPoint> kp;

        TEST_CYCLE() surf(src, Mat(), kp, cpu_dp);
    }

    SANITY_CHECK_NOTHING();
}

PERF_TEST_P(OCL_SURF, DISABLED_without_data_transfer, testing::Values(SURF_IMAGES))
{
    string filename = getDataPath(GetParam());
    Mat src = imread(filename, IMREAD_GRAYSCALE);
    ASSERT_FALSE(src.empty());

    Mat cpu_kp, cpu_dp;
    declare.time(60);

    if (getSelectedImpl() == "ocl")
    {
        SURF_OCL d_surf;
        oclMat d_keypoints, d_descriptors, d_src(src);

        OCL_TEST_CYCLE() d_surf(d_src, oclMat(), d_keypoints, d_descriptors);
    }
    else if (getSelectedImpl() == "plain")
    {
        cv::SURF surf;
        std::vector<cv::KeyPoint> kp;

        TEST_CYCLE() surf(src, Mat(), kp, cpu_dp);
    }

    SANITY_CHECK_NOTHING();
}

PERF_TEST_P(OCL_SURF, DISABLED_detect, testing::Values(SURF_IMAGES))
{
    String filename = getDataPath(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);
    ASSERT_FALSE(frame.empty()) << "Unable to load source image " << filename;

    declare.in(frame);

    Mat mask;
    vector<KeyPoint> points;
    Ptr<Feature2D> detector;

    if (getSelectedImpl() == "plain")
    {
        detector = new SURF;
        TEST_CYCLE() detector->operator()(frame, mask, points, noArray());
    }
    else if (getSelectedImpl() == "ocl")
    {
        detector = new ocl::SURF_OCL;
        OCL_TEST_CYCLE() detector->operator()(frame, mask, points, noArray());
    }
    else CV_TEST_FAIL_NO_IMPL();

    SANITY_CHECK_KEYPOINTS(points, 1e-3);
}

PERF_TEST_P(OCL_SURF, DISABLED_extract, testing::Values(SURF_IMAGES))
{
    String filename = getDataPath(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);
    ASSERT_FALSE(frame.empty()) << "Unable to load source image " << filename;

    declare.in(frame);

    Mat mask;
    Ptr<Feature2D> detector;
    vector<KeyPoint> points;
    vector<float> descriptors;

    if (getSelectedImpl() == "plain")
    {
        detector = new SURF;
        detector->operator()(frame, mask, points, noArray());
        TEST_CYCLE() detector->operator()(frame, mask, points, descriptors, true);
    }
    else if (getSelectedImpl() == "ocl")
    {
        detector = new ocl::SURF_OCL;
        detector->operator()(frame, mask, points, noArray());
        OCL_TEST_CYCLE() detector->operator()(frame, mask, points, descriptors, true);
    }
    else CV_TEST_FAIL_NO_IMPL();

    SANITY_CHECK(descriptors, 1e-4);
}

PERF_TEST_P(OCL_SURF, DISABLED_full, testing::Values(SURF_IMAGES))
{
    String filename = getDataPath(GetParam());
    Mat frame = imread(filename, IMREAD_GRAYSCALE);
    ASSERT_FALSE(frame.empty()) << "Unable to load source image " << filename;

    declare.in(frame).time(90);

    Mat mask;
    Ptr<Feature2D> detector;
    vector<KeyPoint> points;
    vector<float> descriptors;

    if (getSelectedImpl() == "plain")
    {
        detector = new SURF;
        TEST_CYCLE() detector->operator()(frame, mask, points, descriptors, false);
    }
    else if (getSelectedImpl() == "ocl")
    {
        detector = new ocl::SURF_OCL;
        detector->operator()(frame, mask, points, noArray());
        OCL_TEST_CYCLE() detector->operator()(frame, mask, points, descriptors, false);
    }
    else CV_TEST_FAIL_NO_IMPL();

    SANITY_CHECK_KEYPOINTS(points, 1e-3);
    SANITY_CHECK(descriptors, 1e-4);
}

#endif // HAVE_OPENCV_OCL


text:
<?xml version="1.0"?>
<opencv_storage>
<alpha>1.0000000000000000e-002</alpha>
<enableThreshold>1</enableThreshold>
<threshold>15</threshold>
<showOutput>0</showOutput>
</opencv_storage>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="fab_elevation_primary">6dp</dimen>
    <dimen name="fab_elevation_secondary">2dp</dimen>

    <dimen name="search_bar_margin_start">12dp</dimen>
    <dimen name="search_bar_margin_end">12dp</dimen>
    <dimen name="search_bar_margin_top">12dp</dimen>
    <dimen name="search_bar_margin_bottom">0dp</dimen>

</resources>


text:
package main

import (
	log "github.com/sirupsen/logrus"

	"flag"
	"io"
	"net/http"
	"os"

	rootLog "github.com/zqureshi/go/log"
	"github.com/zqureshi/go/redirect"
)

var (
	logger = &log.Logger{
		Out:       os.Stdout,
		Formatter: new(log.TextFormatter),
		Hooks:     make(log.LevelHooks),
		Level:     log.InfoLevel,
	}

	listenAddr     string
	airtableAPIKey string
	airtableBaseID string
)

func init() {
	flag.StringVar(&listenAddr, "listen", ":80", "[host]:port on which to bind server")
	flag.Parse()

	airtableAPIKey = os.Getenv("AIRTABLE_API_KEY")
	if airtableAPIKey == "" {
		logger.Fatal("AIRTABLE_API_KEY must be specified")
	}

	airtableBaseID = os.Getenv("AIRTABLE_BASE_ID")
	if airtableBaseID == "" {
		logger.Fatal("AIRTABLE_BASE_ID must be specified")
	}

	rootLog.SetLogger(logger)
}

func init() {
	http.HandleFunc("/_ah/health", func(w http.ResponseWriter, _ *http.Request) {
		io.WriteString(w, "PONG")
	})
}

func main() {
	c, err := redirect.NewClient(airtableAPIKey, airtableBaseID)
	if err != nil {
		logger.Fatal(err)
	}

	client, err := redirect.NewCachingClient(c)
	if err != nil {
		logger.Fatal(err)
	}

	defaultRedirect, err := client.Get(redirect.DefaultRedirectKey)
	if err != nil {
		logger.Fatal("A 'default' redirect must be specified")
	}
	logger.Info("Default redirect " + defaultRedirect.URL)

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		if r, err := client.Get(req.URL.Path[1:]); req.URL.Path != "/" && err == nil {
			http.Redirect(w, req, r.URL, 302)
		} else {
			d, _ := client.Get(redirect.DefaultRedirectKey)
			http.Redirect(w, req, d.URL, 302)
		}
	})

	logger.Fatal(http.ListenAndServe(listenAddr, nil))
}


text:
NNTestClassDecl(BatchNorm);

#endif


text:
import unittest

import requests_mock

from canvasapi import Canvas
from canvasapi.blueprint import BlueprintMigration, ChangeRecord
from canvasapi.course import Course
from canvasapi.paginated_list import PaginatedList
from tests import settings
from tests.util import register_uris

@requests_mock.Mocker()
class TestBlueprint(unittest.TestCase):
    def setUp(self):
        self.canvas = Canvas(settings.BASE_URL, settings.API_KEY)

        with requests_mock.Mocker() as m:
            requires = {
                "course": [
                    "get_blueprint",
                    "get_by_id",
                    "list_blueprint_subscriptions",
                ],
                "blueprint": ["show_blueprint_migration"],
            }
            register_uris(requires, m)

            self.course = self.canvas.get_course(1)
            self.blueprint = self.course.get_blueprint(1)
            self.blueprint_migration = self.blueprint.show_blueprint_migration(1)

    # __str__()
    def test__str__(self, m):
        string = str(self.blueprint)
        self.assertIsInstance(string, str)

    # get_associated_courses()
    def test_get_associated_courses(self, m):
        register_uris({"blueprint": ["get_associated_courses"]}, m)
        associated_courses = self.blueprint.get_associated_courses()
        self.assertIsInstance(associated_courses, PaginatedList)
        self.assertEqual(associated_courses[0].id, 1)
        self.assertIsInstance(associated_courses[0], Course)

    # update_associated_courses()
    def test_update_associated_courses(self, m):
        register_uris({"blueprint": ["update_associated_courses"]}, m)
        updated_associations = self.blueprint.update_associated_courses()
        self.assertEqual(updated_associations, True)

    # associated_course_migration()
    def test_associated_course_migration(self, m):
        register_uris({"blueprint": ["associated_course_migration"]}, m)
        associated_migration = self.blueprint.associated_course_migration()
        self.assertEqual(associated_migration.id, 1)
        self.assertEqual(associated_migration.comment, "test1")

    # change_blueprint_restrictions()
    def test_change_blueprint_restrictions(self, m):
        register_uris({"blueprint": ["change_blueprint_restrictions"]}, m)
        blueprint_restriction = self.blueprint.change_blueprint_restrictions(
            "quiz", 1, True
        )
        self.assertIsInstance(blueprint_restriction, bool)

    # get_unsynced_changes()
    def test_get_unsynced_changes(self, m):
        register_uris({"blueprint": ["get_unsynced_changes"]}, m)
        unsynced_changes = self.blueprint.get_unsynced_changes()
        self.assertIsInstance(unsynced_changes, PaginatedList)
        self.assertIsInstance(unsynced_changes[0], ChangeRecord)
        self.assertEqual(unsynced_changes[0].asset_id, 1)
        self.assertEqual(unsynced_changes[0].asset_type, "quiz")
        self.assertEqual(unsynced_changes[0].asset_name, "test quiz")
        self.assertEqual(unsynced_changes[0].change_type, "updated")

    # list_blueprint_migrations()
    def test_list_blueprint_migrations(self, m):
        register_uris({"blueprint": ["list_blueprint_migrations"]}, m)
        blueprint_migrations = self.blueprint.list_blueprint_migrations()
        self.assertIsInstance(blueprint_migrations, PaginatedList)
        self.assertIsInstance(blueprint_migrations[0], BlueprintMigration)
        self.assertEqual(blueprint_migrations[0].id, 1)
        self.assertEqual(blueprint_migrations[0].user_id, 1)
        self.assertEqual(blueprint_migrations[0].template_id, 1)

    # show_blueprint_migration()
    def test_show_blueprint_migration(self, m):
        register_uris({"blueprint": ["show_blueprint_migration"]}, m)
        blueprint_migration = self.blueprint.show_blueprint_migration(1)
        self.assertIsInstance(blueprint_migration, BlueprintMigration)
        self.assertEqual(blueprint_migration.id, 1)
        self.assertEqual(blueprint_migration.user_id, 1)
        self.assertEqual(blueprint_migration.workflow_state, "completed")
        self.assertEqual(blueprint_migration.template_id, 1)

@requests_mock.Mocker()
class TestBlueprintSubscription(unittest.TestCase):
    def setUp(self):
        self.canvas = Canvas(settings.BASE_URL, settings.API_KEY)

        with requests_mock.Mocker() as m:
            requires = {
                "course": [
                    "get_blueprint",
                    "get_by_id",
                    "list_blueprint_subscriptions",
                ],
                "blueprint": ["show_blueprint_migration"],
            }
            register_uris(requires, m)

            self.course = self.canvas.get_course(1)
            self.blueprint = self.course.get_blueprint(1)
            self.blueprint_migration = self.blueprint.show_blueprint_migration(1)
            self.blueprint_subscription = self.course.list_blueprint_subscriptions()[0]

    # __str__()
    def test__str__(self, m):
        string = str(self.blueprint_subscription)
        self.assertIsInstance(string, str)

        # list_blueprint_imports()

    def test_list_blueprint_imports(self, m):
        register_uris({"blueprint": ["list_blueprint_imports"]}, m)
        blueprint_imports = self.blueprint_subscription.list_blueprint_imports()
        self.assertIsInstance(blueprint_imports, PaginatedList)
        self.assertIsInstance(blueprint_imports[0], BlueprintMigration)
        self.assertEqual(blueprint_imports[0].id, 3)
        self.assertEqual(blueprint_imports[0].subscription_id, 10)

        # show_blueprint_import

    def test_show_blueprint_import(self, m):
        register_uris({"blueprint": ["show_blueprint_import"]}, m)
        blueprint_import = self.blueprint_subscription.show_blueprint_import(3)
        self.assertIsInstance(blueprint_import, BlueprintMigration)

@requests_mock.Mocker()
class TestBlueprintMigration(unittest.TestCase):
    def setUp(self):
        self.canvas = Canvas(settings.BASE_URL, settings.API_KEY)

        with requests_mock.Mocker() as m:
            requires = {
                "course": [
                    "get_blueprint",
                    "get_by_id",
                    "list_blueprint_subscriptions",
                ],
                "blueprint": [
                    "show_blueprint_migration",
                    "list_blueprint_imports",
                    "show_blueprint_import",
                ],
            }
            register_uris(requires, m)

            self.course = self.canvas.get_course(1)
            self.blueprint = self.course.get_blueprint(1)
            self.blueprint_migration = self.blueprint.show_blueprint_migration(1)
            self.blueprint_subscription = self.course.list_blueprint_subscriptions()[0]
            self.blueprint_imports = (
                self.blueprint_subscription.list_blueprint_imports()[0]
            )
            self.b_import = self.blueprint_subscription.show_blueprint_import(3)

    # __str__()
    def test__str__(self, m):
        string = str(self.blueprint_migration)
        self.assertIsInstance(string, str)

    # get_details()
    def test_get_details(self, m):
        register_uris({"blueprint": ["get_details"]}, m)
        migration_details = self.blueprint_migration.get_details()
        self.assertIsInstance(migration_details, PaginatedList)
        self.assertIsInstance(migration_details[0], ChangeRecord)
        self.assertEqual(migration_details[0].asset_id, 1)
        self.assertEqual(migration_details[0].asset_type, "assignment")
        self.assertEqual(migration_details[0].asset_name, "Test Assignment")
        self.assertEqual(migration_details[0].locked, True)
        self.assertEqual(migration_details[1].asset_id, 2)
        self.assertEqual(migration_details[1].asset_type, "quiz")
        self.assertEqual(migration_details[1].asset_name, "Test Quiz")
        self.assertEqual(migration_details[1].locked, False)

    # get_import_details()
    def test_get_import_details(self, m):
        register_uris({"blueprint": ["get_import_details"]}, m)
        import_details = self.b_import.get_import_details()
        self.assertIsInstance(import_details, PaginatedList)
        self.assertIsInstance(import_details[0], ChangeRecord)

@requests_mock.Mocker()
class TestChangeRecord(unittest.TestCase):
    def setUp(self):
        self.canvas = Canvas(settings.BASE_URL, settings.API_KEY)

        with requests_mock.Mocker() as m:
            requires = {
                "course": ["get_blueprint", "get_by_id"],
                "blueprint": ["get_unsynced_changes"],
            }
            register_uris(requires, m)

            self.course = self.canvas.get_course(1)
            self.blueprint = self.course.get_blueprint(1)
            self.change_record = self.blueprint.get_unsynced_changes()[0]

    # __str__()
    def test__str__(self, m):
        string = str(self.change_record)
        self.assertIsInstance(string, str)


text:
package aQute.json.codec;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;
import java.util.regex.Pattern;

import aQute.lib.base64.Base64;
import aQute.lib.hex.Hex;

/**
 * Will now use hex for encoding byte arrays
 */
public class ByteArrayHandler extends Handler {
	Pattern ENCODING = Pattern.compile(
			"((:?[\\dA-Za-z][\\dA-Za-z])*)|((:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/)+={1,3})");

	@Override
	public void encode(Encoder app, Object object, Map<Object, Type> visited) throws IOException, Exception {
		StringHandler.string(app, Hex.toHexString((byte[]) object));
	}

	@Override
	public Object decodeArray(Decoder r) throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		ArrayList<Object> list = new ArrayList<Object>();
		r.codec.parseArray(list, Byte.class, r);
		for (Object b : list) {
			out.write(((Byte) b).byteValue());
		}
		return out.toByteArray();
	}

	@Override
	public Object decode(Decoder dec, String s) throws Exception {
		boolean hex = true;
		StringBuilder sb = new StringBuilder(s);
		for (int i = sb.length() - 1; i >= 0; i--) {
			char c = sb.charAt(i);
			if (Character.isWhitespace(c))
				sb.delete(i, i + 1);
			else {
				switch (c) {
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
				case 'A':
				case 'B':
				case 'C':
				case 'D':
				case 'E':
				case 'F':
				case 'a':
				case 'b':
				case 'c':
				case 'd':
				case 'e':
				case 'f':
					break;

				default:
					hex = false;
					break;
				}
			}
		}
		if (hex)
			return Hex.toByteArray(sb.toString());
		else
			return Base64.decodeBase64(sb.toString());
	}
}


text:
<set xmlns:android="http://schemas.android.com/apk/res/android">
   <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:valueFrom="0"
    android:valueTo="1.0"
    android:propertyName="yFraction"
    android:duration="1500" />
</set>


text:
<?php defined('ROOT') or die ('Not allowed!');

class Admin extends Module
{
    public function __construct()
    {
        parent::__construct();

        if (!User::loggedin()) redirect('login');
    }

    /**
     * {inheritdoc}
     */
    public static function initialize(App $app = null, Config $config = null)
    {
        defined('ADMIN_SIDEBAR') or define('ADMIN_SIDEBAR', __DIR__.'/layouts/sidebar.php');
    }

    public function index()
    {
        redirect('admin-shop/orders');

        return $this->render('dashboard', [
            'heading' => 'Administrasi',
            'navigation' => [],
        ]);
    }

    public function pages($do = '', $id = '')
    {
        $data = ['heading' => 'Administrasi: Halaman'];

        switch ($do) {
            case 'form':
                if (post('submit')) {
                    $form_data = [
                        'id_pengguna' => User::current('id'),
                        'tgl_input' => date('Y-m-d'),
                        'judul' => post('judul'),
                        'alias' => post('alias'),
                        'konten' => post('konten', false),
                    ];

                    $form_data['konten'] = str_replace(['
', '
'], '', $form_data['konten']);

                    if (Page::save($form_data, $id)) {
                        if ($id) {
                            set_alert('success', 'Halaman '.$form_data['judul'].' berhasil diperbarui');
                        } else {
                            set_alert('success', 'Halaman '.$form_data['judul'].' berhasil dibuat');
                        }

                        return redirect('admin/pages');
                    }

                    set_alert('error', 'Terjadi kesalahan dalam penyimpanan halaman '.$form_data['judul'].'');
                    return redirect($this->uri->path());
                }

                if ($id) {
                    $data['data'] = Page::show((int) $id)->fetchOne();
                }

                return $this->render('page-form', $data);
                break;

            case 'delete':
                if (Page::del((int) $id)) {
                    set_alert('success', 'Halaman berhasil terhapus');
                } else {
                    set_alert('error', 'Terjadi kesalahan dalam penghapusan halaman');
                }

                return redirect('admin/pages');
                break;

            default:
                $data['data'] = Page::show();

                return $this->render('page-table', $data);
                break;
        }
    }

    public function users($do = '', $id = '')
    {
        $data = ['heading' => 'Administrasi: Pengguna'];

        switch ($do) {
            case 'form':
                if (post('submit')) {
                    $form_data = [
                        'username' => post('username'),
                        'email' => post('email'),
                    ];

                    if (User::is('admin')) {
                        $form_data['level'] = post('level');
                    }

                    if (($password = post('password')) and $password == post('passconf')) {
                        $form_data['password'] = $password;
                    }

                    if (User::save($form_data, $id)) {
                        if ($id) {
                            set_alert('success', 'Berhasil memperbarui data pengguna '.$form_data['username'].'');
                        } else {
                            set_alert('success', 'Berhasil menambahkan '.$form_data['username'].' sebagai pengguna');
                        }

                        return redirect('admin/users');
                    }

                    set_alert('error', 'Terjadi kesalahan dalam penyimpanan pengguna '.$form_data['username'].'');
                    return redirect($this->uri->path());
                }

                if ($id) {
                    $data['data'] = User::show((int) $id)->fetchOne();
                }

                return $this->render('user-form', $data);
                break;

            case 'delete':
                if (User::del((int) $id)) {
                    set_alert('success', 'Pengguna berhasil terhapus');
                } else {
                    set_alert('error', 'Terjadi kesalahan dalam penghapusan pengguna');
                }

                return redirect('admin/users');
                break;

            default:
                $data['data'] = User::show();

                return $this->render('user-table', $data);
                break;
        }
    }
}


text:
"""
Sub-package with tools for the analysis of results.
"""
from .sim_result_tools import *


text:
layout: page
title: Davidson - Alvarado Wedding
date: 2016-05-24
author: Betty Harris
tags: weekly links, java
status: published
summary: Quisque quis sapien fermentum, convallis.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/29/2019
  endDate: 08/01/2019
  ctyhocn: ATLFBHX
  groupCode: DAW
published: true
---
Donec vitae arcu vel arcu semper pharetra. Nulla placerat ultrices enim sit amet elementum. Vestibulum sit amet erat at purus iaculis aliquet ac nec purus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Fusce diam augue, accumsan non tempor quis, porttitor eget mauris. Curabitur ut dolor a leo tempus cursus. Pellentesque fermentum enim in purus vehicula suscipit. Vivamus finibus metus sit amet arcu pharetra, non sagittis ex mattis. Phasellus pellentesque mi eu placerat sagittis. Cras id massa ante.

1 Etiam vitae lectus aliquet, aliquet est sit amet, fermentum orci
1 Cras eget felis id libero ornare finibus
1 Maecenas cursus augue et dolor molestie aliquet
1 Mauris porttitor ex eu elit luctus, vel pellentesque nulla aliquet
1 Nulla sed magna at ex ultricies finibus fringilla vel lacus.

Nam ullamcorper magna at arcu mattis consectetur. Sed at felis efficitur lorem blandit aliquet. Proin eu leo sit amet est maximus dictum. In ligula sem, ornare a tortor at, ultricies iaculis risus. Fusce porta tortor id arcu porttitor, et tristique nisi sodales. Ut ut iaculis nisi. Duis vitae imperdiet mi. Sed a vehicula velit. Proin neque tellus, consectetur ac tincidunt tempor, varius vitae turpis.


text:
package org.springframework.security.samples.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Joe Grandja
 */
@Controller
public class MainController {

	@RequestMapping("/")
	public String root() {
		return "redirect:/index";
	}

	@RequestMapping("/index")
	public String index() {
		return "index";
	}

	@RequestMapping("/user/index")
	public String userIndex() {
		return "user/index";
	}

	@RequestMapping(value = "/login")
	public String login() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String postLogin() {
		// TODO Enable form login with Spring Security (trigger error for now)
		return "redirect:/login-error";
	}

	@RequestMapping("/login-error")
	public String loginError(Model model) {
		model.addAttribute("loginError", true);
		return "login";
	}

}


text:
using Microsoft.EntityFrameworkCore;
using Microsoft.OData.Edm;
using OdataToEntity.EfCore;
using OdataToEntity.Test.Model;
using System;
using System.Linq;
using Xunit;

namespace OdataToEntity.Test
{
    public class EdmModelBuilderTest
    {
        private class MyFinanceDbContext1 : DbContext
        {
            public MyFinanceDbContext1() : base(Create<MyFinanceDbContext1>())
            {
            }

            protected override void OnModelCreating(Microsoft.EntityFrameworkCore.ModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);

                modelBuilder.Entity<Dept>().HasAlternateKey(d => d.Ref);
                modelBuilder.Entity<Acct>().HasOne(a => a.DeptRefNavigation).WithMany(d => d.AcctRefs).HasForeignKey(a => a.DeptRef).HasPrincipalKey(d => d.Ref);
            }

            public DbSet<Acct> Accts { get; set; }
            public DbSet<Dept> Depts { get; set; }
            public DbSet<Stat> Stats { get; set; }
        }

        private class MyFinanceDbContext2 : DbContext
        {
            public MyFinanceDbContext2() : base(Create<MyFinanceDbContext2>())
            {
            }

            public DbSet<Car> Cars { get; set; }
            public DbSet<State> States { get; set; }
        }

        private static DbContextOptions Create<T>() where T : DbContext
        {
            var optionsBuilder = new DbContextOptionsBuilder<T>();
            optionsBuilder.UseSqlServer(@"Server=.\sqlexpress;Initial Catalog=OdataToEntity;Trusted_Connection=Yes;", opt => opt.UseRelationalNulls(true));
            return optionsBuilder.Options;
        }

        [Fact]
        public void FluentApi()
        {
            var ethalonDataAdapter = new OrderDataAdapter(false, false);
            EdmModel ethalonEdmModel = ethalonDataAdapter.BuildEdmModel();
            String ethalonSchema = TestHelper.GetCsdlSchema(ethalonEdmModel);
            if (ethalonSchema == null)
                throw new InvalidOperationException("Invalid ethalon schema");

            var testDataAdapter = new OrderDataAdapter(false, false);
            EdmModel testEdmModel = testDataAdapter.BuildEdmModelFromEfCoreModel();
            String testSchema = TestHelper.GetCsdlSchema(testEdmModel);
            if (testSchema == null)
                throw new InvalidOperationException("Invalid test schema");

            ethalonSchema = TestHelper.SortCsdlSchema(ethalonSchema);
            testSchema = TestHelper.SortCsdlSchema(testSchema);
            Assert.Equal(ethalonSchema, testSchema);
        }
        [Fact]
        public void MissingDependentNavigationProperty()
        {
            var da = new OeEfCoreDataAdapter<MyFinanceDbContext1>();
            da.BuildEdmModelFromEfCoreModel();
        }
        [Fact]
        public void AlternativeKey()
        {
            var da = new OeEfCoreDataAdapter<MyFinanceDbContext1>();
            IEdmModel edmModel = da.BuildEdmModelFromEfCoreModel();
            var acct = (IEdmStructuredType)edmModel.FindType(typeof(Acct).FullName);
            var deptRefNavigation = acct.NavigationProperties().Single(p => p.Name == nameof(Acct.DeptRefNavigation));
            var key = deptRefNavigation.PrincipalProperties().Single();
            Assert.Equal(nameof(Dept.Ref), key.Name);
        }
        [Fact]
        public void ShadowProperty()
        {
            var da = new OeEfCoreDataAdapter<MyFinanceDbContext2>();
            da.BuildEdmModelFromEfCoreModel();
        }
    }
}


text:
/*
 *
 * LegendShop 多用户商城系统
 *
 *  版权所有,并保留所有权利。
 *
 */
package com.legendshop.core.cache;

import java.util.Collection;
import java.util.LinkedHashSet;

import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Status;

import org.springframework.cache.Cache;
import org.springframework.util.Assert;

/**
 * The Class EhCacheCacheManager.
 */
public class EhCacheCacheManager extends AbstractLegendCacheManager implements LegendCacheManager {

	/** The cache manager. */
	private net.sf.ehcache.CacheManager cacheManager;

	/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.cache.support.AbstractCacheManager#loadCaches()
	 */
	@Override
	protected Collection<Cache> loadCaches() {
		Assert.notNull(this.cacheManager, "A backing EhCache CacheManager is required");
		Status status = this.cacheManager.getStatus();
		Assert.isTrue(Status.STATUS_ALIVE.equals(status), "An 'alive' EhCache CacheManager is required - current cache is "
				+ status.toString());

		String[] names = this.cacheManager.getCacheNames();
		Collection<Cache> caches = new LinkedHashSet<Cache>(names.length);
		for (String name : names) {
			caches.add(new LegendCache(this, this.cacheManager.getEhcache(name)));
		}
		return caches;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.springframework.cache.support.AbstractCacheManager#getCache(java.
	 * lang.String)
	 */

	@Override
	public Cache getCache(String name) {
		Cache cache = super.getCache(name);
		if (cache == null) {
			// check the EhCache cache again
			// (in case the cache was added at runtime)
			Ehcache ehcache = this.cacheManager.getEhcache(name);
			if (ehcache != null) {
				cache = new LegendCache(this, ehcache);
				addCache(cache);
			}
		}
		return cache;
	}

	/**
	 * Set the backing EhCache {@link net.sf.ehcache.CacheManager}.
	 *
	 * @param cacheManager
	 *            the new cache manager
	 */
	public void setCacheManager(net.sf.ehcache.CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}
}


text:
<?php

// @codingStandardsIgnoreFile

namespace Magento\Catalog\Test\Unit\Model\Indexer\Product\Price\Plugin;

class CustomerGroupTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
     */
    protected $_objectManager;

    /**
     * @var \Magento\Catalog\Model\Indexer\Product\Price\Plugin\CustomerGroup
     */
    protected $_model;

    /**
     * @var \Magento\Customer\Api\GroupRepositoryInterface|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $_subjectMock;

    /**
     * @var \Magento\Framework\Indexer\IndexerRegistry|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $indexerRegistryMock;

    protected function setUp()
    {
        $this->_objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->_subjectMock = $this->getMock(
            '\Magento\Customer\Api\GroupRepositoryInterface', [], [], '', false
        );

        $indexerMock = $this->getMock(
            'Magento\Indexer\Model\Indexer',
            ['getId', 'invalidate'],
            [],
            '',
            false
        );
        $indexerMock->expects($this->once())->method('invalidate');
        $this->indexerRegistryMock = $this->getMock('Magento\Framework\Indexer\IndexerRegistry', ['get'], [], '', false);
        $this->indexerRegistryMock->expects($this->once())
            ->method('get')
            ->with(\Magento\Catalog\Model\Indexer\Product\Price\Processor::INDEXER_ID)
            ->will($this->returnValue($indexerMock));

        $this->_model = $this->_objectManager->getObject(
            'Magento\Catalog\Model\Indexer\Product\Price\Plugin\CustomerGroup',
            ['indexerRegistry' => $this->indexerRegistryMock]
        );
    }

    public function testAroundDelete()
    {
        $this->assertEquals('return_value', $this->_model->afterDelete($this->_subjectMock, 'return_value'));
    }

    public function testAroundDeleteById()
    {
        $this->assertEquals('return_value', $this->_model->afterDeleteById($this->_subjectMock, 'return_value'));
    }

    public function testAroundSave()
    {
        $this->assertEquals('return_value', $this->_model->afterSave($this->_subjectMock, 'return_value'));
    }
}


text:
ARG SCW_ARCH
FROM scaleway/ubuntu:${SCW_ARCH}-xenial

MAINTAINER Scaleway <opensource@scaleway.com> (@scaleway)

# Prepare rootfs for image-builder
RUN /usr/local/sbin/builder-enter

ARG GOVER

# Install golang from PPA
RUN add-apt-repository ppa:gophers/archive \
    && apt-get -qq update \
    && apt-get -qq install git golang-${GOVER}-go \
    && echo "PATH=$PATH:/usr/lib/go-${GOVER}/bin/" > /etc/profile.d/golang.sh

# Activate the go binaries
RUN for binary in $(ls /usr/lib/go-${GOVER}/bin); do \
        ln -s /usr/lib/go-${GOVER}/bin/$binary /usr/local/bin/$binary; \
    done

# Clean rootfs from image-builder
RUN /usr/local/sbin/builder-leave


text:
import tempfile

from django.conf import settings
from django.utils.encoding import smart_str
from mediagenerator.generators.bundles.base import Filter

COMPILATION_LEVEL = getattr(settings, 'CLOSURE_COMPILATION_LEVEL',
                            'SIMPLE_OPTIMIZATIONS')

class Closure(Filter):
    def __init__(self, **kwargs):
        self.config(kwargs, compilation_level=COMPILATION_LEVEL)
        super(Closure, self).__init__(**kwargs)
        assert self.filetype == 'js', (
            'Closure only supports compilation to js. '
            'The parent filter expects "%s".' % self.filetype)

    def get_output(self, variation):
        # We import this here, so App Engine Helper users don't get import
        # errors.
        from subprocess import Popen, PIPE
        for input in self.get_input(variation):
            # Creating a temporary file to store the compiler input
            print "Generating temporary file"
            temp = tempfile.NamedTemporaryFile()
            print "Done"
            print "Writing stuff to the file"
            temp.write(smart_str(input))
            temp.flush()
            print "Done"

            try:
                compressor = settings.CLOSURE_COMPILER_PATH
                cmd = Popen(['java', '-jar', compressor,
                             '--charset', 'utf-8',
                             '--js', temp.name,
                             '--compilation_level', self.compilation_level],
                            stdin=temp, stdout=PIPE, stderr=PIPE,
                            universal_newlines=True)
                print "Running the compressor"
                output, error = cmd.communicate()
                print "Done"
                assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error
                temp.close() # Close, and remove, the temporary file
                yield output.decode('utf-8')
            except Exception, e:
                if temp:
                    temp.close() # Close, and remove, the temporary file
                raise ValueError("Failed to execute Java VM or Closure. "
                    "Please make sure that you have installed Java "
                    "and that it's in your PATH and that you've configured "
                    "CLOSURE_COMPILER_PATH in your settings correctly.\n"
                    "Error was: %s" % e)


text: A Test Case and Requirements management system implemented in Python/Flask.


text:
package com.synedge.oss.client;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class SynEdgeClientBuilderTest {
    @Rule
    public ExpectedException expectedEx = ExpectedException.none();

    @Test
    public void testMissingInfo() {
        expectedEx.expect(IllegalArgumentException.class);
        expectedEx.expectMessage("Username must be supplied");
        SynEdgeClientBuilder.create().build();
    }

    @Test
    public void testMissingUsername() {
        expectedEx.expect(IllegalArgumentException.class);
        expectedEx.expectMessage("Username must be supplied");
        SynEdgeClientBuilder.create().withPassword("test").build();
    }

    @Test
    public void testMissingPassword() {
        expectedEx.expect(IllegalArgumentException.class);
        expectedEx.expectMessage("Password must be supplied");
        SynEdgeClientBuilder.create().withUsername("test").build();
    }

    @Test
    public void testBuildClientWithCustomEndpoint() {
        SynEdgeClient client = SynEdgeClientBuilder.create().withUsername(TestConstants.USERNAME).withPassword(TestConstants.PASSWORD).toEndpoint(TestConstants.ENDPOINT).build();
        Assert.assertNotNull("Expected to get a client", client);
    }
}


text:
import React, { Component, Ref } from 'react';
import cx from 'classnames';

type NetworkLink<LinkOptions> = (url: string, options: LinkOptions) => string;

type WindowPosition = 'windowCenter' | 'screenCenter';

const isPromise = (obj: any | Promise<any>) =>
  !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';

const getBoxPositionOnWindowCenter = (width: number, height: number) => ({
  left: window.outerWidth / 2 + (window.screenX || window.screenLeft || 0) - width / 2,
  top: window.outerHeight / 2 + (window.screenY || window.screenTop || 0) - height / 2,
});

const getBoxPositionOnScreenCenter = (width: number, height: number) => ({
  top: (window.screen.height - height) / 2,
  left: (window.screen.width - width) / 2,
});

function windowOpen(
  url: string,
  { height, width, ...configRest }: { height: number; width: number; [key: string]: any },
  onClose?: (dialog: Window | null) => void,
) {
  const config: { [key: string]: string | number } = {
    height,
    width,
    location: 'no',
    toolbar: 'no',
    status: 'no',
    directories: 'no',
    menubar: 'no',
    scrollbars: 'yes',
    resizable: 'no',
    centerscreen: 'yes',
    chrome: 'yes',
    ...configRest,
  };

  const shareDialog = window.open(
    url,
    '',
    Object.keys(config)
      .map(key => `${key}=${config[key]}`)
      .join(', '),
  );

  if (onClose) {
    const interval = window.setInterval(() => {
      try {
        if (shareDialog === null || shareDialog.closed) {
          window.clearInterval(interval);
          onClose(shareDialog);
        }
      } catch (e) {
        /* eslint-disable no-console */
        console.error(e);
        /* eslint-enable no-console */
      }
    }, 1000);
  }

  return shareDialog;
}

interface CustomProps<LinkOptions> {
  children: React.ReactNode;
  className?: string;
  /** Disables click action and adds `disabled` class */
  disabled?: boolean;
  /**
   * Style when button is disabled
   * @default { opacity: 0.6 }
   */
  disabledStyle?: React.CSSProperties;
  forwardedRef?: Ref<HTMLButtonElement>;
  networkName: string;
  networkLink: NetworkLink<LinkOptions>;
  onClick?: (event: React.MouseEvent<HTMLButtonElement>, link: string) => void;
  openShareDialogOnClick?: boolean;
  opts: LinkOptions;
  /**
   * URL of the shared page
   */
  url: string;
  style?: React.CSSProperties;
  windowWidth?: number;
  windowHeight?: number;
  windowPosition?: WindowPosition;
  /**
   *  Takes a function that returns a Promise to be fulfilled before calling
   * `onClick`. If you do not return promise, `onClick` is called immediately.
   */
  beforeOnClick?: () => Promise<void> | void;
  /**
   * Takes a function to be called after closing share dialog.
   */
  onShareWindowClose?: () => void;
  resetButtonStyle?: boolean;
}

export type Props<LinkOptions> = Omit<
  React.ButtonHTMLAttributes<HTMLButtonElement>,
  keyof CustomProps<LinkOptions>
> &
  CustomProps<LinkOptions>;

export default class ShareButton<LinkOptions> extends Component<Props<LinkOptions>> {
  static defaultProps = {
    disabledStyle: { opacity: 0.6 },
    openShareDialogOnClick: true,
    resetButtonStyle: true,
  };

  openShareDialog = (link: string) => {
    const {
      onShareWindowClose,
      windowHeight = 400,
      windowPosition = 'windowCenter',
      windowWidth = 550,
    } = this.props;

    const windowConfig = {
      height: windowHeight,
      width: windowWidth,
      ...(windowPosition === 'windowCenter'
        ? getBoxPositionOnWindowCenter(windowWidth, windowHeight)
        : getBoxPositionOnScreenCenter(windowWidth, windowHeight)),
    };

    windowOpen(link, windowConfig, onShareWindowClose);
  };

  handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {
    const { beforeOnClick, disabled, networkLink, onClick, url, openShareDialogOnClick, opts } =
      this.props;

    const link = networkLink(url, opts);

    if (disabled) {
      return;
    }

    event.preventDefault();

    if (beforeOnClick) {
      const returnVal = beforeOnClick();

      if (isPromise(returnVal)) {
        await returnVal;
      }
    }

    if (openShareDialogOnClick) {
      this.openShareDialog(link);
    }

    if (onClick) {
      onClick(event, link);
    }
  };

  render() {
    const {
      beforeOnClick,
      children,
      className,
      disabled,
      disabledStyle,
      forwardedRef,
      networkLink,
      networkName,
      onShareWindowClose,
      openShareDialogOnClick,
      opts,
      resetButtonStyle,
      style,
      url,
      windowHeight,
      windowPosition,
      windowWidth,
      ...rest
    } = this.props;

    const newClassName = cx(
      'react-share__ShareButton',
      {
        'react-share__ShareButton--disabled': !!disabled,
        disabled: !!disabled,
      },
      className,
    );

    const newStyle = resetButtonStyle
      ? {
          backgroundColor: 'transparent',
          border: 'none',
          padding: 0,
          font: 'inherit',
          color: 'inherit',
          cursor: 'pointer',
          ...style,
          ...(disabled && disabledStyle),
        }
      : {
          ...style,
          ...(disabled && disabledStyle),
        };

    return (
      <button
        {...rest}
        aria-label={rest['aria-label'] || networkName}
        className={newClassName}
        onClick={this.handleClick}
        ref={forwardedRef}
        style={newStyle}
      >
        {children}
      </button>
    );
  }
}


text:
/**
 * \kernelgroup{SceNet}
 * \usage{psp2/net/net_syscalls.h,SceNetPsForSyscalls_stub}
 */

#ifndef _PSP2_NET_NET_SYSCALLS_H_
#define _PSP2_NET_NET_SYSCALLS_H_

#include <psp2/net/net.h>
#include <psp2/types.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef struct SceNetSyscallParameter SceNetSyscallParameter; // missing struct

int sceNetSyscallAccept(int s, void *addr, void *addrlen);
int sceNetSyscallBind(int s, const void *addr, int addrlen);
int sceNetSyscallClose(int s);
int sceNetSyscallConnect(int s, const void *name, int namelen);
int sceNetSyscallControl(int if_index, int code, void *ptr, int len);
int sceNetSyscallDescriptorClose(int id);
int sceNetSyscallDescriptorCreate(const char *name, int flags);
int sceNetSyscallDescriptorCtl(int id, int op, int s, void *info);
int sceNetSyscallDumpAbort(int id, int flags);
int sceNetSyscallDumpClose(int id);
int sceNetSyscallDumpCreate(const char *name, int len, int flags);
int sceNetSyscallDumpRead(int id, void *buf, int len, void *pflags);
int sceNetSyscallEpollAbort(int eid, int flags);
int sceNetSyscallEpollClose(int eid);
int sceNetSyscallEpollCreate(const char *name, int flags);
int sceNetSyscallEpollCtl(int eid, int op, int id, void *event);
int sceNetSyscallEpollWait(SceNetSyscallParameter *param);

/**
 * @brief Get net if list
 *
 * @param[out] list - The output buffer list. size is (0x140 * n)
 * @param[in]  n    - The output size number.
 *
 * @return 0 on success, < 0 on error.
 */
int sceNetSyscallGetIfList(void *list, int n);

int sceNetSyscallGetSockinfo(int s, void *ptr, int n, int flags);
int sceNetSyscallGetpeername(int s, void *name, void *namelen);
int sceNetSyscallGetsockname(int s, void *name, void *namelen);
int sceNetSyscallGetsockopt(SceNetSyscallParameter *param);
int sceNetSyscallIcmConnect(int s, int flags);
int sceNetSyscallIoctl(int s, unsigned int com, void *data);
int sceNetSyscallListen(int s, int backlog);
int sceNetSyscallRecvfrom(SceNetSyscallParameter *param);
int sceNetSyscallRecvmsg(int s, void *msg, int flags);
int sceNetSyscallSendmsg(int s, const void *msg, int flags);
int sceNetSyscallSendto(SceNetSyscallParameter *param);
int sceNetSyscallSetsockopt(SceNetSyscallParameter *param);
int sceNetSyscallShutdown(int s, int how);
int sceNetSyscallSocket(const char *name, int domain, int type, int protocol);
int sceNetSyscallSocketAbort(int s, int flags);
int sceNetSyscallSysctl(SceNetSyscallParameter *param);

#ifdef __cplusplus
}
#endif

#endif /* _PSP2_NET_NET_SYSCALLS_H_ */


text:
# Swift functions
## Make swiftly iOS development

Mobile Applications for iPhone and iPad

Telerik Software Academy

  http://academy.telerik.com

# Table of Contents
- Swift overview
- Language syntax and specifics
  - Functions as first-class objects, closures, etc…

# Defining Functions in Swift
- Functions in Swift have the following syntax:
  - Function returning void:
```
funcprintMessage(message: String) {
println(String(format: "Message: %@", message))
}
```
  - Function returning integer:
```
funcsum(x:Int, y:Int) ->Int{
return x + y
}
```
  - Function with parameters put inside an array:
```
funcsum(numbers:Int…) ->Int{
var sum = 0
for number in numbers { sum += number}
return sum
}
```

# Functions in Swift
## Live Demo

## Questions


text:
/*
 ONOS GUI -- Topology Event Module.

 Defines the conduit between the client and the server:
    - provides a clean API for sending events to the server
    - dispatches incoming events from the server to the appropriate sub-module

 */

(function () {
    'use strict';

    // injected refs
    var $log, $interval, wss, tps, tis, tfs, tss, tov, tspr;

    // internal state
    var handlerMap,
        openListener;

    // ==========================

    function createHandlerMap() {
        handlerMap = {
            showSummary: tps,

            showDetails: tss,

            showHighlights: tov,

            addInstance: tis,
            updateInstance: tis,
            removeInstance: tis,

            addDevice: tfs,
            updateDevice: tfs,
            removeDevice: tfs,
            addHost: tfs,
            updateHost: tfs,
            moveHost: tfs,
            removeHost: tfs,
            addLink: tfs,
            updateLink: tfs,
            removeLink: tfs,

            topoStartDone: tfs,

            spriteListResponse: tspr,
            spriteDataResponse: tspr
        };
    }

    function wsOpen(host, url) {
        $log.debug('TOPO: web socket open - cluster node:', host, 'URL:', url);
        // Request batch of initial data from the new server
        wss.sendEvent('topoStart');
    }

    angular.module('ovTopo')
    .factory('TopoEventService',
        ['$log', '$interval', 'WebSocketService',
            'TopoPanelService', 'TopoInstService', 'TopoForceService',
            'TopoSelectService', 'TopoOverlayService', 'TopoSpriteService',

        function (_$log_,  _$interval_, _wss_,
                  _tps_, _tis_, _tfs_, _tss_, _tov_, _tspr_) {
            $log = _$log_;
            $interval = _$interval_;
            wss = _wss_;
            tps = _tps_;
            tis = _tis_;
            tfs = _tfs_;
            tss = _tss_;
            tov = _tov_;
            tspr = _tspr_;

            createHandlerMap();

            function bindHandlers() {
                wss.bindHandlers(handlerMap);
                $log.debug('topo event handlers bound');
            }

            function start() {
                // in case we fail over to a new server, listen for wsock-open
                openListener = wss.addOpenListener(wsOpen);
                wss.sendEvent('topoStart');
                $log.debug('topo comms started');
            }

            function stop() {
                wss.sendEvent('topoStop');
                wss.unbindHandlers(handlerMap);
                wss.removeOpenListener(openListener);
                openListener = null;
                $log.debug('topo comms stopped');
            }

            return {
                bindHandlers: bindHandlers,
                start: start,
                stop: stop
            };
        }]);
}());


text:
@interface AlreadyFieldViewController : UIViewController

- (instancetype)initWithData:(NSMutableArray*)data;

@end


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model frontend\models\AnswerTemp */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'jawapan')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'question_temp_id')->textInput() ?>

    <?= $form->field($model, 'people_id')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php

namespace Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper;

use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator as BaseGenerator;
use Symfony\Component\DependencyInjection\Definition;
use Zend\Code\Generator\ClassGenerator;

/**
 * @internal
 */
class LazyLoadingValueHolderGenerator extends BaseGenerator
{
    private $fluentSafe = false;

    public function setFluentSafe(bool $fluentSafe)
    {
        $this->fluentSafe = $fluentSafe;
    }

    /**
     * {@inheritdoc}
     */
    public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator)
    {
        parent::generate($originalClass, $classGenerator);

        foreach ($classGenerator->getMethods() as $method) {
            $body = preg_replace(
                '/(\$this->initializer[0-9a-f]++) && \1->__invoke\(\$this->(valueHolder[0-9a-f]++), (.*?), \1\);/',
                '$1 && ($1->__invoke(\$$2, $3, $1) || 1) && $this->$2 = \$$2;',
                $method->getBody()
            );
            $body = str_replace('(new \ReflectionClass(get_class()))', '$reflection', $body);

            if ($originalClass->isInterface()) {
                $body = str_replace('get_parent_class($this)', var_export($originalClass->name, true), $body);
                $body = preg_replace_callback('/\n\n\$realInstanceReflection = [^{]++\{([^}]++)\}\n\n.*/s', function ($m) {
                    $r = '';
                    foreach (explode("\n", $m[1]) as $line) {
                        $r .= "\n".substr($line, 4);
                        if (0 === strpos($line, '    return ')) {
                            break;
                        }
                    }

                    return $r;
                }, $body);
            }

            if ($this->fluentSafe) {
                $indent = $method->getIndentation();
                $method->setIndentation('');
                $code = $method->generate();
                if (null !== $docBlock = $method->getDocBlock()) {
                    $code = substr($code, \strlen($docBlock->generate()));
                }
                $refAmp = (strpos($code, '&') ?: \PHP_INT_MAX) <= strpos($code, '(') ? '&' : '';
                $body = preg_replace(
                    '/\nreturn (\$this->valueHolder[0-9a-f]++)(->[^;]++);$/',
                    "\nif ($1 === \$returnValue = {$refAmp}$1$2) {\n    \$returnValue = \$this;\n}\n\nreturn \$returnValue;",
                    $body
                );
                $method->setIndentation($indent);
            }

            if (0 === strpos($originalClass->getFilename(), __FILE__)) {
                $body = str_replace(var_export($originalClass->name, true), '__CLASS__', $body);
            }

            $method->setBody($body);
        }

        if ($classGenerator->hasMethod('__destruct')) {
            $destructor = $classGenerator->getMethod('__destruct');
            $body = $destructor->getBody();
            $newBody = preg_replace('/^(\$this->initializer[a-zA-Z0-9]++) && .*;\n\nreturn (\$this->valueHolder)/', '$1 || $2', $body);

            if ($body === $newBody) {
                throw new \UnexpectedValueException(sprintf('Unexpected lazy-proxy format generated for method %s::__destruct()', $originalClass->name));
            }

            $destructor->setBody($newBody);
        }

        if (0 === strpos($originalClass->getFilename(), __FILE__)) {
            $interfaces = $classGenerator->getImplementedInterfaces();
            array_pop($interfaces);
            $classGenerator->setImplementedInterfaces(array_merge($interfaces, $originalClass->getInterfaceNames()));
        }
    }

    public function getProxifiedClass(Definition $definition): ?string
    {
        if (!$definition->hasTag('proxy')) {
            return \class_exists($class = $definition->getClass()) || \interface_exists($class) ? $class : null;
        }
        if (!$definition->isLazy()) {
            throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": setting the "proxy" tag on a service requires it to be "lazy".', $definition->getClass()));
        }
        $tags = $definition->getTag('proxy');
        if (!isset($tags[0]['interface'])) {
            throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": the "interface" attribute is missing on the "proxy" tag.', $definition->getClass()));
        }
        if (1 === \count($tags)) {
            return \class_exists($tags[0]['interface']) || \interface_exists($tags[0]['interface']) ? $tags[0]['interface'] : null;
        }

        $proxyInterface = 'LazyProxy';
        $interfaces = '';
        foreach ($tags as $tag) {
            if (!isset($tag['interface'])) {
                throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": the "interface" attribute is missing on a "proxy" tag.', $definition->getClass()));
            }
            if (!\interface_exists($tag['interface'])) {
                throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": several "proxy" tags found but "%s" is not an interface.', $definition->getClass(), $tag['interface']));
            }

            $proxyInterface .= '\\'.$tag['interface'];
            $interfaces .= ', \\'.$tag['interface'];
        }

        if (!\interface_exists($proxyInterface)) {
            $i = strrpos($proxyInterface, '\\');
            $namespace = substr($proxyInterface, 0, $i);
            $interface = substr($proxyInterface, 1 + $i);
            $interfaces = substr($interfaces, 2);

            eval("namespace {$namespace}; interface {$interface} extends {$interfaces} {}");
        }

        return $proxyInterface;
    }
}


text:
require 'test_helper'

class ActivitiesControllerTest < ActionDispatch::IntegrationTest
  test "should get new" do
    get activities_new_url
    assert_response :success
  end

end


text:
package org.gw4e.eclipse.launching.runasmanual;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.jdt.launching.AbstractJavaLaunchConfigurationDelegate;
import org.gw4e.eclipse.builder.BuildPolicy;
import org.gw4e.eclipse.facade.ResourceManager;
import org.gw4e.eclipse.launching.ui.ModelData;
import org.gw4e.eclipse.wizard.runasmanual.RunAsManualWizard;

/**
 * a Java launch implementation configuration delegate. Provides convenience
 * methods for accessing and verifying launch configuration attributes.
 *
 */
public class GW4ELaunchConfigurationDelegate extends AbstractJavaLaunchConfigurationDelegate
		implements LaunchingConstant {

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.
	 * eclipse.debug.core.ILaunchConfiguration, java.lang.String,
	 * org.eclipse.debug.core.ILaunch,
	 * org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public synchronized void launch(ILaunchConfiguration configuration, String mode, ILaunch launch,
			IProgressMonitor monitor) throws CoreException {
		String modelPath = getMainModel(configuration);
		String generatorstopcondition = getMainPathGenerators(configuration).getPathGenerator();
		String startnode = configuration.getAttribute(CONFIG_LAUNCH_STARTNODE, (String) null);
		String removeBlockedElements = configuration.getAttribute(CONFIG_LAUNCH_REMOVE_BLOCKED_ELEMENT_CONFIGURATION,"true");
		String omitEgdeswithoutDescription = configuration.getAttribute(GW4E_LAUNCH_CONFIGURATION_BUTTON_ID_OMIT_EMPTY_EDGE_DESCRIPTION,"true");
		String models = configuration.getAttribute(CONFIG_LAUNCH_ADDITIONNAL_MODELS_CONFIGURATION, "");
		StringTokenizer st = new StringTokenizer(models, ";");
		ModelData[] additionalModels = getModels(configuration);
		RunAsManualWizard.open(modelPath,
				additionalModels,
				generatorstopcondition,
				startnode,
				new Boolean(removeBlockedElements),
				new Boolean (omitEgdeswithoutDescription));
	}

	private ModelData[] getModels(ILaunchConfiguration config) throws CoreException {
		List<ModelData> temp = new ArrayList<ModelData>();
		String paths = config.getAttribute(CONFIG_GRAPH_MODEL_PATHS, "");

		if (paths == null || paths.trim().length() == 0)
			return new ModelData[0];
		StringTokenizer st = new StringTokenizer(paths, ";");
		st.nextToken(); // the main model path
		st.nextToken(); // main model : Always "1"
		st.nextToken(); // the main path generator
		while (st.hasMoreTokens()) {
			String path = st.nextToken();
			IFile file = (IFile) ResourceManager
					.getResource(new Path(path).toString());
			if (file==null) continue;
			ModelData data = new ModelData(file);
			boolean selected = st.nextToken().equalsIgnoreCase("1");
			String pathGenerator = st.nextToken();
			data.setSelected(selected);
			data.setSelectedPolicy(pathGenerator);
			if (selected) temp.add(data);
		}
		ModelData[] ret = new ModelData[temp.size()];
		temp.toArray(ret);
		return ret;
	}

	private String getMainModel(ILaunchConfiguration config) throws CoreException {
		String ret = config.getAttribute(CONFIG_GRAPH_MODEL_PATHS, "");
		StringTokenizer st = new StringTokenizer(ret, ";");
		if (st.hasMoreTokens())
			return st.nextToken();
		return "";
	}

	private BuildPolicy getMainPathGenerators(ILaunchConfiguration config) throws CoreException {
		String paths = config.getAttribute(CONFIG_GRAPH_MODEL_PATHS, "");
		if (paths == null || paths.trim().length() == 0)
			return null;
		StringTokenizer stFirst = new StringTokenizer(paths, ";");
		stFirst.nextToken(); // the main model path
		stFirst.nextToken(); // main model : Always "1"
		String generators = stFirst.nextToken(); // the main path generator
		if (generators == null || generators.trim().length() == 0)
			return null;
		StringTokenizer st = new StringTokenizer(generators, ";");
		if (st.hasMoreTokens()) {
			String path = st.nextToken();
			if (path==null || path.trim().length()==0) return null;
			String model = getMainModel(config);
			IFile file = (IFile) ResourceManager
					.getResource(new Path(model).toString());
			if (file==null) return null;
			ModelData md = new ModelData(file);
			BuildPolicy[] policies = md.getPolicies();
			for (BuildPolicy buildPolicy : policies) {
				if (path.trim().equals(buildPolicy.getPathGenerator())) {
					return buildPolicy;
				}
			}
			if (policies.length > 0) return policies[0];
		}
		return null;
	}
}


text:
require 'rails_helper'

RSpec.describe Party::ChangePhoneFormObject, type: :model do
  let!(:party) { create :party }
  let(:form_object) { Party::ChangePhoneFormObject.new(party, params) }

  describe 'validate' do
    context 'success' do
      let(:params) { { unconfirmed_phone: '0922888888' } }
      it { expect(form_object.valid?).to be_truthy }
    end

    context 'fail' do
      context 'empty phone_number' do
        let(:params) { { unconfirmed_phone: '' } }
        it { expect(form_object.valid?).to be_falsey }
      end

      context 'invalid phone_number' do
        let(:params) { { unconfirmed_phone: '002xx' } }
        it { expect(form_object.valid?).to be_falsey }
      end

      context 'same phone_number' do
        let(:params) { { unconfirmed_phone: party.phone_number } }
        it { expect(form_object.valid?).to be_falsey }
      end

      context 'exist phone_number' do
        let!(:party2) { create :party }
        let(:params) { { unconfirmed_phone: party2.phone_number } }
        it { expect(form_object.valid?).to be_falsey }
      end

      context 'exist unconfirm_phone_number' do
        let!(:party2) { create :party, :with_unconfirmed_phone }
        let(:params) { { unconfirmed_phone: party2.unconfirmed_phone } }
        it { expect(form_object.valid?).to be_falsey }
      end
    end
  end

  describe '#save' do
    context 'success' do
      let(:params) { { unconfirmed_phone: '0922888888' } }
      before { form_object.save }
      it { expect(party.unconfirmed_phone).to eq('0922888888') }
    end

    context 'fail' do
      let(:params) { { unconfirmed_phone: '4022888888' } }
      before { form_object.save }
      it { expect(party.unconfirmed_phone).to be_nil }
    end
  end

end