text:
module GraphQL
  class Backtrace
    # A class for turning a context into a human-readable table or array
    class Table
      MIN_COL_WIDTH = 4
      MAX_COL_WIDTH = 100
      HEADERS = [
        "Loc",
        "Field",
        "Object",
        "Arguments",
        "Result",
      ]

      def initialize(context, value:)
        @context = context
        @override_value = value
      end

      # @return [String] A table layout of backtrace with metadata
      def to_table
        @to_table ||= render_table(rows)
      end

      # @return [Array<String>] An array of position + field name entries
      def to_backtrace
        @to_backtrace ||= begin
          backtrace = rows.map { |r| "#{r[0]}: #{r[1]}" }
          # skip the header entry
          backtrace.shift
          backtrace
        end
      end

      private

      def rows
        @rows ||= build_rows(@context, rows: [HEADERS], top: true)
      end

      # @return [String]
      def render_table(rows)
        max = Array.new(HEADERS.length, MIN_COL_WIDTH)

        rows.each do |row|
          row.each_with_index do |col, idx|
            col_len = col.length
            max_len = max[idx]
            if col_len > max_len
              if col_len > MAX_COL_WIDTH
                max[idx] = MAX_COL_WIDTH
              else
                max[idx] = col_len
              end
            end
          end
        end

        table = "".dup
        last_col_idx = max.length - 1
        rows.each do |row|
          table << row.map.each_with_index do |col, idx|
            max_len = max[idx]
            if idx < last_col_idx
              col = col.ljust(max_len)
            end
            if col.length > max_len
              col = col[0, max_len - 3] + "..."
            end
            col
          end.join(" | ")
          table << "\n"
        end
        table
      end

      # @return [Array] 5 items for a backtrace table (not `key`)
      def build_rows(context_entry, rows:, top: false)
        case context_entry
        when Backtrace::Frame
          field_alias = context_entry.ast_node.respond_to?(:alias) && context_entry.ast_node.alias
          value = if top && @override_value
            @override_value
          else
            value_at(@context.query.context.namespace(:interpreter_runtime)[:runtime], context_entry.path)
          end
          rows << [
            "#{context_entry.ast_node ? context_entry.ast_node.position.join(":") : ""}",
            "#{context_entry.field.path}#{field_alias ? " as #{field_alias}" : ""}",
            "#{context_entry.object.object.inspect}",
            context_entry.arguments.to_h.inspect, # rubocop:disable Development/ContextIsPassedCop -- unrelated method
            Backtrace::InspectResult.inspect_result(value),
          ]
          if (parent = context_entry.parent_frame)
            build_rows(parent, rows: rows)
          else
            rows
          end
        when GraphQL::Query::Context
          query = context_entry.query
          op = query.selected_operation
          if op
            op_type = op.operation_type
            position = "#{op.line}:#{op.col}"
          else
            op_type = "query"
            position = "?:?"
          end
          op_name = query.selected_operation_name
          object = query.root_value
          if object.is_a?(GraphQL::Schema::Object)
            object = object.object
          end
          value = value_at(context_entry.namespace(:interpreter_runtime)[:runtime], [])
          rows << [
            "#{position}",
            "#{op_type}#{op_name ? " #{op_name}" : ""}",
            "#{object.inspect}",
            query.variables.to_h.inspect,
            Backtrace::InspectResult.inspect_result(value),
          ]
        else
          raise "Unexpected get_rows subject #{context_entry.class} (#{context_entry.inspect})"
        end
      end

      def value_at(runtime, path)
        response = runtime.final_result
        path.each do |key|
          if response && (response = response[key])
            next
          else
            break
          end
        end
        response
      end
    end
  end
end


text:
{% extends "layout.html" %}
{% set title = _('Overview') %}
{% block body %}

{{ _('Welcome') }}

{%trans%}Start Here{%endtrans%}

{%trans%}Hopsworks Overview{%endtrans%}

         {%trans%}Introduction to Hopsworks Concepts{%endtrans%}p

{%trans%}Get started with Hopsworks{%endtrans%}

         {%trans%}How to get started?{%endtrans%}

{%trans%}Installation Guide{%endtrans%}

         {%trans%}How to install?{%endtrans%}

{%trans%}Hopsworks User Guide{%endtrans%}

         {%trans%}How to use Hopsworks?{%endtrans%}

{%trans%}Hopsworks Adminstration Guide{%endtrans%}

         {%trans%}How to use hops admin panel?{%endtrans%}

{%trans%}licensing{%endtrans%}

         {%trans%}Hopsworks open-source license model{%endtrans%}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
%   Smooth field maps
function data = fm_smooth(data);

extension = data.extension;
echoes_to_use = data.echoes_to_use;
fnCurrentFieldmaps = data.fnCurrentFieldmaps;

number_of_fms_to_smooth = 1;

smooth_fieldmaps = 'no';
%   Check if anything needs to be done
for j = 1:number_of_fms_to_smooth
    fnCurrentFieldmapsS = {strrep(char(fnCurrentFieldmaps(j)), extension, ['_s' extension])};
    if exist(char(fnCurrentFieldmapsS(j)))~=2 || strcmp(data.do_all_remaing_processing_stages, 'yes')
        smooth_fieldmaps = 'yes';
        data.do_all_remaing_processing_stages = 'yes';
    end
end

switch smooth_fieldmaps
    case 'yes'
        smoothing_kernel = data.smoothing_kernel;
        unzip_command = data.unzip_command;
        nii_pixdim = data.nii_pixdim;
        switch ispc
            case 0 % linux
                maths_call_smooth = 'fslmaths';
            case 1 % windows
                maths_call_smooth = 'avwmaths++';
        end
        disp([' * - smoothing field map(s) using the smoothn function with a ' num2str(smoothing_kernel) ' voxel kernel']);
        for j = 1:number_of_fms_to_smooth
            %   using smoothn
            one_fieldmap_nii = load_nii(char(fnCurrentFieldmaps(j)));
            %   don't include zero's - turn these to NaN to omit
            one_fieldmap_NaN = one_fieldmap_nii.img;
            one_fieldmap_NaN(one_fieldmap_nii.img == 0) = NaN;
            one_fieldmap_nii.img = smoothn(one_fieldmap_NaN);
            %   turn back NaNs to 0s
            one_fieldmap_nii.img(isnan(one_fieldmap_nii.img)) = 0;
            centre_and_save_nii(one_fieldmap_nii, char(fnCurrentFieldmapsS(j)), nii_pixdim);
        end
    case 'no'
        disp([' - smoothed field map(s) found']);
end

data.fnCurrentFieldmaps = fnCurrentFieldmapsS;


text:
Augure is a tiny daemon script to look if your websites are down (not answering with http code 200) then send you a email.

### Installation:

Following instruction use a virtualenv, it's not a requirement.

```bash
git clone https://github.com/tristan-c/augure.git
cd augure
pyvenv venv
source venv/bin/activate
python setup.py install

```

Then you can use it like a daemon:

```bash
augure start
augure restart
augure stop
augure status
```

### Config file :
Augure will search for
* /etc/augure.conf
* /etc/augure/augure.conf
* ~/.augure/augure.conf

If there is no config file Augure will not be happy =(

```json
{
    "urls": ["http://first_url.com/",
        "http://second_url.com/",
        "http://thirs_url.com/"],
    "emailRecipient": "tristan@carranante.name",
    "emailServer": "smtp.googlemail.com",
    "emailLogin": "my_gmail_account@gmail.com",
    "emailPassword": "my_gmail_password",
    "logPath": "/var/log/augure.log"
}
```
**Required:**
* **urls**: URLs to look for.
* **emailRecipient**: Mail Address Recipient for alerts.

**Optional:**
* **emailServer**: Address of external SMTP server if your server doesn't have one.
* **emailLogin"**: Login for external SMTP.
* **emailPassword"**: Password for external SMTP.
* **logPath"**: Path for logfile , default to /tmp/augure.log.

## License:

The MIT License (MIT)


text:
using System.Threading;

using Android.App;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.OS;

using Compass.Common.IO.ShapeFile;
using Compass.Tessera.Core;
using Compass.Tessera.Core.Interface;
using Compass.Tessera.IO;

namespace SampleAndroidApplication
{
    /// <summary>
    /// An activity displaying a full screen map
    /// </summary>
    [Activity(Label = "SampleAndroidApplication", MainLauncher = true, Icon = "@drawable/icon")]
    public class MapActivity : Activity
    {
        private TileOverlayOptions tileOverlayOptions;
        private TileProvider tileProvider;
        // ReSharper disable once NotAccessedField.Local
        private TileOverlay tileOverlay;

        private MapFragment mapFragment;

        /// <inheritdoc />
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            mapFragment = FragmentManager.FindFragmentById<MapFragment>(Resource.Id.map);
            var basePath = Environment.ExternalStorageDirectory.AbsolutePath;

            TinyIoC.TinyIoCContainer.Current.Register<ICacheManager>(new CacheManager());
            var cacheManager = TinyIoC.TinyIoCContainer.Current.Resolve<CacheManager>();
            cacheManager.BasePath = basePath;
            TinyIoC.TinyIoCContainer.Current.Register<ITileSystem>(new TileSystem());
            TinyIoC.TinyIoCContainer.Current.Register<IRenderer>(new Renderer());
            TinyIoC.TinyIoCContainer.Current.Register<IShapeFileManager>(new ShapeFileManager());
            TinyIoC.TinyIoCContainer.Current.Register<TileGenerator>().AsSingleton();
            var tileGenerator = TinyIoC.TinyIoCContainer.Current.Resolve<TileGenerator>();

            while (mapFragment.Map == null)
            {
                Thread.Sleep(100);
            }

            var cameraUpdate = CameraUpdateFactory.NewLatLngZoom(new LatLng(53.297990, -6.179508), 15);
            mapFragment.Map.MoveCamera(cameraUpdate);

            tileGenerator.Setup(basePath, "roads.shp");

            tileOverlayOptions = new TileOverlayOptions();
            tileProvider = new TileProvider();
            tileOverlayOptions.Visible(true);
            tileOverlay = mapFragment.Map.AddTileOverlay(tileOverlayOptions.InvokeTileProvider(tileProvider));
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Text;

namespace Microsoft.Protocols.TestSuites.FileSharing.RSVD.TestSuite
{
    [TestClass]
    public class CreateAndDeleteCheckpoint : RSVDTestBase
    {
        #region Test Suite Initialization

        // Use ClassInitialize to run code before running the first test in the class
        [ClassInitialize()]
        public static void ClassInitialize(TestContext testContext)
        {
            TestClassBase.Initialize(testContext);
        }

        // Use ClassCleanup to run code after all tests in a class have run
        [ClassCleanup()]
        public static void ClassCleanup()
        {
            TestClassBase.Cleanup();
        }

        #endregion

        [TestMethod]
        [TestCategory(TestCategories.Bvt)]
        [TestCategory(TestCategories.RsvdVersion2)]
        [Description("Check if server supports handling tunnel operation to create and delete a VM checkpoint.")]
        public void BVT_Create_Delete_Checkpoint()
        {
            ulong requestId = 0;
            BaseTestSite.Log.Add(LogEntryKind.TestStep, "1.	Client opens a shared virtual disk file and expects success.");
            OpenSharedVHD(TestConfig.NameOfSharedVHDS, requestId++);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "2.	Client sends the first tunnel operation SVHDX_META_OPERATION_START_REQUEST to create a snapshot, with Stage1 set to Initialize and expects success.");
            SVHDX_META_OPERATION_START_REQUEST startRequest = new SVHDX_META_OPERATION_START_REQUEST();
            startRequest.TransactionId = System.Guid.NewGuid();
            startRequest.OperationType = Operation_Type.SvhdxMetaOperationTypeCreateSnapshot;
            startRequest.Padding = new byte[4];
            SVHDX_META_OPERATION_CREATE_SNAPSHOT createsnapshot = new SVHDX_META_OPERATION_CREATE_SNAPSHOT();
            createsnapshot.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM;
            createsnapshot.Flags = Snapshot_Flags.SVHDX_SNAPSHOT_DISK_FLAG_ENABLE_CHANGE_TRACKING;
            createsnapshot.Stage1 = Stage_Values.SvhdxSnapshotStageInitialize;
            createsnapshot.Stage2 = Stage_Values.SvhdxSnapshotStageInvalid;
            createsnapshot.Stage3 = Stage_Values.SvhdxSnapshotStageInvalid;
            createsnapshot.Stage4 = Stage_Values.SvhdxSnapshotStageInvalid;
            createsnapshot.Stage5 = Stage_Values.SvhdxSnapshotStageInvalid;
            createsnapshot.Stage6 = Stage_Values.SvhdxSnapshotStageInvalid;
            createsnapshot.SnapshotId = System.Guid.NewGuid();
            createsnapshot.ParametersPayloadSize = (uint)0x00000000;
            createsnapshot.Padding = new byte[24];
            byte[] payload = client.CreateTunnelMetaOperationStartCreateSnapshotRequest(
                startRequest,
                createsnapshot);
            SVHDX_TUNNEL_OPERATION_HEADER? header;
            SVHDX_TUNNEL_OPERATION_HEADER? response;
            //For RSVD_TUNNEL_META_OPERATION_START operation code, the IOCTL code should be FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST
            uint status = client.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>(
                true,//true for Async operation, false for non-async operation
                RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START,
                requestId,
                payload,
                out header,
                out response);
            BaseTestSite.Assert.AreEqual(
                (uint)Smb2Status.STATUS_SUCCESS,
                status,
                "Ioctl should succeed, actual status: {0}",
                GetStatus(status));
            VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, requestId++);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "3.	Client sends the second tunnel operation SVHDX_META_OPERATION_START_REQUEST to create a snapshot and expects success.");
            createsnapshot.Flags = Snapshot_Flags.SVHDX_SNAPSHOT_FLAG_ZERO;
            createsnapshot.Stage1 = Stage_Values.SvhdxSnapshotStageBlockIO;
            createsnapshot.Stage2 = Stage_Values.SvhdxSnapshotStageSwitchObjectStore;
            createsnapshot.Stage3 = Stage_Values.SvhdxSnapshotStageUnblockIO;
            createsnapshot.Stage4 = Stage_Values.SvhdxSnapshotStageFinalize;
            createsnapshot.Stage5 = Stage_Values.SvhdxSnapshotStageInvalid;
            createsnapshot.Stage6 = Stage_Values.SvhdxSnapshotStageInvalid;
            payload = client.CreateTunnelMetaOperationStartCreateSnapshotRequest(
                startRequest,
                createsnapshot);
            //For RSVD_TUNNEL_META_OPERATION_START operation code, the IOCTL code should be FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST
            status = client.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>(
                true,//true for Async operation, false for non-async operation
                RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START,
                requestId,
                payload,
                out header,
                out response);
            BaseTestSite.Assert.AreEqual(
                (uint)Smb2Status.STATUS_SUCCESS,
                status,
                "Ioctl should succeed, actual status: {0}",
                GetStatus(status));
            VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_META_OPERATION_START, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, requestId++);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "4. Verify the snapshot has been created after the operation.");
            DoUntilSucceed(
                () => CheckSnapshotExisted(ref requestId, client, createsnapshot.SnapshotId),
                TestConfig.Timeout,
                "Retry getting the snapshot to make sure it has been created until succeed within timeout span");

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "5.	Client sends the operation SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST to delete a snapshot and expects success.");
            SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST deleteRequest = new SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST();
            deleteRequest.SnapshotId = createsnapshot.SnapshotId;
            deleteRequest.PersistReference = PersistReference_Flags.PersistReferenceFalse;
            deleteRequest.SnapshotType = Snapshot_Type.SvhdxSnapshotTypeVM;
            payload = client.CreateTunnelMetaOperationDeleteSnapshotRequest(
                deleteRequest);
            SVHDX_TUNNEL_OPERATION_HEADER? deleteResponse;
            status = client.TunnelOperation<SVHDX_TUNNEL_OPERATION_HEADER>(
                false,//true for Async operation, false for non-async operation
                RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_DELETE_SNAPSHOT,
                requestId,
                payload,
                out header,
                out deleteResponse);
            BaseTestSite.Assert.AreEqual(
                (uint)Smb2Status.STATUS_SUCCESS,
                status,
                "Ioctl should succeed, actual status: {0}",
                GetStatus(status));

            VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_DELETE_SNAPSHOT, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, requestId++);

            BaseTestSite.Log.Add(LogEntryKind.TestStep, "6.	Client closes the file.");
            client.CloseSharedVirtualDisk();

        }

        private void CheckSnapshotExisted(ref ulong requestId, RsvdClient client, System.Guid snapshotId)
        {
            SetFile_InformationType setFileInforType = SetFile_InformationType.SvhdxSetFileInformationTypeSnapshotEntry;
            Snapshot_Type snapshotType = Snapshot_Type.SvhdxSnapshotTypeVM;
            SVHDX_TUNNEL_OPERATION_HEADER? header;
            SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_SNAPSHOT_ENTRY_RESPONSE? snapshotEntryResponse;
            byte[] payload = client.CreateTunnelGetVHDSetFileInfoRequest(
                setFileInforType,
                snapshotType,
                snapshotId);
            uint status = client.TunnelOperation<SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_SNAPSHOT_ENTRY_RESPONSE>(
                false,//true for Async operation, false for non-async operation
                RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_VHDSET_QUERY_INFORMATION,
                requestId,
                payload,
                out header,
                out snapshotEntryResponse);
            BaseTestSite.Assert.AreEqual(
                (uint)Smb2Status.STATUS_SUCCESS,
                status,
                "Ioctl should succeed, actual status: {0}",
                GetStatus(status));

            VerifyTunnelOperationHeader(header.Value, RSVD_TUNNEL_OPERATION_CODE.RSVD_TUNNEL_VHDSET_QUERY_INFORMATION, (uint)RsvdStatus.STATUS_SVHDX_SUCCESS, requestId++);
        }
    }
}


text:
package com.uwetrottmann.shopr.adapters.explanation;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;

import com.uwetrottmann.shopr.model.SectionItem;

public abstract class SlidingTabStripPagerAdapter extends FragmentPagerAdapter {
	private List<SectionItem> fragmentSections;
	private Fragment fragment;

	public SlidingTabStripPagerAdapter(Fragment fragment) {
		super(fragment.getChildFragmentManager());
		this.fragment = fragment;
		this.fragmentSections = createFragmentSections();
	}

	protected abstract List<SectionItem> createFragmentSections();

	public List<SectionItem> getFragmentSections() {
		return fragmentSections;
	}

	protected Fragment getFragment() {
		return fragment;
	}

	@Override
	public CharSequence getPageTitle(int position) {
		return fragmentSections.get(position).getTitle();
	}

	@Override
	public int getCount() {
		return fragmentSections.size();
	}

	@Override
	public Fragment getItem(int position) {
		return fragmentSections.get(position).getFragment();
	}
}


text:
K Nearest Neighbor (KNN) in pure JavaScript

From
http://burakkanber.com/blog/machine-learning-in-js-k-nearest-neighbor-part-1/

<canvas id="canvas" width=400 height=400></canvas>


text:
import sys
import time
from datetime import datetime
import random
import traceback
import config

# =========================================================================
#  Raspberry PI imports
# =========================================================================

enable_pi_emulator = False

try:
    # noinspection PyUnresolvedReferences
    import RPi.GPIO as GPIO
    # noinspection PyUnresolvedReferences
    import smbus
except ImportError:
    enable_pi_emulator = True

sys.path.append('./SDL_Pi_INA3221')
sys.path.append('./RTC_SDL_DS3231')
sys.path.append('./Adafruit_Python_BMP')
sys.path.append('./Adafruit_Python_GPIO')
sys.path.append('./SDL_Pi_WeatherRack')
sys.path.append('./SDL_Pi_TCA9545')

# noinspection PyUnresolvedReferences
import SDL_DS3231
# noinspection PyUnresolvedReferences
import Adafruit_BMP.BMP280 as BMP280
# noinspection PyUnresolvedReferences
import SDL_Pi_WeatherRack as SDL_Pi_WeatherRack

# =========================================================================
#    I2C ADDRESS/BITS
# =========================================================================
TCA9545_ADDRESS = 0x73  # 1110011 (A0+A1=VDD)
# =========================================================================

# =========================================================================
#    CONFIG REGISTER (R/W)
# =========================================================================
TCA9545_REG_CONFIG = 0x00
TCA9545_CONFIG_BUS0 = 0x01  # 1 = enable, 0 = disable
TCA9545_CONFIG_BUS1 = 0x02  # 1 = enable, 0 = disable
TCA9545_CONFIG_BUS2 = 0x04  # 1 = enable, 0 = disable
TCA9545_CONFIG_BUS3 = 0x08  # 1 = enable, 0 = disable

# =========================================================================

# =========================================================================
# Device Present State Variables
# indicate interrupt has happened from as3936
# =========================================================================

as3935_Interrupt_Happened = False

# =========================================================================
# set to true if you are building the solar powered version
# =========================================================================

config.SolarPower_Mode = False

config.DS3231_Present = False
config.BMP280_Present = False
config.AM2315_Present = False
config.ADS1015_Present = False
config.ADS1115_Present = False

# =========================================================================
# setup lightning i2c mux
# =========================================================================

def returnStatusLine(device, state):
    return_string = device
    if state:
        return_string += ":   \t\tPresent"
    else:
        assert isinstance(return_string, object)
        return_string += ":   \t\tNot Present"
    return return_string

# =========================================================================
# WeatherRack Weather Sensors
#
# GPIO Numbering Mode GPIO.BCM
# =========================================================================

anemometerPin = 21
rainPin = 20

# =========================================================================
# internally, the library checks for ADS1115 or ADS1015 if found
# =========================================================================

SDL_MODE_INTERNAL_AD = 0
SDL_MODE_I2C_ADS1015 = 1

# =========================================================================
# sample mode means return immediately.  THe wind speed is averaged at sampleTime or when you ask, whichever is longer
# =========================================================================
SDL_MODE_SAMPLE = 0

# =========================================================================
# Delay mode means to wait for sampleTime and the average after that time.
# =========================================================================
SDL_MODE_DELAY = 1

weatherStation = SDL_Pi_WeatherRack.SDL_Pi_WeatherRack(anemometerPin, rainPin, SDL_MODE_I2C_ADS1015)

weatherStation.setWindMode(SDL_MODE_SAMPLE, 5.0)
# weatherStation.setWindMode(SDL_MODE_DELAY, 5.0)

# =========================================================================
# DS3231/AT24C32 Setup
# =========================================================================
filename = time.strftime("%Y-%m-%d%H:%M:%SRTCTest") + ".txt"
start_time = datetime.utcnow()

ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)

try:
    # =========================================================================
    # comment out the next line after the clock has been initialized
    # =========================================================================
    ds3231.write_now()
    print "DS3231=\t\t%s" % ds3231.read_datetime()
    config.DS3231_Present = True
    print "----------------- "
    print " AT24C32 EEPROM"
    print "----------------- "
    print "writing first 4 addresses with random data"
    for x in range(0, 4):
        value = random.randint(0, 255)
        print "address = %i writing value=%i" % (x, value)
        ds3231.write_AT24C32_byte(x, value)
    print "----------------- "

    print "reading first 4 addresses"
    for x in range(0, 4):
        print "address = %i value = %i" % (x, ds3231.read_AT24C32_byte(x))
    print "----------------- "

except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
    config.DS3231_Present = False

# =========================================================================
# BMP280 Setup
# =========================================================================

try:
    bmp280 = BMP280.BMP280()
    config.BMP280_Present = True

except IOError as e:
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
    config.BMP280_Present = False

def output_config():
    print "----------------------"
    print returnStatusLine("DS3231", config.DS3231_Present)
    print returnStatusLine("BMP280", config.BMP280_Present)
    print returnStatusLine("AM2315", config.AM2315_Present)
    print returnStatusLine("ADS1015", config.ADS1015_Present)
    print returnStatusLine("ADS1115", config.ADS1115_Present)
    print returnStatusLine("DS3231", config.DS3231_Present)
    print "----------------------"

def check_weather_health():
    output_config()
    return config.DS3231_Present and config.BMP280_Present and config.ADS1115_Present

def get_weather_data():
    response = {}

    try:
        # =========================================================================
        # Detect AM2315
        # =========================================================================
        try:
            # noinspection PyUnresolvedReferences,PyPackageRequirements
            from tentacle_pi.AM2315 import AM2315
            try:
                am2315 = AM2315(0x5c, "/dev/i2c-1")
                temperature, humidity, crc_check = am2315.sense()
                config.AM2315_Present = True
                if crc_check == -1:
                    config.AM2315_Present = False
            except:
                config.AM2315_Present = False
        except:
            config.AM2315_Present = False
            print "------> See Readme to install tentacle_pi"

        if config.DS3231_Present:
            response['DS3231'] = {'raspberry_pi': time.strftime("%Y-%m-%d %H:%M:%S"),
                                  'time': "%s" % ds3231.read_datetime(),
                                  'temperature': ds3231.getTemp()}

        if config.AM2315_Present:
            # noinspection PyUnboundLocalVariable
            temperature, humidity, crc_check = am2315.sense()
            response['AM2315'] = {'temperature': "%0.1f" % temperature,
                                  'humidity': "%0.1f" % humidity,
                                  'crc': "%s" % crc_check}

        currentWindSpeed = weatherStation.current_wind_speed()
        currentWindGust = weatherStation.get_wind_gust()
        totalRain = weatherStation.get_current_rain_total()

        if config.ADS1015_Present or config.ADS1115_Present:
            response['ADS1015'] = {'wind_direction': "%0.2f" % weatherStation.current_wind_direction(),
                                   'wind_voltage': "%0.3f" % weatherStation.current_wind_direction_voltage()}

        response['weather_rack'] = {'rain_total': "%0.2f" % totalRain,
                                    'wind_speed': "%0.2f" % currentWindSpeed,
                                    'wind_gust': "%0.2f" % currentWindGust}

        if config.BMP280_Present:
            response['BMP280'] = {'temperature': '{0:0.2f}'.format(bmp280.read_temperature()),
                                  'pressure': '{0:0.2f}'.format(bmp280.read_pressure() / 1000),
                                  'altitude': '{0:0.2f}'.format(bmp280.read_altitude()),
                                  'sea_level_pressure': '{0:0.2f}'.format(bmp280.read_sealevel_pressure() / 1000)}
    except Exception as error:
        traceback.print_exc()
        print error.message

    return response

if __name__ == '__main__':
    while True:
        print get_weather_data()
        print "Sleeping 10 seconds..."
        time.sleep(10.0)


text:
import pecan
from oslo_log import log as logging

from designate import exceptions
from designate import policy
from designate import utils
from designate.api.v2.controllers import rest
from designate.objects.adapters.api_v2.zone_export \
    import ZoneExportAPIv2Adapter

LOG = logging.getLogger(__name__)

class ZoneExportController(rest.RestController):

    @pecan.expose(template=None, content_type='text/dns')
    @utils.validate_uuid('export_id')
    def get_all(self, export_id):
        context = pecan.request.environ['context']
        policy.check('zone_export', context)

        export = self.central_api.get_zone_export(context, export_id)

        if export.location and export.location.startswith('designate://'):
            return self.zone_manager_api.\
                render_zone(context, export['domain_id'])
        else:
            msg = 'Zone can not be exported synchronously'
            raise exceptions.BadRequest(msg)

class ZoneExportCreateController(rest.RestController):

    @pecan.expose(template='json:', content_type='application/json')
    @utils.validate_uuid('zone_id')
    def post_all(self, zone_id):
        """Create Zone Export"""
        request = pecan.request
        response = pecan.response
        context = request.environ['context']

        # Create the zone_export
        zone_export = self.central_api.create_zone_export(
            context, zone_id)
        response.status_int = 202

        zone_export = ZoneExportAPIv2Adapter.render(
            'API_v2', zone_export, request=request)

        response.headers['Location'] = zone_export['links']['self']
        return zone_export

class ZoneExportsController(rest.RestController):

    SORT_KEYS = ['created_at', 'id', 'updated_at']

    export = ZoneExportController()

    @pecan.expose(template='json:', content_type='application/json')
    @utils.validate_uuid('export_id')
    def get_one(self, export_id):
        """Get Zone Exports"""

        request = pecan.request
        context = request.environ['context']

        return ZoneExportAPIv2Adapter.render(
            'API_v2',
            self.central_api.get_zone_export(
                context, export_id),
            request=request)

    @pecan.expose(template='json:', content_type='application/json')
    def get_all(self, **params):
        """List Zone Exports"""
        request = pecan.request
        context = request.environ['context']
        marker, limit, sort_key, sort_dir = utils.get_paging_params(
            params, self.SORT_KEYS)

        # Extract any filter params.
        accepted_filters = ('status', 'message', 'zone_id', )

        criterion = self._apply_filter_params(
            params, accepted_filters, {})

        return ZoneExportAPIv2Adapter.render(
            'API_v2',
            self.central_api.find_zone_exports(
                context, criterion, marker, limit, sort_key, sort_dir),
            request=request)

    @pecan.expose(template='json:', content_type='application/json')
    @utils.validate_uuid('zone_export_id')
    def delete_one(self, zone_export_id):
        """Delete Zone Export"""
        request = pecan.request
        response = pecan.response
        context = request.environ['context']

        self.central_api.delete_zone_export(context, zone_export_id)
        response.status_int = 204

        return ''


text:
..
 This work is licensed under a Creative Commons Attribution 3.0 Unported
 License.

 http://creativecommons.org/licenses/by/3.0/legalcode

============================================================
Differentiate thick and thin provisioning logic in scheduler
============================================================

Include the URL of your launchpad blueprint:

https://blueprints.launchpad.net/cinder/+spec/differentiate-thick-thin-in-scheduler

Currently in the capacity filter and weigher of the scheduler, we use the
logic to evaluate whether there is enough capacity to thin provision a volume
on a backend if the driver reports `thin_provisioning_support` to be True.
However, a driver may be able to support both thin and non-thin provisioning.
The logic does not check whether the user wants the volume to be provisioned
as thin or not. This blueprint proposes to fix the problem by checking
`thick_provisioning_support` in extra specs of the volume type.

Problem description
===================

If a driver reports both `thin_provisioning_support` to True and
`thick_provisioning_support` to True for a pool that can support both thin and
thick luns, and the user wants to create a thick lun, the logic in the
scheduler would wrongly use the logic for thin provisioning to make decisions.
It would make decisions based on `provisioned_capacity_gb` and
`max_over_subscription_ratio`. This could potentially lead to over
provisioning.

In this spec, we are trying to address this problem by checking whether the
new volume is thin or thick and then use logic accordingly to make decisions.

Use Cases
=========

Currently a driver can report both `thin_provisioning_support` to True
and `thick_provisioning_support` to True if it has a pool that can
support both thin and thick. However the logic in the scheduler
checks capacity for thin provisioning if the driver reports
`thin_provisioning_support` to True even if the volume type specifies
the volume to be thick. The proposed spec wants to fix this problem.

Proposed change
===============

The spec proposes to make the following change in the logic in the capacity
filter and the capacity weigher.

The volume type of the volume to be provisioned will be checked. If
`provisioning_type` is set to `thick` in the extra specs of
the volume type, it will use the thick provisioning logic to evaluate.
Note that this only affects the logic if the driver reports both
`thin_provisioning_support` and `thick_provisioning_support` to True.

Otherwise, the logic remains the same as before.

Alternatives
------------

None.

Data model impact
-----------------

None.

REST API impact
---------------

None.

Security impact
---------------

None.

Notifications impact
--------------------

None.

Other end user impact
---------------------

None.

Performance Impact
------------------

None.

Other deployer impact
---------------------

When the admin sets up volume types, he/she needs to set
the following in the extra specs for a thick volume type::

{'thick_provisioning_support': <is> True>} or
{'capabilities:thick_provisioning_support': <is> True>}

Developer impact
----------------

Driver developer should be aware of this extra spec
and handle it accordingly in volume creation.

Implementation
==============

Assignee(s)
-----------

Primary assignee:
  <xing-yang>

Other contributors:
  <launchpad-id or None>

Work Items
----------

1. Modify capacity filter to check `thick_provisioning_support`.
2. Modify capacity weigher to check `thick_provisioning_support`.

Dependencies
============

None.

Testing
=======

Unit tests will be added for this change.

Documentation Impact
====================

Documentation needs to be changed to include this information.

References
==========

A patch is proposed in Manila to solve a similar problem:
    https://review.openstack.org/#/c/315266/

Note that capabilities reporting for thin and thick provisioning
in Manila is different from that in Cinder. In Manila, a driver reports
`thin_provisioning = [True, False]` if it supports both thin and thick;
In Cinder, a driver reports `thin_provisioning_support = True` and
`thick_provisioning_support = True` if it supports both thin and thick.
Therefore the proposal in this spec is different from the solution in
the Manila patch.


text:
require 'spec_helper'

describe "Teams" do
  describe "GET /teams" do
    it "works! (now write some real specs)" do
      # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
      get teams_path
      response.status.should be(200)
    end
  end
end


text:
namespace net {

class BidirectionalStreamJob;
class ClientSocketHandle;
class HttpStream;
class SpdySession;

class HttpStreamFactoryImpl::Request : public HttpStreamRequest {
 public:
  // Indicates which type of stream is requested.
  enum StreamType {
    BIDIRECTIONAL_STREAM_SPDY_JOB,
    HTTP_STREAM,
  };

  Request(const GURL& url,
          HttpStreamFactoryImpl* factory,
          HttpStreamRequest::Delegate* delegate,
          WebSocketHandshakeStreamBase::CreateHelper*
              websocket_handshake_stream_create_helper,
          const BoundNetLog& net_log,
          StreamType stream_type);

  ~Request() override;

  // The GURL from the HttpRequestInfo the started the Request.
  const GURL& url() const { return url_; }

  const BoundNetLog& net_log() const { return net_log_; }

  // Called when the Job determines the appropriate |spdy_session_key| for the
  // Request. Note that this does not mean that SPDY is necessarily supported
  // for this SpdySessionKey, since we may need to wait for NPN to complete
  // before knowing if SPDY is available.
  void SetSpdySessionKey(const SpdySessionKey& spdy_session_key);
  bool HasSpdySessionKey() const;

  // Attaches |job| to this request. Does not mean that Request will use |job|,
  // but Request will own |job|.
  void AttachJob(HttpStreamFactoryImpl::Job* job);

  // Marks completion of the request. Must be called before OnStreamReady().
  void Complete(bool was_npn_negotiated,
                NextProto protocol_negotiated,
                bool using_spdy);

  // If this Request has a |spdy_session_key_|, remove this session from the
  // SpdySessionRequestMap.
  void RemoveRequestFromSpdySessionRequestMap();

  // Called by an attached Job if it sets up a SpdySession.
  // |stream| is null when |for_bidirectional| is true.
  // |bidirectional_stream_spdy_job| is null when |for_bidirectional| is false.
  void OnNewSpdySessionReady(
      Job* job,
      scoped_ptr<HttpStream> stream,
#if BUILDFLAG(ENABLE_BIDIRECTIONAL_STREAM)
      scoped_ptr<BidirectionalStreamJob> bidirectional_stream_spdy_job,
#else
      void* unused,
#endif
      const base::WeakPtr<SpdySession>& spdy_session,
      bool direct);

  // Called by an attached Job to record connection attempts made by the socket
  // layer for this stream request.
  void AddConnectionAttempts(const ConnectionAttempts& attempts);

  WebSocketHandshakeStreamBase::CreateHelper*
  websocket_handshake_stream_create_helper() {
    return websocket_handshake_stream_create_helper_;
  }

  // HttpStreamRequest::Delegate methods which we implement. Note we don't
  // actually subclass HttpStreamRequest::Delegate.

  void OnStreamReady(Job* job,
                     const SSLConfig& used_ssl_config,
                     const ProxyInfo& used_proxy_info,
                     HttpStream* stream);
  void OnBidirectionalStreamJobReady(Job* job,
                                     const SSLConfig& used_ssl_config,
                                     const ProxyInfo& used_proxy_info,
                                     BidirectionalStreamJob* stream);

  void OnWebSocketHandshakeStreamReady(Job* job,
                                       const SSLConfig& used_ssl_config,
                                       const ProxyInfo& used_proxy_info,
                                       WebSocketHandshakeStreamBase* stream);
  void OnStreamFailed(Job* job,
                      int status,
                      const SSLConfig& used_ssl_config,
                      SSLFailureState ssl_failure_state);
  void OnCertificateError(Job* job,
                          int status,
                          const SSLConfig& used_ssl_config,
                          const SSLInfo& ssl_info);
  void OnNeedsProxyAuth(Job* job,
                        const HttpResponseInfo& proxy_response,
                        const SSLConfig& used_ssl_config,
                        const ProxyInfo& used_proxy_info,
                        HttpAuthController* auth_controller);
  void OnNeedsClientAuth(Job* job,
                         const SSLConfig& used_ssl_config,
                         SSLCertRequestInfo* cert_info);
  void OnHttpsProxyTunnelResponse(
      Job *job,
      const HttpResponseInfo& response_info,
      const SSLConfig& used_ssl_config,
      const ProxyInfo& used_proxy_info,
      HttpStream* stream);

  // HttpStreamRequest methods.

  int RestartTunnelWithProxyAuth(const AuthCredentials& credentials) override;
  void SetPriority(RequestPriority priority) override;
  LoadState GetLoadState() const override;
  bool was_npn_negotiated() const override;
  NextProto protocol_negotiated() const override;
  bool using_spdy() const override;
  const ConnectionAttempts& connection_attempts() const override;
  bool for_bidirectional() const { return for_bidirectional_; }

 private:
  // Used to bind |job| to the request and orphan all other jobs in |jobs_|.
  void BindJob(Job* job);

  // Used to orphan all jobs in |jobs_|.
  void OrphanJobs();

  // Used to cancel all jobs in |jobs_|.
  void CancelJobs();

  // Called when a Job succeeds.
  void OnJobSucceeded(Job* job);

  const GURL url_;
  HttpStreamFactoryImpl* const factory_;
  WebSocketHandshakeStreamBase::CreateHelper* const
      websocket_handshake_stream_create_helper_;
  HttpStreamRequest::Delegate* const delegate_;
  const BoundNetLog net_log_;

  // At the point where Job is irrevocably tied to the Request, we set this.
  scoped_ptr<Job> bound_job_;
  std::set<HttpStreamFactoryImpl::Job*> jobs_;
  scoped_ptr<const SpdySessionKey> spdy_session_key_;

  bool completed_;
  bool was_npn_negotiated_;
  // Protocol negotiated with the server.
  NextProto protocol_negotiated_;
  bool using_spdy_;
  ConnectionAttempts connection_attempts_;

  const bool for_bidirectional_;
  DISALLOW_COPY_AND_ASSIGN(Request);
};

}  // namespace net

#endif  // NET_HTTP_HTTP_STREAM_FACTORY_IMPL_REQUEST_H_


text:
ToL Learner Level:

Target Grade/Age Level:

.

Can be modified for many age/grade levels

Learning Objective(s). Learners will:

Type of Activity

         0">

Science Subject / Key Words

 State Education Standards: (view standards):

National Education Standards (view standards):

Suggested Time Frame

Sequence and Context

Additional Treehouse Type:

Curricular Areas:

         0">

Language:

         0">

Teaching and Learning Strategy:

         0">

Grouping:

Comments


text:
var express = require('express');
var router = express.Router();

var log = require('bristol');

var Project = require('../model/Schema').project;

router.get('/projects', function (req, res) {
    Project.find({}, function (err, data) {
        if (err) {
            log.error(err);
        }

        res.render('project/project_list', {project: data});
    });
});

router.get('/project/new', function (req, res) {
    res.render('project/new_project', {isNew: true});
});

router.post('/project/new', function (req, res) {
    req.assert('title', 'Title may not be empty').notEmpty();
    req.assert('owner', 'Owner may not be empty').notEmpty();

    var err = req.validationErrors();

    if (err) {
        req.flash('errors', err);
        return res.redirect('/project/new');
    }
    // TODO: make use of the owner id
    var project = new Project({startDate     : req.body.start,
                                  endDate    : req.body.end,
                                  title      : req.body.title,
                                  description: req.body.description});
    project.save(function (err) {
        if (err) {
            log.error(err);
            req.flash('errors', err);
            return res.redirect('/project/new');
        }
        res.redirect('/projects');
    });
});

router.get('/project/:id/delete', function (req, res) {
    Project.where().findOneAndRemove({ '_id': req.params.id}, function (err) {
        if (err) {
            log.error(err);
            req.flash('error', {msg: 'Project not found.'});
            return res.redirect('/projects');
        }

        req.flash('info', {msg: 'Project deleted'});
        res.redirect('/projects');
    })
});

router.get('/project/:id/finish', function (req, res) {
    Project.findByIdAndUpdate(req.params.id, {'finished': true}, function (err, data) {
        if (err) {
            log.error(err);
            req.flash(err, {msg: 'Project not found'});
            return res.redirect('/projects');
        }

        req.flash('success', {msg: 'Project ' + data._doc.title + 'is now finished'});
        res.redirect('/projects');
    });
});

router.get('/project/:id/reopen', function (req, res) {
    Project.findByIdAndUpdate(req.params.id, {'finished': false, 'canceled': false}, function (err, data) {
        if (err) {
            log.error(err);
            req.flash(err, {msg: 'Project not found'});
            return res.redirect('/projects');
        }

        req.flash('success', {msg: 'Project ' + data.title + 'is now open'});
        res.redirect('/projects');
    });
});

router.get('/project/:id/cancel', function (req, res) {
    Project.findByIdAndUpdate(req.params.id, {'cancel': true}, function (err, data) {
        if (err) {
            log.error(err);
            req.flash(err, {msg: 'Project not found'});
            return res.redirect('/projects');
        }

        req.flash('success', {msg: 'Project ' + data._doc.title + ' is now canceled'});
        res.redirect('/projects');
    });
});

router.get('/project/:id/edit', function (req, res) {
    Project.findById(req.params.id, function (err, data) {
        if (err) {
            log.error(err);
            req.flash('error', {msg: 'An error occurred. Please try again'});
            return res.redirect('/projects');
        }

        if (!data) {
            log.error(err);
            req.flash('info', {msg: 'Project not found.'});
            return res.redirect('/projects');
        }

        res.render('project/edit_project', {'data': data});
    });
});

router.post('/project/:id/edit', function (req, res) {
    var updatedProject = {startDate: req.body.start,
        endDate                    : req.body.end,
        title                      : req.body.title,
        description                : req.body.description};

    Project.findOneAndUpdate({'_id': req.params.id}, updatedProject, function (err, data) {
        if (err) {
            log.error(err);
            req.flash('error', 'An error occurred. Please try again.');
            return res.redirect('/project/' + req.params.id + '/edit');
        }
        req.flash('info', {msg: 'Project ' + data.title + ' updated'});
        res.redirect('/projects');
    });
});

module.exports = router;


text:
<?php
namespace Golem\Auth;

use Golem\Auth\Storage\StorageInterface;

class Auth implements AuthInterface
{
    /**
     * @var StorageInterface
     */
    protected $storage;

    /**
     * @var string|int|null
     */
    protected $id;

    /**
     * @var Authenticatable|null
     */
    protected $user;

    /**
     * @var UserRepository
     */
    protected $repository;

    /**
     * Auth constructor.
     * @param StorageInterface $storage
     * @param UserRepository $repository
     */
    public function __construct(StorageInterface $storage, UserRepository $repository)
    {
        $this->storage = $storage;
        $this->repository = $repository;
    }

    /**
     * @return bool
     */
    public function loggedIn()
    {
        if ($this->id === null) {
            $this->id = -1;
            if ($this->storage->exists()) {
                $this->id = $this->storage->read();
            }
        }
        return $this->id != -1;
    }

    /**
     * @return Authenticatable|null
     * @throws \RuntimeException
     */
    public function user()
    {
        if ($this->user === null && $this->loggedIn()) {
            $this->user = $this->repository->findUserById($this->id);
        }
        return $this->user;
    }

    /**
     * @return int|string|null
     */
    public function getUserId()
    {
        if (!$this->loggedIn()) {
            return null;
        }
        return $this->id;
    }

    /**
     * @param Authenticatable $user
     */
    public function login(Authenticatable $user)
    {
        $this->storage->store($user->getAuthId());
        $this->user = $user;
        $this->id = $user->getAuthId();
    }

    /**
     * Logs out user
     */
    public function logout()
    {
        $this->storage->clear();
        $this->user = null;
        $this->id = -1;
    }
}


text:
exports.requires = ['navigation', 'articles'];

exports.run = function(view, context){

    // use the list of unique tags generated in the naviagtion view
    context.partials.tags.forEach(function(tag){

        // get the articles with the tag
        var articles = context.data.filter(function(d){
            return d.tags.some(function(t){return t === tag;});
        });

        // render the tag template
        var html = context.templates['tag.jsont'].expand({
            name: tag,
            articles: articles,
            partials: context.partials
        });

        view.emit(tag + '.html', html);

    });

};


text:
package nl.ctrlaltdev.json.transform.select;

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

import nl.ctrlaltdev.json.transform.select.jsonpath.AnyNodesSelector;
import nl.ctrlaltdev.json.transform.select.jsonpath.BasicJsonPathSelector;
import nl.ctrlaltdev.json.transform.select.jsonpath.JsonPathTokenizer;
import nl.ctrlaltdev.json.transform.select.jsonpath.NameType;
import nl.ctrlaltdev.json.transform.select.jsonpath.SliceJsonPathSelector;
import nl.ctrlaltdev.json.transform.select.jsonpath.SubselectSelector;
import nl.ctrlaltdev.json.transform.select.jsonpath.ValueType;
import nl.ctrlaltdev.json.transform.select.jsonpath.JsonPathTokenizer.JsonPathToken;
import nl.ctrlaltdev.json.transform.select.selector.AndSelector;
import nl.ctrlaltdev.json.transform.select.selector.AnyArraySelector;
import nl.ctrlaltdev.json.transform.select.selector.AnyObjectSelector;
import nl.ctrlaltdev.json.transform.select.selector.AnyValueOfTypeSelector;
import nl.ctrlaltdev.json.transform.select.selector.AnyValueSelector;
import nl.ctrlaltdev.json.transform.select.selector.ExorSelector;
import nl.ctrlaltdev.json.transform.select.selector.IndexSelector;
import nl.ctrlaltdev.json.transform.select.selector.NotSelector;
import nl.ctrlaltdev.json.transform.select.selector.ObjectPropertyMatchSelector;
import nl.ctrlaltdev.json.transform.select.selector.ObjectPropertySelector;
import nl.ctrlaltdev.json.transform.select.selector.ObjectPropertyValueSelector;
import nl.ctrlaltdev.json.transform.select.selector.OrSelector;
import nl.ctrlaltdev.json.transform.select.selector.PropertyMatchSelector;
import nl.ctrlaltdev.json.transform.select.selector.PropertySelector;
import nl.ctrlaltdev.json.transform.select.selector.PropertyValueSelector;
import nl.ctrlaltdev.json.transform.select.selector.RootSelector;
import nl.ctrlaltdev.json.transform.select.selector.Selector;
import nl.ctrlaltdev.json.transform.select.selector.WildcardSelector;

public class SelectBuilder {

    public static SelectBuilder select() {
        return new SelectBuilder();
    }

    public static Select selectRoot() {
        return select().root().build();
    }

    private final List<Selector> selectors = new ArrayList<Selector>();
    private boolean one = false;

    protected SelectBuilder() {
    }

    public SelectBuilder one() {
        one = true;
        return this;
    }

    public SelectBuilder any() {
        selectors.add(new WildcardSelector());
        return this;
    }

    public SelectBuilder anyArray() {
        selectors.add(new AnyArraySelector());
        return this;
    }

    public SelectBuilder anyObject() {
        selectors.add(new AnyObjectSelector());
        return this;
    }

    public SelectBuilder anyValue() {
        selectors.add(new AnyValueSelector());
        return this;
    }

    public SelectBuilder anyValueOfType(Class<?> type) {
        selectors.add(new AnyValueOfTypeSelector(type));
        return this;
    }

    public SelectBuilder property(String property) {
        selectors.add(new PropertySelector(property));
        return this;
    }

    public SelectBuilder propertyMatch(String regex) {
        selectors.add(new PropertyMatchSelector(regex));
        return this;
    }

    public SelectBuilder propertyValue(String property, Object value) {
        selectors.add(new PropertyValueSelector(property, value));
        return this;
    }

    public SelectBuilder objectProperty(String property) {
        selectors.add(new ObjectPropertySelector(property));
        return this;
    }

    public SelectBuilder objectPropertyMatch(String regex) {
        selectors.add(new ObjectPropertyMatchSelector(regex));
        return this;
    }

    public SelectBuilder objectPropertyValue(String property, String value) {
        selectors.add(new ObjectPropertyValueSelector(property, value));
        return this;
    }

    public SelectBuilder index(int index) {
        selectors.add(new IndexSelector(index));
        return this;
    }

    public SelectBuilder and(SelectBuilder builder) {
        selectors.add(new AndSelector(builder.buildComposite()));
        return this;
    }

    public SelectBuilder or(SelectBuilder builder) {
        selectors.add(new OrSelector(builder.buildComposite()));
        return this;
    }

    public SelectBuilder exor(SelectBuilder builder) {
        selectors.add(new ExorSelector(builder.buildComposite()));
        return this;
    }

    public SelectBuilder custom(Selector selector) {
        selectors.add(selector);
        return this;
    }

    public SelectBuilder not(Selector selector) {
        selectors.add(new NotSelector(selector));
        return this;
    }

    public SelectBuilder root() {
        selectors.add(new RootSelector());
        return this;
    }

    public SelectBuilder jsonPath(NameType nameType, Object arg, ValueType valueType) {
        selectors.add(new BasicJsonPathSelector(nameType, arg, valueType));
        return this;
    }

    public SelectBuilder anyNodes() {
        selectors.add(new AnyNodesSelector());
        return this;
    }

    public SelectBuilder expression(Select subselect) {
        selectors.add(new SubselectSelector(subselect));
        return this;
    }

    private void slice(List<Integer> argument) {
        selectors.add(new SliceJsonPathSelector(argument.toArray(new Integer[argument.size()])));
    }

    public Select build() {
        return one ? new SingleResultSelectorChain(buildComposite()) : new SelectorChain(buildComposite());
    }

    private Selector[] buildComposite() {
        return selectors.toArray(new Selector[selectors.size()]);
    }

    public static Select fromJsonPath(String str) {
        return buildJsonPath(JsonPathTokenizer.tokenize(str));
    }

    @SuppressWarnings("unchecked")
    private static Select buildJsonPath(List<JsonPathToken> tokenize) {
        SelectBuilder builder = select();
        for (JsonPathToken t : tokenize) {
            switch (t.getNameType()) {
            case EXPRESSION:
                builder.expression(buildJsonPath((List<JsonPathToken>) t.getArgument()));
                break;
            case SLICE:
                builder.slice((List<Integer>) t.getArgument());
                break;
            case NESTED_NODES:
                builder.anyNodes();
                break;
            default:
                builder.jsonPath(t.getNameType(), t.getArgument(), t.getValueType());
                break;
            }
        }
        return builder.build();
    }

}


text:
Suitcase
========

This is the open source code of the iOS app [**Suitcase**][appstore]
([@suitcaseapp][twitter]). It contains the full code of formerly released app
versions (up until 2.3.0).

## Notice

The code is provided as-is and may require additional changes to be able to
build on current versions of Xcode and the iOS SDK.

## Contributions

As this code is more or less outdated, I won't accept pull requests or issue
reports targeting the 1.x/2.x versions of the app.

Please report any bugs or feature request of the current version in the
[issue tracker of this project][issues].

## License

This code is free software; you can redistribute it and/or modify it under the
terms of the new BSD License. A copy of this license can be found in the
included LICENSE file.

## Credits

Suitcase was created by Sebastian Staudt

 [appstore]: https://itunes.apple.com/app/suitcase/id539259008
 [issues]: https://github.com/koraktor/suitcase/issues
 [twitter]: https://twitter.com/suitcaseapp


text:
class CategoryEtymologyAssociation < ActiveRecord::Base
  belongs_to :category
  belongs_to :etymology
end


text:
package net.imagej.updater.util;

import java.io.File;

/**
 * Represents a file to be downloaded from an update site.
 *
 * @author Johannes Schindelin
 */
public interface Downloadable {

	public File getDestination();

	public String getURL();

	public long getFilesize();
}


text:
import * as React from 'react';
import { SxProps } from '@mui/system';
import { Theme } from '../styles';
import { ExtendButtonBase } from '../ButtonBase';
import { OverridableComponent, OverrideProps } from '../OverridableComponent';
import { ListItemClasses } from './listItemClasses';

export interface ListItemComponentsPropsOverrides {}

export interface ListItemBaseProps {
  /**
   * Defines the `align-items` style property.
   * @default 'center'
   */
  alignItems?: 'flex-start' | 'center';
  /**
   * If `true`, the list item is focused during the first mount.
   * Focus will also be triggered if the value changes from false to true.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  autoFocus?: boolean;
  /**
   * The content of the component if a `ListItemSecondaryAction` is used it must
   * be the last child.
   */
  children?: React.ReactNode;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<ListItemClasses>;
  /**
   * The container component used when a `ListItemSecondaryAction` is the last child.
   * @default 'li'
   * @deprecated
   */
  ContainerComponent?: React.ElementType<React.HTMLAttributes<HTMLDivElement>>;
  /**
   * Props applied to the container component if used.
   * @default {}
   * @deprecated
   */
  ContainerProps?: React.HTMLAttributes<HTMLDivElement>;
  /**
   * If `true`, compact vertical padding designed for keyboard and mouse input is used.
   * The prop defaults to the value inherited from the parent List component.
   * @default false
   */
  dense?: boolean;
  /**
   * If `true`, the component is disabled.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  disabled?: boolean;
  /**
   * If `true`, the left and right padding is removed.
   * @default false
   */
  disableGutters?: boolean;
  /**
   * If `true`, all padding is removed.
   * @default false
   */
  disablePadding?: boolean;
  /**
   * If `true`, a 1px light border is added to the bottom of the list item.
   * @default false
   */
  divider?: boolean;
  /**
   * The element to display at the end of ListItem.
   */
  secondaryAction?: React.ReactNode;
  /**
   * Use to apply selected styling.
   * @default false
   * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
   */
  selected?: boolean;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme>;
}

export interface ListItemTypeMap<P, D extends React.ElementType> {
  props: P &
    ListItemBaseProps & {
      /**
       * The components used for each slot inside the InputBase.
       * Either a string to use a HTML element or a component.
       * @default {}
       */
      components?: {
        Root?: React.ElementType;
      };
      /**
       * The props used for each slot inside the Input.
       * @default {}
       */
      componentsProps?: {
        root?: React.HTMLAttributes<HTMLDivElement> & ListItemComponentsPropsOverrides;
      };
    };
  defaultComponent: D;
}

/**
 * Uses an additional container component if `ListItemSecondaryAction` is the last child.
 *
 * Demos:
 *
 * - [Lists](https://mui.com/material-ui/react-list/)
 * - [Transfer list](https://mui.com/material-ui/react-transfer-list/)
 *
 * API:
 *
 * - [ListItem API](https://mui.com/material-ui/api/list-item/)
 */
declare const ListItem: ExtendButtonBase<
  ListItemTypeMap<
    {
      /**
       * If `true`, the list item is a button (using `ButtonBase`). Props intended
       * for `ButtonBase` can then be applied to `ListItem`.
       * @default false
       * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
       *
       */
      button: true;
    },
    'div'
  >
> &
  OverridableComponent<
    ListItemTypeMap<
      {
        /**
         * If `true`, the list item is a button (using `ButtonBase`). Props intended
         * for `ButtonBase` can then be applied to `ListItem`.
         * @default false
         * @deprecated checkout [ListItemButton](/material-ui/api/list-item-button/) instead
         */
        button?: false;
      },
      'li'
    >
  >;

export type ListItemProps<D extends React.ElementType = 'li', P = {}> = OverrideProps<
  ListItemTypeMap<P, D>,
  D
>;

export default ListItem;


text:
<?php

/**
 * Main extension helper
 *
 * @category    Easylife
 * @package     Easylife_Relations
 * @author      Marius Strajeru <marius.strajeru@gmail.com>
 */
class Easylife_Relations_Helper_Data extends Mage_Core_Helper_Abstract {

}


text:
import { AxiosRequestHeaders } from 'axios'
import type { AxiosInstance } from 'contentful-sdk-core'
import { errorHandler } from 'contentful-sdk-core'
import copy from 'fast-copy'
import { SetOptional } from 'type-fest'
import { CollectionProp, GetSpaceEnvironmentParams, QueryParams } from '../../../common-types'
import {
  AssetFileProp,
  AssetProcessingForLocale,
  AssetProps,
  CreateAssetProps,
} from '../../../entities/asset'
import { getUploadHttpClient } from '../../../upload-http-client'
import { RestEndpoint } from '../types'
import * as raw from './raw'
import { create as createUpload } from './upload'
import { normalizeSelect } from './utils'

export const get: RestEndpoint<'Asset', 'get'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string } & QueryParams,
  rawData?: unknown,
  headers?: AxiosRequestHeaders
) => {
  return raw.get<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`,
    {
      params: normalizeSelect(params.query),
      headers: { ...headers },
    }
  )
}

export const getMany: RestEndpoint<'Asset', 'getMany'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & QueryParams
) => {
  return raw.get<CollectionProp<AssetProps>>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`,
    {
      params: normalizeSelect(params.query),
    }
  )
}

export const update: RestEndpoint<'Asset', 'update'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string },
  rawData: AssetProps,
  headers?: AxiosRequestHeaders
) => {
  const data: SetOptional<typeof rawData, 'sys'> = copy(rawData)
  delete data.sys
  return raw.put<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`,
    data,
    {
      headers: {
        'X-Contentful-Version': rawData.sys.version ?? 0,
        ...headers,
      },
    }
  )
}

export const del: RestEndpoint<'Asset', 'delete'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string }
) => {
  return raw.del(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`
  )
}

export const publish: RestEndpoint<'Asset', 'publish'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string },
  rawData: AssetProps
) => {
  return raw.put<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`,
    null,
    {
      headers: {
        'X-Contentful-Version': rawData.sys.version ?? 0,
      },
    }
  )
}

export const unpublish: RestEndpoint<'Asset', 'unpublish'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string }
) => {
  return raw.del<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/published`
  )
}

export const archive: RestEndpoint<'Asset', 'archive'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string }
) => {
  return raw.put<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/archived`
  )
}

export const unarchive: RestEndpoint<'Asset', 'unarchive'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string }
) => {
  return raw.del<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}/archived`
  )
}

export const create: RestEndpoint<'Asset', 'create'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams,
  rawData: CreateAssetProps
) => {
  const data = copy(rawData)

  return raw.post<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets`,
    data
  )
}

export const createWithId: RestEndpoint<'Asset', 'createWithId'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string },
  rawData: CreateAssetProps
) => {
  const data = copy(rawData)

  return raw.put<AssetProps>(
    http,
    `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${params.assetId}`,
    data
  )
}

export const createFromFiles: RestEndpoint<'Asset', 'createFromFiles'> = (
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams,
  data: Omit<AssetFileProp, 'sys'>
) => {
  const httpUpload = getUploadHttpClient(http)

  const { file } = data.fields
  return Promise.all(
    Object.keys(file).map((locale) => {
      const { contentType, fileName } = file[locale]

      return createUpload(httpUpload, params, file[locale]).then((upload) => {
        return {
          [locale]: {
            contentType,
            fileName,
            uploadFrom: {
              sys: {
                type: 'Link',
                linkType: 'Upload',
                id: upload.sys.id,
              },
            },
          },
        }
      })
    })
  )
    .then((uploads) => {
      const file = uploads.reduce((fieldsData, upload) => ({ ...fieldsData, ...upload }), {})
      const asset = {
        ...data,
        fields: {
          ...data.fields,
          file,
        },
      }
      return create(http, params, asset)
    })
    .catch(errorHandler)
}

/**
 * Asset processing
 */

const ASSET_PROCESSING_CHECK_WAIT = 3000
const ASSET_PROCESSING_CHECK_RETRIES = 10

function checkIfAssetHasUrl(
  http: AxiosInstance,
  params: GetSpaceEnvironmentParams & { assetId: string },
  {
    resolve,
    reject,
    locale,
    processingCheckWait = ASSET_PROCESSING_CHECK_WAIT,
    processingCheckRetries = ASSET_PROCESSING_CHECK_RETRIES,
    checkCount = 0,
  }: {
    resolve: (asset: AssetProps) => unknown
    reject: (err: Error) => unknown
    locale: string
    checkCount?: number
  } & AssetProcessingForLocale
) {
  return get(http, params).then((asset) => {
    if (asset.fields.file[locale].url) {
      resolve(asset)
    } else if (checkCount === processingCheckRetries) {
      const error = new Error()
      error.name = 'AssetProcessingTimeout'
      error.message = 'Asset is taking longer then expected to process.'
      reject(error)
    } else {
      checkCount++
      setTimeout(
        () =>
          checkIfAssetHasUrl(http, params, {
            resolve: resolve,
            reject: reject,
            locale: locale,
            checkCount: checkCount,
            processingCheckWait,
            processingCheckRetries,
          }),
        processingCheckWait
      )
    }
  })
}

export const processForLocale: RestEndpoint<'Asset', 'processForLocale'> = (
  http: AxiosInstance,
  {
    asset,
    locale,
    options: { processingCheckRetries, processingCheckWait } = {},
    ...params
  }: GetSpaceEnvironmentParams & {
    asset: AssetProps
    locale: string
    options?: AssetProcessingForLocale
  }
) => {
  return raw
    .put<AssetProps>(
      http,
      `/spaces/${params.spaceId}/environments/${params.environmentId}/assets/${asset.sys.id}/files/${locale}/process`,
      null,
      {
        headers: {
          'X-Contentful-Version': asset.sys.version,
        },
      }
    )
    .then(() => {
      return new Promise<AssetProps>((resolve, reject) =>
        checkIfAssetHasUrl(
          http,
          {
            spaceId: params.spaceId,
            environmentId: params.environmentId,
            assetId: asset.sys.id,
          },
          {
            resolve,
            reject,
            locale,
            processingCheckWait,
            processingCheckRetries,
          }
        )
      )
    })
}

export const processForAllLocales: RestEndpoint<'Asset', 'processForAllLocales'> = (
  http: AxiosInstance,
  {
    asset,
    options = {},
    ...params
  }: GetSpaceEnvironmentParams & { asset: AssetProps; options?: AssetProcessingForLocale }
) => {
  const locales = Object.keys(asset.fields.file || {})

  let mostUpToDateAssetVersion: AssetProps = asset

  // Let all the locales process
  // Since they all resolve at different times,
  // we need to pick the last resolved value
  // to reflect the most recent state
  const allProcessingLocales = locales.map((locale) =>
    processForLocale(http, { ...params, asset, locale, options }).then((result) => {
      // Side effect of always setting the most up to date asset version
      // The last one to call this will be the last one that finished
      // and thus the most up to date
      mostUpToDateAssetVersion = result
    })
  )

  return Promise.all(allProcessingLocales).then(() => mostUpToDateAssetVersion)
}


text:
"""
Test preset builder non-JS functionality.
"""

from django.test import TestCase
from django.utils import simplejson as json
from django.conf import settings
from django.test.client import Client
from django.contrib.auth.models import User

from ocradmin.ocrtasks.models import OcrTask

from ocradmin.core.tests import testutils

class BuilderTest(TestCase):
    fixtures = [
            "presets/fixtures/profile_fixtures.json",
            "presets/fixtures/test_fixtures.json",
            "ocrmodels/fixtures/test_fixtures.json"
            "projects/fixtures/test_fixtures.json",
            "batch/fixtures/test_batch.json",
            "ocrtasks/fixtures/test_task.json"]

    def setUp(self):
        """
            Setup OCR tests.  Creates a test user.
        """
        self.testuser = User.objects.create_user("test_user", "test@testing.com", "testpass")
        self.client = Client()
        self.client.login(username="test_user", password="testpass")

    def tearDown(self):
        """
        Revert any changes.
        """
        self.testuser.delete()

    def test_builder(self):
        r = self.client.get("/presets/builder/")
        self.assertEqual(r.status_code, 200)


text:
using LinqToDB.Mapping;

#pragma warning disable 1573, 1591
#nullable enable

namespace Cli.Default.Firebird
{
	[Table("Doctor")]
	public class Doctor
	{
		[Column("PersonID", IsPrimaryKey = true )] public int    PersonId { get; set; } // integer
		[Column("Taxonomy", CanBeNull    = false)] public string Taxonomy { get; set; } = null!; // varchar(50)

		#region Associations
		/// <summary>
		/// FK_Doctor_Person
		/// </summary>
		[Association(CanBeNull = false, ThisKey = nameof(PersonId), OtherKey = nameof(Firebird.Person.PersonId))]
		public Person Person { get; set; } = null!;
		#endregion
	}
}


text:
module TravelAdmin
  module ApplicationHelper
    def type_text
      TypeText.instance
    end

    def full_path(related_path = '')
      "#{$redis.get('admin_path')}/#{related_path}"
    end

    def get_image_path(img_path, img_id)
      if img_path.start_with?('destinations')
        # e_tag(row.title_photo.pic.url(:thumb), :size => '40x40' ) if row.title_photo
        "/pics/website/logo.png"
      else
        "/pics/website/logo.png"
      end
    end

    def has_auth(action_name)
      roles = current_employee.employee_info.roles
      auth = Auth.find_by_action(action_name)
      if auth.nil?
        auth = Auth.new(:role => '', :action => action_name)
        auth.save
      end
      return true if /X/.match(roles)
      return false if auth.role.empty?
      auth.role.match(Regexp.new("[#{roles}]"))
    end

    def website_link_to_view(resource, options={})
      options[:target] = 'website'
      options[:class] = 'btn btn-default btn-xs'
      options[:title] = 'View on website'
      link_to(raw(''), website_url(resource), options)
    end
    def link_to_new(resource_label, resource_url)
      link_to raw(" #{resource_label}"), resource_url, :remote => true,
              :class => 'btn btn-primary btn-xs'
    end

    def row_link_to_edit(resource, options = {})
      options[:remote] = true
      options[:title] = 'Edit'
      options[:class] = 'btn btn-success'
      link_to(raw(''), edit_object_url(resource), options)
    end
    def button_link_to_edit(resource, options = {})
      options[:remote] = true
      options[:title] = 'Edit'
      options[:class] = 'btn btn-primary btn-sm'
      link_to(raw(' Edit'), edit_object_url(resource), options)
    end

    def row_link_to_photo(resource_path, options = {})
      options[:title] = 'Photos'
      options[:class] = 'btn btn-default'
      options[:target] = 'edit-win'
      link_to(raw(''), resource_path, options)
    end

    def row_link_to_hide(resource, options = {})
      options[:title] = 'Show/Hide'
      options[:class] = 'btn btn-warning'
      options['data-method'] = 'delete'
      options[:remote] = true
      options['data-confirm'] = "Make this data Show/Hide from website.\n\nAre you sure?"
      link_to(raw(''), object_url(resource), options)
    end

    def icon_link_to(label_text, to_url, options = {})
      icon = options[:icon]
      options.delete(:icon)
      if options[:class]
        options[:class] += ' btn btn-default btn-xs' if (options[:class].exclude? 'btn')
      else
        options[:class] = 'btn btn-default btn-xs'
      end
      lb = label_text
      lb = " " + label_text if icon
      link_to( raw(lb), to_url, options)
    end
    def icon_link(label_text, to_url, options = {})
      icon = options[:icon]
      options.delete(:icon)
      lb = label_text
      lb = " " + label_text if icon
      if options[:class] && options[:class].include?('disabled')
        options.delete(:onclick)
        options.delete(:remote)
        options.delete(:method)
        options.delete(:confirm)
        link_to(raw(lb), '#', options)
      else
        link_to( raw(lb), to_url, options)
      end
    end
    def search_button
      button_tag raw(''), :class => 'btn btn-default'
    end

    def edit_object_url(object, options = {})
      send "edit_#{object.class.name.underscore.split('/').last}_url", object, options
    end

    def generate_html(form_builder, method, options = {})
      options[:object] ||= form_builder.object.class.reflect_on_association(method).klass.new
      options[:partial] ||= method.to_s.singularize
      options[:form_builder_local] ||= :f

      form_builder.fields_for(method, options[:object], :child_index => 'NEW_RECORD') do |f|
        render(:partial => options[:partial], :locals => { options[:form_builder_local] => f })
      end

    end

    def generate_template(form_builder, method, options = {})
      escape_javascript generate_html(form_builder, method, options)
    end
    def add_object_js_link(name, form, method, partial, where)
      link_to_function name, %{
var new_object_id = new Date().getTime();
var html = $("#{generate_template(form, method, :partial => partial)}".replace(/NEW_RECORD/g, new_object_id)).hide();html.appendTo($("#{where}")).slideDown('slow')}
    end
		def link_to_function(name, js)
			link_to name, '#', onclick: js
		end

    def website_url(object, options ={})
      "/#{object.class.name.underscore.split('/').last.pluralize}/#{object.id}"
    end
    def object_url(object, options = {})
      if object.class.name == 'Spot'
        send "tour_spot_path", object, options
      else
        send "#{object.class.name.underscore.split('/').last}_path", object, options
      end
    end
    def objects_url(object)
      if object.class.name == 'Spot'
        send "tour_spots_path"
      else
        send "#{object.class.name.underscore.split('/').last.pluralize}_path"
      end
    end
    def objects_path(object)
      "travel_admin/#{object.class.name.underscore.pluralize}"
    end

    def field_container(model, method, options = {}, &block)
      css_classes = options[:class].to_a
      if error_message_on(model, method).present?
        css_classes << 'withError'
      end
      content_tag('p', capture(&block), :class => css_classes.join(' '), :id => "#{model}_#{method}_field")
    end

    def error_message_on(object, method, options = {})
      object = convert_to_model(object)
      obj = object.respond_to?(:errors) ? object : instance_variable_get("@#{object}")

      if obj && obj.errors[method].present?
        errors = obj.errors[method].map { |err| h(err) }.join('
').html_safe
        content_tag(:span, errors, :class => 'formError')
      else
        ''
      end
    end
    def formatted_date(date)
      if date
        date.strftime('%Y-%m-%d')
      else
        ''
      end
    end

    def date_tag(date)
      dt = ''
      dt = date.strftime("%Y-%m-%d") if date
      "<time class='local-date' datetime='#{dt}T00:00:00Z'>#{dt}</time>".html_safe
    end
    def date_text_field(form, field)
      dt = ''
      dt = form.object[field].strftime("%Y-%m-%d") if form.object[field]
      form.text_field field, :value => dt, :class => 'date-picker'
    end

    def current_path
			case controller_name
				when 'destinations'
        	"Data/Destinations"
      	when 'tours'
        	"Data/Tours"
      	when 'companies'
        	"Manage/Companies"
      	when 'photos'
        	"Data/#{request.fullpath.split('/')[2].capitalize}"
      	when 'employees'
        	"Manage/My Account"
      	when 'employee_infos'
        	"Manage/Employees"
      	when 'schedules'
        	"Data/Schedules"
				when 'schedule_assignments'
        	"Data/Schedules"
      	when 'buses'
        	"Data/Vehicles"
				when 'user_infos'
					"Data/Users"
				when 'orders'
					"Orders/Orders"
				when 'app_configurations'
					"Manage/Configurations"
				when 'input_types'
					"Manage/Presettings"
				when 'accounts'
					"Accounts/Accounts"
      	else
        	controller_name
      end
    end

    def class_if_deleted(dat)
      if dat.status && dat.status == 1
        ""
      else
        "deleted"
      end
    end

    private
    def attribute_name_for(field_name)
      field_name.gsub(' ', '_').downcase
    end
  end
end


text:
package hu.akarnokd.reactive4javaflow.impl;

import hu.akarnokd.reactive4javaflow.fused.FusedSubscription;

import java.io.IOException;

public final class FailingFusedSubscription implements FusedSubscription<Integer> {

        final int mode;

        public FailingFusedSubscription(int mode) {
            this.mode = mode;
        }

        @Override
        public int requestFusion(int mode) {
            return mode & this.mode;
        }

        @Override
        public Integer poll() throws Throwable {
            throw new IOException("Forced failure");
        }

        @Override
        public boolean isEmpty() {
            return false;
        }

        @Override
        public void clear() {

        }

        @Override
        public void request(long n) {

        }

        @Override
        public void cancel() {

        }
    }


text:
<?php

if(!defined('MAIN_DIR')){define('MAIN_DIR',dirname('__FILENAME__'));}
require_once(MAIN_DIR.'/../_php/_config/session.php');
require_once(MAIN_DIR.'/../_php/_config/connection.php');
require_once(MAIN_DIR.'/../_php/_config/functions.php');

confirm_logged_in();
require_priv('priv_catalog');

$image = $_POST['image'];
$work = $_POST['work'];

$sql = "UPDATE $DB_NAME.work
			SET preferred_image = '{$image}'
			WHERE id = '{$work}' ";

$result = db_query($mysqli, $sql);

		$sql ="SELECT legacy_id
					FROM $DB_NAME.image
					WHERE id ='{$image}'";

					$result_prefLegId = db_query($mysqli, $sql);

				while ($row = $result_prefLegId->fetch_assoc()){
				$prefLegId = $row['legacy_id'];
				}

				?>

	<img src="<?php echo $image_dir; echo $prefLegId; ?>.jpg"
	onclick="image_viewer('<?php echo $prefLegId; ?>');">