text:
package fm.pattern.tokamak.server.service;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import fm.pattern.tokamak.server.model.Audience;
import fm.pattern.tokamak.server.repository.Cache;
import fm.pattern.tokamak.server.repository.DataRepository;
import fm.pattern.valex.Result;

@Service
@SuppressWarnings("unchecked")
class AudienceServiceImpl extends DataServiceImpl<Audience> implements AudienceService {

	private final DataRepository repository;
	private final Cache cache;

	@Autowired
	AudienceServiceImpl(@Qualifier("dataRepository") DataRepository repository, @Qualifier("clientCache") Cache cache) {
		this.repository = repository;
		this.cache = cache;
	}

	@Transactional
	public Result<Audience> update(Audience audience) {
		Result<Audience> result = super.update(audience);
		if (result.accepted()) {
			cache.flush();
		}
		return result;
	}

	@Transactional
	public Result<Audience> delete(Audience audience) {
		Long count = repository.count(repository.sqlQuery("select count(_id) from ClientAudiences where audience_id = :id").setParameter("id", audience.getId()));
		if (count != 0) {
			return Result.reject("audience.delete.conflict", count, (count != 1 ? "clients are" : "client is"));
		}
		return repository.delete(audience);
	}

	@Transactional(readOnly = true)
	public Result<Audience> findById(String id) {
		return super.findById(id, Audience.class);
	}

	@Transactional(readOnly = true)
	public Result<List<Audience>> findExistingById(List<String> ids) {
		if (ids == null || ids.isEmpty()) {
			return Result.accept(new ArrayList<>());
		}

		List<String> parameters = ids.stream().filter(id -> isNotBlank(id)).collect(Collectors.toList());
		if (parameters == null || parameters.isEmpty()) {
			return Result.accept(new ArrayList<>());
		}

		return Result.accept(query("from Audiences where id in (:ids)").setParameter("ids", parameters).getResultList());
	}

	@Transactional(readOnly = true)
	public Result<Audience> findByName(String name) {
		if (isBlank(name)) {
			return Result.reject("audience.name.required");
		}

		Result<Audience> result = super.findBy("name", name, Audience.class);
		return result.accepted() ? result : Result.reject("audience.name.not_found", name);
	}

	@Transactional(readOnly = true)
	public Result<List<Audience>> list() {
		return Result.accept(repository.query("from Audiences order by name").getResultList());
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.terasology.core.world.generator.facetProviders;

import org.terasology.entitySystem.Component;
import org.terasology.math.TeraMath;
import org.terasology.math.geom.Vector2f;
import org.terasology.rendering.nui.properties.Range;
import org.terasology.utilities.procedural.BrownianNoise;
import org.terasology.utilities.procedural.PerlinNoise;
import org.terasology.utilities.procedural.SubSampledNoise;
import org.terasology.world.generation.Border3D;
import org.terasology.world.generation.ConfigurableFacetProvider;
import org.terasology.world.generation.GeneratingRegion;
import org.terasology.world.generation.Produces;
import org.terasology.world.generation.facets.SurfaceHumidityFacet;

/**
 * Defines surface humidity in the range [0..1] based on random noise.
 */
@Produces(SurfaceHumidityFacet.class)
public class PerlinHumidityProvider implements ConfigurableFacetProvider {
    private static final int SAMPLE_RATE = 4;

    private SubSampledNoise humidityNoise;

    private Configuration config = new Configuration();

    private long seed;

    public PerlinHumidityProvider() {
        // use default values
    }

    /**
     * @param config the config to use
     */
    public PerlinHumidityProvider(Configuration config) {
        this.config = config;
    }

    @Override
    public void setSeed(long seed) {
        this.seed = seed;
        reload();
    }

    @Override
    public void process(GeneratingRegion region) {
        Border3D border = region.getBorderForFacet(SurfaceHumidityFacet.class);
        SurfaceHumidityFacet facet = new SurfaceHumidityFacet(region.getRegion(), border);

        float[] noise = humidityNoise.noise(facet.getWorldRegion());
        for (int i = 0; i < noise.length; ++i) {
            noise[i] = TeraMath.clamp((noise[i] * 2.11f + 1f) * 0.5f);
        }
        facet.set(noise);
        region.setRegionFacet(SurfaceHumidityFacet.class, facet);
    }

    @Override
    public String getConfigurationName() {
        return "Humidity";
    }

    @Override
    public Component getConfiguration() {
        return config;
    }

    @Override
    public void setConfiguration(Component configuration) {
        this.config = (Configuration) configuration;
        reload();
    }

    private void reload() {
        float realScale = config.scale * 0.01f;
        Vector2f scale = new Vector2f(realScale, realScale);
        BrownianNoise brown = new BrownianNoise(new PerlinNoise(seed + 6), config.octaves);
        humidityNoise = new SubSampledNoise(brown, scale, SAMPLE_RATE);
    }

    public static class Configuration implements Component {
        @Range(min = 0, max = 10.0f, increment = 1f, precision = 0, description = "The number of noise octaves")
        public int octaves = 8;

        @Range(min = 0.01f, max = 5f, increment = 0.01f, precision = 2, description = "The noise scale")
        public float scale = 0.05f;
    }
}


text:
package org.apache.kafka.streams.kstream.internals;

import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.Consumed;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.TopologyTestDriver;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.ValueTransformer;
import org.apache.kafka.streams.kstream.ValueTransformerSupplier;
import org.apache.kafka.streams.kstream.ValueTransformerWithKey;
import org.apache.kafka.streams.kstream.ValueTransformerWithKeySupplier;
import org.apache.kafka.streams.processor.Processor;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.To;
import org.apache.kafka.streams.test.ConsumerRecordFactory;
import org.apache.kafka.test.MockProcessorSupplier;
import org.apache.kafka.test.StreamsTestUtils;
import org.junit.Test;

import java.util.Properties;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.fail;

public class KStreamTransformValuesTest {

    private String topicName = "topic";
    private final MockProcessorSupplier<Integer, Integer> supplier = new MockProcessorSupplier<>();
    private final ConsumerRecordFactory<Integer, Integer> recordFactory = new ConsumerRecordFactory<>(new IntegerSerializer(), new IntegerSerializer());
    private final Properties props = StreamsTestUtils.topologyTestConfig(Serdes.Integer(), Serdes.Integer());

    @Test
    public void testTransform() {
        StreamsBuilder builder = new StreamsBuilder();

        ValueTransformerSupplier<Number, Integer> valueTransformerSupplier =
            new ValueTransformerSupplier<Number, Integer>() {
                public ValueTransformer<Number, Integer> get() {
                    return new ValueTransformer<Number, Integer>() {

                        private int total = 0;

                        @Override
                        public void init(ProcessorContext context) {
                        }

                        @Override
                        public Integer transform(Number value) {
                            total += value.intValue();
                            return total;
                        }

                        @Override
                        public Integer punctuate(long timestamp) {
                            return null;
                        }

                        @Override
                        public void close() {
                        }
                    };
                }
            };

        final int[] expectedKeys = {1, 10, 100, 1000};

        KStream<Integer, Integer> stream;
        stream = builder.stream(topicName, Consumed.with(Serdes.Integer(), Serdes.Integer()));
        stream.transformValues(valueTransformerSupplier).process(supplier);

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props, 0L)) {
            for (int expectedKey : expectedKeys) {
                driver.pipeInput(recordFactory.create(topicName, expectedKey, expectedKey * 10, 0L));
            }
        }
        String[] expected = {"1:10", "10:110", "100:1110", "1000:11110"};

        assertArrayEquals(expected, supplier.theCapturedProcessor().processed.toArray());
    }

    @Test
    public void testTransformWithKey() {
        StreamsBuilder builder = new StreamsBuilder();

        ValueTransformerWithKeySupplier<Integer, Number, Integer> valueTransformerSupplier =
                new ValueTransformerWithKeySupplier<Integer, Number, Integer>() {
            public ValueTransformerWithKey<Integer, Number, Integer> get() {
                return new ValueTransformerWithKey<Integer, Number, Integer>() {
                    private int total = 0;
                    @Override
                    public void init(final ProcessorContext context) {

                    }
                    @Override
                    public Integer transform(final Integer readOnlyKey, final Number value) {
                        total += value.intValue() + readOnlyKey;
                        return total;
                    }

                    @Override
                    public void close() {

                    }
                };
            }
        };

        final int[] expectedKeys = {1, 10, 100, 1000};

        KStream<Integer, Integer> stream;
        stream = builder.stream(topicName, Consumed.with(Serdes.Integer(), Serdes.Integer()));
        stream.transformValues(valueTransformerSupplier).process(supplier);

        try (final TopologyTestDriver driver = new TopologyTestDriver(builder.build(), props, 0L)) {
            for (int expectedKey : expectedKeys) {
                driver.pipeInput(recordFactory.create(topicName, expectedKey, expectedKey * 10, 0L));
            }
        }
        String[] expected = {"1:11", "10:121", "100:1221", "1000:12221"};

        assertArrayEquals(expected, supplier.theCapturedProcessor().processed.toArray());
    }

    @Test
    public void shouldNotAllowValueTransformerToCallInternalProcessorContextMethods() {
        final BadValueTransformer badValueTransformer = new BadValueTransformer();
        final KStreamTransformValues<Integer, Integer, Integer> transformValue = new KStreamTransformValues<>(new InternalValueTransformerWithKeySupplier<Integer, Integer, Integer>() {
            @Override
            public InternalValueTransformerWithKey<Integer, Integer, Integer> get() {
                return new InternalValueTransformerWithKey<Integer, Integer, Integer>() {
                    @Override
                    public Integer punctuate(long timestamp) {
                        throw new StreamsException("ValueTransformerWithKey#punctuate should not be called.");
                    }

                    @Override
                    public void init(final ProcessorContext context) {
                        badValueTransformer.init(context);
                    }

                    @Override
                    public Integer transform(final Integer readOnlyKey, final Integer value) {
                        return badValueTransformer.transform(readOnlyKey, value);
                    }

                    @Override
                    public void close() {
                        badValueTransformer.close();
                    }
                };
            }
        });

        final Processor transformValueProcessor = transformValue.get();
        transformValueProcessor.init(null);

        try {
            transformValueProcessor.process(null, 0);
            fail("should not allow call to context.forward() within ValueTransformer");
        } catch (final StreamsException e) {
            // expected
        }

        try {
            transformValueProcessor.process(null, 1);
            fail("should not allow call to context.forward() within ValueTransformer");
        } catch (final StreamsException e) {
            // expected
        }

        try {
            transformValueProcessor.process(null, 2);
            fail("should not allow call to context.forward() within ValueTransformer");
        } catch (final StreamsException e) {
            // expected
        }

        try {
            transformValueProcessor.process(null, 3);
            fail("should not allow call to context.forward() within ValueTransformer");
        } catch (final StreamsException e) {
            // expected
        }
    }

    private static final class BadValueTransformer implements ValueTransformerWithKey<Integer, Integer, Integer> {
        private ProcessorContext context;

        @Override
        public void init(final ProcessorContext context) {
            this.context = context;
        }

        @Override
        public Integer transform(final Integer key, final Integer value) {
            if (value == 0) {
                context.forward(null, null);
            }
            if (value == 1) {
                context.forward(null, null, (String) null);
            }
            if (value == 2) {
                context.forward(null, null, 0);
            }
            if (value == 3) {
                context.forward(null, null, To.all());
            }
            throw new RuntimeException("Should never happen in this test");
        }

        @Override
        public void close() { }
    }
}


text:
#region Using Statements
using MarkLight.Views.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.EventSystems;
#endregion

namespace MarkLight.Views.UI
{
    /// <summary>
    /// Virtualized items to be presented on demand.
    /// </summary>
    [HideInPresenter]
    public class VirtualizedItemsContainer : UIView
    {
        #region Fields

        public View Owner;

        #endregion

        #region Methods

        /// <summary>
        /// Initializes the view.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();
        }

        #endregion

        #region Properties
        #endregion
    }
}


text:
import Cookies from './cookies';

let config = {
  urlPrefix: "",
  visitsUrl: "/ahoy/visits",
  eventsUrl: "/ahoy/events",
  page: null,
  platform: "Web",
  useBeacon: true,
  startOnReady: true,
  trackVisits: true,
  cookies: true,
  cookieDomain: null,
  headers: {},
  visitParams: {},
  withCredentials: false,
  visitDuration: 4 * 60, // default 4 hours
  visitorDuration: 2 * 365 * 24 * 60 // default 2 years
};

let ahoy = window.ahoy || window.Ahoy || {};

ahoy.configure = function (options) {
  for (let key in options) {
    if (options.hasOwnProperty(key)) {
      config[key] = options[key];
    }
  }
};

// legacy
ahoy.configure(ahoy);

let $ = window.jQuery || window.Zepto || window.$;
let visitId, visitorId, track;
let isReady = false;
let queue = [];
let canStringify = typeof(JSON) !== "undefined" && typeof(JSON.stringify) !== "undefined";
let eventQueue = [];

function visitsUrl() {
  return config.urlPrefix + config.visitsUrl;
}

function eventsUrl() {
  return config.urlPrefix + config.eventsUrl;
}

function isEmpty(obj) {
  return Object.keys(obj).length === 0;
}

function canTrackNow() {
  return (config.useBeacon || config.trackNow) && isEmpty(config.headers) && canStringify && typeof(window.navigator.sendBeacon) !== "undefined" && !config.withCredentials;
}

function serialize(object) {
  let data = new FormData();
  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      data.append(key, object[key]);
    }
  }
  return data;
}

// cookies

function setCookie(name, value, ttl) {
  Cookies.set(name, value, ttl, config.cookieDomain || config.domain);
}

function getCookie(name) {
  return Cookies.get(name);
}

function destroyCookie(name) {
  Cookies.set(name, "", -1);
}

function log(message) {
  if (getCookie("ahoy_debug")) {
    window.console.log(message);
  }
}

function setReady() {
  let callback;
  while ((callback = queue.shift())) {
    callback();
  }
  isReady = true;
}

ahoy.ready = function (callback) {
  if (isReady) {
    callback();
  } else {
    queue.push(callback);
  }
};

function matchesSelector(element, selector) {
  let matches = element.matches ||
    element.matchesSelector ||
    element.mozMatchesSelector ||
    element.msMatchesSelector ||
    element.oMatchesSelector ||
    element.webkitMatchesSelector;

  if (matches) {
    if (matches.apply(element, [selector])) {
      return element;
    } else if (element.parentElement) {
      return matchesSelector(element.parentElement, selector);
    }
    return null;
  } else {
    log("Unable to match");
    return null;
  }
}

function onEvent(eventName, selector, callback) {
  document.addEventListener(eventName, function (e) {
    let matchedElement = matchesSelector(e.target, selector);
    if (matchedElement) {
      callback.call(matchedElement, e);
    }
  });
}

// http://beeker.io/jquery-document-ready-equivalent-vanilla-javascript
function documentReady(callback) {
  if (document.readyState === "interactive" || document.readyState === "complete") {
    setTimeout(callback, 0);
  } else {
    document.addEventListener("DOMContentLoaded", callback);
  }
}

// https://stackoverflow.com/a/2117523/1177228
function generateId() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    let r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
  });
}

function saveEventQueue() {
  if (config.cookies && canStringify) {
    setCookie("ahoy_events", JSON.stringify(eventQueue), 1);
  }
}

// from rails-ujs

function csrfToken() {
  let meta = document.querySelector("meta[name=csrf-token]");
  return meta && meta.content;
}

function csrfParam() {
  let meta = document.querySelector("meta[name=csrf-param]");
  return meta && meta.content;
}

function CSRFProtection(xhr) {
  let token = csrfToken();
  if (token) xhr.setRequestHeader("X-CSRF-Token", token);
}

function sendRequest(url, data, success) {
  if (canStringify) {
    if ($ && $.ajax) {
      $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: CSRFProtection,
        success: success,
        headers: config.headers,
        xhrFields: {
          withCredentials: config.withCredentials
        }
      });
    } else {
      let xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.withCredentials = config.withCredentials;
      xhr.setRequestHeader("Content-Type", "application/json");
      for (let header in config.headers) {
        if (config.headers.hasOwnProperty(header)) {
          xhr.setRequestHeader(header, config.headers[header]);
        }
      }
      xhr.onload = function() {
        if (xhr.status === 200) {
          success();
        }
      };
      CSRFProtection(xhr);
      xhr.send(JSON.stringify(data));
    }
  }
}

function eventData(event) {
  let data = {
    events: [event]
  };
  if (config.cookies) {
    data.visit_token = event.visit_token;
    data.visitor_token = event.visitor_token;
  }
  delete event.visit_token;
  delete event.visitor_token;
  return data;
}

function trackEvent(event) {
  ahoy.ready( function () {
    sendRequest(eventsUrl(), eventData(event), function() {
      // remove from queue
      for (let i = 0; i < eventQueue.length; i++) {
        if (eventQueue[i].id == event.id) {
          eventQueue.splice(i, 1);
          break;
        }
      }
      saveEventQueue();
    });
  });
}

function trackEventNow(event) {
  ahoy.ready( function () {
    let data = eventData(event);
    let param = csrfParam();
    let token = csrfToken();
    if (param && token) data[param] = token;
    // stringify so we keep the type
    data.events_json = JSON.stringify(data.events);
    delete data.events;
    window.navigator.sendBeacon(eventsUrl(), serialize(data));
  });
}

function page() {
  return config.page || window.location.pathname;
}

function presence(str) {
  return (str && str.length > 0) ? str : null;
}

function cleanObject(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key] === null) {
        delete obj[key];
      }
    }
  }
  return obj;
}

function eventProperties() {
  return cleanObject({
    tag: this.tagName.toLowerCase(),
    id: presence(this.id),
    "class": presence(this.className),
    page: page(),
    section: getClosestSection(this)
  });
}

function getClosestSection(element) {
  for ( ; element && element !== document; element = element.parentNode) {
    if (element.hasAttribute('data-section')) {
      return element.getAttribute('data-section');
    }
  }

  return null;
}

function createVisit() {
  isReady = false;

  visitId = ahoy.getVisitId();
  visitorId = ahoy.getVisitorId();
  track = getCookie("ahoy_track");

  if (config.cookies === false || config.trackVisits === false) {
    log("Visit tracking disabled");
    setReady();
  } else if (visitId && visitorId && !track) {
    // TODO keep visit alive?
    log("Active visit");
    setReady();
  } else {
    if (!visitId) {
      visitId = generateId();
      setCookie("ahoy_visit", visitId, config.visitDuration);
    }

    // make sure cookies are enabled
    if (getCookie("ahoy_visit")) {
      log("Visit started");

      if (!visitorId) {
        visitorId = generateId();
        setCookie("ahoy_visitor", visitorId, config.visitorDuration);
      }

      let data = {
        visit_token: visitId,
        visitor_token: visitorId,
        platform: config.platform,
        landing_page: window.location.href,
        screen_width: window.screen.width,
        screen_height: window.screen.height,
        js: true
      };

      // referrer
      if (document.referrer.length > 0) {
        data.referrer = document.referrer;
      }

      for (let key in config.visitParams) {
        if (config.visitParams.hasOwnProperty(key)) {
          data[key] = config.visitParams[key];
        }
      }

      log(data);

      sendRequest(visitsUrl(), data, function () {
        // wait until successful to destroy
        destroyCookie("ahoy_track");
        setReady();
      });
    } else {
      log("Cookies disabled");
      setReady();
    }
  }
}

ahoy.getVisitId = ahoy.getVisitToken = function () {
  return getCookie("ahoy_visit");
};

ahoy.getVisitorId = ahoy.getVisitorToken = function () {
  return getCookie("ahoy_visitor");
};

ahoy.reset = function () {
  destroyCookie("ahoy_visit");
  destroyCookie("ahoy_visitor");
  destroyCookie("ahoy_events");
  destroyCookie("ahoy_track");
  return true;
};

ahoy.debug = function (enabled) {
  if (enabled === false) {
    destroyCookie("ahoy_debug");
  } else {
    setCookie("ahoy_debug", "t", 365 * 24 * 60); // 1 year
  }
  return true;
};

ahoy.track = function (name, properties) {
  // generate unique id
  let event = {
    name: name,
    properties: properties || {},
    time: (new Date()).getTime() / 1000.0,
    id: generateId(),
    js: true
  };

  ahoy.ready( function () {
    if (config.cookies && !ahoy.getVisitId()) {
      createVisit();
    }

    ahoy.ready( function () {
      log(event);

      event.visit_token = ahoy.getVisitId();
      event.visitor_token = ahoy.getVisitorId();

      if (canTrackNow()) {
        trackEventNow(event);
      } else {
        eventQueue.push(event);
        saveEventQueue();

        // wait in case navigating to reduce duplicate events
        setTimeout( function () {
          trackEvent(event);
        }, 1000);
      }
    });
  });

  return true;
};

ahoy.trackView = function (additionalProperties) {
  let properties = {
    url: window.location.href,
    title: document.title,
    page: page()
  };

  if (additionalProperties) {
    for(let propName in additionalProperties) {
      if (additionalProperties.hasOwnProperty(propName)) {
        properties[propName] = additionalProperties[propName];
      }
    }
  }
  ahoy.track("$view", properties);
};

ahoy.trackClicks = function (selector) {
  if (selector === undefined) {
    throw new Error("Missing selector");
  }
  onEvent("click", selector, function (e) {
    let properties = eventProperties.call(this, e);
    properties.text = properties.tag == "input" ? this.value : (this.textContent || this.innerText || this.innerHTML).replace(/[\s\r\n]+/g, " ").trim();
    properties.href = this.href;
    ahoy.track("$click", properties);
  });
};

ahoy.trackSubmits = function (selector) {
  if (selector === undefined) {
    throw new Error("Missing selector");
  }
  onEvent("submit", selector, function (e) {
    let properties = eventProperties.call(this, e);
    ahoy.track("$submit", properties);
  });
};

ahoy.trackChanges = function (selector) {
  log("trackChanges is deprecated and will be removed in 0.5.0");
  if (selector === undefined) {
    throw new Error("Missing selector");
  }
  onEvent("change", selector, function (e) {
    let properties = eventProperties.call(this, e);
    ahoy.track("$change", properties);
  });
};

// push events from queue
try {
  eventQueue = JSON.parse(getCookie("ahoy_events") || "[]");
} catch (e) {
  // do nothing
}

for (let i = 0; i < eventQueue.length; i++) {
  trackEvent(eventQueue[i]);
}

ahoy.start = function () {
  createVisit();

  ahoy.start = function () {};
};

documentReady(function() {
  if (config.startOnReady) {
    ahoy.start();
  }
});

export default ahoy;


text:
class CreateExtensions < ActiveRecord::Migration
  def change
    create_table :extensions do |t|
      t.string :name
      t.timestamps null: false
    end
  end
end


text:
package org.bbottema.javareflection.valueconverter;

import lombok.experimental.UtilityClass;
import org.bbottema.javareflection.LookupCaches;
import org.bbottema.javareflection.util.MiscUtil;
import org.bbottema.javareflection.util.graph.GraphHelper;
import org.bbottema.javareflection.util.graph.Node;
import org.bbottema.javareflection.valueconverter.converters.BooleanConverters;
import org.bbottema.javareflection.valueconverter.converters.CharacterConverters;
import org.bbottema.javareflection.valueconverter.converters.FileConverters;
import org.bbottema.javareflection.valueconverter.converters.NumberConverters;
import org.bbottema.javareflection.valueconverter.converters.StringConverters;
import org.bbottema.javareflection.valueconverter.converters.UUIDConverters;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.util.Arrays.asList;
import static org.bbottema.javareflection.util.MiscUtil.trustedCast;

/**
 * This reflection utility class predicts (and converts) which types a specified value can be converted into. It can only do conversions of
 * known 'common' types, which include:
 *

 *
Any {@link Number} type (Integer, Character, Double, byte, etc.)

 *
String

 *
Boolean

 *
Character

 *

 * In addition enums can be converted as well.
 *
 * @see IncompatibleTypeException
 */
@UtilityClass
public final class ValueConversionHelper {

	/**
	 * A list of all primitive number types.
	 */
	private static final List<Class<?>> PRIMITIVE_NUMBER_TYPES = asList(new Class<?>[] { byte.class, short.class, int.class, long.class,
			float.class, double.class });

	/**
	 * Contains all user-provided converters. User converters also act as intermediate converters, ie. if a user converter can go to int,
	 * double is automatically supported as well as common conversion.
	 */
	// TODO make value converters name based instead of type based for lookups and naming in the conversion graph
	// TODO once working by name, replace Map<from, Map<To, converter>> to Map<from, Map<To, Collection<converter>>>.
	// The above enables us to have multiple converters for the same targetType
	private static final Map<Class<?>, Map<Class<?>, ValueFunction<Object, Object>>> valueConverters = new HashMap<>();

	/**
	 * Graph of from-to type conversions so we can calculate shortes conversion path between two types.
	 */
	private static final Map<Class<?>, Node<Class<?>>> converterGraph = new HashMap<>();

	private static final int LOW_CONVERTER_PRIORITY = 10; // higher edge weight, heavier in cost
	private static final int HIGH_CONVERTER_PRIORITY = 1; // lower edge weight, lighter in cost

	static {
		resetDefaultConverters();
	}

	public static void resetDefaultConverters() {
		valueConverters.clear();

		final Collection<ValueFunction<?, ?>> defaultConverters = new HashSet<>();
		defaultConverters.addAll(NumberConverters.NUMBER_CONVERTERS);
		defaultConverters.addAll(BooleanConverters.BOOLEAN_CONVERTERS);
		defaultConverters.addAll(CharacterConverters.CHARACTER_CONVERTERS);
		defaultConverters.addAll(StringConverters.STRING_CONVERTERS);
		defaultConverters.addAll(UUIDConverters.UUID_CONVERTERS);
		defaultConverters.addAll(FileConverters.FILE_CONVERTERS);

		for (ValueFunction<?, ?> numberConverter : defaultConverters) {
			registerValueConverter(numberConverter);
		}
	}

	/**
	 * Registers a user-provided converter. User converters also act as intermediate converters, ie. if a user converter can go to int,
	 * double is automatically supported as well as common conversion.
	 */
	@SuppressWarnings({"unused", "WeakerAccess"})
	public static void registerValueConverter(final ValueFunction<?, ?> userConverter) {
		if (!valueConverters.containsKey(userConverter.getFromType())) {
			valueConverters.put(userConverter.getFromType(), new HashMap<Class<?>, ValueFunction<Object, Object>>());
		}
		valueConverters.get(userConverter.getFromType()).put(userConverter.getTargetType(),
				MiscUtil.<ValueFunction<Object, Object>>trustedCast(userConverter));

		updateTypeGraph();
		LookupCaches.resetCache();
	}

	private static void updateTypeGraph() {
		converterGraph.clear();

		// add nodes and edges
		for (Map.Entry<Class<?>, Map<Class<?>, ValueFunction<Object, Object>>> convertersForFromType : valueConverters.entrySet()) {
			Class<?> fromType = convertersForFromType.getKey();
			Node<Class<?>> fromNode = converterGraph.containsKey(fromType) ? converterGraph.get(fromType) : new Node<Class<?>>(fromType);
			converterGraph.put(fromType, fromNode);
			for (Class<?> toType : convertersForFromType.getValue().keySet()) {
				Node<Class<?>> toNode = converterGraph.containsKey(toType) ? converterGraph.get(toType) : new Node<Class<?>>(toType);
				converterGraph.put(toType, toNode);
				ValueFunction<Object, Object> converter = convertersForFromType.getValue().get(toType);
				fromNode.getToNodes().put(toNode, determineConversionCost(converter)); // edge
			}
		}
	}

	private static Integer determineConversionCost(ValueFunction<Object, Object> converter) {
		if (converter.getFromType() == converter.getTargetType()) {
			return 0;
		} else {
			String converterPackage = ValueConversionHelper.class.getPackage().toString();
			boolean isSystemConverter = converter.getClass().getPackage().toString().contains(converterPackage);
			return isSystemConverter ? LOW_CONVERTER_PRIORITY : HIGH_CONVERTER_PRIORITY;
		}
	}

	@SuppressWarnings("WeakerAccess")
	public static boolean isCommonType(final Class<?> c) {
		Map<Class<?>, ValueFunction<Object, Object>> classValueFunctionMap = valueConverters.get(c);
		return valueConverters.containsKey(c) &&
				(classValueFunctionMap.keySet().size() > 1 ||
				!classValueFunctionMap.keySet().contains(String.class));
	}

	/**
	 * Determines to which types the specified value (its type) can be converted to. Most common types can be converted to most other common
	 * types and all types can be converted into a String using {@link Object#toString()}.
	 *
	 * @param fromType The input type to find compatible conversion output types for
	 * @return The list with compatible conversion output types.
	 */
	@SuppressWarnings("WeakerAccess")
	@NotNull
	public static Set<Class<?>> collectRegisteredCompatibleTargetTypes(final Class<?> fromType) {
		Set<Class<?>> compatibleTypes = new HashSet<>(Collections.<Class<?>>singleton(fromType));
		if (converterGraph.containsKey(fromType)) {
			for (Node<Class<?>> reachableNode : GraphHelper.findReachableNodes(converterGraph.get(fromType))) {
				compatibleTypes.add(reachableNode.getType());
			}
		}
		return compatibleTypes;
	}

	/**
	 * @return Whether targetType can be derived from fromType.
	 */
	@SuppressWarnings("unused")
	public static boolean typesCompatible(final Class<?> fromType, final Class<?> targetType) {
		if (targetType.isAssignableFrom(fromType)) {
			return true;
		} else {
			for (Class<?> registeredCompatibleTargetType : collectCompatibleTargetTypes(fromType)) {
				if (targetType.isAssignableFrom(registeredCompatibleTargetType)) {
					return true;
				}
			}
		}
		return false;
	}

	public static Set<Class<?>> collectCompatibleTargetTypes(Class<?> fromType) {
		checkForAndRegisterToStringConverter(fromType);

		Set<Class<?>> compatibleTargetTypes = new HashSet<>();
		Node<Class<?>> fromNode = converterGraph.get(fromType);
		for (Map<Class<?>, ValueFunction<Object, Object>> convertersForFromTypes : valueConverters.values()) {
			for (Class<?> targetType : convertersForFromTypes.keySet()) {
				if (isCompatibleTargetType(fromNode, targetType)) {
					compatibleTargetTypes.add(targetType);
				}
			}
		}
		return compatibleTargetTypes;
	}

	private static boolean isCompatibleTargetType(Node<Class<?>> fromNode, Class<?> targetType) {
		for (Node<Class<?>> toNode : collectTypeCompatibleNodes(targetType)) {
			if (GraphHelper.isPathPossible(fromNode, toNode)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Converts a list of values to their converted form, as indicated by the specified targetTypes.
	 *
	 * @param args The list with value to convert.
	 * @param targetTypes The output types the specified values should be converted into.
	 * @param useOriginalValueWhenIncompatible Indicates whether an exception should be thrown for inconvertible values or that the original
	 *            value should be used instead. Basically change mode to "convert what you can".
	 * @return Array containing converted values where convertible or the original value otherwise.
	 * @throws IncompatibleTypeException Thrown when unable to convert and not use the original value.
	 */
	@NotNull
	public static Object[] convert(final Object[] args, final Class<?>[] targetTypes, boolean useOriginalValueWhenIncompatible)
			throws IncompatibleTypeException {
		if (args.length != targetTypes.length) {
			throw new IllegalStateException("number of target types should match the number of arguments");
		}
		final Object[] convertedValues = new Object[args.length];
		for (int i = 0; i < targetTypes.length; i++) {
			try {
				convertedValues[i] = convert(args[i], targetTypes[i]);
			} catch (IncompatibleTypeException e) {
				if (useOriginalValueWhenIncompatible) {
					// simply take over the original value and keep converting where possible
					convertedValues[i] = args[i];
				} else {
					throw e;
				}
			}
		}
		return convertedValues;
	}

	/**
	 * Converts a single value into a target output datatype. Only input/output pairs should be passed in here according to the possible
	 * conversions as determined by {@link #collectRegisteredCompatibleTargetTypes(Class)}.

	 *

	 * First checks if the input and output types aren't the same. Then the conversions are checked for and done in the following order:
	 *

	 *
conversion to String (value.toString())

	 *

	 *
	 * @param fromValue The value to convert.
	 * @param targetType The target data type the value should be converted into.
	 * @return The converted value according the specified target data type.
	 * @throws IncompatibleTypeException Thrown by the various convert() methods used.
	 */
	@SuppressWarnings("unchecked")
	@Nullable
	public static <T> T convert(@Nullable final Object fromValue, final Class<T> targetType)
			throws IncompatibleTypeException {
		if (fromValue == null) {
			return null;
		} else if (targetType.isAssignableFrom(fromValue.getClass())) {
			return convertWithoutConversionGraph(fromValue, targetType);
		} else {
			checkForAndRegisterEnumConverter(targetType);
			checkForAndRegisterToStringConverter(fromValue.getClass());
			return convertWithConversionGraph(fromValue, targetType);
		}
	}

	@NotNull
	private static <T> T convertWithoutConversionGraph(final Object fromValue, final Class<T> targetType) {
		if (valueConverters.containsKey(fromValue.getClass())) {
			Map<Class<?>, ValueFunction<Object, Object>> fromConverters = valueConverters.get(fromValue.getClass());
			if (fromConverters.containsKey(targetType)) {
				try {
					return trustedCast(fromConverters.get(targetType).convertValue(fromValue));
				} catch (IncompatibleTypeException e) {
					// ignore
				}
			}
		}
		return trustedCast(fromValue);
	}

	@SuppressWarnings("unchecked")
	@NotNull
	private static <T> T convertWithConversionGraph(final Object fromValue, final Class<T> targetType) {
		final Node<Class<?>> fromNode = converterGraph.get(fromValue.getClass());

		final List<IncompatibleTypeException> incompatibleTypeExceptions = new ArrayList<>();

		if (fromNode != null) {
			for (Node<Class<?>> toNode : collectTypeCompatibleNodes(targetType)) {
				for (List<Node<Class<?>>> conversionPathAscending : GraphHelper.findAllPathsAscending(fromNode, toNode)) {
					try {
						Object evolvingValueToConvert = fromValue;
							for (Node<Class<?>> nodeInConversionPath : conversionPathAscending) {
							Class<?> currentFromType = evolvingValueToConvert.getClass();
							Class<?> currentToType = nodeInConversionPath.getType();
							evolvingValueToConvert = valueConverters.get(currentFromType).get(currentToType).convertValue(evolvingValueToConvert);
						}
						return (T) evolvingValueToConvert;
					} catch (IncompatibleTypeException e) {
						incompatibleTypeExceptions.add(e);
						// keep trying conversion paths...
					}
				}
			}
		}

		// conversion paths exhausted.
		throw new IncompatibleTypeException(fromValue, fromValue.getClass(), targetType, incompatibleTypeExceptions);
	}

	@SuppressWarnings("unchecked")
	private static <T extends Enum<T>> void checkForAndRegisterEnumConverter(Class<?> targetType) {
		if (Enum.class.isAssignableFrom(targetType)) {
			if (!valueConverters.get(String.class).containsKey(targetType)) {
				registerValueConverter(StringConverters.produceStringToEnumConverter((Class<T>) targetType));
			}
		}
	}

	private static void checkForAndRegisterToStringConverter(Class<?> fromType) {
		if (!valueConverters.containsKey(fromType) || !valueConverters.get(fromType).containsKey(String.class)) {
			registerValueConverter(StringConverters.produceTypeToStringConverter(fromType));
		}
	}

	static Set<Node<Class<?>>> collectTypeCompatibleNodes(Class<?> targetType) {
		final Set<Node<Class<?>>> typeCompatibleNodes = new HashSet<>();
		for (Map.Entry<Class<?>, Node<Class<?>>> converterNodeEntry : converterGraph.entrySet()) {
			if (targetType.isAssignableFrom(converterNodeEntry.getKey())) {
				typeCompatibleNodes.add(converterNodeEntry.getValue());
			}
		}
		return typeCompatibleNodes;
	}

	/**
	 * Returns whether a {@link Class} is a primitive number.
	 *
	 * @param targetType The class to check whether it's a number.
	 * @return Whether specified class is a primitive number.
	 */
	@SuppressWarnings("WeakerAccess")
	public static boolean isPrimitiveNumber(final Class<?> targetType) {
		return PRIMITIVE_NUMBER_TYPES.contains(targetType);
	}
}


text:
Figuring out how to use the CK9561 music chip with 4 sound effects - alarm/siren/weapon sounds that sound strangely familiar if you have ever walked through a toy department at Christmas!

![Build](./assets/CK9561_build.jpg?raw=true)

Here's a quick demo..

[![clip](https://img.youtube.com/vi/wS0hG0z_4rM/0.jpg)](https://www.youtube.com/watch?v=wS0hG0z_4rM)

## Notes

The CK9561 is the latest in a series of music effects chips I've been testing.
The CK9561 is sometimes labelled KD9561 of XK9561 - I presume these are just different manufacturer's names for boards based on the same chip.

The module,with pins attached for testing on a breadboard:

![Build](./assets/CK9561_module.jpg?raw=true)

## Usage and Schematic

The chip requires just a few external components to operate:

* the resistor (100kΩ-390kΩ) controls the speed of the effect - higher resistance slows the effect down
* a small signal NPN transistor (I used a 2N3904) for controlling the speaker
* and switches - not shown in the schematic below:
    * the effect is "always on", so a switch in the power line can be used for on/off control
    * switching connections "1" and "2" between unconnected/pulled-low/pulled-high select from the range of sound effects according to the following table

| Pad 1 | Pad 2      | Effect      |
|-------|------------|-------------|
| n/c   | n/c        | alarm       |
| high  | n/c or low | fire alarm  |
| low   | n/c        | ambulance   |
| any   | high       | machine gun |

![Schematic](./assets/CK9561_schematic.jpg?raw=true)

Testing on a breadboard:

![Build](./assets/CK9561_bb_build.jpg?raw=true)

I also added the chip to one of my "audio effects" copper-clad test boards. I've added a few components:

* resistor is 100kΩ fixed + 200kΩ variable resistor
* mini push-button switch on the power connection (effect on/off)
* a 3-position switch for toggling pad 1 between unconnected/pulled-low/pulled-high
* mini push-button switch on pad 2
* external 8Ω speaker

![Build](./assets/CK9561_build.jpg?raw=true)

## Credits and References

* [KD9561 CK9561 Alarm Module](https://www.aliexpress.com/item/32893135639.html) - from a seller on aliexpress
* [2N3904 datasheet](https://www.futurlec.com/Transistors/2N3904.shtml)


text:
<model>
    <mount>//OPNsense/postfix/general</mount>
    <description>Postfix configuration</description>
    <version>1.2.3</version>
    <items>
        <enabled type="BooleanField">
            <default>0</default>
            <Required>Y</Required>
        </enabled>
        <myhostname type="TextField">
            <default></default>
            <Required>N</Required>
        </myhostname>
        <mydomain type="TextField">
            <default></default>
            <Required>N</Required>
        </mydomain>
        <myorigin type="TextField">
            <default></default>
            <Required>N</Required>
        </myorigin>
        <inet_interfaces type="TextField">
            <default>all</default>
            <Required>Y</Required>
        </inet_interfaces>
        <inet_port type="PortField">
            <default>25</default>
            <Required>Y</Required>
        </inet_port>
        <bind_address type="NetworkField">
            <Required>N</Required>
            <AddressFamily>ipv4</AddressFamily>
        </bind_address>
        <bind_address6 type="NetworkField">
            <Required>N</Required>
            <AddressFamily>ipv6</AddressFamily>
        </bind_address6>
        <mynetworks type="CSVListField">
            <default>127.0.0.0/8,[::ffff:127.0.0.0]/104,[::1]/128</default>
            <Required>Y</Required>
        </mynetworks>
        <banner type="TextField">
            <default></default>
            <Required>N</Required>
        </banner>
        <message_size_limit type="IntegerField">
            <default>51200000</default>
            <Required>Y</Required>
        </message_size_limit>
        <masquerade_domains type="CSVListField">
            <Required>N</Required>
            <mask>/^([0-9a-z\.\-\_]{1,128})(,[0-9a-z\.\-\_]{1,128})*$/ui</mask>
            <ValidationMessage>Only up to 128 of the following characters are allowed: 0-9a-zA-Z.-_</ValidationMessage>
        </masquerade_domains>
        <disable_ssl type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </disable_ssl>
        <disable_weak_ciphers type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </disable_weak_ciphers>
        <tlswrappermode type="BooleanField">
            <default>0</default>
            <Required>Y</Required>
        </tlswrappermode>
        <certificate type="CertificateField">
            <Type>cert</Type>
            <Required>N</Required>
        </certificate>
        <ca type="CertificateField">
            <Type>ca</Type>
            <Required>N</Required>
        </ca>
        <smtpclient_security type="OptionField">
            <default>may</default>
            <Required>Y</Required>
            <OptionValues>
                <none>none</none>
                <may>may</may>
                <encrypt>encrypt</encrypt>
            </OptionValues>
        </smtpclient_security>
        <relayhost type="TextField">
            <Required>N</Required>
            <mask>/^([0-9a-zA-Z.:\-\[\]]){1,64}$/u</mask>
            <ValidationMessage>Only 64 of the following characters are allowed: 0-9a-zA-Z.:-[]</ValidationMessage>
        </relayhost>
        <smtpauth_enabled type="BooleanField">
            <default>0</default>
            <Required>Y</Required>
        </smtpauth_enabled>
        <smtpauth_user type="TextField">
            <default></default>
            <Required>N</Required>
        </smtpauth_user>
        <smtpauth_password type="TextField">
            <default></default>
            <Required>N</Required>
        </smtpauth_password>
        <enforce_recipient_check type="BooleanField">
            <default>0</default>
            <Required>Y</Required>
        </enforce_recipient_check>
        <reject_unauth_pipelining type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </reject_unauth_pipelining>
        <reject_unknown_sender_domain type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </reject_unknown_sender_domain>
        <reject_unknown_recipient_domain type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </reject_unknown_recipient_domain>
        <reject_non_fqdn_sender type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </reject_non_fqdn_sender>
        <reject_non_fqdn_recipient type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </reject_non_fqdn_recipient>
        <permit_sasl_authenticated type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </permit_sasl_authenticated>
        <permit_tls_clientcerts type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </permit_tls_clientcerts>
        <permit_mynetworks type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </permit_mynetworks>
        <reject_unauth_destination type="BooleanField">
            <default>1</default>
            <Required>Y</Required>
        </reject_unauth_destination>
    </items>
</model>


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ff333333" />
        </shape>
    </item>
    <item android:left="-10.0px" android:right="-10.0px" android:bottom="-10.0px">
        <shape android:shape="rectangle">
            <stroke android:width="1.0dip" android:color="#ff2b2b2b" />
            <solid android:color="@null" />
        </shape>
    </item>
</layer-list>


text:
/* the overlayed element */
#voverlay {

	/* growing background image */
	background-image:url(https://raw.githubusercontent.com/iSC-Host/jdsf.isc/gh-pages/src/assets/videolb/white.png);

	/* dimensions after the growing animation finishes  */
	width:1280px;
	height:720px;

	/* initially overlay is hidden */
	display:none;

	/* some padding to layout nested elements nicely  */
	padding:35px;
}

/* default close button positioned on upper right corner */
#voverlay .close {
	background-image:url(https://raw.githubusercontent.com/iSC-Host/jdsf.isc/gh-pages/src/assets/videolb/close.png);
	position:absolute;
	right:5px;
	top:5px;
	cursor:pointer;
	height:35px;
	width:35px;
}

#voverlay .vcontainer{
	left:0;
	top:0;
	width:100%;
	height:100%;
	background:url(https://raw.githubusercontent.com/iSC-Host/jdsf.isc/gh-pages/src/assets/videolb/loading.gif) no-repeat 50% 50%;
}

#voverlay .vcontainer > div{
	height:100%;
}


text:
#import <UIKit/UIKit.h>

@interface FBLikeButton : UIButton

- (void)setSelected:(BOOL)selected animated:(BOOL)animated;

@end


text:
require File.join(File.dirname(__FILE__), "spec_helper")

describe Burgatron::Sources::Foursquare do

  subject do
    Burgatron::Sources::Foursquare.new(
      foursquare_config: FOURSQUARE_CONFIG
    )
  end

  it "should return processed results" do
    VCR.use_cassette('fsq-results') do
      destinations = subject.retrieve(count: 20,
                       latitude:  45.504620,
                       longitude: -122.654206)
      destinations.any?{|dest|
        dest.name == "Ford Food and Drink" # since the lat/lng are right on top of it
      }.should be_true
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
	<Properties>
		<Property name="PID">????</Property>
		<Property name="LOG_PATTERN">[%d{yyyy-MM-dd HH:mm:ss.SSS}]
			log4j2%X{context} - ${sys:PID} %5p [%t] --- %c{1}: %m%n</Property>
	</Properties>
	<Appenders>
		<RollingFile name="RollingFile" fileName="logs/app_hairy_batman_dev.log"
			filePattern="logs/app-%d{MM-dd-yyyy}.log.gz" ignoreExceptions="false">
			<PatternLayout>
				<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
			</PatternLayout>
			<TimeBasedTriggeringPolicy />
		</RollingFile>
		<Console name="STDOUT" target="SYSTEM_OUT" ignoreExceptions="false">
			<PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Logger name="org.hibernate.validator.internal.util.Version"
			level="warn" />
		<Logger name="org.apache.coyote.http11.Http11NioProtocol"
			level="warn" />
		<Logger name="org.apache.tomcat.util.net.NioSelectorPool"
			level="warn" />
		<Logger name="org.apache.catalina.startup.DigesterFactory"
			level="error" />

		<Root level="info">
			<AppenderRef ref="RollingFile" />
			<AppenderRef ref="STDOUT" />
		</Root>
	</Loggers>
</Configuration>


text:
static CIDetector *jk_detector;

@implementation UIImageView (JKBetterFace)

void jk_hack_uiimageview_bf(){
    Method oriSetImgMethod = class_getInstanceMethod([UIImageView class], @selector(setImage:));
    Method newSetImgMethod = class_getInstanceMethod([UIImageView class], @selector(jk_setBetterFaceImage:));
    method_exchangeImplementations(newSetImgMethod, oriSetImgMethod);
}

- (void)jk_setBetterFaceImage:(UIImage *)image{
    [self setJk_needsBetterFace:image];
    if (![self jk_needsBetterFace]) {
        return;
    }

    [self jk_faceDetect:image];
}

char nbfKey;
- (void)setJk_needsBetterFace:(BOOL)needsBetterFace{
    objc_setAssociatedObject(self,
                             &nbfKey,
                             [NSNumber numberWithBool:needsBetterFace],
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)jk_needsBetterFace{
    NSNumber *associatedObject = objc_getAssociatedObject(self, &nbfKey);
    return [associatedObject boolValue];
}

char fastSpeedKey;
- (void)setJk_fast:(BOOL)fast{
    objc_setAssociatedObject(self,
                             &fastSpeedKey,
                             [NSNumber numberWithBool:fast],
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

char detectorKey;
- (void)setJk_detector:(CIDetector *)detector{
    objc_setAssociatedObject(self,
                             &detectorKey,
                             detector,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(CIDetector *)jk_detector{
    return objc_getAssociatedObject(self, &detectorKey);
}

- (BOOL)jk_fast{
    NSNumber *associatedObject = objc_getAssociatedObject(self, &fastSpeedKey);
    return [associatedObject boolValue];
}

- (void)jk_faceDetect:(UIImage *)aImage
{
    dispatch_queue_t queue = dispatch_queue_create("com.croath.betterface.queue", NULL);
    dispatch_async(queue, ^{
        CIImage* image = aImage.CIImage;
        if (image == nil) { // just in case the UIImage was created using a CGImage revert to the previous, slower implementation
            image = [CIImage imageWithCGImage:aImage.CGImage];
        }
        if (jk_detector == nil) {
            NSDictionary  *opts = [NSDictionary dictionaryWithObject:[self jk_fast] ? CIDetectorAccuracyLow : CIDetectorAccuracyHigh
                                                              forKey:CIDetectorAccuracy];
            jk_detector = [CIDetector detectorOfType:CIDetectorTypeFace
                                                      context:nil
                                                      options:opts];
        }

        NSArray* features = [jk_detector featuresInImage:image];

        if ([features count] == 0) {
            BFLog(@"no faces");
            dispatch_async(dispatch_get_main_queue(), ^{
                [[self jk_imageLayer] removeFromSuperlayer];
            });
        } else {
            BFLog(@"succeed %lu faces", (unsigned long)[features count]);
            [self jk_markAfterFaceDetect:features
                                 size:CGSizeMake(CGImageGetWidth(aImage.CGImage),
                                                 CGImageGetHeight(aImage.CGImage))];
        }
    });
}

-(void)jk_markAfterFaceDetect:(NSArray *)features size:(CGSize)size{
    CGRect fixedRect = CGRectMake(MAXFLOAT, MAXFLOAT, 0, 0);
    CGFloat rightBorder = 0, bottomBorder = 0;
    for (CIFaceFeature *f in features){
        CGRect oneRect = f.bounds;
        oneRect.origin.y = size.height - oneRect.origin.y - oneRect.size.height;

        fixedRect.origin.x = MIN(oneRect.origin.x, fixedRect.origin.x);
        fixedRect.origin.y = MIN(oneRect.origin.y, fixedRect.origin.y);

        rightBorder = MAX(oneRect.origin.x + oneRect.size.width, rightBorder);
        bottomBorder = MAX(oneRect.origin.y + oneRect.size.height, bottomBorder);
    }

    fixedRect.size.width = rightBorder - fixedRect.origin.x;
    fixedRect.size.height = bottomBorder - fixedRect.origin.y;

    CGPoint fixedCenter = CGPointMake(fixedRect.origin.x + fixedRect.size.width / 2.0,
                                      fixedRect.origin.y + fixedRect.size.height / 2.0);
    CGPoint offset = CGPointZero;
    CGSize finalSize = size;
    if (size.width / size.height > self.bounds.size.width / self.bounds.size.height) {
        //move horizonal
        finalSize.height = self.bounds.size.height;
        finalSize.width = size.width/size.height * finalSize.height;
        fixedCenter.x = finalSize.width / size.width * fixedCenter.x;
        fixedCenter.y = finalSize.width / size.width * fixedCenter.y;

        offset.x = fixedCenter.x - self.bounds.size.width * 0.5;
        if (offset.x < 0) {
            offset.x = 0;
        } else if (offset.x + self.bounds.size.width > finalSize.width) {
            offset.x = finalSize.width - self.bounds.size.width;
        }
        offset.x = - offset.x;
    } else {
        //move vertical
        finalSize.width = self.bounds.size.width;
        finalSize.height = size.height/size.width * finalSize.width;
        fixedCenter.x = finalSize.width / size.width * fixedCenter.x;
        fixedCenter.y = finalSize.width / size.width * fixedCenter.y;

        offset.y = fixedCenter.y - self.bounds.size.height * (1-GOLDEN_RATIO);
        if (offset.y < 0) {
            offset.y = 0;
        } else if (offset.y + self.bounds.size.height > finalSize.height){
            offset.y = finalSize.height = self.bounds.size.height;
        }
        offset.y = - offset.y;
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        CALayer *layer = [self jk_imageLayer];
        layer.frame = CGRectMake(offset.x,
                                 offset.y,
                                 finalSize.width,
                                 finalSize.height);
        layer.contents = (id)self.image.CGImage;
    });
}

- (CALayer *)jk_imageLayer {
    for (CALayer *layer in [self.layer sublayers]) {
        if ([[layer name] isEqualToString:BETTER_LAYER_NAME]) {
            return layer;
        }
    }

    CALayer *layer = [CALayer layer];
    [layer setName:BETTER_LAYER_NAME];
    layer.actions = @{@"contents": [NSNull null],
                      @"bounds": [NSNull null],
                      @"position": [NSNull null]};
    [self.layer addSublayer:layer];
    return layer;
}

@end


text:
/* globals $ */

/*

Create a function that takes an id or DOM element and:

*/

function solve() {

    function toggleShowHideState(element) {

        if (element.innerHTML === 'show') {
            element.innerHTML = 'hide';
        } else if (element.innerHTML === 'hide') {
            element.innerHTML = 'show';
        } else {
            throw new Error('Invalid element!');
        }
    }

    function toggleDisplayMode(element) {
        if (element.style.display === 'none') {
            element.style.display = '';
        } else {
            element.style.display = 'none';
        }
    }

  return function (selector) {
      var selectedElement,
          buttonElements,
          i, len;

      if (typeof selector !== 'string') {
          throw new Error('Invalid input selector!');
      }

      selector = selector.substring(1, selector.length);
      //console.log(selector);
      selectedElement = document.querySelector(selector);

      if (selectedElement === null) {
          throw new Error('Invalid id selector!');
      }

      buttonElements = selectedElement.getElementsByClassName('button');

      for (i = 0,len = buttonElements.length; i < len; i+=1) {
          buttonElements[i].innerHTML = 'hide';
      }

      selectedElement.addEventListener('click', function (ev) {
          var currentButton = ev.target,
              nextElementSibling,
              previuosElementSibling;

          if (ev.target.className === 'button') {

              nextElementSibling = currentButton.nextElementSibling;
              previuosElementSibling = currentButton.previousElementSibling;

              while (previuosElementSibling) {
                  if (previuosElementSibling.className === 'button') {
                      toggleShowHideState(previuosElementSibling);
                  }

                  if (previuosElementSibling.className === 'content') {
                      break;
                  }
                  previuosElementSibling = previuosElementSibling.previousElementSibling;
              }

              while (nextElementSibling) {

                  if (nextElementSibling.className === 'button'){
                      toggleShowHideState(nextElementSibling);
                  }

                  if (nextElementSibling.className === 'content') {
                      toggleShowHideState(currentButton);
                      toggleDisplayMode(nextElementSibling);
                      break;
                  }

                  nextElementSibling = nextElementSibling.nextElementSibling;
              }
          }
      }, false);

      var contentElements = selectedElement.getElementsByClassName('content');

  };
};

module.exports = solve;


text:
var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();
var rewire = require('rewire');

var config = require('config');
var Promise = require('bluebird');
var jwt = require('jsonwebtoken');
var shortid = require('shortid');
var _ = require('lodash');

var umpack = require('./helpers/umpack');
var utils = require('./helpers/utils');
var mongoose = require('mongoose');
var ObjectId = require('mongodb').ObjectID;

var usersCollection = 'users';
var rolesCollection = 'roleactions';
var userDevicesCollection = 'userdevices';
var username = 'test';
var password = '123456';

chai.use(chaiHttp);
global.Promise = Promise;

describe('device control', function() {
  var umpackJs;
  var firstConfig = _.cloneDeep(require('../config'));

  function toggleControl(deviceControl) {
    var conf = require('../config');

    var fileConf = config.get('umpack');

    var options = Object.keys(fileConf).reduce(function (con, key) {
      con[key] = fileConf[key];

      return con;
    }, {
      deviceControl: deviceControl
    });

    conf.handleOptions(options);
  }

  before(function() {
    umpackJs = rewire('../umpack');

    return mongoose.connection.dropCollection(rolesCollection)
      .then(function() {
        return mongoose.connection.db.collection(rolesCollection)
          .insert({
            "name": "admin",
            "actions": [{
              "_id": new ObjectId("58a301b880a92f3930ebfef4"),
              "pattern": "/deviceUm/*",
              "name": "um",
              "verbDelete": true,
              "verbPost": true,
              "verbPut": true,
              "verbGet": true
            }],
            "__v": 0
          });
      });
  });

  beforeEach(function() {
    toggleControl(true);

    return Promise.all([
        mongoose.connection.db.collection(userDevicesCollection).remove(),
        mongoose.connection.db.collection(usersCollection).remove()
      ])
      .then(function() {
        return mongoose.connection.db.collection(usersCollection)
          .insert({
            userName: username,
            password: utils.passwordHash(password),
            isActivated: true,
            roles: ['admin'],
            '__v': 0
          });
      });
  });

  after(function() {
    utils.refreshToFirstState(require('../config'), firstConfig);
  });

  describe('POST /login', function() {
    var app = require('./helpers/app');

    before(function() {
      app.use('/deviceUm', umpackJs.__get__('router'));
    });

    it('should create jwt with device token', function() {
      var deviceToken = shortid.generate();

      return mongoose.connection.db.collection(userDevicesCollection)
        .insert({
          userName: username,
          devices: [{
            deviceToken: deviceToken,
            canAccess: true
          }]
        })
        .then(function() {
          return chai.request(app)
            .post('/deviceUm/login')
            .send({
              userName: username,
              password: password,
              deviceToken: deviceToken
            });
        })
        .then(function(res) {
          res.should.have.status(200);

          var payload = jwt.decode(res.text);

          payload.should.have.property('device');
        });
    });

    it('should set device lastUsageDate field', function() {
      var deviceToken = shortid.generate();

      return mongoose.connection.db.collection(userDevicesCollection)
        .insert({
          userName: username,
          devices: [{
            deviceToken: deviceToken,
            canAccess: true
          }]
        })
        .then(function() {
          return chai.request(app)
            .post('/deviceUm/login')
            .send({
              userName: username,
              password: password,
              deviceToken: deviceToken
            });
        })
        .then(function(res) {
          res.should.have.status(200);

          return mongoose.connection.db.collection(userDevicesCollection)
            .findOne({
              userName: username
            });
        })
        .then(function(userDevice) {
          userDevice.devices[0].should.have.property('lastUsageDate');
        });
    });

    it('should not write device field in jwt when device control is disabled', function() {
      toggleControl(false);

      return chai.request(app)
        .post('/deviceUm/login')
        .send({
          userName: username,
          password: password
        })
        .then(function(res) {
          res.should.have.status(200);

          should.exist(res.text);

          var payload = jwt.decode(res.text);

          payload.should.not.have.property('device');
        });
    });

    it('should return INVALID_DEVICE_TOKEN when deviceToken not passed', function() {
      var promise = chai.request(app)
        .post('/deviceUm/login')
        .send({
          userName: username,
          password: password
        });

      return utils.shouldBeBadRequest(promise, 805);
    });

    it('should return DEVICE_ACCESS_DENIED when device access is denied', function() {
      var promise = chai.request(app)
        .post('/deviceUm/login')
        .send({
          userName: username,
          password: password,
          deviceToken: 'one'
        });

      return utils.shouldBeBadRequest(promise, 806);
    });
  });

  describe('isAuthorized()', function() {
    var isAuthorized = umpack.isAuthorized;

    var nextCallError = new chai.AssertionError(
      'next() function should not be called');

    function shouldBeForbidden(result) {
      should.exist(result.status);
      result.status.should.equal(403);
    }

    function shouldReturnErrorWithStatus(result, internalStatus) {
      should.exist(result.data);

      result.data.should.have.property('message');
      result.data.should.have.property('internalStatus', internalStatus);
    }

    function callMockedIsAuthorized(reqStub) {
      var resMock;

      return new Promise(function(resolve, reject) {

        resMock = utils.createResponseMock(resolve);

        isAuthorized(reqStub, resMock, function() {
          reject(nextCallError);
        });

      });
    }

    function createReqStub(deviceToken) {
      var token = jwt.sign({
        user: username,
        roles: ['admin'],
        device: deviceToken
      }, config.get('umpack.accessTokenSecret'), {
        expiresIn: config.get('umpack.accessTokenExpiresIn')
      });

      var reqStub = {
        headers: {
          authorization: token
        },
        method: 'GET',
        originalUrl: '/deviceUm/something'
      };

      return reqStub;
    }

    it('should pass when device access is enabled', function() {
      var deviceToken = shortid.generate();

      return mongoose.connection.db.collection(userDevicesCollection)
        .insert({
          userName: username,
          devices: [{
            deviceToken: deviceToken,
            canAccess: true
          }]
        })
        .then(function() {
          var reqStub = createReqStub(deviceToken);

          return new Promise(function(resolve, reject) {
            var resMock = utils.createResponseMock(reject);

            isAuthorized(reqStub, resMock, resolve);
          });
        });

    });

    it('should return DEVICE_ACCESS_DENIED when device access is disabled', function() {
      var deviceToken = shortid.generate();

      return mongoose.connection.db.collection(userDevicesCollection)
        .insert({
          userName: username,
          devices: [{
            deviceToken: deviceToken,
            canAccess: false
          }]
        })
        .then(function() {
          var reqStub = createReqStub(deviceToken);

          return callMockedIsAuthorized(reqStub);
        })
        .then(function(result) {
          shouldBeForbidden(result);

          shouldReturnErrorWithStatus(result, 806);
        });
    });

    it('should register device if not registered and return DEVICE_ACCESS_DENIED', function() {
      var deviceToken = shortid.generate();

      var reqStub = createReqStub(deviceToken);

      return callMockedIsAuthorized(reqStub)
        .then(function(result) {
          shouldBeForbidden(result);

          shouldReturnErrorWithStatus(result, 806);

          return mongoose.connection.db.collection(userDevicesCollection)
            .findOne({
              userName: username
            });
        })
        .then(function(userDevice) {
          should.exist(userDevice);

          userDevice.devices.should.have.length(1);
          userDevice.devices[0].deviceToken.should.equal(deviceToken);
          userDevice.devices[0].canAccess.should.equal(false);
        });
    });

    it('should not set field lastUsageDate to device', function() {
      var deviceToken = shortid.generate();

      var reqStub = createReqStub(deviceToken);

      return callMockedIsAuthorized(reqStub)
        .then(function(result) {
          shouldBeForbidden(result);

          shouldReturnErrorWithStatus(result, 806);

          return mongoose.connection.db.collection(userDevicesCollection)
            .findOne({
              userName: username
            });
        })
        .then(function(userDevice) {
          userDevice.devices[0].should.not.have.property('lastUsageDate');
        });
    });

    it('should not call checkDevice when device control is disabled', function() {
      toggleControl(false);

      var umpackJs = rewire('../umpack');

      var interactorMock = {
        called: false,
        checkDevice: function(userName, deviceToken) {
          this.called = true;
        }
      };

      umpackJs.__set__('credentialsInteractor', interactorMock);

      var isAuthorized = umpackJs.__get__('isAuthorized');

      var deviceToken = shortid.generate();

      var reqStub = createReqStub(deviceToken);

      return new Promise(function(resolve, reject) {
          var resMock = utils.createResponseMock(reject);

          isAuthorized(reqStub, resMock, resolve);
        })
        .then(function() {
          interactorMock.called.should.equal(false);
        });
    });
  });

  describe('administration', function() {
    var app = require('./helpers/app');

    before(function() {
      app.use('/deviceUm', umpackJs.__get__('router'));
    });

    function login(deviceToken) {
      return chai.request(app)
        .post('/deviceUm/login')
        .send({
          userName: username,
          password: password,
          deviceToken: deviceToken
        });
    }

    describe('GET /users/:userName/devices', function() {
      it('should return DEVICE_CONTROL_NOT_SUPPORTED when device control is disabled', function() {
        toggleControl(false);

        var promise = mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
              deviceToken: 'token',
              canAccess: true
            }]
          })
          .then(function() {
            return chai.request(app)
              .post('/deviceUm/login')
              .send({
                userName: username,
                password: password
              });
          })
          .then(function(res) {
            return chai.request(app)
              .get('/deviceUm/users/' + username + '/devices')
              .set('authorization', res.text);
          });

        return utils.shouldBeBadRequest(promise, 807);
      });

      it('should return all devices of the user', function() {
        var token = shortid.generate();

        return mongoose.connection.db.collection(userDevicesCollection)
          .insert([{
              userName: username,
              devices: [{
                  deviceToken: token,
                  canAccess: true
                },
                {
                  deviceToken: 'two',
                  canAccess: false
                }
              ]
            },
            {
              userName: 'other',
              devices: [{
                deviceToken: 'three',
                canAccess: true
              }]
            }
          ])
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .get('/deviceUm/users/' + username + '/devices')
              .set('authorization', res.text);
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.length(2);

            res.body.forEach(function(device) {
              should.exist(device);

              device.deviceToken.should.not.equal('three');
            });
          });
      });

      it('should return USER_NOT_EXISTS when user with userName not exists', function() {
        var token = shortid.generate();

        var promise = mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
              deviceToken: token,
              canAccess: true
            }]
          })
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .get('/deviceUm/users/other/devices')
              .set('authorization', res.text);
          });

        return utils.shouldBeBadRequest(promise, 605);
      });
    });

    describe('GET /users/:userName/devices/permitted', function() {
      it('should get all permitted', function() {
        var token = shortid.generate();

        return mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
                deviceToken: token,
                canAccess: true
              },
              {
                deviceToken: 'one',
                canAccess: false
              },
              {
                deviceToken: 'two',
                canAccess: true
              }
            ]
          })
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .get('/deviceUm/users/' + username + '/devices/permitted')
              .set('authorization', res.text);
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.length(2);

            res.body.forEach(function(device) {
              should.exist(device);

              device.deviceToken.should.not.equal('one');

              if (device.deviceToken === token) device.should.have.property('lastUsageDate');
            });
          });
      });
    });

    describe('POST /users/:userName/devices/access', function() {
      it('should grant access to existing device', function() {
        var token = shortid.generate();

        return mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
                deviceToken: token,
                canAccess: true
              },
              {
                deviceToken: 'one',
                canAccess: false
              }
            ]
          })
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .post('/deviceUm/users/' + username + '/devices/access')
              .set('authorization', res.text)
              .send({
                deviceToken: 'one'
              });
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.property('success', true);

            return mongoose.connection.db.collection(userDevicesCollection)
              .findOne({
                userName: username
              });
          })
          .then(function(userDevice) {
            should.exist(userDevice);

            var devices = userDevice.devices.filter(function(device) {
              return device.deviceToken === 'one';
            });

            devices.should.have.length(1);

            devices[0].canAccess.should.equal(true);
          });
      });

      it('should register device and grant access if not exists', function() {
        var token = shortid.generate();

        return mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
              deviceToken: token,
              canAccess: true
            }]
          })
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .post('/deviceUm/users/' + username + '/devices/access')
              .set('authorization', res.text)
              .send({
                deviceToken: 'one'
              });
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.property('success', true);

            return mongoose.connection.db.collection(userDevicesCollection)
              .findOne({
                userName: username
              });
          })
          .then(function(userDevice) {
            should.exist(userDevice);

            var devices = userDevice.devices.filter(function(device) {
              return device.deviceToken === 'one';
            });

            devices.should.have.length(1);

            devices[0].canAccess.should.equal(true);
          });
      });

      it('should create new userDevice if not exists and grant its device access', function() {
        var token = shortid.generate();

        return Promise.all([
            mongoose.connection.db.collection(usersCollection)
            .insert({
              userName: 'someone',
              password: utils.passwordHash(password),
              isActivated: true,
              roles: ['user'],
              '__v': 0
            }),
            mongoose.connection.db.collection(userDevicesCollection)
            .insert({
              userName: username,
              devices: [{
                deviceToken: token,
                canAccess: true
              }]
            })
          ])
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .post('/deviceUm/users/someone/devices/access')
              .set('authorization', res.text)
              .send({
                deviceToken: 'one'
              });
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.property('success', true);

            return mongoose.connection.db.collection(userDevicesCollection)
              .findOne({
                userName: 'someone'
              });
          })
          .then(function(userDevice) {
            should.exist(userDevice);

            userDevice.devices.should.have.length(1);
            userDevice.devices[0].deviceToken.should.equal('one');
          });

      });
    });

    describe('POST /users/:userName/devices/restriction', function() {
      it('should restrict access of existing device', function() {
        var token = shortid.generate();

        return mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
                deviceToken: token,
                canAccess: true
              },
              {
                deviceToken: 'one',
                canAccess: true
              }
            ]
          })
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .post('/deviceUm/users/' + username + '/devices/restriction')
              .set('authorization', res.text)
              .send({
                deviceToken: 'one'
              });
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.property('success', true);

            return mongoose.connection.db.collection(userDevicesCollection)
              .findOne({
                userName: username
              });
          })
          .then(function(userDevice) {
            should.exist(userDevice);

            var devices = userDevice.devices.filter(function(device) {
              return device.deviceToken === 'one';
            });

            devices.should.have.length(1);

            devices[0].canAccess.should.equal(false);
          });
      });

      it('should register device and restrict access if not exists', function() {
        var token = shortid.generate();

        return mongoose.connection.db.collection(userDevicesCollection)
          .insert({
            userName: username,
            devices: [{
              deviceToken: token,
              canAccess: true
            }]
          })
          .then(function() {
            return login(token);
          })
          .then(function(res) {
            return chai.request(app)
              .post('/deviceUm/users/' + username + '/devices/restriction')
              .set('authorization', res.text)
              .send({
                deviceToken: 'one'
              });
          })
          .then(function(res) {
            res.should.have.status(200);

            should.exist(res.body);

            res.body.should.have.property('success', true);

            return mongoose.connection.db.collection(userDevicesCollection)
              .findOne({
                userName: username
              });
          })
          .then(function(userDevice) {
            should.exist(userDevice);

            var devices = userDevice.devices.filter(function(device) {
              return device.deviceToken === 'one';
            });

            devices.should.have.length(1);

            devices[0].canAccess.should.equal(false);
          });
      });
    });
  });

});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.security.keyvault.jca.implementation.signature;

import com.azure.security.keyvault.jca.implementation.KeyVaultPrivateKey;
import com.azure.security.keyvault.jca.implementation.KeyVaultClient;

import java.nio.ByteBuffer;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.SignatureSpi;
import java.security.SecureRandom;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.spec.AlgorithmParameterSpec;

/**
 * KeyVault Signature to key less sign
 */
public abstract class AbstractKeyVaultKeyLessSignature extends SignatureSpi {

    protected KeyVaultClient keyVaultClient;

    // message digest implementation we use for hashing the data
    protected MessageDigest messageDigest;

    protected String keyId;

    /**
     * The default algorithm for certificate sign when the certificate is stored in Key Vault.
     * @return the default algorithm.
     */
    public abstract String getAlgorithmName();

    // After throw UnsupportedOperationException, other methods will be called.
    // such as RSAPSSSignature#engineInitVerify.
    @Override
    protected void engineInitVerify(PublicKey publicKey) {
        throw new UnsupportedOperationException("engineInitVerify() not supported");
    }

    // After throw UnsupportedOperationException, other methods will be called.
    // such as RSAPSSSignature#engineVerify.
    @Override
    protected boolean engineVerify(byte[] signature) {
        throw new UnsupportedOperationException("getParameter() not supported");
    }

    // After throw UnsupportedOperationException, other methods will be called.
    // such as ECDSASignature#engineGetParameter.
    @Override
    @Deprecated
    protected Object engineGetParameter(String param)
        throws InvalidParameterException {
        throw new UnsupportedOperationException("getParameter() not supported");
    }

    // After throw UnsupportedOperationException, other methods will be called.
    // such as RSAPSSSignature#engineSetParameter.
    @Override
    @Deprecated
    protected void engineSetParameter(String param, Object value)
        throws InvalidParameterException {
        throw new UnsupportedOperationException("setParameter() not supported");
    }

    // After throw UnsupportedOperationException, other methods will be called.
    // such as RSAPSSSignature#engineInitSign.
    @Override
    protected void engineInitSign(PrivateKey privateKey, SecureRandom random) {
        if (privateKey instanceof KeyVaultPrivateKey) {
            keyId = ((KeyVaultPrivateKey) privateKey).getKid();
            keyVaultClient = ((KeyVaultPrivateKey) privateKey).getKeyVaultClient();
        } else {
            throw new UnsupportedOperationException("engineInitSign() not supported which private key is not instance of KeyVaultPrivateKey");
        }
    }

    @Override
    protected void engineInitSign(PrivateKey privateKey) {
        engineInitSign(privateKey, null);
    }

    /**
     * Get the message digest value.
     * @return the message digest value.
     */
    protected byte[] getDigestValue() {
        return messageDigest.digest();
    }

    @Override
    protected void engineUpdate(byte b) {
        this.messageDigest.update(b);
    }

    @Override
    protected void engineUpdate(byte[] b, int off, int len) {
        this.messageDigest.update(b, off, len);
    }

    @Override
    protected void engineUpdate(ByteBuffer b) {
        this.messageDigest.update(b);
    }

    //Override this method just do not throw an exception to enable this signature
    @Override
    protected void engineSetParameter(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException {
    }

    /**
     * Add this method to enable getParameters which added in this commit:
     * https://github.com/openjdk/jdk/commit/316140ff92af7ac1aadb74de9cd37a5f3c412406
     * You can find this logic in file SignatureScheme.java and line 202 in this commit.
     * Which will call this method. If we don't support this method, this algorithm won't be available
     * @return AlgorithmParameters
     */
    @Override
    protected AlgorithmParameters engineGetParameters() {
        return null;
    }

}


text:
package com.spectralogic.ds3autogen.java.utils;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.spectralogic.ds3autogen.api.FileUtils;
import com.spectralogic.ds3autogen.api.models.docspec.Ds3DocSpec;
import com.spectralogic.ds3autogen.docspec.Ds3DocSpecImpl;
import com.spectralogic.ds3autogen.testutil.logging.FileTypeToLog;
import com.spectralogic.ds3autogen.testutil.logging.GeneratedCodeLogger;
import freemarker.template.TemplateModelException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.regex.Pattern;

import static com.spectralogic.ds3autogen.java.utils.JavaDocGenerator.toConstructorDocs;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

public class JavaFunctionalDocs_Test {

    private final static Logger LOG = LoggerFactory.getLogger(JavaFunctionalDocs_Test.class);
    private final static GeneratedCodeLogger CODE_LOGGER = new GeneratedCodeLogger(FileTypeToLog.REQUEST, LOG);

    @Test
    public void getBucketRequest_Test() throws IOException, TemplateModelException {
        final String requestName = "GetBucketRequest";
        final FileUtils fileUtils = mock(FileUtils.class);
        final TestGeneratedCode codeGenerator = new TestGeneratedCode(
                fileUtils,
                requestName,
                "./ds3-sdk/src/main/java/com/spectralogic/ds3client/commands/");

        final Ds3DocSpec docSpec = new Ds3DocSpecImpl(
                ImmutableMap.of(
                        requestName, "This is how you use the request"
                ),
                ImmutableMap.of(
                        "Delimiter", "This is how you use delimiter",
                        "Marker", "This is how you use marker",
                        "MaxKeys", "This is how you use max keys",
                        "Prefix", "This is how you use prefix",
                        "BucketName", "This is how you use bucket name"));

        codeGenerator.generateCode(fileUtils, "/input/getBucketRequestHandler.xml", docSpec);

        //Generate Request code
        final String requestCode = codeGenerator.getRequestGeneratedCode();
        CODE_LOGGER.logFile(requestCode, FileTypeToLog.REQUEST);

        assertTrue(requestCode.contains(toConstructorDocs(requestName, ImmutableList.of("Delimiter"), docSpec, 1)));
        assertTrue(requestCode.contains(toConstructorDocs(requestName, ImmutableList.of("Marker"), docSpec, 1)));
        assertTrue(requestCode.contains(toConstructorDocs(requestName, ImmutableList.of("MaxKeys"), docSpec, 1)));
        assertTrue(requestCode.contains(toConstructorDocs(requestName, ImmutableList.of("Prefix"), docSpec, 1)));
        assertTrue(requestCode.contains(toConstructorDocs(requestName, ImmutableList.of("BucketName"), docSpec, 1)));

        //Generate Client code
        final String ds3ClientCode = codeGenerator.getDs3ClientGeneratedCode();
        CODE_LOGGER.logFile(ds3ClientCode, FileTypeToLog.CLIENT);

        final Pattern expectedCommandDoc = Pattern.compile("\\s+/\\*\\*" +
                        "\\s+\\* This is how you use the request" +
                        "\\s+\\*/" +
                        "\\s+GetBucketResponse getBucket\\(final GetBucketRequest request\\)",
                Pattern.MULTILINE | Pattern.UNIX_LINES);

        assertTrue(expectedCommandDoc.matcher(ds3ClientCode).find());
    }
}


text:
package java.lang.reflect;

/**
 * Thrown when a syntactically malformed signature attribute is
 * encountered by a reflective method that needs to interpret the generic
 * signature information for a class or interface, method or constructor.
 *
 * @since 1.5
 */
public class GenericSignatureFormatError extends ClassFormatError {
    @java.io.Serial
    private static final long serialVersionUID = 6709919147137911034L;

    /**
     * Constructs a new {@code GenericSignatureFormatError}.
     *
     */
    public GenericSignatureFormatError() {
        super();
    }

    /**
     * Constructs a new {@code GenericSignatureFormatError} with the
     * specified message.
     *
     * @param message the detail message, may be {@code null}
     */
    public GenericSignatureFormatError(String message) {
        super(message);
    }
}


text:
<?php

namespace Dan\Irc\Packets;

use Dan\Events\Traits\EventTrigger;
use Dan\Irc\Traits\Parser;

class Packet333 extends Packet
{
    use EventTrigger;
    use Parser;

    /**
     * @param array $from
     * @param array $data
     */
    public function handle(array $from, array $data)
    {
        if (!$this->connection->inChannel($data[1])) {
            return;
        }

        $channel = $this->connection->getChannel($data[1]);

        $this->triggerEvent('irc.topic.set_by', [
            'connection'    => $this->connection,
            'channel'       => $channel,
            'user'          => $this->makeUser(parseUserString($data[2])),
            'time'          => $data[3],
        ]);
    }
}


text:
1. Create scripts for loading/unloading:

	```
	/usr/bin/nvidia-load
	--------------------
	#!/bin/sh
	systemctl stop tlp
	echo 1 > /sys/bus/pci/rescan
	systemctl start tlp
	```

	```
	/usr/bin/nvidia-unload
	----------------------
	#!/bin/sh
	echo 1 > /sys/bus/pci/devices/0000:01:00.0/remove
	```
	Make sure they can be executed (`chmod +x $file`)

2. Create udev rules to trigger them

	```
	/etc/udev/rules.d/80-nvidia_power.rules
	---------------------------------------
	SUBSYSTEM=="power_supply", KERNEL=="AC", ATTR{online}=="1" RUN+="/usr/bin/nvidia-load"

	SUBSYSTEM=="power_supply", KERNEL=="AC", ATTR{online}=="0" RUN+="/usr/bin/nvidia-unload"

	```
	Make sure, to add the newlines after the rules and to adapt the name of the power supply (search under `/sys/class/power_supply`).

3. For proper detection after hibernate, add another script:

	```
	/usr/bin/nvidia-auto-detect
	---------------------------
	#!/usr/bin/env sh
	AC_ON=$(cat /sys/class/power_supply/AC/online)
	if [[ $AC_ON == 0 ]]; then
		nvidia-unload
		echo unloaded nvidia
	else
		nvidia-load
		echo loaded nvidia
	fi
	```

	and create and enable the following service in systemd
	```
	/etc/systemd/system/nvidia-auto-detect.service
	----------------------------------------------
	[Unit]
	Description=Detect AC state to enable or disable Nvidia card after suspension
	After=suspend.target

	[Service]
	User=root
	Type=oneshot
	ExecStart=/usr/bin/nvidia-auto-detect
	TimeoutSec=0
	StandardOutput=syslog

	[Install]
	WantedBy=suspend.target
	```


text:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import Validator from 'ember-model-validator/decorators/model-validator';

@Validator
class ForPresence extends Model {
  @attr('string') fullName;
  @attr('string') fruit;
  @attr('string') color;

  validations = {
    fullName: {
      presence: true,
    },
    fruit: {
      presence: true,
    },
  };
}

export default ForPresence;


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="description" content="Reddit image viewer for your favourite subreddits. RedFetch loads images progressively for faster performance.">
    <meta name="keywords" content="reddit, image, viewer, redfetch, aww, fetch, reddit">
    <meta name="robots" content="index,follow">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>RedFetch - Reddit Image Fetch</title>
    <meta name="theme-color" content="#ffffff">
    <link rel="shortcut icon" href="favicon.ico?" type="image/x-icon">
    <link rel="icon" href="favicon.ico?" type="image/x-icon">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <link rel="canonical" href="https://davidyoung.tech/redfetch/">

                        davidyoung.tech

                        github

What's this?

                    An example of lazily loading images using fetch and the onload event attached to images. We gather images from reddit's API and display them using flexbox. Thumbnails are loaded first and then the full image.

                    Enter a subreddit or series of subreddits separated by spaces below. Arrow keys can be used after clicking an image.

            <form id="input-search">
                <select class="input-style">
                    <option value="r">/r/</option>
                    <option value="user">/user/</option>
                </select>
                <input id="input" class="input-style" placeholder="aww puppies" type="text">
                <input type="submit" value="Search" class="input-style">
            </form>

Loading...

                    <button id="overlay-user"></button>


text:
package main

import (
	"compress/lzw"
	"encoding/gob"
	"os"
)

var PersistantData = new(struct {
	GameSettings *Settings
	SavedGames   [10]*gamestate
})

const persistantDataFile = ".traildata.persist"
const persistantDataOrder = lzw.LSB

func savePersistantToDisk() error {
	home := os.Getenv("HOME")
	err := os.Chdir(home)
	if err != nil {
		return err
	}
	os.Remove(persistantDataFile)
	f, err := os.Create(persistantDataFile)
	if err != nil {
		return err
	}
	defer f.Close()
	compressedStream := lzw.NewWriter(f, persistantDataOrder, 8)
	defer compressedStream.Close()
	enc := gob.NewEncoder(compressedStream)
	return enc.Encode(PersistantData)
}

func loadPersistantFromDisk() error {
	home := os.Getenv("HOME")
	err := os.Chdir(home)
	if err != nil {
		return err
	}
	f, err := os.Open(persistantDataFile)
	if err != nil {
		return err
	}
	defer f.Close()
	compressedStream := lzw.NewReader(f, persistantDataOrder, 8)
	defer compressedStream.Close()
	dec := gob.NewDecoder(compressedStream)
	return dec.Decode(&PersistantData)
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

# Re-raise errors caught by the controller.
# PageEventsController.class_eval { def rescue_action(e) raise e end }
#
# class PageEventsControllerTest < Test::Unit::TestCase
#   def setup
#     @controller = PageEventsController.new
#     @request    = ActionController::TestRequest.new
#     @response   = ActionController::TestResponse.new
#   end
#
# 	def test_index_without_authentication
# 		get :index
# 		assert_response :redirect
# 	end
# end


text:
<?php
class WxfcAction extends BackAction{

	public function index(){

	}
}


text:
package main

import (
	"github.com/kbatten/httpcanvas"
	"github.com/kbatten/noc"
)

type Mouse struct {
	Mover
}

func newMouse(context *httpcanvas.Context) *Mouse {
	v := &Mouse{*newMover(10, 10, context)}
	v.color = "rgba(0, 175, 0, 0.80)"
	v.size = 10
	return v
}

func (self *Mouse) Step() {
	self.location = noc.NewPVector(self.context.MouseLocation())

	self.limitLocation()
}

func (self *Mouse) limitLocation() {
	if self.location.X > self.context.Width {
		self.location.X = self.context.Width
	}
	if self.location.X < 0 {
		self.location.X = 0
	}
	if self.location.Y > self.context.Height {
		self.location.Y = self.context.Height
	}
	if self.location.Y < 0 {
		self.location.Y = 0
	}
}


text:
#pragma once
#include <aws/directconnect/DirectConnect_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace DirectConnect
{
namespace Model
{
  enum class LagState
  {
    NOT_SET,
    requested,
    pending,
    available,
    down,
    deleting,
    deleted,
    unknown
  };

namespace LagStateMapper
{
AWS_DIRECTCONNECT_API LagState GetLagStateForName(const Aws::String& name);

AWS_DIRECTCONNECT_API Aws::String GetNameForLagState(LagState value);
} // namespace LagStateMapper
} // namespace Model
} // namespace DirectConnect
} // namespace Aws