text:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import cats.effect.IO
import korolev.Context
import korolev.akka.{AkkaHttpServerConfig, akkaHttpService}
import korolev.cats._
import korolev.server.{KorolevServiceConfig, StateLoader}
import korolev.state.javaSerialization._

import scala.concurrent.ExecutionContext.Implicits.global

object CatsIOExample extends App {

  private implicit val actorSystem: ActorSystem = ActorSystem()

  val applicationContext: Context[IO, State, Any] = {
    Context[IO, State, Any]
  }

  import applicationContext._
  import levsha.dsl._
  import html._

  // Handler to input
  private val inputId = elementId()
  private val editInputId = elementId()

  val config = KorolevServiceConfig[IO, State, Any](
    stateLoader = StateLoader.default(State()),
    document = state => {
      Html(
        body(
          div("Super TODO tracker"),
          div(height @= "250px", overflow @= "scroll",
            (state.todos zipWithIndex) map {
              case (todo, i) =>
                div(
                  input(
                    `type` := "checkbox",
                    if (state.edit.nonEmpty) disabled else void,
                    if (todo.done) checked else void,
                    // Generate transition when clicking checkboxes
                    event("click") { access =>
                      access.transition { s =>
                        val updated = s.todos.updated(i, s.todos(i).copy(done = !todo.done))
                        s.copy(todos = updated)
                      }
                    }
                  ),
                  if (state.edit.contains(i)) {
                    form(
                      marginBottom @= "-10px",
                      display @= "inline-block",
                      input(
                        editInputId,
                        display @= "inline-block",
                        `type` := "text",
                        value := todo.text
                      ),
                      button(display @= "inline-block", "Save"),
                      event("submit") { access =>
                        access.valueOf(editInputId) flatMap { value =>
                          access.transition { s =>
                            val updatedTodo = s.todos(i).copy(text = value)
                            val updatedTodos = s.todos.updated(i, updatedTodo)
                            s.copy(todos = updatedTodos, edit = None)
                          }
                        }
                      }
                    )
                  } else {
                    span(
                      if (todo.done) textDecoration @= "line-through" else void,
                      todo.text,
                      event("dblclick") { access =>
                        access.transition(_.copy(edit = Some(i)))
                      }
                    )
                  }
                )
            }
          ),
          form(
            // Generate AddTodo action when Add' button clicked
            event("submit") { access =>
              val prop = access.property(inputId)
              prop.get("value") flatMap { value =>
                prop.set("value", "") flatMap { _ =>
//                  IO.trace flatMap { trace =>
//                    println(trace)
//                    val todo = State.Todo(value, done = false)
//                    access.transition(s => s.copy(todos = s.todos :+ todo))
//                  }

                  val todo = State.Todo(value, done = false)
                  access.transition(s => s.copy(todos = s.todos :+ todo))
                }
              }
            },
            input(
              if (state.edit.nonEmpty) disabled else void,
              inputId,
              `type` := "text",
              placeholder := "What should be done?"
            ),
            button(
              if (state.edit.nonEmpty) disabled else void,
              "Add todo"
            )
          )
        )
      )
    }
  )

  private val route = akkaHttpService(config).apply(AkkaHttpServerConfig())

  Http().newServerAt("0.0.0.0", 8080).bindFlow(route)
}

case class State(
  todos: Vector[State.Todo] = (0 to 9).toVector.map(i => State.Todo(s"This is TODO #$i", done = false)),
  edit: Option[Int] = None
)

object State {
  case class Todo(text: String, done: Boolean)
}


text:
using System.Threading.Tasks;
using NSwag.CodeGeneration;
using NSwag.Commands;
using NSwag.Commands.SwaggerGeneration;
using NSwagStudio.ViewModels.SwaggerGenerators;

namespace NSwagStudio.Views.SwaggerGenerators
{
    public partial class SwaggerInputView : ISwaggerGeneratorView
    {
        private readonly FromSwaggerCommand _command;

        public SwaggerInputView(FromSwaggerCommand command)
        {
            _command = command;
            InitializeComponent();

            Model.Command = command;
            Model.RaiseAllPropertiesChanged();
        }

        public IOutputCommand Command => _command;

        private SwaggerInputViewModel Model => (SwaggerInputViewModel)Resources["ViewModel"];

        public NSwagDocument Document { get; set; }

        public string Title => "Swagger Specification";

        public Task<string> GenerateSwaggerAsync()
        {
            return Model.GenerateSwaggerAsync();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// <copyright file="MapToQueryableOperator.cs" company="Kyubisation">
// Copyright (c) Kyubisation. All rights reserved.
// </copyright>

// ReSharper disable once CheckNamespace
namespace FluentRestBuilder
{
    using System;
    using System.Linq;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyInjection;
    using Operators;
    using Storage;

    public static class MapToQueryableOperator
    {
        /// <summary>
        /// Map to a <see cref="IQueryable{TTarget}"/> from the received <see cref="DbContext"/>.
        /// Use the <see cref="DbContext.Set{TEntity}"/> method to select the appropriate
        /// <see cref="IQueryable{TEntity}"/>.
        /// </summary>
        /// <typeparam name="TSource">The type of the value.</typeparam>
        /// <typeparam name="TTarget">The type of the resulting queryable.</typeparam>
        /// <param name="observable">The parent observable.</param>
        /// <param name="mapping">The mapping function</param>
        /// <returns>An instance of <see cref="IProviderObservable{TSource}"/>.</returns>
        public static IProviderObservable<IQueryable<TTarget>> MapToQueryable<TSource, TTarget>(
            this IProviderObservable<TSource> observable,
            Func<TSource, DbContext, IQueryable<TTarget>> mapping) =>
            new MapToQueryableObservable<TSource, TTarget>(mapping, observable);

        private sealed class MapToQueryableObservable<TSource, TTarget> : Operator<TSource, IQueryable<TTarget>>
        {
            private readonly Func<TSource, DbContext, IQueryable<TTarget>> mapping;

            public MapToQueryableObservable(
                Func<TSource, DbContext, IQueryable<TTarget>> mapping,
                IProviderObservable<TSource> observable)
                : base(observable)
            {
                this.mapping = mapping;
            }

            protected override IObserver<TSource> Create(
                IObserver<IQueryable<TTarget>> observer, IDisposable disposable)
            {
                var context = this.ServiceProvider.GetService<IScopedStorage<DbContext>>();
                return new MapToQueryableObserver(this.mapping, context, observer, disposable);
            }

            private sealed class MapToQueryableObserver : SafeObserver
            {
                private readonly Func<TSource, DbContext, IQueryable<TTarget>> mapping;
                private readonly IScopedStorage<DbContext> context;

                public MapToQueryableObserver(
                    Func<TSource, DbContext, IQueryable<TTarget>> mapping,
                    IScopedStorage<DbContext> context,
                    IObserver<IQueryable<TTarget>> child,
                    IDisposable disposable)
                    : base(child, disposable)
                {
                    this.mapping = mapping;
                    this.context = context;
                }

                protected override IQueryable<TTarget> SafeOnNext(TSource value) =>
                    this.mapping(value, this.context.Value);
            }
        }
    }
}


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var XmlElementNames_1 = require("../Core/XmlElementNames");
var ServiceId_1 = require("./ServiceId");
/**
 * Represents the Id of a Conversation.
 */
var ConversationId = (function (_super) {
    __extends(ConversationId, _super);
    function ConversationId(uniqueId) {
        arguments.length === 0 ? _super.call(this) : _super.call(this, uniqueId);
    }
    /**
     * @internal Gets the name of the XML element.
     *
     * @return  {string}      XML element name.
     */
    ConversationId.prototype.GetXmlElementName = function () { return XmlElementNames_1.XmlElementNames.ConversationId; };
    /**
     * Gets a string representation of the Conversation Id.
     *
     * @return  {string}      The string representation of the conversation id.
     */
    ConversationId.prototype.ToString = function () {
        // We have ignored the change key portion
        return this.UniqueId;
    };
    ConversationId.prototype.toString = function () { return this.ToString(); };
    return ConversationId;
}(ServiceId_1.ServiceId));
exports.ConversationId = ConversationId;


text:
/*
Theme Name:         Isolunch
Theme URI:          https://github.com/frozzare/isolunch
Description:        What's for lunch today?
Version:            1.0.0
Author:             Isolunch contributors
Author URI:         https://github.com/frozzare/isolunch

License:            MIT License
License URI:        http://opensource.org/licenses/MIT
*/


text:
extern crate gannai;
extern crate argparse;
extern crate rustc_serialize;

use rustc_serialize::json;

use gannai::neural_network::NetworkBuf;
use gannai::tools::common::{Sample, make_conf, make_samples, make_network_buf};

struct Args {
    conf: String,
    samples: String,
    network: String,
}

#[derive(RustcDecodable)]
struct Conf {
    group_size: usize,
    threshold: f64,
    max_function_calls_count: usize,
}

fn main() {
    let mut args = Args {conf: String::new(), samples: String::new(), network: String::new()};
    parse_args(&mut args);
    let conf = make_conf::<Conf>(&args.conf);
    let mut network_buf = make_network_buf(&args.network);
    let samples = make_samples(&args.samples);
    train(&conf, &samples, &mut network_buf);
    println!("{}", json::encode(&network_buf).unwrap());
}

fn parse_args(args: &mut Args) {
    use argparse::{ArgumentParser, Store};
    let mut parser = ArgumentParser::new();
    parser.set_description("Trains neural network by using samples");
    parser.refer(&mut args.conf)
        .add_argument("conf", Store, "Path to conf json file").required();
    parser.refer(&mut args.network)
        .add_argument("network", Store, "Path to neural network json file").required();
    parser.refer(&mut args.samples)
        .add_argument("samples", Store, "Path to samples json file (default is stdin)");
    parser.parse_args_or_exit();
}

fn train(conf: &Conf, src_samples: &[Sample], network_buf: &mut NetworkBuf) {
    use gannai::neural_network::{
        ApplyConf,
        ErrorConf,
        Sample,
        Train,
        TrainConf,
    };
    let apply_conf = ApplyConf {
        group_size: conf.group_size,
        threshold: conf.threshold,
    };
    let samples: Vec<Sample> = src_samples.iter()
        .map(|x| Sample {input: &x.input[..], output: &x.output[..]})
        .collect::<_>();
    let error_conf = ErrorConf {
        apply_conf: &apply_conf,
        samples: &samples[..],
    };
    let train_conf = TrainConf {
        error_conf: &error_conf,
        max_function_calls_count: conf.max_function_calls_count,
    };
    network_buf.as_network_mut().train(&train_conf);
}


text:
const {
  app,
  dialog: electronDialog,
  screen: electronScreen,
  session,
  BrowserWindow
} = require('electron');

const Sentry = require('@sentry/node');

const path = require('path');

const Cli = require('./cli');
const Config = require('./config');
const Dialog = require('./dialog');
const Flags = require('./flags');
const Log = require('./log');
const logTransports = require('./log/transports');
const Menu = require('./menu');
const Platform = require('./platform');
const Plugins = require('./plugins');
const WindowManager = require('./window-manager');
const Workspace = require('./workspace');

const {
  readFile,
  readFileStats,
  writeFile
} = require('./file-system');

const browserOpen = require('./util/browser-open');
const renderer = require('./util/renderer');

const errorTracking = require('./util/error-tracking');

const log = Log('app:main');
const bootstrapLog = Log('app:main:bootstrap');
const clientLog = Log('client');

bootstrapLogging();

const name = app.name = 'Camunda Modeler';
const version = app.version = require('../package').version;

bootstrapLog.info(`starting ${ name } v${ version }`);

const {
  platform
} = process;

const {
  config,
  dialog,
  files,
  flags,
  menu,
  plugins,
  windowManager
} = bootstrap();

app.flags = flags;
app.metadata = {
  version,
  name
};
app.plugins = plugins;

Platform.create(platform, app, config);

// only allow single instance if not disabled via `--no-single-instance` flag
if (flags.get('single-instance') === false) {
  log.info('single instance disabled via flag');
} else {
  const gotLock = app.requestSingleInstanceLock();

  if (gotLock) {

    app.on('second-instance', (event, argv, cwd) => {

      const {
        files
      } = Cli.parse(argv, cwd);

      app.openFiles(files);

      // focus existing running instance window
      if (app.mainWindow) {
        if (app.mainWindow.isMinimized()) {
          app.mainWindow.restore();
        }

        app.mainWindow.focus();
      }
    });
  } else {
    app.quit();
  }
}

// external //////////

renderer.on('external:open-url', function(options) {
  const url = options.url;

  browserOpen(url);
});

// dialogs //////////

renderer.on('dialog:open-files', async function(options, done) {
  const {
    activeFile
  } = options;

  if (activeFile && activeFile.path) {
    options = {
      ...options,
      defaultPath: path.dirname(activeFile.path)
    };
  }

  const filePaths = await dialog.showOpenDialog(options);

  done(null, filePaths);
});

renderer.on('dialog:open-file-error', async function(options, done) {
  const response = await dialog.showOpenFileErrorDialog(options);

  done(null, response);
});

renderer.on('dialog:save-file', async function(options, done) {
  const { file } = options;

  if (file.path) {
    options = {
      ...options,
      defaultPath: path.dirname(file.path)
    };
  }

  const filePath = await dialog.showSaveDialog(options);

  done(null, filePath);
});

renderer.on('dialog:show', async function(options, done) {
  const response = await dialog.showDialog(options);

  done(null, response);
});

// filesystem //////////

renderer.on('file:read', function(filePath, options = {}, done) {
  try {
    const newFile = readFile(filePath, options);

    done(null, newFile);
  } catch (err) {
    done(err);
  }
});

renderer.on('file:read-stats', function(file, done) {
  const newFile = readFileStats(file);

  done(null, newFile);
});

renderer.on('file:write', function(filePath, file, options = {}, done) {
  try {
    const newFile = writeFile(filePath, file, options);

    done(null, newFile);
  } catch (err) {
    done(err);
  }
});

// config //////////

renderer.on('config:get', function(key, ...args) {
  const done = args.pop();

  let value;

  try {
    value = config.get(key, ...args);

    done(null, value);
  } catch (error) {
    done(error);
  }
});

renderer.on('config:set', function(key, value, ...args) {
  const done = args.pop();

  try {
    value = config.set(key, value, ...args);

    done(null, value);
  } catch (error) {
    done(error);
  }
});

// plugin toggling //////////

renderer.on('toggle-plugins', function() {

  const pluginsDisabled = flags.get('disable-plugins');

  app.emit('restart', [ pluginsDisabled ? '--no-disable-plugins' : '--disable-plugins' ]);
});

// open file handling //////////

app.on('app:client-ready', function() {
  bootstrapLog.info('received client-ready');

  // open pending files
  if (files.length) {
    app.openFiles(files);
  }

  renderer.send('client:started');
});

renderer.on('client:ready', function() {
  app.clientReady = true;

  app.emit('app:client-ready');
});

renderer.on('client:error', function(...args) {
  const done = args.pop();

  clientLog.error(...args);
  done(null);
});

app.on('web-contents-created', (event, webContents) => {

  // open all external links in new window
  webContents.on('new-window', function(event, url) {
    event.preventDefault();

    browserOpen(url);
  });

  // disable web-view (not used)
  webContents.on('will-attach-webview', () => {
    event.preventDefault();
  });

  // open in-page links externally by default
  // @see https://github.com/electron/electron/issues/1344#issuecomment-171516636
  webContents.on('will-navigate', (event, url) => {

    if (url !== webContents.getURL()) {
      event.preventDefault();

      browserOpen(url);
    }
  });
});

/**
 * Open the given filePaths in the editor.
 *
 * @param {Array<string>} filePaths
 */
app.openFiles = function(filePaths) {

  log.info('open files', filePaths);

  if (!app.clientReady) {

    // defer file open
    return files.push(...filePaths);
  }

  const existingFiles = filePaths.map(filePath => {

    try {
      return readFile(filePath);
    } catch (e) {
      dialog.showOpenFileErrorDialog({
        name: path.basename(filePath)
      });
    }
  }).filter(f => f);

  // open files
  renderer.send('client:open-files', existingFiles);
};

/**
 * Create the main window that represents the editor.
 *
 * @return {BrowserWindow}
 */
app.createEditorWindow = function() {

  const nodeIntegration = !!flags.get('dangerously-enable-node-integration');

  if (nodeIntegration) {
    log.warn('nodeIntegration is enabled via --dangerously-enable-node-integration');
  }

  const windowOptions = {
    resizable: true,
    show: false,
    title: 'Camunda Modeler' + getTitleSuffix(app.metadata.version),
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration
    }
  };

  if (process.platform === 'linux') {
    windowOptions.icon = path.join(__dirname + '/../resources/favicon.png');
  }

  const mainWindow = app.mainWindow = new BrowserWindow(windowOptions);

  windowManager.manage(mainWindow);

  dialog.setActiveWindow(mainWindow);

  let url = 'file://' + path.resolve(__dirname + '/../public/index.html');

  if (process.env.NODE_ENV === 'development') {
    url = 'file://' + path.resolve(__dirname + '/../../client/build/index.html');
  }

  mainWindow.loadURL(url);

  // handling case when user clicks on window close button
  mainWindow.on('close', function(e) {
    log.info('initating close of main window');

    if (app.quitAllowed) {

      // dereferencing main window and resetting client state
      app.mainWindow = null;
      dialog.setActiveWindow(null);

      app.clientReady = false;

      return log.info('main window closed');
    }

    // preventing window from closing until client allows to do so
    e.preventDefault();

    log.info('asking client to allow quit');

    app.emit('app:quit-denied');

    renderer.send('menu:action', 'quit');
  });

  mainWindow.on('focus', function() {
    log.info('window focused');

    renderer.send('client:window-focused');
  });

  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });

  app.emit('app:window-created', mainWindow);

  // only set by client, when it is ok to exit
  app.quitAllowed = false;
};

app.on('restart', function(args) {

  const effectiveArgs = Cli.appendArgs(process.argv.slice(1), [ ...args, '--relaunch' ]);

  log.info('restarting with args', effectiveArgs);

  app.relaunch({
    args: effectiveArgs
  });

  app.exit(0);
});

/**
 * Application entry point
 * Emitted when Electron has finished initialization.
 */
app.on('ready', function() {

  bootstrapLog.info('received ready');

  menu.registerMenuProvider('plugins', {
    plugins: plugins.getAll()
  });

  session.defaultSession.webRequest.onBeforeRequest((details, callback) => {

    const { url } = details;

    const redirectURL = plugins.getAssetPath(url);

    if (redirectURL) {
      return callback({
        redirectURL
      });
    }

    return callback({});
  });

  // quit command from menu/shortcut
  app.on('app:quit', function() {
    log.info('initiating quit');

    renderer.send('menu:action', 'quit');
  });

  // client quit verification event
  renderer.on('app:quit-allowed', function() {
    log.info('quit allowed');

    app.quitAllowed = true;

    app.mainWindow.close();
  });

  app.createEditorWindow();
});

function bootstrapLogging() {

  let logPath;

  try {
    logPath = app.getPath('logs');
  } catch (e) {
    logPath = app.getPath('userData');
  }

  Log.addTransports(
    new logTransports.Console(),
    new logTransports.File(path.join(logPath, 'log.log'))

    // TODO(nikku): we're not doing this for now
    // first we must decide how to separate diagram open warnings from
    // actual app errors in the client user interface
    // new logTransports.Client(renderer, () => app.clientReady)
  );
}

/**
 * Bootstrap and return application components.
 *
 * @return {Object}
 */
function bootstrap() {
  const appPath = path.dirname(app.getPath('exe')),
        cwd = process.cwd(),
        userDesktopPath = app.getPath('userDesktop');

  const {
    files,
    flags: flagOverrides
  } = Cli.parse(process.argv, cwd);

  // (1) user path
  if (flagOverrides['user-data-dir']) {
    app.setPath('userData', flagOverrides['user-data-dir']);
  }

  const userPath = app.getPath('userData');

  let resourcesPaths = [
    path.join(appPath, 'resources'),
    path.join(userPath, 'resources')
  ];

  if (process.env.NODE_ENV === 'development') {
    resourcesPaths = [
      ...resourcesPaths,
      path.join(cwd, 'resources')
    ];
  }

  // (2) config
  const config = new Config({
    appPath,
    resourcesPaths,
    userPath
  });

  // (3) flags
  const flags = new Flags({
    paths: resourcesPaths,
    overrides: flagOverrides
  });

  // error tracking can start as soon as config and flags are initialized.
  errorTracking.start(Sentry, version, config, flags, renderer);

  // (4) menu
  const menu = new Menu({
    platform
  });

  // (5) dialog
  const dialog = new Dialog({
    config,
    electronDialog,
    userDesktopPath
  });

  // (6) workspace
  new Workspace(config);

  // (7) plugins
  const pluginsDisabled = flags.get('disable-plugins');

  // (8) window manager
  const windowManager = new WindowManager({
    config,
    electronScreen
  });

  let paths;

  if (pluginsDisabled) {
    paths = [];

    log.info('plug-ins disabled via feature toggle');
  } else {
    paths = [
      appPath,
      ...resourcesPaths,
      userPath
    ];
  }

  const plugins = new Plugins({
    paths
  });

  // track plugins
  errorTracking.setTag(Sentry, 'plugins', plugins.getAll().map(({ name }) => name).join(','));

  return {
    config,
    dialog,
    files,
    flags,
    menu,
    plugins,
    windowManager
  };
}

/**
 * Returns the app title suffix based on app version.
 *
 * @param {string} version
 * @return {string}
 */
function getTitleSuffix(version) {
  if (version.includes('dev')) {
    return ' (dev)';
  } else if (version.includes('nightly')) {
    return ' (' + version.split('-')[1] + ')';
  }
  return '';
}

// expose app
module.exports = app;


text:
[![Gem Version](https://badge.fury.io/rb/rack-test-rest.png)](http://badge.fury.io/rb/rack-test-rest)

`rack-test-rest` is an extension to `rack-test` that when combined with
`Test::Unit` simplifies the process of unit testing properly
designed RESTful API's.

# Installation
    $ gem install rack-test-rest

# Use

`rack-test-rest` extends `rack-test` with a set of higher-level methods that
perform _CRUD_ operations against resources through a RESTful API that conforms
to best practices and validates that they respond correctly.
It's designed to be mixed into a subclass of `Test::Unit::Testcase`
that is testing a specific resource e.g.:

      class GaugeTest < Test::Unit::TestCase
        include Rack::Test::Methods
        include Rack::Test::Rest

        def setup
          @rack_test_rest = {
            #:debug => true,
            :root_uri => "/v1/metrics",
            :resource => "gauges",
            :extension => ".json" #other possibilities ".xml", "_json",".html", etc
          }
        end

        def test_create
          create_resource(:name => "foo")
          create_resource(:code => 422, :name => "foo")
        end

        def test_read
          create_resource(:name => "foo")

          gauge = read_resource(:id => "foo")
          assert gauge['name'] == "foo"
        end

        def test_update
          create_resource(:name => "foo", :description => "bar")

          update_resource(:id => "foo", :description => "baz")

          gauge = read_resource(:id => "foo")
          assert gauge['description'] == "baz"
        end

        def test_delete
          create_resource(:name => "foo")
          delete_resource(:id => "foo")
          read_resource(:code => 404, :id => "foo")
        end

`rack-test-rest` exploits _convention over configuration_ to minimize the amount of work
required to test any particular resource. You need only specify `:root_uri` and `:resource`
in your test setup (through the `@rack_test_rest` instance variable). These are combined
to create either the URI for creating/indexing resources or the URI for a particular resource:

    :root_uri + '/' + :resource + :extension
    :root_uri + '/' + :resource + '/' + params[:id].to_s + :extension

Currently JSON is the only supported response Content-Type.

## `create_resource(params={})`

Performs a POST to with any specified parameters to `:root_uri/:resource:extension`
and ensures that it returns `201`. Returns the string value found in the response's
`Location` header.

## `read_resource(params={})`

Performs a GET with any specified parameters and validates that it returns `200`.
If `:id` is specified the GET is performed against a singular resource i.e.
`:root_uri/:resource/:id:extension`. In the absence of `:id` the GET is performed
as an index operation against `:root_uri/:resource:extension`. Returns parsed
JSON of the response body on a `200`.

## `update_resource(params={})`

Requires an :id parameter. Performs a PUT against `:root_uri/:resource/:id:extension`
with any other specified parameters and asserts that it returns `204`.

## `delete_resource(params={})`

Requires an :id parameter. Performs a DELETE against `:root_uri/:resource/:id:extension`
and asserts that it returns `204`.

## Testing invalid input

Any of the CRUD operations can be altered to check that invalid input is properly
detected and returns the correct error code by specifying `:code` as a parameter
e.g.
    create_resource(:code => 422, :name => duplicate_name)
    read_resource(:code => 404, :id => invalid_id)

## Debugging
The point of unit tests is to surface and fix defects and/or regressions in your code
in the lab rather than than in production. When your tests fail you can include
`:debug => true` to instruct `rack-rest-test` to verbosely log to STDOUT the individual
HTTP requests it's performing and the results of each.

## Pagination
`rack-test-rest` also supports randomized tests for paginated resources assuming you follow
the [standard pagination scheme](http://dev.librato.com/v1/pagination). All you need supply it
with is a block it can use to generate unique parameters for populating the resources prior
to pagination tests. You can specify `:count` to control how many records are created and
paginated through (defaults to 512) and `:length` to specify the maximum number of resources
that a single index operation may return (defaults to 100).

    def test_gauge_pagination
      @db.run("DELETE FROM gauges")
      paginate_resource(){ |id| {:name => "foo_#{id}", :description => "gauge #{id}"} }
    end

# Contributions

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
* Fork the project
* Start a feature/bugfix branch
* Commit and push until you are happy with your contribution
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
* Submit a pull request!

# Copyright

Copyright (c) 2011-2014 Joseph Ruscio. See LICENSE.txt for
further details.


text:
extras Package
==============

:mod:`extras` Package
---------------------

.. automodule:: rdflib.extras
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`cmdlineutils` Module
--------------------------

.. automodule:: rdflib.extras.cmdlineutils
    :members:
    :undoc-members:
    :show-inheritance:

:mod:`describer` Module
-----------------------

.. automodule:: rdflib.extras.describer
    :members:
    :undoc-members:
    :show-inheritance:
    :exclude-members: __dict__,__weakref__

:mod:`infixowl` Module
----------------------

.. automodule:: rdflib.extras.infixowl
    :members:
    :undoc-members:
    :show-inheritance:
    :exclude-members: __dict__,__weakref__


text:
export const importPrompt = 'Add a sampling of sci-fi movies to your dataset on the hosted backend?'
export const datasetUrl = 'https://public.sanity.io/moviesdb-2018-03-06.tar.gz'

export const dependencies = {
  '@sanity/google-maps-input': '^0.99.0',
  'react-icons': '^3.11.0',
}

export const generateSanityManifest = (base) => ({
  ...base,
  plugins: base.plugins.concat(['@sanity/google-maps-input']),
})


text:
namespace STFS {

int
STFSd_getEfm ( STFS_OpenIdentifier        *pp_OpenId,
               STFS_ExternalFileMetadata  *pp_Efm,
               int                         pv_OpenerNodeId,
               int                         pv_OpenerPID);

} //namespace STFS
#endif //STFSD_GETEFM_H


text:
namespace System.Windows.Forms
{

#if CONFIG_FRAMEWORK_2_0 && !CONFIG_COMPACT_FORMS

public enum PowerState
{
	Suspend			= 0,
	Hibernate		= 1
}; // enum PowerState

#endif // CONFIG_FRAMEWORK_2_0 && !CONFIG_COMPACT_FORMS

}; // namespace System.Windows.Forms


text:
static const int ddLogLevel = LOG_LEVEL_VERBOSE;

@interface SignInViewController () <XMPPStreamDelegate>

@property (weak, nonatomic) IBOutlet NSTextField * jidTextField;
@property (weak, nonatomic) IBOutlet NSTextField * passwordTextField;
@property (weak, nonatomic) IBOutlet NSButton * signInButton;
@property (weak, nonatomic) IBOutlet NSTextField * errorLabel;

@property (strong, nonatomic) XMPPStream * xmppStream;
@property (assign, nonatomic, getter=isConnectionOpen) BOOL connectionOpen;
@property (assign, nonatomic, getter=isAuthenticating) BOOL authenticating;

@end

@implementation SignInViewController

#pragma mark - View Controller Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.xmppStream = [[XMPPStream alloc] init];
    [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)dealloc
{
    [self.xmppStream removeDelegate:self];
}

#pragma mark - UI Methods

- (IBAction)signInButtonPressed:(id)sender
{
    [self.view.window makeFirstResponder:nil];

    [self displayErrorMessage:nil];

    NSString *resource = (__bridge_transfer NSString *)SCDynamicStoreCopyComputerName(NULL, NULL);
    self.xmppStream.myJID = [XMPPJID jidWithString:self.jidTextField.stringValue resource:resource];

    NSError *error;
    BOOL success;

    if (!self.xmppStream.isConnected)
    {
        success = [[self xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:&error];
    }
    else
    {
        success = [[self xmppStream] authenticateWithPassword:self.passwordTextField.stringValue error:&error];
    }

    if (success)
    {
        self.authenticating = YES;
        [self lockSignInUI];
    }
    else
    {
        [self displayErrorMessage:error.localizedDescription];
    }
}

- (void)enableSignInUI:(BOOL)enabled
{
    self.jidTextField.enabled = enabled;
    self.passwordTextField.enabled = enabled;
    self.signInButton.enabled = enabled;
}

- (void)lockSignInUI
{
    [self enableSignInUI:NO];
}

- (void)unlockSignInUI
{
    [self enableSignInUI:YES];
}

- (void)displayErrorMessage:(NSString *)message
{
    self.errorLabel.stringValue = message ?: @"";
    self.errorLabel.hidden = (message.length == 0);
}

#pragma mark - XMPPStream Delegate

- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

    // Allow self-signed certificates
    //[settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
}

- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

    self.connectionOpen = YES;

    NSString *password = self.passwordTextField.stringValue;

    NSError *error = nil;
    BOOL operationInProgress = [self.xmppStream authenticateWithPassword:password error:&error];

    if (!operationInProgress)
    {
        [self displayErrorMessage:error.localizedDescription];
    }
}

- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

    self.authenticating = NO;

    XMPPPresence *presence = [XMPPPresence presence];
    [self.xmppStream sendElement:presence];

    [self.delegate signInViewController:self didOpenXMPPStream:self.xmppStream];
}

- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

    self.authenticating = NO;

    [self unlockSignInUI];
    [self displayErrorMessage:@"Invalid username/password"];
}

- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}

- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);

    [self displayErrorMessage:@"Cannot connect to server"];

    self.connectionOpen = NO;
    self.authenticating = NO;

    [self unlockSignInUI];
}

@end


text:
package training.medium.thereIsNoSpoonEpisode1;

import java.util.*;

class Coord {
	final int x;
	final int y;

	Coord(int col, int row) {
		this.x = col;
		this.y = row;
	}

	public String toString() {
		return x + " " + y;
	}
}

class Board {
	static final char POWER = '0';
	static final Coord NONE = new Coord(-1, -1);

	final int width;
	final int height;
	private final String[] cells;

	Board(int width, int height) {
		this.width = width;
		this.height = height;
		cells = new String[height];
	}

	Board(Scanner in) {
		this(in.nextInt(), in.nextInt());
		for (int rowIdx = 0; rowIdx < height; rowIdx++) {
			cells[rowIdx] = in.next();
		}
	}

	char getCellAt(int col, int row) {
		return cells[row].charAt(col);
	}

	boolean isPowerNode(int col, int row) {
		return getCellAt(col, row) == POWER;
	}

	Coord searchRight(Coord from) {
		for (int colIdx = from.x + 1; colIdx < width; colIdx++) {
			if (isPowerNode(colIdx, from.y)) {
				return new Coord(colIdx, from.y);
			}
		}
		return NONE;
	}

	Coord searchDown(Coord from) {
		for (int rowIdx = from.y + 1; rowIdx < height; rowIdx++) {
			if (isPowerNode(from.x, rowIdx)) {
				return new Coord(from.x, rowIdx);
			}
		}
		return NONE;
	}
}

class Player {

	public static void main(String[] args) {
		new Player().run();
	}

	Scanner in = new Scanner(System.in);
	private Board board;

	void run() {
		board = new Board(in);

		for (int rowIdx = 0; rowIdx < board.height; rowIdx++) {
			for (int colIdx = 0; colIdx < board.width; colIdx++) {
				if (board.isPowerNode(colIdx, rowIdx)) {
					Coord pos = new Coord(colIdx, rowIdx);
					Coord right = board.searchRight(pos);
					Coord down = board.searchDown(pos);

					// Three coordinates: a node, its right neighbor, its bottom neighbor
					System.out.println(pos + " " + right + " " + down);
				}
			}
		}
	}

}


text:
function [state,options] = psoplotscorediversity(options,state,flag)
% Plots a histogram containing the best and mean scores of particle swarm.

if strcmp(flag,'init')
    set(gca,'NextPlot','replacechildren',...
        'XLabel',xlabel('Scores'),...
        'YLabel',ylabel('Number of inidividuals'))
end

[n,bins] = hist(state.Score) ;
bar(bins,n,'Tag','scorehistogram','FaceColor',[0.1 0.1 0.5])