text:
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
  <types>
      <members>%%%NAMESPACE%%%Facility__c.Display_Name__c</members>
      <name>CustomField</name>
  </types>
  <types>
    <members>%%%NAMESPACE%%%Facility__c-ca</members>
    <members>%%%NAMESPACE%%%Facility__c-en_GB</members>
    <members>%%%NAMESPACE%%%Facility__c-es_MX</members>
    <members>%%%NAMESPACE%%%Facility__c-es</members>
    <members>%%%NAMESPACE%%%Facility__c-fr</members>
    <name>CustomObjectTranslation</name>
  </types>
  <version>48.0</version>
</Package>


text:
{-# LANGUAGE DeriveGeneric #-}
module D22Lib.Node where

{-import Debug.Trace-}

import Data.Hashable (Hashable)
import GHC.Generics (Generic)

type Pos = (Int, Int) -- x, y
type Move = (Pos, Pos) -- from, to
type NodeSizes = (Int, Int) -- capacity, used

data NodeKind = Empty | Avail | Wall | Data deriving (Eq, Show, Generic)
data Node a = Node
    { pos :: Pos
    , info :: a
    } deriving (Eq, Show, Generic)

instance Hashable NodeKind
instance Hashable a => Hashable (Node a)

used :: Node NodeSizes -> Int
used Node { info = (_, u) } = u

capacity :: Node NodeSizes -> Int
capacity Node { info = (c, _) } = c

free :: Node NodeSizes -> Int
free n = capacity n - used n

-- All pairs of distinct nodes
allPairs :: [Node a] -> [(Node a, Node a)]
allPairs ns = filter notEq $ concatMap (\n -> zip ns (repeat n)) ns
  where
    notEq (n1, n2) = (pos n1) /= (pos n2)

-- all pairs where (used n1 < free n2)
viablePairs :: [Node NodeSizes] -> [(Node NodeSizes, Node NodeSizes)]
viablePairs = filter viable . allPairs
  where
    viable (n1, n2) = used n1 > 0 && used n1 <= free n2

-- All moves that can be made given a set of nodes
viableMoves :: [Node NodeKind] -> [Move]
viableMoves =
    map (\(n1, n2) -> (pos n1, pos n2)) . filter f . allPairs
  where
    f (n1, n2) =
        areNeighbors n1 n2 &&
        (info n2) == Empty &&
        (info n1) /= Wall

areNeighbors :: Node a -> Node a -> Bool
{-areNeighors n0 n1 = 1 == distance n0 n1-}
areNeighbors Node { pos = (x0, y0) } Node { pos = (x1, y1) } =
    (x0 `nextTo` x1 && y0 == y1) || (y0 `nextTo` y1 && x0 == x1)
  where
    nextTo n0 n1 = n0 + 1 == n1 || n0 - 1 == n1

-- manhattan distance between two nodes
distance :: Node a -> Node a -> Int
distance Node { pos = (x0, y0) } Node { pos = (x1, y1) } =
  abs (x1 - x0) + abs (y1 - y0)

-- if a node's used is > all neighbors capacity, it's a wall
isWall :: [Node NodeSizes] -> Node NodeSizes -> Bool
isWall ns n = all (\n' -> capacity n' < used n) neighbors
  where
    neighbors = map snd $ filter f (allPairs ns)
    f (n1, n2) = n1 == n && areNeighbors n1 n2

simplify :: [Node NodeSizes] -> [Node NodeKind]
simplify ns = map f ns
  where
    f n = Node { pos = (pos n), info = detectKind n }
    detectKind n | pos n == (maxX, 0) = Data
                 | used n == 0 = Empty
                 | isWall ns n = Wall
                 | otherwise = Avail
    maxX = maximum $ map (fst . pos) ns

redpajama_set_name: RedPajamaGithub


text:
To build sqlpp17 without any connector run:
```shell
cmake -B build
cmake --build build
```

Variables to build connector:
* `MYSQL_CONNECTOR`
* `POSTGRESQL_CONNECTOR`
* `SQLITE3_CONNECTOR`
* `SQLCIPHER_CONNECTOR`

```shell
cmake -B build -DMYSQL_CONNECTOR=ON -DPOSTGRESQL_CONNECTOR=ON
cmake --build build
```

## Testing

Tests will be build by default and can be run with:

```shell
ctest --test-dir build
```

## CMakeUserPreset

For convenience you can define a `CMakeUserPresets.json` if you have a recent cmake version.

For example:
```json
{
  "version": 2,
  "configurePresets": [
      {
          "name": "default",
          "generator": "Ninja",
          "binaryDir": "build",
          "cacheVariables": {
              "CMAKE_EXPORT_COMPILE_COMMANDS": "1",
              "MYSQL_CONNECTOR": "1",
              "POSTGRESQL_CONNECTOR": "1",
              "SQLITE3_CONNECTOR": "1",
              "SQLCIPHER_CONNECTOR": "1"
          }
      }
  ],
  "buildPresets": [
      {
          "name": "default",
          "configurePreset": "default"
      }
  ],
  "testPresets": [
      {
          "name": "default",
          "configurePreset": "default"
      }
  ]
}
```

To build and test:

```shell
cmake --preset="default"
cmake --build --preset="default"
ctest --preset="default"
```


text:
import os
import time

from watchman.integration.lib import WatchmanTestCase

@WatchmanTestCase.expand_matrix
class TestSinceTerm(WatchmanTestCase.WatchmanTestCase):
    def test_since_term(self) -> None:
        root = self.mkdtemp()

        self.touchRelative(root, "foo.c")
        os.mkdir(os.path.join(root, "subdir"))
        self.touchRelative(root, "subdir", "bar.txt")

        watch = self.watchmanCommand("watch", root)

        res = self.watchmanCommand("find", root, "foo.c")
        first_clock = res["clock"]
        base_mtime = res["files"][0]["mtime"]

        # Since is GT not GTE
        res = self.watchmanCommand(
            "query",
            root,
            {"expression": ["since", base_mtime, "mtime"], "fields": ["name"]},
        )
        self.assertFileListsEqual(res["files"], ["foo.c", "subdir", "subdir/bar.txt"])

        res = self.watchmanCommand(
            "query",
            root,
            {
                "expression": [
                    "allof",
                    ["since", base_mtime - 1, "mtime"],
                    ["name", "foo.c"],
                ],
                "fields": ["name"],
            },
        )
        self.assertFileListsEqual(res["files"], ["foo.c"])

        if self.isCaseInsensitive():
            res = self.watchmanCommand(
                "query",
                root,
                {
                    "expression": [
                        "allof",
                        ["since", base_mtime - 1, "mtime"],
                        ["name", "FOO.c"],
                    ],
                    "fields": ["name"],
                },
            )
            self.assertFileListsEqual(res["files"], ["foo.c"])

        # Try with a clock
        res = self.watchmanCommand(
            "query", root, {"expression": ["since", first_clock], "fields": ["name"]}
        )
        expected = []
        if watch["watcher"] == "kqueue+fsevents":
            # A cookie is written to subdir in the split watcher, thus it is
            # expected to have it in the files returned by the query.
            expected.append("subdir")
        self.assertFileListsEqual(res["files"], expected)

        future = base_mtime + 15
        self.touch(os.path.join(root, "foo.c"), (future, future))

        # Try again with a clock
        res = self.watchmanCommand(
            "query", root, {"expression": ["since", first_clock], "fields": ["name"]}
        )
        self.assertFileListsEqual(res["files"], ["foo.c"] + expected)

        # And check that we're still later than a later but not current mtime
        res = self.watchmanCommand(
            "query",
            root,
            {"expression": ["since", base_mtime + 5, "mtime"], "fields": ["name"]},
        )
        self.assertFileListsEqual(res["files"], ["foo.c"])

        # If using a timestamp against the oclock, ensure that we're comparing
        # in the correct order.  We need to force a 2 second delay so that the
        # timestamp moves forward by at least 1 increment for this test to
        # work correctly
        time.sleep(2)

        res = self.watchmanCommand(
            "query",
            root,
            {
                "expression": ["allof", ["since", int(time.time())], ["name", "foo.c"]],
                "fields": ["name"],
            },
        )
        self.assertFileListsEqual(res["files"], [])

        # Try with a fresh clock instance; we must only return files that exist.
        self.removeRelative(root, "subdir", "bar.txt")
        self.assertFileList(root, files=["foo.c", "subdir"], cursor="c:0:0")


text:
module Spec
  module Matchers
    module GeneratorMatchers
      class DirectoryGenerated
        def initialize(dir)             @dir = dir end
        def failure_message()           "expected directory '#{@path}' should exist but doesn't" end
        def negative_failure_message()  "expected no directory, but directory '#{@path}' was found" end

        def matches?(base)
          @base = base
          @path = File.join(RADIANT_ROOT, @base, @dir)
          File.exist?(@path) && File.directory?(@path)
        end
      end

      class FileGenerated
        def initialize(file)            @file = file end
        def failure_message()           "expected file '#{@path}' should exist but doesn't" end
        def negative_failure_message()  "expected no file, but file '#{@path}' was found" end

        def matches?(base)
          @base = base
          @path = File.join(RADIANT_ROOT, @base, @file)
          if (exists = File.exist?(@path)) && block_given?
            File.open(@path) { |f| yield(f.read) }
          end
          return exists
        end
      end

      class YamlGenerated
        def initialize(path)            @path = path end
        def failure_message()           "the file '#{@path}.yml' should be a YAML file" end
        def negative_failure_message()  "expected no file, but file '#{@path}.yml' was found" end

        def matches?(base)
          FileGenerated.new("#{@path}.yml").matches?(base) do |body|
            yield(YAML.load(body.to_s)) if block_given?
            return true
          end
          false
        end
      end

      class ClassGenerated
        def initialize(path, parent=nil)  @path = path; @parent = parent; end
        def failure_message()             "the file '#{@path}.rb' should be a class" end
        def negative_failure_message()    "expected no file, but file '#{@path}.rb' was found" end

        def matches?(base)
          if @path.split('/').size > 3
            @path =~ /\/?(\d+_)?(\w+)\/(\w+)$/
            class_name = "#{$2.camelize}::#{$3.camelize}"
          else
            @path =~ /\/?(\d+_)?(\w+)$/
            class_name = $2.camelize
          end

          FileGenerated.new("#{@path}.rb").matches?(base) do |body|
            match_data = body.match(/class #{class_name}#{@parent.nil? ? '':" < #{@parent}"}\n((\n|\s*.*\n)*)end/)
            yield(match_data[1]) if block_given? && !!match_data
            return !!match_data
          end
          false
        end
      end

      class ModuleGenerated
        def initialize(path, parent=nil)  @path = path; @parent = parent; end
        def failure_message()             "the file '#{@path}.rb' should be a module" end
        def negative_failure_message()    "expected no file, but file '#{@path}.rb' was found" end

        def matches?(base)
          if @path.split('/').size > 3
            @path =~ /\/?(\d+_)?(\w+)\/(\w+)$/
            module_name = "#{$2.camelize}::#{$3.camelize}"
          else
            @path =~ /\/?(\d+_)?(\w+)$/
            module_name = $2.camelize
          end

          FileGenerated.new("#{@path}.rb").matches?(base) do |body|
            match_data = body.match(/module #{module_name}#{@parent.nil? ? '':" < #{@parent}"}\n((\n|\s*.*\n)*)end/)
            yield(match_data[1]) if block_given? && !!match_data
            return !!match_data
          end
          false
        end
      end

      class SpecGenerated
        def initialize(path, class_name=true) @path = path; @class_name = class_name; end
        def failure_message()                 "the file '#{@path}.rb' should be a spec" end
        def negative_failure_message()        "expected no file, but file '#{@path}.rb' was found" end

        def matches?(base)
          unless @class_name == false
            if @path.split('/').size > 3
              @path =~ /\/?(\d+_)?(\w+)\/(\w+)$/
              @class_name = "#{$2.camelize}::#{$3.camelize}"
            else
              @path =~ /\/?(\d+_)?(\w+)$/
              @class_name = $2.camelize
            end
          end

          FileGenerated.new("#{@path}_spec.rb").matches?(base) do |body|
            if @class_name
              match_data = body.match(/describe #{@class_name} do\n((\s*.*\n)+)\s*end/)
              yield(match_data[1]) if block_given? && !!match_data
              return !!match_data
            else
              yield(body) if block_given?
              return true
            end
          end
          false
        end
      end

      class MigrationGenerated
        def initialize(name, parent="ActiveRecord::Migration")  @name = name; @parent = parent; end
        def failure_message()                                   "the file '#{@path}' should be a spec" end
        def negative_failure_message()                          "expected no file, but file '#{@path}.rb' was found" end

        def matches?(base)
          root_path = File.expand_path(File.join(RADIANT_ROOT, base))
          @path = Dir.glob("#{root_path}/db/migrate/*_#{@name.to_s.underscore}.rb").first
          return false if @path.nil?
          @path = @path.match(/db\/migrate\/[0-9]+_\w+/).to_s

          ClassGenerated.new(@path, @parent).matches?(base) do |body|
            yield(body) if block_given?
            return true
          end
          false
        end
      end

      class MethodMatcher
        def initialize(name)            @name = name end
        def failure_message()           "the string should contain a method definition for #{@name}" end
        def negative_failure_message()  "expected no method definition for #{@name}, but found it" end

        def matches?(actual)
          match_data = actual.match(/^\s*def #{@name}(\(.+\))?\n((\n|\s+.*\n)*)\s*end/)
          if !!match_data && block_given?
            yield(match_data[2])
          end
          return !!match_data
        end
      end

      def have_generated_directory(dir)
        DirectoryGenerated.new(dir)
      end

      def have_generated_file(file)
        FileGenerated.new(file)
      end

      def have_generated_class(path, parent = nil)
        ClassGenerated.new(path, parent)
      end

      def have_generated_module(path, parent = nil)
        ModuleGenerated.new(path, parent)
      end

      def have_generated_spec(path, class_name = true)
        SpecGenerated.new(path, class_name)
      end

      def have_generated_controller_for(name, parent = "ApplicationController")
        ClassGenerated.new("app/controllers/#{name.to_s.underscore}_controller", parent)
      end

      def have_generated_model_for(name, parent = "ActiveRecord::Base")
        ClassGenerated.new("app/models/#{name.to_s.underscore}", parent)
      end

      def have_generated_model_spec_for(name)
        SpecGenerated.new("spec/models/#{name.to_s.underscore}")
      end

      def have_generated_controller_spec_for(name)
        SpecGenerated.new("spec/controllers/#{name.to_s.underscore}_controller")
      end

      def have_generated_helper_spec_for(name)
        SpecGenerated.new("spec/helpers/#{name.to_s.underscore}_helper")
      end

      def have_generated_view_spec_for(controller, action)
        SpecGenerated.new("spec/views/#{controller.to_s.underscore}/#{action.to_s.underscore}_view", false)
      end

      def have_generated_helper_for(name)
        ModuleGenerated.new("app/helpers/#{name.to_s.underscore}_helper")
      end

      def have_generated_functional_test_for(name, parent = "ActionController::TestCase")
        ClassGenerated.new("test/functional/#{name.to_s.underscore}_controller_test", parent)
      end

      def have_generated_unit_test_for(name, parent = "ActiveSupport::TestCase")
        ClassGenerated.new("test/unit/#{name.to_s.underscore}_test", parent)
      end

      def have_generated_migration(name, parent = "ActiveRecord::Migration")
        MigrationGenerated.new(name, parent)
      end

      def have_generated_yaml(path)
        YamlGenerated.new(path)
      end

      def have_generated_fixtures_for(name)
        YamlGenerated.new("test/fixtures/#{name.to_s.underscore}")
      end

      def have_generated_view_for(name, action, suffix = "html.erb")
        FileGenerated.new("app/views/#{name.to_s.underscore}/#{action}.#{suffix}")
      end

      def have_method(name)
        MethodMatcher.new(name)
      end

      def have_generated_column(name, type)
        simple_matcher("migration defines column") { |given| given =~ /t\.#{type.to_s} :#{name.to_s}/ }
      end
    end
  end
end


text:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/status_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true">

            <FrameLayout
                android:id="@+id/fragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="?android:colorBackground" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                app:title="@string/app_name"
                android:background="@drawable/gradient" />

        </FrameLayout>

    </FrameLayout>

    <FrameLayout
        android:id="@+id/drawer"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start" />

</android.support.v4.widget.DrawerLayout>


text:
package info.tongrenlu.mapper;

import info.tongrenlu.domain.ShopBean;

import java.util.Map;

public interface ShopMapper {

    public ShopBean fetchBean(Map<String, Object> params);

    public void update(ShopBean shopBean);

}


text:
indri_stuff
===========

bla bla bla, if you wanna know, ask me


text:
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;

namespace System
{
    // A place holder class for signed bytes.
    [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
    [System.Runtime.InteropServices.ComVisible(true)]
    public struct SByte : IComparable, IFormattable, IComparable<SByte>, IEquatable<SByte>, IConvertible
    {
        private sbyte _value;

        // The maximum value that a Byte may represent: 127.
        public const sbyte MaxValue = (sbyte)0x7F;

        // The minimum value that a Byte may represent: -128.
        public const sbyte MinValue = unchecked((sbyte)0x80);

        // Compares this object to another object, returning an integer that
        // indicates the relationship.
        // Returns a value less than zero if this  object
        // null is considered to be less than any instance.
        // If object is not of type SByte, this method throws an ArgumentException.
        //
        int IComparable.CompareTo(Object obj)
        {
            if (obj == null)
            {
                return 1;
            }
            if (!(obj is SByte))
            {
                throw new ArgumentException(SR.Arg_MustBeSByte);
            }
            return _value - ((SByte)obj)._value;
        }

        public int CompareTo(SByte value)
        {
            return _value - value;
        }

        // Determines whether two Byte objects are equal.
        public override bool Equals(Object obj)
        {
            if (!(obj is SByte))
            {
                return false;
            }
            return _value == ((SByte)obj)._value;
        }

        [NonVersionable]
        public bool Equals(SByte obj)
        {
            return _value == obj;
        }

        // Gets a hash code for this instance.
        public override int GetHashCode()
        {
            return ((int)_value ^ (int)_value << 8);
        }

        // Provides a string representation of a byte.
        public override String ToString()
        {
            Contract.Ensures(Contract.Result<String>() != null);
            return FormatProvider.FormatInt32(_value, null, null);
        }

        public String ToString(IFormatProvider provider)
        {
            Contract.Ensures(Contract.Result<String>() != null);
            return FormatProvider.FormatInt32(_value, null, provider);
        }

        public String ToString(String format)
        {
            Contract.Ensures(Contract.Result<String>() != null);
            return ToString(format, null);
        }

        public String ToString(String format, IFormatProvider provider)
        {
            Contract.Ensures(Contract.Result<String>() != null);

            if (_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
            {
                uint temp = (uint)(_value & 0x000000FF);
                return FormatProvider.FormatUInt32(temp, format, provider);
            }
            return FormatProvider.FormatInt32(_value, format, provider);
        }

        [CLSCompliant(false)]
        public static sbyte Parse(String s)
        {
            return Parse(s, NumberStyles.Integer, null);
        }

        [CLSCompliant(false)]
        public static sbyte Parse(String s, NumberStyles style)
        {
            UInt32.ValidateParseStyleInteger(style);
            return Parse(s, style, null);
        }

        [CLSCompliant(false)]
        public static sbyte Parse(String s, IFormatProvider provider)
        {
            return Parse(s, NumberStyles.Integer, provider);
        }

        // Parses a signed byte from a String in the given style.  If
        // a NumberFormatInfo isn't specified, the current culture's
        // NumberFormatInfo is assumed.
        //
        [CLSCompliant(false)]
        public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider)
        {
            UInt32.ValidateParseStyleInteger(style);
            int i = 0;
            try
            {
                i = FormatProvider.ParseInt32(s, style, provider);
            }
            catch (OverflowException e)
            {
                throw new OverflowException(SR.Overflow_SByte, e);
            }

            if ((style & NumberStyles.AllowHexSpecifier) != 0)
            { // We are parsing a hexadecimal number
                if ((i < 0) || i > Byte.MaxValue)
                {
                    throw new OverflowException(SR.Overflow_SByte);
                }
                return (sbyte)i;
            }

            if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte);
            return (sbyte)i;
        }

        [CLSCompliant(false)]
        public static bool TryParse(String s, out SByte result)
        {
            return TryParse(s, NumberStyles.Integer, null, out result);
        }

        [CLSCompliant(false)]
        public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result)
        {
            UInt32.ValidateParseStyleInteger(style);
            result = 0;
            int i;
            if (!FormatProvider.TryParseInt32(s, style, provider, out i))
            {
                return false;
            }

            if ((style & NumberStyles.AllowHexSpecifier) != 0)
            { // We are parsing a hexadecimal number
                if ((i < 0) || i > Byte.MaxValue)
                {
                    return false;
                }
                result = (sbyte)i;
                return true;
            }

            if (i < MinValue || i > MaxValue)
            {
                return false;
            }
            result = (sbyte)i;
            return true;
        }

        //
        // IConvertible implementation
        //

        TypeCode IConvertible.GetTypeCode()
        {
            return TypeCode.SByte;
        }

        /// <internalonly/>
        bool IConvertible.ToBoolean(IFormatProvider provider)
        {
            return Convert.ToBoolean(_value);
        }

        /// <internalonly/>
        char IConvertible.ToChar(IFormatProvider provider)
        {
            return Convert.ToChar(_value);
        }

        /// <internalonly/>
        sbyte IConvertible.ToSByte(IFormatProvider provider)
        {
            return _value;
        }

        /// <internalonly/>
        byte IConvertible.ToByte(IFormatProvider provider)
        {
            return Convert.ToByte(_value);
        }

        /// <internalonly/>
        short IConvertible.ToInt16(IFormatProvider provider)
        {
            return Convert.ToInt16(_value);
        }

        /// <internalonly/>
        ushort IConvertible.ToUInt16(IFormatProvider provider)
        {
            return Convert.ToUInt16(_value);
        }

        /// <internalonly/>
        int IConvertible.ToInt32(IFormatProvider provider)
        {
            return _value;
        }

        /// <internalonly/>
        uint IConvertible.ToUInt32(IFormatProvider provider)
        {
            return Convert.ToUInt32(_value);
        }

        /// <internalonly/>
        long IConvertible.ToInt64(IFormatProvider provider)
        {
            return Convert.ToInt64(_value);
        }

        /// <internalonly/>
        ulong IConvertible.ToUInt64(IFormatProvider provider)
        {
            return Convert.ToUInt64(_value);
        }

        /// <internalonly/>
        float IConvertible.ToSingle(IFormatProvider provider)
        {
            return Convert.ToSingle(_value);
        }

        /// <internalonly/>
        double IConvertible.ToDouble(IFormatProvider provider)
        {
            return Convert.ToDouble(_value);
        }

        /// <internalonly/>
        Decimal IConvertible.ToDecimal(IFormatProvider provider)
        {
            return Convert.ToDecimal(_value);
        }

        /// <internalonly/>
        DateTime IConvertible.ToDateTime(IFormatProvider provider)
        {
            throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "SByte", "DateTime"));
        }

        /// <internalonly/>
        Object IConvertible.ToType(Type type, IFormatProvider provider)
        {
            return Convert.DefaultToType((IConvertible)this, type, provider);
        }
    }
}


text:
package fr.reden.mvmod.serializer.field.setter;

import net.minecraft.entity.Entity;

import java.lang.reflect.Field;

public interface IFieldSetter<V> {

    /**
     * Set the field's value for the given entity instance.
     * @param field The field to be set.
     * @param value The value of the field.
     * @param entity The entity instance.
     */
    void setFieldValue(Field field, V value, Entity entity) throws Exception;

}


text:
module Mutant
  # Module providing isolation
  module Isolation
    Error = Class.new(RuntimeError)

    module None

      # Call block in isolation
      #
      # @return [Object]
      #
      # @raise [Error]
      #   if block terminates abnormal
      #
      # @api private
      def self.call(&block)
        block.call
      rescue => exception
        raise Error, exception
      end
    end

    module Fork

      # Call block in isolation
      #
      # This isolation implements the fork strategy.
      # Future strategies will probably use a process pool that can
      # handle multiple mutation kills, in-isolation at once.
      #
      # @return [Object]
      #   returns block execution result
      #
      # @raise [Error]
      #   if block terminates abnormal
      #
      # rubocop:disable MethodLength
      #
      # @api private
      def self.call(&block)
        IO.pipe(binmode: true) do |reader, writer|
          writer.binmode
          begin
            pid = Process.fork do
              File.open(File::NULL, File::WRONLY) do |file|
                $stderr.reopen(file)
                reader.close
                writer.write(Marshal.dump(block.call))
                writer.close
              end
            end

            writer.close
            Marshal.load(reader.read)
          ensure
            Process.waitpid(pid) if pid
          end
        end
      rescue => exception
        raise Error, exception
      end

    end # Fork

  end # Isolator
end # Mutant


text:
var step = ''
            +'
Preconditions:
'
            +'
Test device is connected to the network.
'
            +'
Test Purpose:
'
            +'
Verifies CSP policies support in manifest.json.
'
          +'';


text:
layout: post
title: "ClojureScript and Figwheel"
modified:
categories: blog
excerpt:
tags: [Code, Clojure]
image:
  feature:
date: 2015-05-03T08:30:50+01:00
---

[Last week](/2015/04/29/Clojure/) I wrote about Clojure and I posted a video about [fighweel](https://github.com/bhauman/lein-figwheel). After the post a talk by the original author was posted from the [Clojure/West Conference](http://clojurewest.org/). In it he goes through [fighweel](https://github.com/bhauman/lein-figwheel) and the rationel behind it. He shows off many cool features, so it is well worth watching it fully!

<iframe width="560" height="315" src="https://www.youtube.com/embed/j-kj2qwJa_E" frameborder="0" allowfullscreen></iframe>

# Pomegrante #

He also notes that he uses [pomegrante](https://github.com/cemerick/pomegranate) for dependency loading. This library is also usable from the normal lein repl to load dependencies while you are hacking away. This means that it is not necessary to reload the repl when you need another dependency! This is awesome!


text:
/*package com.jaquadro.minecraft.storagedrawers.item;

import com.jaquadro.minecraft.storagedrawers.block.BlockFramingTable;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

import javax.annotation.Nonnull;

public class ItemFramingTable extends ItemBlock
{
    public ItemFramingTable (Block block) {
        super(block);
        setMaxDamage(0);
    }

    @Override
    public boolean placeBlockAt (@Nonnull ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, IBlockState newState) {
        newState = newState.withProperty(BlockFramingTable.RIGHT_SIDE, true);

        if (side == EnumFacing.DOWN)
            return false;
        if (side == EnumFacing.UP)
            side = EnumFacing.fromAngle(player.rotationYaw).getOpposite();

        newState = newState.withProperty(BlockFramingTable.FACING, side);

        int xOff = 0;
        int zOff = 0;

        if (side == EnumFacing.NORTH)
            xOff = 1;
        if (side == EnumFacing.SOUTH)
            xOff = -1;
        if (side == EnumFacing.WEST)
            zOff = -1;
        if (side == EnumFacing.EAST)
            zOff = 1;

        if (!world.isAirBlock(pos) || !world.isAirBlock(pos.add(0, 1, 0)))
            return false;
        if (!world.isAirBlock(pos.add(xOff, 0, zOff)) || !world.isAirBlock(pos.add(xOff, 1, zOff))) {
            if (side == EnumFacing.NORTH || side == EnumFacing.SOUTH)
                xOff *= -1;
            if (side == EnumFacing.WEST || side == EnumFacing.EAST)
                zOff *= -1;
            if (!world.isAirBlock(pos.add(xOff, 0, zOff)) || !world.isAirBlock(pos.add(xOff, 1, zOff)))
                return false;

            newState = newState.withProperty(BlockFramingTable.RIGHT_SIDE, false);
        }

        if (!world.setBlockState(pos, newState, 3))
            return false;

        IBlockState altState = newState.withProperty(BlockFramingTable.RIGHT_SIDE, !newState.getValue(BlockFramingTable.RIGHT_SIDE));
        if (!world.setBlockState(pos.add(xOff, 0, zOff), altState, 3)) {
            world.setBlockToAir(pos);
            return false;
        }

        if (world.getBlockState(pos).getBlock() == block)
            block.onBlockPlacedBy(world, pos, newState, player, stack);

        return true;
    }
}
*/


text:
package com.azure.resourcemanager.machinelearning.generated;

import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.machinelearning.models.IdAssetReference;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public final class IdAssetReferenceTests {
    @Test
    public void testDeserialize() {
        IdAssetReference model =
            BinaryData
                .fromString("{\"referenceType\":\"Id\",\"assetId\":\"itpkpztrgdg\"}")
                .toObject(IdAssetReference.class);
        Assertions.assertEquals("itpkpztrgdg", model.assetId());
    }

    @Test
    public void testSerialize() {
        IdAssetReference model = new IdAssetReference().withAssetId("itpkpztrgdg");
        model = BinaryData.fromObject(model).toObject(IdAssetReference.class);
        Assertions.assertEquals("itpkpztrgdg", model.assetId());
    }
}


text:
Generating patterns

Topographica provides comprehensive support for creating
two-dimensional patterns of various sorts.  These patterns can be used
for generating training or testing inputs, generating initial or fixed
weight patterns, neighborhood kernels, or any similar application.

Simple patterns

The basic types of patterns supported by Topographica include:

These patterns are created using objects of type
<?php classref('topo.base.patterngenerator','PatternGenerator')?>,
which is an object that will return a 2D pattern
when it is called as a function.  For instance, the Gaussian
PatternGenerator will return Gaussian-shaped patterns:

$ topographica -g
Topographica> from topo import pattern
Topographica> pg=pattern.Gaussian(xdensity=60,ydensity=60,size=0.3,aspect_ratio=1.0)
Topographica>
Topographica> matrixplot(pg())
Topographica> matrixplot(pg(size=0.5))

As you can see, the parameters of a PatternGenerator can be set up
when you create the object, or they can be supplied when you generate
the pattern.  Any parameter not supplied in either location inherits
the default value set for it in that PatternGenerator class.

The reason for the name PatternGenerator is that the objects can
each actually return an infinite number of different patterns, if any
of the parameters are set to Dynamic values.  For instance, a Gaussian
input pattern can be specified to have a random orientation and (x,y)
location:

$ topographica -g
Topographica> from topo import pattern, numbergen
Topographica> input_pattern = pattern.Gaussian(size=0.08, aspect_ratio=4,
                 xdensity=60,ydensity=60,
                 x=numbergen.UniformRandom(lbound=-0.5,ubound=0.5,seed=12),
                 y=numbergen.UniformRandom(lbound=-0.5,ubound=0.5,seed=34),
                 orientation=numbergen.UniformRandom(lbound=-pi,ubound=pi,seed=56))
Topographica> matrixplot(input_pattern())
Topographica> matrixplot(input_pattern())

There are many other types of patterns available already defined in
the
topo/pattern directory, and adding new patterns is
straightforward.  Just create a new class inheriting from
PatternGenerator or one of its subclasses, make sure it is loaded
before you start the GUI, and it will then show up in the Test Pattern
window of the GUI automatically, and can be used in scripts the same
way.

Composite patterns

Often, rather than writing a new PatternGenerator class, you can
combine existing PatternGenerators to make a new pattern.  To do this,
Topographica provides the special Composite PatternGenerator, which
accepts a list of other PatternGenerators and an operator for
combining them.  For instance, you can make connection weights be
random but with a Gaussian falloff in strength by setting:

CFProjection.weights_generator=pattern.Composite(
    generators=[pattern.random.UniformRandom(),
                pattern.Gaussian(aspect_ratio=1.0,size=0.2)],
    operator=numpy.multiply)

More complex patterns can be created by combining multiple Composite PatternGenerators:

$ topographica -g
Topographica> from topo import pattern
Topographica> import numpy
Topographica> surroundsine   = pattern.SineGrating(frequency=8.0,orientation=0.25*pi,
Topographica>                                      phase=3*pi/2)
Topographica> centersine     = pattern.SineGrating(frequency=8.0,orientation=0.60*pi)
Topographica> centerdisk     = pattern.Disk(aspect_ratio=1.0, size=0.35, smoothing=0.005)
Topographica> surrounddisk   = pattern.Disk(aspect_ratio=1.0, size=0.90, smoothing=0.005)
Topographica> surroundring   = pattern.Composite(generators=[surrounddisk,centerdisk],
Topographica>                                    operator=numpy.subtract)
Topographica> center         = pattern.Composite(generators=[centersine,centerdisk],
Topographica>                                    operator=numpy.multiply)
Topographica> surround       = pattern.Composite(generators=[surroundsine,surroundring],
Topographica>                                    operator=numpy.multiply)
Topographica> centersurround = pattern.Composite(generators=[center,surround],
Topographica>                                    operator=numpy.add,
Topographica>                                    xdensity=160,ydensity=160)
Topographica> matrixplot(centersurround())

Once created, even very complex composite patterns can be scaled,
rotated, and placed together as a unit:

$ topographica -g
Topographica> from topo import pattern
Topographica> import numpy
Topographica> pattern.Disk.smoothing=0.005
Topographica> lefteye    = pattern.Disk(    aspect_ratio=0.7, x=0.04, y=0.10, size=0.08, scale=1.00)
Topographica> leftpupil  = pattern.Disk(    aspect_ratio=1.0, x=0.03, y=0.08, size=0.04, scale=-1.6)
Topographica> righteye   = pattern.Disk(    aspect_ratio=0.7, x=0.04, y=-0.1, size=0.08, scale=1.00)
Topographica> rightpupil = pattern.Disk(    aspect_ratio=1.0, x=0.03, y=-0.08,size=0.04, scale=-1.6)
Topographica> nose       = pattern.Gaussian(aspect_ratio=0.8, x=-0.1, y=0.00, size=0.04, scale=-0.5)
Topographica> mouth      = pattern.Gaussian(aspect_ratio=0.8, x=-0.2, y=0.00, size=0.06, scale=-0.8)
Topographica> head       = pattern.Disk(    aspect_ratio=1.5, x=-0.02,y=0.00, size=0.40, scale=0.70)
Topographica> pg=pattern.Composite(generators=[lefteye,leftpupil,righteye,rightpupil,nose,mouth,head],
Topographica>                      operator=numpy.add,xdensity=160,ydensity=160)
Topographica> matrixplot(pg(orientation=pi/1.8, x=0.2, y=0.1, offset=0.5, size=0.75))

A wide variety of operators are provided for combining the patterns; see the

Composite parameter operator for more details.

Selector patterns

Instead of combining the patterns, it can also be useful to choose
one from a set of different patterns, such as choosing randomly from a
database of natural images.  This can be done with the Selector
PatternGenerator.  As a contrived example, weights can be choosen at
random from a set of four different pattern generators:

CFProjection.weights_generator=pattern.Selector(generators=[
    pattern.Gaussian(orientation=numbergen.UniformRandom(lbound=-pi,ubound=pi,seed=99)),
    pattern.Gaussian(aspect_ratio=1.0,
                     x=numbergen.UniformRandom(lbound=-0.2,ubound=0.2,seed=12),
                     y=numbergen.UniformRandom(lbound=-0.2,ubound=0.2,seed=34)),
    pattern.Rectangle(orientation=numbergen.UniformRandom(lbound=-pi,ubound=pi,seed=99),
                      size=0.3),
    pattern.Disk(size=0.2)])


text:
require 'write_xlsx'

workbook  = WriteXLSX.new('hide_row_col.xlsx')
worksheet = workbook.add_worksheet

# Write some data
worksheet.write('D1', 'Some hidden columns.')
worksheet.write('A8', 'Some hidden rows.')

# Hide all rows without data.
worksheet.set_default_row(nil, 1)

# Set emptys row that we do want to display. All other will be hidden.
(1..6).each { |row| worksheet.set_row(row, 15) }

# Hide a range of columns.
worksheet.set_column('G:XFD', nil, nil, 1)

workbook.close


text:
package com.linkedin.pinot.transport.metrics;

import com.linkedin.pinot.common.metrics.AggregatedCounter;
import com.linkedin.pinot.common.metrics.AggregatedHistogram;
import com.linkedin.pinot.common.metrics.AggregatedMetricsRegistry;
import com.linkedin.pinot.common.metrics.LatencyMetric;
import com.linkedin.pinot.common.metrics.MetricsHelper;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.Sampling;
import com.yammer.metrics.core.Summarizable;

/**
 *
 * Aggregated Transport Server Metrics. Provides multi-level aggregation.
 *
 */
public class AggregatedTransportServerMetrics implements TransportServerMetrics {

  public static final String REQUESTS_RECEIVED = "Requests-Sent";
  public static final String BYTES_SENT = "bytes-Sent";
  public static final String BYTES_RECEIVED = "bytes-received";
  public static final String SEND_RESPONSE_MS = "Send-Response-MS";
  public static final String PROCESSING_LATENCY_MS = "Processing-Latency-MS";
  public static final String ERRORS = "errors";

  // Num Requests
  private final AggregatedCounter _requestsReceived;

  // Request bytes
  private final AggregatedCounter _bytesSent;

  // Response Bytes
  private final AggregatedCounter _bytesReceived;

  // Errors
  private final AggregatedCounter _errors;

  // Latency for sending response
  private final AggregatedHistogram<Sampling> _sendResponseMsHistogram;

  // Total processing latency including that of sending response
  private final AggregatedHistogram<Sampling> _processingLatencyMsHistogram;

  public AggregatedTransportServerMetrics(AggregatedMetricsRegistry registry, String group) {
    _requestsReceived = MetricsHelper.newAggregatedCounter(registry, new MetricName(group, "", REQUESTS_RECEIVED));
    _bytesSent = MetricsHelper.newAggregatedCounter(registry, new MetricName(group, "", BYTES_SENT));
    _bytesReceived = MetricsHelper.newAggregatedCounter(registry, new MetricName(group, "", BYTES_RECEIVED));
    _errors = MetricsHelper.newAggregatedCounter(registry, new MetricName(group, "", ERRORS));
    _sendResponseMsHistogram =
        MetricsHelper.newAggregatedHistogram(registry, new MetricName(group, "", SEND_RESPONSE_MS));
    _processingLatencyMsHistogram =
        MetricsHelper.newAggregatedHistogram(registry, new MetricName(group, "", PROCESSING_LATENCY_MS));
  }

  /**
   * Add NettyServerMetrics to aggregated metrics
   * @param metric metric to be aggregated
   */
  public void addTransportClientMetrics(NettyServerMetrics metric) {
    _requestsReceived.add(metric.getRequestsReceived());
    _bytesSent.add(metric.getBytesSent());
    _bytesReceived.add(metric.getBytesReceived());
    _errors.add(metric.getErrors());
    _sendResponseMsHistogram.add(metric.getSendResponseMsHistogram());
    _processingLatencyMsHistogram.add(metric.getProcessingLatencyMsHistogram());
  }

  /**
   * Add another AggregatedTransportServerMetrics to this aggregated metrics to create
   * multi-level aggregation
   * @param metric metric to be aggregated
   */
  public void addTransportClientMetrics(AggregatedTransportServerMetrics metric) {
    _requestsReceived.add(metric.getRequestsReceived());
    _bytesSent.add(metric.getBytesSent());
    _bytesReceived.add(metric.getBytesReceived());
    _errors.add(metric.getErrors());
    _sendResponseMsHistogram.add(metric.getSendResponseMsHistogram());
    _processingLatencyMsHistogram.add(metric.getProcessingLatencyMsHistogram());
  }

  /**
   * Remove NettyServerMetrics to aggregated metrics
   * @param metric metric to be be removed
   */
  public void removeTransportClientMetrics(NettyServerMetrics metric) {
    _requestsReceived.remove(metric.getRequestsReceived());
    _bytesSent.remove(metric.getBytesSent());
    _bytesReceived.remove(metric.getBytesReceived());
    _errors.remove(metric.getErrors());
    _sendResponseMsHistogram.remove(metric.getSendResponseMsHistogram());
    _processingLatencyMsHistogram.remove(metric.getProcessingLatencyMsHistogram());
  }

  /**
   * Remove AggregatedTransportServerMetrics to aggregated metrics
   * @param metric metric to be be removed
   */
  public void removeTransportClientMetrics(AggregatedTransportServerMetrics metric) {
    _requestsReceived.remove(metric.getRequestsReceived());
    _bytesSent.remove(metric.getBytesSent());
    _bytesReceived.remove(metric.getBytesReceived());
    _errors.remove(metric.getErrors());
    _sendResponseMsHistogram.remove(metric.getSendResponseMsHistogram());
    _processingLatencyMsHistogram.remove(metric.getProcessingLatencyMsHistogram());
  }

  @Override
  public long getTotalRequests() {
    return _requestsReceived.count();
  }

  @Override
  public long getTotalBytesSent() {
    return _bytesSent.count();
  }

  @Override
  public long getTotalBytesReceived() {
    return _bytesReceived.count();
  }

  @Override
  public long getTotalErrors() {
    return _errors.count();
  }

  @Override
  public <T extends Sampling & Summarizable> LatencyMetric<T> getSendResponseLatencyMs() {
    return new LatencyMetric(_sendResponseMsHistogram);
  }

  @Override
  public <T extends Sampling & Summarizable> LatencyMetric<T> getProcessingLatencyMs() {
    return new LatencyMetric(_processingLatencyMsHistogram);
  }

  private AggregatedCounter getRequestsReceived() {
    return _requestsReceived;
  }

  private AggregatedCounter getBytesSent() {
    return _bytesSent;
  }

  private AggregatedCounter getBytesReceived() {
    return _bytesReceived;
  }

  private AggregatedCounter getErrors() {
    return _errors;
  }

  private AggregatedHistogram<Sampling> getSendResponseMsHistogram() {
    return _sendResponseMsHistogram;
  }

  private AggregatedHistogram<Sampling> getProcessingLatencyMsHistogram() {
    return _processingLatencyMsHistogram;
  }
}


text:
class InputView
  include Puppis

  text_field :first_text_field, index: 0
  text_field :text_field_by_index, index: 1
  text_field :text_field_by_class, class: 'UITextField'
  text_field :text_field_by_marked, marked: 'regular text field'
  text_field :text_field_by_label, label: 'regular text field'
  text_field :text_field_by_query, query: 'UITextField'
end


text:
require "spec_helper"

module ControllerActions
  def index
    render plain: "index"
  end

  def show
    render plain: "show"
  end

  def doorkeeper_unauthorized_render_options(*); end

  def doorkeeper_forbidden_render_options(*); end
end

describe "doorkeeper authorize filter" do
  context "accepts token code specified as" do
    controller do
      before_action :doorkeeper_authorize!

      def index
        render plain: "index"
      end
    end

    let(:token_string) { "1A2BC3" }
    let(:token) do
      double(Doorkeeper::AccessToken,
             acceptable?: true, previous_refresh_token: "",
             revoke_previous_refresh_token!: true)
    end

    it "access_token param" do
      expect(Doorkeeper::AccessToken).to receive(:by_token).with(token_string).and_return(token)
      get :index, params: { access_token: token_string }
    end

    it "bearer_token param" do
      expect(Doorkeeper::AccessToken).to receive(:by_token).with(token_string).and_return(token)
      get :index, params: { bearer_token: token_string }
    end

    it "Authorization header" do
      expect(Doorkeeper::AccessToken).to receive(:by_token).with(token_string).and_return(token)
      request.env["HTTP_AUTHORIZATION"] = "Bearer #{token_string}"
      get :index
    end

    it "different kind of Authorization header" do
      expect(Doorkeeper::AccessToken).not_to receive(:by_token)
      request.env["HTTP_AUTHORIZATION"] = "MAC #{token_string}"
      get :index
    end

    it "does not change Authorization header value" do
      expect(Doorkeeper::AccessToken).to receive(:by_token).exactly(2).times.and_return(token)
      request.env["HTTP_AUTHORIZATION"] = "Bearer #{token_string}"
      get :index
      controller.send(:remove_instance_variable, :@doorkeeper_token)
      get :index
    end
  end

  context "defined for all actions" do
    controller do
      before_action :doorkeeper_authorize!

      include ControllerActions
    end

    context "with valid token", token: :valid do
      it "allows into index action" do
        get :index, params: { access_token: token_string }
        expect(response).to be_successful
      end

      it "allows into show action" do
        get :show, params: { id: "4", access_token: token_string }
        expect(response).to be_successful
      end
    end

    context "with invalid token", token: :invalid do
      it "does not allow into index action" do
        get :index, params: { access_token: token_string }
        expect(response.status).to eq 401
        expect(response.header["WWW-Authenticate"]).to match(/^Bearer/)
      end

      it "does not allow into show action" do
        get :show, params: { id: "4", access_token: token_string }
        expect(response.status).to eq 401
        expect(response.header["WWW-Authenticate"]).to match(/^Bearer/)
      end
    end
  end

  context "defined with scopes" do
    controller do
      before_action -> { doorkeeper_authorize! :write }

      include ControllerActions
    end

    let(:token_string) { "1A2DUWE" }

    it "allows if the token has particular scopes" do
      token = double(Doorkeeper::AccessToken,
                     accessible?: true, scopes: %w[write public],
                     previous_refresh_token: "",
                     revoke_previous_refresh_token!: true)
      expect(token).to receive(:acceptable?).with([:write]).and_return(true)
      expect(
        Doorkeeper::AccessToken
      ).to receive(:by_token).with(token_string).and_return(token)

      get :index, params: { access_token: token_string }
      expect(response).to be_successful
    end

    it "does not allow if the token does not include given scope" do
      token = double(Doorkeeper::AccessToken,
                     accessible?: true, scopes: ["public"], revoked?: false,
                     expired?: false, previous_refresh_token: "",
                     revoke_previous_refresh_token!: true)
      expect(
        Doorkeeper::AccessToken
      ).to receive(:by_token).with(token_string).and_return(token)
      expect(token).to receive(:acceptable?).with([:write]).and_return(false)

      get :index, params: { access_token: token_string }
      expect(response.status).to eq 403
      expect(response.header).to_not include("WWW-Authenticate")
    end
  end

  context "when custom unauthorized render options are configured" do
    controller do
      before_action :doorkeeper_authorize!

      include ControllerActions
    end

    context "with a JSON custom render", token: :invalid do
      before do
        module ControllerActions
          remove_method :doorkeeper_unauthorized_render_options

          def doorkeeper_unauthorized_render_options(error: nil)
            { json: ActiveSupport::JSON.encode(error_message: error.description) }
          end
        end
      end

      after do
        module ControllerActions
          remove_method :doorkeeper_unauthorized_render_options

          def doorkeeper_unauthorized_render_options(error: nil); end
        end
      end

      it "it renders a custom JSON response", token: :invalid do
        get :index, params: { access_token: token_string }
        expect(response.status).to eq 401
        expect(response.content_type).to include("application/json")
        expect(response.header["WWW-Authenticate"]).to match(/^Bearer/)

        expect(json_response).not_to be_nil
        expect(json_response["error_message"]).to match("token is invalid")
      end
    end

    context "with a text custom render", token: :invalid do
      before do
        module ControllerActions
          remove_method :doorkeeper_unauthorized_render_options

          def doorkeeper_unauthorized_render_options(**)
            { plain: "Unauthorized" }
          end
        end
      end

      after do
        module ControllerActions
          remove_method :doorkeeper_unauthorized_render_options

          def doorkeeper_unauthorized_render_options(error: nil); end
        end
      end

      it "it renders a custom text response", token: :invalid do
        get :index, params: { access_token: token_string }
        expect(response.status).to eq 401
        expect(response.content_type).to include("text/plain")
        expect(response.header["WWW-Authenticate"]).to match(/^Bearer/)
        expect(response.body).to eq("Unauthorized")
      end
    end
  end

  context "when custom forbidden render options are configured" do
    before do
      expect(Doorkeeper::AccessToken).to receive(:by_token).with(token_string).and_return(token)
      expect(token).to receive(:acceptable?).with([:write]).and_return(false)
    end

    after do
      module ControllerActions
        remove_method :doorkeeper_forbidden_render_options

        def doorkeeper_forbidden_render_options(*); end
      end
    end

    controller do
      before_action -> { doorkeeper_authorize! :write }

      include ControllerActions
    end

    let(:token) do
      double(Doorkeeper::AccessToken,
             accessible?: true, scopes: ["public"], revoked?: false,
             expired?: false, previous_refresh_token: "",
             revoke_previous_refresh_token!: true)
    end

    let(:token_string) { "1A2DUWE" }

    context "with a JSON custom render" do
      before do
        module ControllerActions
          remove_method :doorkeeper_forbidden_render_options

          def doorkeeper_forbidden_render_options(*)
            { json: { error_message: "Forbidden" } }
          end
        end
      end

      it "renders a custom JSON response" do
        get :index, params: { access_token: token_string }
        expect(response.header).to_not include("WWW-Authenticate")
        expect(response.content_type).to include("application/json")
        expect(response.status).to eq 403

        expect(json_response).not_to be_nil
        expect(json_response["error_message"]).to match("Forbidden")
      end
    end

    context "with a status and JSON custom render" do
      before do
        module ControllerActions
          remove_method :doorkeeper_forbidden_render_options
          def doorkeeper_forbidden_render_options(*)
            { json: { error_message: "Not Found" },
              respond_not_found_when_forbidden: true, }
          end
        end
      end

      it "overrides the default status code" do
        get :index, params: { access_token: token_string }
        expect(response.status).to eq 404
      end
    end

    context "with a text custom render" do
      before do
        module ControllerActions
          remove_method :doorkeeper_forbidden_render_options

          def doorkeeper_forbidden_render_options(*)
            { plain: "Forbidden" }
          end
        end
      end

      it "renders a custom status code and text response" do
        get :index, params: { access_token: token_string }
        expect(response.header).to_not include("WWW-Authenticate")
        expect(response.status).to eq 403
        expect(response.body).to eq("Forbidden")
      end
    end

    context "with a status and text custom render" do
      before do
        module ControllerActions
          remove_method :doorkeeper_forbidden_render_options

          def doorkeeper_forbidden_render_options(*)
            { respond_not_found_when_forbidden: true, plain: "Not Found" }
          end
        end
      end

      it "overrides the default status code" do
        get :index, params: { access_token: token_string }
        expect(response.status).to eq 404
      end
    end
  end

  context "when handle_auth_errors option is set to :raise" do
    subject { get :index, params: { access_token: token_string } }

    before do
      config_is_set(:handle_auth_errors, :raise)
    end

    controller do
      before_action :doorkeeper_authorize!
      include ControllerActions
    end

    context "when token is unknown" do
      it "raises Doorkeeper::Errors::TokenUnknown exception", token: :invalid do
        expect { subject }.to raise_error(Doorkeeper::Errors::TokenUnknown)
      end
    end

    context "when token is expired" do
      it "raises Doorkeeper::Errors::TokenExpired exception", token: :expired do
        expect { subject }.to raise_error(Doorkeeper::Errors::TokenExpired)
      end
    end

    context "when token is revoked" do
      it "raises Doorkeeper::Errors::TokenRevoked exception", token: :revoked do
        expect { subject }.to raise_error(Doorkeeper::Errors::TokenRevoked)
      end
    end

    context "when token is forbidden" do
      it "raises Doorkeeper::Errors::TokenForbidden exception", token: :forbidden do
        expect { subject }.to raise_error(Doorkeeper::Errors::TokenForbidden)
      end
    end

    context "when token is valid" do
      it "allows into index action", token: :valid do
        expect(response).to be_successful
      end
    end
  end
end


text:
incisive
========

**incisive** is a tiny library for handling CSV in Python. It's a wrapper for the csv module.

Usage
-----

* You can read a csv file like this::

    >>> iris = read_csv("data/iris.csv")
    >>> iris.next()
    {'petal_length': 1.4,
     'petal_width': 0.2,
     'sepal_length': 5.1,
     'sepal_width': 3.5,
     'species': 'setosa'}

`read_csv` returns a generator. Note that `incisive`, by default, tries to guess the type of the columns.

* Writing a CSV file can be done in two ways:

1. with a list of dictionaries::

    >>> data = [{'name': 'Lancelot', 'actor': 'John Cleese', 'color': 'blue'},
               {'name': 'Galahad', 'actor': 'Michael Palin', 'color': 'yellow'}]

    >>> write_csv('bridge.csv', ('name', 'actor', 'color'), data=data)

(the keys are the field names of the CSV file.)

2. or with just a list of rows::

    >>> rows = [('Lancelot', 'John Cleese', 'blue'),
            ('Galahad', 'Michael Palin', 'yellow')]

    >>> write_csv('bridge.csv', ('name', 'actor', 'color'), rows=rows)

Note that this second method requires that your field names correspond exactly
to the elements of your rows.

Features
--------

* Simple API
* Guess the types when it's possible
* Accept functions to specify the types


text:
@interface ZXEmailAddressParsedResultTestCase : XCTestCase

@end


text:
```
systemd-cgls
```

## PS with groups:
```
alias psc='ps xawf -eo pid,user,cgroup,args'
psc
```

## How to schedule some task
### Create task file inside `/etc/systemd/system/task.service`
```bash
[Unit]
Description=Run some task

[Service]
Type=simple
User=saikek
WorkingDirectory=/home/saikek/
ExecStart=/home/saikek/task.sh
ExecStop=/bin/kill -15
```

### Create execute timer inside `/etc/systemd/system/task.timer`
```bash
[Unit]
Description=Execute some task daily at 09:00

[Timer]
OnCalendar=*-*-* 09:00:00

[Install]
WantedBy=multi-user.target
```

Note that `[Timer]` section can have different useful units:
```bash
OnBootSec=15min # start timer only 15 minutes after boot
OnUnitActiveSec=1min # Execute every minute
```


text:
```html

```

### Import Statement

```

```

## Attributes

* attribute-name - attribute-description


text:
package com.example.microsoft.getstartednh;

/**
 * Created by Wesley on 7/1/2016.
 */

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.microsoft.windowsazure.notifications.NotificationsHandler;

public class MyHandler extends NotificationsHandler {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context ctx;

    @Override
    public void onReceive(Context context, Bundle bundle) {
        ctx = context;
        String nhMessage = bundle.getString("message");
        sendNotification(nhMessage);
        if (MainActivity.isVisible) {
            MainActivity.mainActivity.ToastNotify(nhMessage);
        }
    }

    private void sendNotification(String msg) {

        Intent intent = new Intent(ctx, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        mNotificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("Notification Hub Demo")
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setSound(defaultSoundUri)
                        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}


text:
---
uid: Cuemon.Extensions.Threading.Tasks
summary: *content
---
The Cuemon.Extensions.Threading.Tasks namespace contains extension methods that complements the System.Threading.Tasks namespace.

Availability: NET Standard 2.0, .NET 6.0

Complements: [System.Threading.Tasks namespace](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks?view=netstandard-2.0) 🔗

## Github branches 🖇

[development](https://github.com/gimlichael/Cuemon/tree/development/src/Cuemon.Extensions.Threading/Tasks) 🧪\
[release](https://github.com/gimlichael/Cuemon/tree/release/src/Cuemon.Extensions.Threading/Tasks) 🎬\
[master](https://github.com/gimlichael/Cuemon/tree/master/src/Cuemon.Extensions.Threading/Tasks) 🛡

## NuGet packages

📦 Focus Pack\
[Cuemon.Extensions.Threading (CI)](https://nuget.cuemon.net/packages/Cuemon.Extensions.Threading)\
[Cuemon.Extensions.Threading (Stable and Preview)](https://www.nuget.org/packages/Cuemon.Extensions.Threading)\
![NuGet Version](https://img.shields.io/nuget/v/Cuemon.Extensions.Threading?logo=nuget) ![NuGet Preview Version](https://img.shields.io/nuget/vpre/Cuemon.Extensions.Threading?logo=nuget) ![NuGet Downloads](https://img.shields.io/nuget/dt/Cuemon.Extensions.Threading?color=blueviolet&logo=nuget)
\
\
🏭 Productivity Pack\
[Cuemon.App (CI)](https://nuget.cuemon.net/packages/Cuemon.Core.App)\
[Cuemon.App (Stable and Preview)](https://www.nuget.org/packages/Cuemon.Core.App)\
![NuGet Version](https://img.shields.io/nuget/v/Cuemon.Core.App?logo=nuget) ![NuGet Preview Version](https://img.shields.io/nuget/vpre/Cuemon.Core.App?logo=nuget) ![NuGet Downloads](https://img.shields.io/nuget/dt/Cuemon.Core.App?color=blueviolet&logo=nuget)

### Extension Methods

|Type|Ext|Methods|
|--:|:-:|---|
|Task|⬇|`ContinueWithCapturedContext`, `ContinueWithCapturedContext{TResult}`, `ContinueWithSuppressedContext`, `ContinueWithSuppressedContext{TResult}`|


text:
class PointLight : public Light
{
public:
    PointLight();
    glm::vec3 GetDirection(const HitRec& hr);
    RGBColor L(const HitRec& hr);
    bool IsInShadow(const Ray& ray, const HitRec& hr) const;
    PointLight& SetColor(const RGBColor& color);
    RGBColor GetColor() const;
    PointLight& SetLightIntensity(const float ls);
    float GetLightIntensity() const;
    PointLight& SetLocation(const glm::vec3& location);
    glm::vec3 GetLocation() const;

private:
    float ls;
    RGBColor color;
    glm::vec3 location;
};


text:
Survey settings

    <form action="" id="survey-settings-form">
      <input type="text" placeholder="Survey name" class="large survey-name" name="name" value="<%= survey.name %>">
      <input type="text" placeholder="Survey city and state" class="large survey-location" name="location" value="<%= survey.location %>">

What data are you collecting?

        <input type="radio" value="point" name="type" <% if(survey.type === 'point') { %>checked <% } %>>
        Points on a map (for example, potholes, trees, data that doesn't correspond to an address)

        <input type="radio" value="parcel" name="type" <% if(survey.type !== 'point' && survey.type !== 'pointandparcel') { %>checked <% } %>>
        Data using a parcel map (for example, property, homes, businesses with an address)

        <input type="radio" value="pointandparcel" name="type" <% if(survey.type === 'pointandparcel') { %>checked <% } %>>
        We need to collect information about points and parcels

      <button class="save flex">Save changes</button>

Changes saved

We couldn't save your changes.

    </form>

    <a class="button mini flex" href="#/surveys/<%=survey.slug %>/settings/zones">Edit survey zones


text:
Compétences

  Type : <input type="text" id="type" [(ngModel)]="competence.type" />
  Nom : <input type="text" id="nom" [(ngModel)]="competence.name" />

Type : <input type="text" id="type" [(ngModel)]="newCompetence.type" (keyup.enter)="add(newCompetence)" />
Nom : <input type="text" id="nom" [(ngModel)]="newCompetence.name" (keyup.enter)="add(newCompetence)" />
<button (click)="add(newCompetence)" [disabled]="!newCompetenceCheck()">ajouter</button>


text:
#pragma once

#include "sdkconfig.h"
#include <esp_types.h>

#include "soc/soc_caps.h"
#include "driver/gpio.h"

#if SOC_GPIO_SUPPORT_SLP_SWITCH
#if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL
/**
  * @brief Emulate ESP32S2 behaviour to backup FUN_PU, FUN_PD information
  *
  * @note Need to be called before sleep.
  *
  * @return
  *      - ESP_OK Success
  */
esp_err_t gpio_sleep_pupd_config_apply(gpio_num_t gpio_num);

/**
  * @brief Emulate ESP32S2 behaviour to restore FUN_PU, FUN_PD information
  *
  * @note Need to be called after sleep.
  *
  * @return
  *      - ESP_OK Success
  */
esp_err_t gpio_sleep_pupd_config_unapply(gpio_num_t gpio_num);
#endif
#endif


text:
namespace atom {

ContentSettingsObserver::ContentSettingsObserver(
    content::RenderFrame* render_frame)
    : content::RenderFrameObserver(render_frame) {
  render_frame->GetWebFrame()->SetContentSettingsClient(this);
}

ContentSettingsObserver::~ContentSettingsObserver() {
}

bool ContentSettingsObserver::AllowDatabase(
    const blink::WebString& name,
    const blink::WebString& display_name,
    unsigned estimated_size) {
  blink::WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique())
    return false;
  auto origin = blink::WebStringToGURL(frame->GetSecurityOrigin().ToString());
  if (!origin.IsStandard())
    return false;
  return true;
}

bool ContentSettingsObserver::AllowStorage(bool local) {
  blink::WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique())
    return false;
  auto origin = blink::WebStringToGURL(frame->GetSecurityOrigin().ToString());
  if (!origin.IsStandard())
    return false;
  return true;
}

bool ContentSettingsObserver::AllowIndexedDB(
    const blink::WebString& name,
    const blink::WebSecurityOrigin& security_origin) {
  blink::WebFrame* frame = render_frame()->GetWebFrame();
  if (frame->GetSecurityOrigin().IsUnique() ||
      frame->Top()->GetSecurityOrigin().IsUnique())
    return false;
  auto origin = blink::WebStringToGURL(frame->GetSecurityOrigin().ToString());
  if (!origin.IsStandard())
    return false;
  return true;
}

void ContentSettingsObserver::OnDestruct() {
  delete this;
}

}  // namespace atom


text:
package core.utils

import javax.inject.Inject

import play.api.{ Configuration, Environment, Mode }
import play.api.mvc.{ Call, RequestHeader }

/**
 * A helper class which allows to build JS routes, based on the current environment.
 *
 * @param env  The Play environment.
 * @param conf The Play configuration.
 */
class JSRouter @Inject() (env: Environment, conf: Configuration) {

  /**
   * Build a absolute URL for the given route.
   *
   * @param route   The route to create the absolute URL.
   * @param request The current request header.
   * @return The absolute URL for the given route.
   */
  def absoluteURL(route: String)(implicit request: RequestHeader): String = {
    env.mode match {
      case Mode.Prod => Call("GET", route).absoluteURL()
      case _ =>
        val host = conf.getOptional[String]("ui.dev.url")
          .getOrElse(throw new RuntimeException("Cannot get `ui.dev.url` from config"))

        host.stripSuffix("/") + "/" + route.stripPrefix("/")
    }
  }
}


text:
from django.conf.urls import url
from . import views

app_name = 'frontend'
urlpatterns = [
    url('^$', views.index, name='index'),
    url(r'^classify$', views.classification, name='classify'),
    url(r'^crawl', views.crawl),
    url(r'^show', views.show),
]


text:
title: 'GetAttachmentCollection'
function: '$().SPServices'
web_service: 'Lists'
web_service_operation: 'GetAttachmentCollection'
---

## Notes

* This operation accepts a webURL option. This allows you to change the context for the operation to a different site. Using a GUID for the listName does NOT change the context as it does with the Object Model, so you need to use the webURL option as well if your list is in a different site.

## Example

This is an example from Matt Bramer ([iOnline247](http://www.codeplex.com/site/users/view/iOnline247)) from his [post in the discussions](https://spservices.codeplex.com/discussions/400677).
```javascript
$().SPServices({
  operation: "GetAttachmentCollection",
  listName: "MahAwesomeListName",
  ID: id,
  completefunc: function(xData, Status) {
    //console.log( Status );
    //console.log( xData.responseText );

    var output = "";

    //debugger;

    $(xData.responseXML).find("Attachments > Attachment").each(function(i, el) {
      var $node = $(this),
        filePath = $node.text(),
        arrString = filePath.split("/"),
        fileName = arrString[arrString.length - 1];

      output += "<a href='" + filePath + "' target='_blank'>" + fileName + "</a><br />";
    });

    $("#drop-zone").html(output);
  }
});
```