text:
local jid = require 'util.jid';
local http = require "net.http";
local json = require "util.json";
local st = require "util.stanza";
local timer = require 'util.timer';
local datetime = require 'util.datetime';

local get_room_from_jid = module:require "util".get_room_from_jid;
local is_healthcheck_room = module:require "util".is_healthcheck_room;
local room_jid_match_rewrite = module:require "util".room_jid_match_rewrite;

local api_prefix = module:get_option("reservations_api_prefix");
local api_headers = module:get_option("reservations_api_headers");
local api_timeout = module:get_option("reservations_api_timeout", 20);
local api_retry_count = tonumber(module:get_option("reservations_api_retry_count", 3));
local api_retry_delay = tonumber(module:get_option("reservations_api_retry_delay", 3));
local max_occupants_enabled = module:get_option("reservations_enable_max_occupants", false);
local lobby_support_enabled = module:get_option("reservations_enable_lobby_support", false);
local password_support_enabled = module:get_option("reservations_enable_password_support", false);
local skip_breakout_room = module:get_option("reservations_skip_breakout_rooms", true);

-- Option for user to control HTTP response codes that will result in a retry.
-- Defaults to returning true on any 5XX code or 0
local api_should_retry_for_code = module:get_option("reservations_api_should_retry_for_code", function (code)
   return code >= 500;
end)

local muc_component_host = module:get_option_string("main_muc");
local breakout_muc_component_host = module:get_option_string('breakout_rooms_muc', 'breakout.'..module.host);

-- How often to check and evict expired reservation data
local expiry_check_period = 60;

-- Cannot proceed if "reservations_api_prefix" not configured
if not api_prefix then
    module:log("error", "reservations_api_prefix not specified. Disabling %s", module:get_name());
    return;
end

-- get/infer focus component hostname so we can intercept IQ bound for it
local focus_component_host = module:get_option_string("focus_component");
if not focus_component_host then
    local muc_domain_base = module:get_option_string("muc_mapper_domain_base");
    if not muc_domain_base then
        module:log("error", "Could not infer focus domain. Disabling %s", module:get_name());
        return;
    end
    focus_component_host = 'focus.'..muc_domain_base;
end

-- common HTTP headers added to all API calls
local http_headers = {
    ["User-Agent"] = "Prosody ("..prosody.version.."; "..prosody.platform..")";
};
if api_headers then -- extra headers from config
    for key, value in pairs(api_headers) do
       http_headers[key] = value;
    end
end

--- Utils

--- Converts int timestamp to datetime string compatible with Java SimpleDateFormat
-- @param t timestamps in seconds. Supports int (as returned by os.time()) or higher
--          precision (as returned by socket.gettime())
-- @return formatted datetime string (yyyy-MM-dd'T'HH:mm:ss.SSSX)
local function to_java_date_string(t)
    local t_secs, mantissa = math.modf(t);
    local ms_str = (mantissa == 0) and '.000' or tostring(mantissa):sub(2,5);
    local date_str = os.date("!%Y-%m-%dT%H:%M:%S", t_secs);
    return date_str..ms_str..'Z';
end

--- Start non-blocking HTTP call
-- @param url URL to call
-- @param options options table as expected by net.http where we provide optional headers, body or method.
-- @param callback if provided, called with callback(response_body, response_code) when call complete.
-- @param timeout_callback if provided, called without args when request times out.
-- @param retries how many times to retry on failure; 0 means no retries.
local function async_http_request(url, options, callback, timeout_callback, retries)
    local completed = false;
    local timed_out = false;
    local retries = retries or api_retry_count;

    local function cb_(response_body, response_code)
        if not timed_out then  -- request completed before timeout
            completed = true;
            if (response_code == 0 or api_should_retry_for_code(response_code)) and retries > 0 then
                module:log("warn", "API Response code %d. Will retry after %ds", response_code, api_retry_delay);
                timer.add_task(api_retry_delay, function()
                    async_http_request(url, options, callback, timeout_callback, retries - 1)
                end)
                return;
            end

            if callback then
                callback(response_body, response_code)
            end
        end
    end

    local request = http.request(url, options, cb_);

    timer.add_task(api_timeout, function ()
        timed_out = true;

        if not completed then
            http.destroy_request(request);
            if timeout_callback then
                timeout_callback()
            end
        end
    end);

end

--- Returns current timestamp
local function now()
    -- Don't really need higher precision of socket.gettime(). Besides, we loose
    -- milliseconds precision when converting back to timestamp from date string
    -- when we use datetime.parse(t), so let's be consistent.
    return os.time();
end

--- Start RoomReservation implementation

-- Status enums used in RoomReservation:meta.status
local STATUS = {
    PENDING = 0;
    SUCCESS = 1;
    FAILED  = -1;
}

local RoomReservation = {};
RoomReservation.__index = RoomReservation;

function newRoomReservation(room_jid, creator_jid)
    return setmetatable({
        room_jid = room_jid;

        -- Reservation metadata. store as table so we can set and read atomically.
        -- N.B. This should always be updated using self.set_status_*
        meta = {
            status = STATUS.PENDING;
            mail_owner = jid.bare(creator_jid);
            conflict_id = nil;
            start_time = now();  -- timestamp, in seconds
            expires_at = nil;  -- timestamp, in seconds
            error_text = nil;
            error_code = nil;
        };

        -- Array of pending events that we need to route once API call is complete
        pending_events = {};

        -- Set true when API call trigger has been triggered (by enqueue of first event)
        api_call_triggered = false;
    }, RoomReservation);
end

--- Extracts room name from room jid
function RoomReservation:get_room_name()
    return jid.node(self.room_jid);
end

--- Checks if reservation data is expires and should be evicted from store
function RoomReservation:is_expired()
    return self.meta.expires_at ~= nil and now() > self.meta.expires_at;
end

--- Main entry point for handing and routing events.
function RoomReservation:enqueue_or_route_event(event)
    if self.meta.status == STATUS.PENDING then
        table.insert(self.pending_events, event)
        if not self.api_call_triggered == true then
            self:call_api_create_conference();
        end
    else
        -- API call already complete. Immediately route without enqueueing.
        -- This could happen if request comes in between the time reservation approved
        -- and when Jicofo actually creates the room.
        module:log("debug", "Reservation details already stored. Skipping queue for %s", self.room_jid);
        self:route_event(event);
    end
end

--- Updates status and initiates event routing. Called internally when API call complete.
function RoomReservation:set_status_success(start_time, duration, mail_owner, conflict_id, data)
    module:log("info", "Reservation created successfully for %s", self.room_jid);
    self.meta = {
        status = STATUS.SUCCESS;
        mail_owner = mail_owner or self.meta.mail_owner;
        conflict_id = conflict_id;
        start_time = start_time;
        expires_at = start_time + duration;
        error_text = nil;
        error_code = nil;
    }
    if max_occupants_enabled and data.max_occupants then
        self.meta.max_occupants = data.max_occupants
    end
    if lobby_support_enabled and data.lobby then
        self.meta.lobby = data.lobby
    end
    if password_support_enabled and data.password then
        self.meta.password = data.password
    end
    self:route_pending_events()
end

--- Updates status and initiates error response to pending events. Called internally when API call complete.
function RoomReservation:set_status_failed(error_code, error_text)
    module:log("info", "Reservation creation failed for %s - (%s) %s", self.room_jid, error_code, error_text);
    self.meta = {
        status = STATUS.FAILED;
        mail_owner = self.meta.mail_owner;
        conflict_id = nil;
        start_time = self.meta.start_time;
        -- Retain reservation rejection for a short while so we have time to report failure to
        -- existing clients and not trigger a re-query too soon.
        -- N.B. Expiry could take longer since eviction happens periodically.
        expires_at = now() + 30;
        error_text = error_text;
        error_code = error_code;
    }
    self:route_pending_events()
end

--- Triggers routing of all enqueued events
function RoomReservation:route_pending_events()
    if self.meta.status == STATUS.PENDING then  -- should never be called while PENDING. check just in case.
        return;
    end

    module:log("debug", "Routing all pending events for %s", self.room_jid);
    local event;

    while #self.pending_events ~= 0 do
        event = table.remove(self.pending_events);
        self:route_event(event)
    end
end

--- Event routing implementation
function RoomReservation:route_event(event)
    -- this should only be called after API call complete and status no longer PENDING
    assert(self.meta.status ~= STATUS.PENDING, "Attempting to route event while API call still PENDING")

    local meta = self.meta;
    local origin, stanza = event.origin, event.stanza;

    if meta.status == STATUS.FAILED then
        module:log("debug", "Route: Sending reservation error to %s", stanza.attr.from);
        self:reply_with_error(event, meta.error_code, meta.error_text);
    else
        if meta.status == STATUS.SUCCESS then
            if self:is_expired() then
                module:log("debug", "Route: Sending reservation expiry to %s", stanza.attr.from);
                self:reply_with_error(event, 419, "Reservation expired");
            else
                module:log("debug", "Route: Forwarding on event from %s", stanza.attr.from);
                prosody.core_post_stanza(origin, stanza, false); -- route iq to intended target (focus)
            end
        else
            -- this should never happen unless dev made a mistake. Block by default just in case.
            module:log("error", "Reservation for %s has invalid state %s. Rejecting request.", self.room_jid, meta.status);
            self:reply_with_error(event, 500, "Failed to determine reservation state");
        end
    end
end

--- Generates reservation-error stanza and sends to event origin.
function RoomReservation:reply_with_error(event, error_code, error_text)
    local stanza = event.stanza;
    local id = stanza.attr.id;
    local to = stanza.attr.from;
    local from = stanza.attr.to;

    event.origin.send(
        st.iq({ type="error", to=to, from=from, id=id })
            :tag("error", { type="cancel" })
                :tag("service-unavailable", { xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" }):up()
                :tag("text", { xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" }):text(error_text):up()
                :tag("reservation-error", { xmlns="http://jitsi.org/protocol/focus", ["error-code"]=tostring(error_code) })
    );
end

--- Initiates non-blocking API call to validate reservation
function RoomReservation:call_api_create_conference()
    self.api_call_triggered = true;

    local url = api_prefix..'/conference';
    local request_data = {
        name = self:get_room_name();
        start_time = to_java_date_string(self.meta.start_time);
        mail_owner = self.meta.mail_owner;
    }

    local http_options = {
        body = http.formencode(request_data);  -- because Jicofo reservation encodes as form data instead JSON
        method = 'POST';
        headers = http_headers;
    }

    module:log("debug", "Sending POST /conference for %s", self.room_jid);
    async_http_request(url, http_options, function (response_body, response_code)
        self:on_api_create_conference_complete(response_body, response_code);
    end, function ()
        self:on_api_call_timeout();
    end);
end

--- Parses and validates HTTP response body for conference payload
--  Ref: https://github.com/jitsi/jicofo/blob/master/doc/reservation.md
--  @return nil if invalid, or table with payload parsed from JSON response
function RoomReservation:parse_conference_response(response_body)
    local data = json.decode(response_body);

    if data == nil then  -- invalid JSON payload
        module:log("error", "Invalid JSON response from API - %s", response_body);
        return;
    end

    if data.name == nil or data.name:lower() ~= self:get_room_name() then
        module:log("error", "Missing or mismatching room name - %s", data.name);
        return;
    end

    if data.id == nil then
        module:log("error", "Missing id");
        return;
    end

    if data.mail_owner == nil then
        module:log("error", "Missing mail_owner");
        return;
    end

    local duration = tonumber(data.duration);
    if duration == nil then
        module:log("error", "Missing or invalid duration - %s", data.duration);
        return;
    end
    data.duration = duration;

    -- if optional "max_occupants" field set, cast to number
    if data.max_occupants ~= nil then
        local max_occupants = tonumber(data.max_occupants)
        if max_occupants == nil or max_occupants < 1 then
            -- N.B. invalid max_occupants rejected even if max_occupants_enabled=false
            module:log("error", "Invalid value for max_occupants - %s", data.max_occupants);
            return;
        end
        data.max_occupants = max_occupants
    end

    -- if optional "lobby" field set, accept boolean true or "true"
    if data.lobby ~= nil then
        if (type(data.lobby) == "boolean" and data.lobby) or data.lobby == "true" then
            data.lobby = true
        else
            data.lobby = false
        end
    end

    -- if optional "password" field set, it has to be string
    if data.password ~= nil then
        if type(data.password) ~= "string" then
            -- N.B. invalid "password" rejected even if reservations_enable_password_support=false
            module:log("error", "Invalid type for password - string expected");
            return;
        end
    end

    local start_time = datetime.parse(data.start_time);  -- N.B. we lose milliseconds portion of the date
    if start_time == nil then
        module:log("error", "Missing or invalid start_time - %s", data.start_time);
        return;
    end
    data.start_time = start_time;

    return data;
end

--- Parses and validates HTTP error response body for API call.
--  Expect JSON with a "message" field.
--  @return message string, or generic error message if invalid payload.
function RoomReservation:parse_error_message_from_response(response_body)
    local data = json.decode(response_body);
    if data ~= nil and data.message ~= nil then
        module:log("debug", "Invalid error response body. Will use generic error message.");
        return data.message;
    else
        return "Rejected by reservation server";
    end
end

--- callback on API timeout
function RoomReservation:on_api_call_timeout()
    self:set_status_failed(500, 'Reservation lookup timed out');
end

--- callback on API response
function RoomReservation:on_api_create_conference_complete(response_body, response_code)
    if response_code == 200 or response_code == 201 then
        self:handler_conference_data_returned_from_api(response_body);
    elseif response_code == 409 then
        self:handle_conference_already_exist(response_body);
    elseif response_code == nil then  -- warrants a retry, but this should be done automatically by the http call method.
        self:set_status_failed(500, 'Could not contact reservation server');
    else
        self:set_status_failed(response_code, self:parse_error_message_from_response(response_body));
    end
end

function RoomReservation:handler_conference_data_returned_from_api(response_body)
    local data = self:parse_conference_response(response_body);
    if not data then  -- invalid response from API
        module:log("error", "API returned success code but invalid payload");
        self:set_status_failed(500, 'Invalid response from reservation server');
    else
        self:set_status_success(data.start_time, data.duration, data.mail_owner, data.id, data)
    end
end

function RoomReservation:handle_conference_already_exist(response_body)
    local data = json.decode(response_body);
    if data == nil or data.conflict_id == nil then
        -- yes, in the case of 409, API expected to return "id" as "conflict_id".
        self:set_status_failed(409, 'Invalid response from reservation server');
    else
        local url = api_prefix..'/conference/'..data.conflict_id;
        local http_options = {
            method = 'GET';
            headers = http_headers;
        }

        async_http_request(url, http_options, function(response_body, response_code)
            if response_code == 200 then
                self:handler_conference_data_returned_from_api(response_body);
            else
                self:set_status_failed(response_code, self:parse_error_message_from_response(response_body));
            end
        end, function ()
            self:on_api_call_timeout();
        end);
    end
end

--- End RoomReservation

--- Store reservations lookups that are still pending or with room still active
local reservations = {}

local function get_or_create_reservations(room_jid, creator_jid)
    if reservations[room_jid] == nil then
        module:log("debug", "Creating new reservation data for %s", room_jid);
        reservations[room_jid] = newRoomReservation(room_jid, creator_jid);
    end

    return reservations[room_jid];
end

local function evict_expired_reservations()
    local expired = {}

    -- first, gather jids of expired rooms. So we don't remove from table while iterating.
    for room_jid, res in pairs(reservations) do
        if res:is_expired() then
            table.insert(expired, room_jid);
        end
    end

    local room;
    for _, room_jid in ipairs(expired) do
        room = get_room_from_jid(room_jid);
        if room then
            -- Close room if still active (reservation duration exceeded)
            module:log("info", "Room exceeded reservation duration. Terminating %s", room_jid);
            room:destroy(nil, "Scheduled conference duration exceeded.");
            -- Rely on room_destroyed to calls DELETE /conference and drops reservation[room_jid]
        else
            module:log("error", "Reservation references expired room that is no longer active. Dropping %s", room_jid);
            -- This should not happen unless evict_expired_reservations somehow gets triggered
            -- between the time room is destroyed and room_destroyed callback is called. (Possible?)
            -- But just in case, we drop the reservation to avoid repeating this path on every pass.
            reservations[room_jid] = nil;
        end
    end
end

timer.add_task(expiry_check_period, function()
    evict_expired_reservations();
    return expiry_check_period;
end)

--- Intercept conference IQ to Jicofo handle reservation checks before allowing normal event flow
module:log("info", "Hook to global pre-iq/host");
module:hook("pre-iq/host", function(event)
    local stanza = event.stanza;

    if stanza.name ~= "iq" or stanza.attr.to ~= focus_component_host or stanza.attr.type ~= 'set' then
        return;  -- not IQ for jicofo. Ignore this event.
    end

    local conference = stanza:get_child('conference', 'http://jitsi.org/protocol/focus');
    if conference == nil then
        return; -- not Conference IQ. Ignore.
    end

    local room_jid = room_jid_match_rewrite(conference.attr.room);

    if get_room_from_jid(room_jid) ~= nil then
        module:log("debug", "Skip reservation check for existing room %s", room_jid);
        return;  -- room already exists. Continue with normal flow
    end

    if skip_breakout_room then
        local _, host = jid.split(room_jid);
        if host == breakout_muc_component_host then
            module:log("debug", "Skip reservation check for breakout room %s", room_jid);
            return;
        end
    end

    local res = get_or_create_reservations(room_jid, stanza.attr.from);
    res:enqueue_or_route_event(event);  -- hand over to reservation obj to route event
    return true;

end);

--- Forget reservation details once room destroyed so query is repeated if room re-created
local function room_destroyed(event)
    local res;
    local room = event.room

    if not is_healthcheck_room(room.jid) then
        res = reservations[room.jid]

        -- drop reservation data for this room
        reservations[room.jid] = nil

        if res then  -- just in case event triggered more than once?
            module:log("info", "Dropped reservation data for destroyed room %s", room.jid);

            local conflict_id = res.meta.conflict_id
            if conflict_id then
                local url = api_prefix..'/conference/'..conflict_id;
                local http_options = {
                    method = 'DELETE';
                    headers = http_headers;
                }

                module:log("debug", "Sending DELETE /conference/%s", conflict_id);
                async_http_request(url, http_options);
            end
        end
    end
end

local function room_created(event)
    local room = event.room

    if is_healthcheck_room(room.jid) then
        return;
    end

    local res = reservations[room.jid]

    if res and max_occupants_enabled and res.meta.max_occupants ~= nil then
        module:log("info", "Setting max_occupants %d for room %s", res.meta.max_occupants, room.jid);
        room._data.max_occupants = res.meta.max_occupants
    end

    if res and password_support_enabled and res.meta.password ~= nil then
        module:log("info", "Setting password for room %s", room.jid);
        room:set_password(res.meta.password);
    end
end

local function room_pre_create(event)
    local room = event.room

    if is_healthcheck_room(room.jid) then
        return;
    end

    local res = reservations[room.jid]

    if res and lobby_support_enabled and res.meta.lobby then
        module:log("info", "Enabling lobby for room %s", room.jid);
        prosody.events.fire_event("create-persistent-lobby-room", { room = room; });
    end
end

function process_host(host)
    if host == muc_component_host then -- the conference muc component
        module:log("info", "Hook to muc-room-destroyed on %s", host);
        module:context(host):hook("muc-room-destroyed", room_destroyed, -1);

        if max_occupants_enabled or password_support_enabled then
            module:log("info", "Hook to muc-room-created on %s (max_occupants or password integration enabled)", host);
            module:context(host):hook("muc-room-created", room_created);
        end

        if lobby_support_enabled then
            module:log("info", "Hook to muc-room-pre-create on %s (lobby integration enabled)", host);
            module:context(host):hook("muc-room-pre-create", room_pre_create);
        end
    end
end

if prosody.hosts[muc_component_host] == nil then
    module:log("info", "No muc component found, will listen for it: %s", muc_component_host)
    prosody.events.add_handler("host-activated", process_host);
else
    process_host(muc_component_host);
end


text:
/** Automatically generated file. DO NOT MODIFY */
package in.pathri.codenvydownloadbeta;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}

redpajama_set_name: RedPajamaGithub


text:
package org.infinispan.hadoop.flink.sample;

import java.util.List;
import java.util.stream.IntStream;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.hadoopcompatibility.HadoopInputs;
import org.apache.flink.util.Collector;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.infinispan.hadoop.InfinispanConfiguration;
import org.infinispan.hadoop.InfinispanInputFormat;

/**
 * Apache Flink job to calculate histograms with number of words on phrases.
 *

 * This demonstrates connecting Flink with Infinispan by using {@link org.infinispan.hadoop.InfinispanInputFormat} and
 * {@link org.infinispan.hadoop.InfinispanOutputFormat}.
 *
Data is located in the cache "phrases" of Infinispan server with types <Long,String> and each entry has a
 * phrase with 1 or more words

 * Output should be:

 * HISTOGRAM:
 *

 * 2 word phrases: ****** (6)

 * 3 word phrases: ************ (12)

 * 4 word phrases: ***************************************** (41)

 * 5 word phrases: ********** (10)

 *

 */
public class WordFrequency {

   public static void main(String[] args) throws Exception {
      if (args.length < 1) {
         System.err.println("Usage: WordFrequency <ispn-server-ip>");
         System.exit(1);
      }

      // Configure the Infinispan InputFormat wrapping it in a Hadoop Job class.
      // In this sample, no writing to Infinispan will happen, so no need to configure
      // an InfinispanOutputFormat
      Configuration configuration = new Configuration();
      configuration.set(InfinispanConfiguration.INPUT_REMOTE_CACHE_SERVER_LIST, args[0]);
      configuration.set(InfinispanConfiguration.INPUT_REMOTE_CACHE_NAME, "phrases");
      Job job = Job.getInstance(configuration, "Infinispan Integration");
      InfinispanInputFormat<Integer, String> infinispanInputFormat = new InfinispanInputFormat<>();

      // Obtain the Execution environment from Flink
      final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

      // Create a DataSource that reads data using the InfinispanInputFormat

      DataSource<Tuple2<Integer, String>> infinispanDS = env.createInput(
            HadoopInputs.createHadoopInput(infinispanInputFormat, Integer.class, String.class, job)
      );

      // Count entries
      long count = infinispanDS.count();

      // Obtain the values from entries
      DataSet<String> values = infinispanDS.map(entry -> entry.f1).returns(String.class);

      // Obtain phrase lengths (length,1) for the values
      DataSet<Tuple2<Integer, Integer>> lengthsCount = values.flatMap(new FlatMapFunction<String, Tuple2<Integer, Integer>>() {
         @Override
         public void flatMap(String s, Collector<Tuple2<Integer, Integer>> collector) throws Exception {
            collector.collect(new Tuple2<>(s.split(" ").length, 1));
         }
      });

      // Create the histogram
      List<Tuple2<Integer, Integer>> results = lengthsCount.groupBy(0).sum(1).collect();

      // Format results and print to stdout
      printResults(count, results);
   }

   private static void printResults(long entries, List<Tuple2<Integer, Integer>> results) {
      System.out.printf("TOTAL PHRASES ANALYZED: %d. HISTOGRAM:\n", entries);
      results.forEach(t -> {
         Integer wordNumber = t.f0;
         Integer count = t.f1;
         System.out.printf("%-3d word phrases:", wordNumber);
         IntStream.range(1, count).boxed().forEach(c -> System.out.print("*"));
         System.out.printf("(%d)\n", count);
      });
   }

}


text:
@include('admin.header')

		@if (Session::has('getscrap'))

		@else

		@endif
			{{ Form::open(array('action'=>'AdminController@post_advance_scraping')) }}

Scrap Setting

						Crawled URL

							{{ Form::select('crawled_url', $geturl, Input::old('crawled_url'), array('class'=>'ui dropdown')) }}

						Title Element

							{{ Form::input('text', 'title', null, array('placeholder'=>'Ex: div#title')) }}

						Article Element

							{{ Form::input('text', 'article', null, array('placeholder'=>'Ex: div#article')) }}

				{{ Form::submit('Scrap', array('class'=>'ui submit button')) }}
			{{ Form::close() }}

Scrap Result

				Scrapped URL
				Article Title
				Article Content

@include('admin.footer')


text:
CC=g++
CXX=g++
BUILD_INFO=-DPP_VERSION=\"$(shell git describe --always)\" -DPP_BUILD_ID=\"$(BUILD_ID)\" -DPP_BUILD_NUMBER=\"$(BUILD_NUMBER)\" -DPP_BUILD_TIME=\"$(shell date +%Y-%m-%dT%H:%M:%S)\"
CFLAGS += -g -O3
CXXFLAGS += -fPIC -Ijson11 $(shell pkg-config --cflags opencv4) -I3rd/fmt/include -I3rd/spdlog/include -I3rd/json/single_include/nlohmann -ICatch/include -ISimple-Web-Server -ISimple-Web-Extra -Wall -Wno-sign-compare -std=c++17 -fopenmp -g -O3 -pthread -msse4.2 $(BUILD_INFO)
#CXXFLAGS += -fPIC -Ijson11 $(shell pkg-config --cflags opencv4) -ICatch/include -ISimple-Web-Server -ISimple-Web-Extra -Wall -Wno-sign-compare -std=c++17 -fopenmp -g -O3 -pthread -msse4.2 $(BUILD_INFO)
#CXXFLAGS += -DSUPPORT_AUDIO_SPECTROGRAM=1
LDFLAGS += -fopenmp -std=c++17
LDLIBS = libpicpac.a $(shell pkg-config --libs opencv4) -lboost_timer -lboost_chrono -lboost_program_options -lboost_thread -lboost_system -lglog -lgflags

SERVER_LIBS = \
          -lopencv_highgui -lopencv_imgproc -lopencv_imgcodecs -lopencv_core \
	      -lturbojpeg -ltiff -lpng -lwebp -llibjasper -lippicv \
	      -lboost_timer -lboost_chrono -lboost_program_options -lboost_thread -lboost_filesystem -lboost_system \
	      -lglog -lgflags \
	      -lmagic -lunwind \
	      -lz -lrt -lcares -ldl

HEADERS = picpac.h picpac-image.h picpac-util.h
COMMON = picpac-util.o picpac-image.o picpac.o json11.o picpac-image.o shapes.o transforms.o

PROGS = picpac-filter picpac-kfold picpac-unpack picpac-merge picpac-split picpac-downsize picpac-crop picpac-split-region picpac-dupe test stress picpac-import picpac-stream picpac-proto picpac-roi-scale picpac-stat picpac-point2ellipse #picpac-annotate picpac-dumpvec#load-caffe load-dir test test_tr server

.PHONY:	all release python upload_test upload sdist bfdfs

all:	libpicpac.so libpicpac.a $(PROGS) python

python:
	python setup.py build

release:
	rm -rf release
	mkdir -p release
	for p in $(PROGS) ; do cp $$p release/picpac-$$p; done

libpicpac.a:	$(COMMON)
	ar rvs $@ $^

libpicpac.so:	$(COMMON)
	gcc -shared -o $@ $^

%.o:	%.cpp $(HEADERS)
	$(CXX) $(CXXFLAGS) -c $*.cpp

json11.o:	json11/json11.cpp
	$(CXX) $(CXXFLAGS) -o $@ -c $^

$(PROGS):	%:	%.o libpicpac.a
	$(CXX) $(LDFLAGS) -o $@ $^ $(LDLIBS)

picpac-explorer:	picpac-explorer.o html_static.o libpicpac.a
	if [ ! -d /opt/cbox ] ; then echo "!!!BUILD SERVER WITH make-server.sh !!!"; false; fi
	$(CXX) $(LDFLAGS) -static -o $@ $^ $(SERVER_LIBS)
	mv html_static.o html_static.o.last
	cp $@ $@.full
	objcopy --only-keep-debug $@ $@.debug
	strip -g $@
	cp $@ $@.bin
	upx $@

bfdfs:
	if [ ! -f bfdfs/bfdfs-load ] ; then \
		pushd bfdfs; cmake . ; make ; popd ; fi

html_static.o:	bfdfs
	if [ -f html_static.o.bz2 ]; then	\
		bzcat html_static.o.bz2 > html_static.o ; \
	else \
		make -C copilot ; \
		bfdfs/bfdfs-load $@ copilot/dist --name html_static ; \
	fi
	#cat magic/* > magic.tmp
	#file -C -m magic.tmp
	#mv magic.tmp.mgc html/static/magic.mgc

clean:
	rm *.o $(PROGS)

upload_test:
	python setup.py sdist upload -r pypitest

sdist:
	python setup.py sdist


text:
package org.apache.lucene.search;

import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

import junit.framework.TestCase;

import java.io.IOException;
import java.util.LinkedList;

/**
 * This class tests PhrasePrefixQuery class.
 *
 * @author Otis Gospodnetic
 * @version $Id: TestPhrasePrefixQuery.java 150694 2004-12-05 18:21:58Z bmesser $
 */
public class TestPhrasePrefixQuery
    extends TestCase
{
    public TestPhrasePrefixQuery(String name)
    {
        super(name);
    }

    /**
     *
     */
    public void testPhrasePrefix()
        throws IOException
    {
        RAMDirectory indexStore = new RAMDirectory();
        IndexWriter writer = new IndexWriter(indexStore, new SimpleAnalyzer(), true);
        Document doc1 = new Document();
        Document doc2 = new Document();
        Document doc3 = new Document();
        Document doc4 = new Document();
        Document doc5 = new Document();
        doc1.add(Field.Text("body", "blueberry pie"));
        doc2.add(Field.Text("body", "blueberry strudel"));
        doc3.add(Field.Text("body", "blueberry pizza"));
        doc4.add(Field.Text("body", "blueberry chewing gum"));
        doc5.add(Field.Text("body", "piccadilly circus"));
        writer.addDocument(doc1);
        writer.addDocument(doc2);
        writer.addDocument(doc3);
        writer.addDocument(doc4);
        writer.addDocument(doc5);
        writer.optimize();
        writer.close();

        IndexSearcher searcher = new IndexSearcher(indexStore);

        PhrasePrefixQuery query1 = new PhrasePrefixQuery();
        PhrasePrefixQuery query2 = new PhrasePrefixQuery();
        query1.add(new Term("body", "blueberry"));
        query2.add(new Term("body", "strawberry"));

        LinkedList termsWithPrefix = new LinkedList();
        IndexReader ir = IndexReader.open(indexStore);

        // this TermEnum gives "piccadilly", "pie" and "pizza".
        String prefix = "pi";
        TermEnum te = ir.terms(new Term("body", prefix + "*"));
        do {
            if (te.term().text().startsWith(prefix))
            {
                termsWithPrefix.add(te.term());
            }
        } while (te.next());

        query1.add((Term[])termsWithPrefix.toArray(new Term[0]));
        query2.add((Term[])termsWithPrefix.toArray(new Term[0]));

        Hits result;
        result = searcher.search(query1);
        assertEquals(2, result.length());

        result = searcher.search(query2);
        assertEquals(0, result.length());
    }
}


text:
package com.db4o.io;

/**
 * Bounded handle into an IoAdapter: Can only access a restricted area.
 * @exclude
 */
public class BlockAwareBinWindow {

	private BlockAwareBin _bin;
	private int _blockOff;
	private int _len;
	private boolean _disabled;

	/**
	 * @param io The delegate I/O adapter
	 * @param blockOff The block offset address into the I/O adapter that maps to the start index (0) of this window
	 * @param len The size of this window in bytes
	 */
	public BlockAwareBinWindow(BlockAwareBin io,int blockOff,int len) {
		_bin = io;
		_blockOff=blockOff;
		_len=len;
		_disabled=false;
	}

	/**
	 * @return Size of this I/O adapter window in bytes.
	 */
	public int length() {
		return _len;
	}

	/**
	 * @param off Offset in bytes relative to the window start
	 * @param data Data to write into the window starting from the given offset
	 */
	public void write(int off,byte[] data) throws IllegalArgumentException, IllegalStateException{
		checkBounds(off, data);
		_bin.blockWrite(_blockOff+off, data);
	}

	/**
	 * @param off Offset in bytes relative to the window start
	 * @param data Data buffer to read from the window starting from the given offset
	 */
	public int read(int off,byte[] data) throws IllegalArgumentException, IllegalStateException {
		checkBounds(off, data);
		return _bin.blockRead(_blockOff+off, data);
	}

	/**
	 * Disable IO Adapter Window
	 */
	public void disable() {
		_disabled=true;
	}

	/**
	 * Flush IO Adapter Window
	 */
	public void flush()  {
		if(!_disabled) {
			_bin.sync();
		}
	}

	private void checkBounds(int off, byte[] data) {
		if(_disabled) {
			throw new IllegalStateException();
		}
		if(data==null||off<0||off+data.length>_len) {
			throw new IllegalArgumentException();
		}
	}
}


text:
@interface DBMessagingPhotoPickerPresentationController ()

@property (strong, nonatomic) UIView *dimmingView;
@property (strong, nonatomic) UITapGestureRecognizer *dimmingViewTap;

@end

@implementation DBMessagingPhotoPickerPresentationController

#pragma mark - Getters

- (UIView *)dimmingView {

    if (!_dimmingView) {
        _dimmingView = [[UIView alloc] init];
        _dimmingView.frame = self.containerView.bounds;
        _dimmingView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _dimmingView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        _dimmingView.alpha = 0.0;

        _dimmingViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)];
        [_dimmingView addGestureRecognizer:_dimmingViewTap];
    }

    return _dimmingView;
}

- (void)presentationTransitionWillBegin {
    [super presentationTransitionWillBegin];

    // Add the dimming view and the presented view to the heirarchy
    [self.containerView addSubview:self.dimmingView];
    [self.containerView addSubview:self.presentedView];

    // Fade in the dimming view alongside the transition
    id<UIViewControllerTransitionCoordinator> transitionCoordinator = self.presentingViewController.transitionCoordinator;

    [transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        self.dimmingView.alpha = 1.0;
    } completion:nil];
}

- (void)presentationTransitionDidEnd:(BOOL)completed {
    [super presentationTransitionDidEnd:completed];

    // If the presentation didn't complete, remove the dimming view
    if (!completed) {
        [self.dimmingView removeFromSuperview];
    }
}

- (void)dismissalTransitionWillBegin {
    [super dismissalTransitionWillBegin];

    // Fade out the dimming view alongside the transition
    id<UIViewControllerTransitionCoordinator> transitionCoordinator = self.presentingViewController.transitionCoordinator;

    [transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        self.dimmingView.alpha = 0.0;
    } completion:nil];
}

- (void)dismissalTransitionDidEnd:(BOOL)completed {
    [super dismissalTransitionDidEnd:completed];

    // If the dismissal completed, remove the dimming view
    if (completed) {
        [self.dimmingView removeFromSuperview];
    }
}

- (CGRect)frameOfPresentedViewInContainerView {
    CGRect superFrame = [super frameOfPresentedViewInContainerView];

    CGRect frame = superFrame;
    frame.size.height = MAX(290.0, superFrame.size.height * 0.7);
    frame.origin.y = superFrame.size.height  - frame.size.height;
    return frame;
}

#pragma mark - Actions

- (void)dismiss:(id)sender {
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
// Auto-generated. Do not edit.

    /**
     * Functions to support the MLX90614 sensor
     */
    //%
declare namespace mlx90614 {

    /**
     * Reads the temperature from the IR sensor MLX90614
     */
    //% blockId=mlx90614 block="temperature %loc" shim=mlx90614::temperature
    function temperature(loc: TemperatureLocation): number;
}

// Auto-generated. Do not edit. Really.


text:
<?php
/**
 * Created by IntelliJ IDEA.
 * User: vova
 * Date: 06.01.14
 * Time: 19:39
 */

namespace GeekHub\BlogBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;

class TagAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name', 'text');
    }

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('name');
    }
}


text:
<?php

namespace Modules\Content\Models;

use Illuminate\Database\Eloquent\Model;
use Modules\Admin\Traits\BootStapler;
use Codesleeve\Stapler\ORM\EloquentTrait;
use Codesleeve\Stapler\ORM\StaplerableInterface;

class WidgetBlockItem extends Model
{

    /**
     * @var string
     */
    protected $table = 'netcore_content__widget_block_items';

    /**
     * @var bool
     */
    public $timestamps = false;

    /**
     * @var array
     */
    protected $fillable = [
        'order',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function widgetBlock()
    {
        return $this->belongsTo(WidgetBlock::class);
    }

    /**
     * @return mixed
     */
    public function fields()
    {
        return $this->hasMany(WidgetBlockItemField::class);
    }

    /**
     * @param String $key
     * @return mixed
     */
    public function getField(String $key)
    {
        $field = $this->fields->where('key', $key)->first();

        return $field ? $field->value : '';
    }

    /**
     * @return mixed
     */
    public function getFieldAttribute()
    {
        return $this->fields->mapWithKeys(function ($item) {
            if($item->image_file_name) {
                return [
                    $item->key => $item->image->url()
                ];
            }
            return [
                $item->key => $item->value
            ];
        });
    }

    /**
     * @param String $key
     * @return mixed
     */
    public function getStaplerObj(String $key)
    {
        $field = $this->fields->where('key', $key)->first();

        return $field ? $field->image : null;
    }
}


text:
import socket, sys

from mccorelib.config    import ConfigError
from squib.oxidizers.base import PeriodicOxidizer

##############################################################################

class HaproxyOxidizer (PeriodicOxidizer):

    stats = ( 'qcur', 'qmax', 'scur', 'smax', 'slim', 'stot', 'bin', 'bout',
              'dreq', 'dresp', 'erep', 'econ', 'eresp', 'wretr', 'wredis', 'status',
              'weight', 'act', 'bck', 'chkfail', 'chkdown', 'lastchg', 'downtime' )

    def setup (self):
        super(HaproxyOxidizer, self).setup()
        self.setup_stats_socket()
        self.num_stats = len(self.stats)

    def setup_stats_socket (self):
        self.stats_socket = self.config.get('stats_socket')
        if self.stats_socket is None:
            raise ConfigError('%s::stats_socket must be specified' % self.name)

    def run_once (self):
        raw = self.read_stats_socket()
        if raw is None: return
        for line in raw.split('\n'):
            if not line or line[0] == '#': continue
            parts = line.split(',', self.num_stats + 2)
            if parts[1] == 'BACKEND': continue
            for idx in range(self.num_stats):
                val = parts[idx+2]
                if val:
                    m = self.stats[idx]
                    if m == 'status':
                        mtype = 'string'
                    else:
                        mtype = 'gauge'
                    print '%s.%s.%s.%s %s %s' % (self.name, parts[0], parts[1], m, mtype, val)

    def read_stats_socket (self):
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            try:
                sock.connect(self.stats_socket)
                sock.sendall('show stat\n')
                results = ''
                data = sock.recv(8192)
                while data:
                    results += data
                    data = sock.recv(2048)
                return results
            finally:
                sock.close()
        except socket.error, msg:
            # Failed to retrieve the stats. Damn
            return None

##############################################################################

if __name__ == "__main__":
    HaproxyOxidizer('haproxy', dict(period=5.0, stats_socket='/var/run/haproxy.stats')).run()

##############################################################################
## THE END


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Boltovskoy, Limnobios 2(8): 643 (1984)

#### Original name
Aphanomycopsis peridiniella Boltovskoy & Aramb., 1984

### Remarks
null


text:
'use strict';

var assert = require('assert');
var extend = require('extend');
var format = require('string-format-obj');
var nodeutil = require('util');
var proxyquire = require('proxyquire');
var ServiceObject = require('@google-cloud/common').ServiceObject;
var util = require('@google-cloud/common').util;

var promisified = false;
var fakeUtil = extend({}, util, {
  promisifyAll: function(Class, options) {
    if (Class.name !== 'Network') {
      return;
    }

    promisified = true;
    assert.deepEqual(options.exclude, ['firewall']);
  }
});

function FakeServiceObject() {
  this.calledWith_ = arguments;
  ServiceObject.apply(this, arguments);
}

nodeutil.inherits(FakeServiceObject, ServiceObject);

describe('Network', function() {
  var Network;
  var network;

  var REGION;
  var Region;

  var COMPUTE = {
    projectId: 'project-id',
    createNetwork: util.noop
  };
  var NETWORK_NAME = 'network-name';
  var NETWORK_FULL_NAME = format('projects/{pId}/global/networks/{name}', {
    pId: COMPUTE.projectId,
    name: NETWORK_NAME
  });
  var REGION_NAME = 'region-name';

  before(function() {
    Network = proxyquire('../src/network.js', {
      '@google-cloud/common': {
        ServiceObject: FakeServiceObject,
        util: fakeUtil
      }
    });

    Region = require('../src/region.js');
  });

  beforeEach(function() {
    network = new Network(COMPUTE, NETWORK_NAME);
    REGION = new Region(COMPUTE, REGION_NAME);
  });

  describe('instantiation', function() {
    it('should promisify all the things', function() {
      assert(promisified);
    });

    it('should localize the compute instance', function() {
      assert.strictEqual(network.compute, COMPUTE);
    });

    it('should localize the name', function() {
      assert.strictEqual(network.name, NETWORK_NAME);
    });

    it('should format the network name', function() {
      var formatName_ = Network.formatName_;
      var formattedName = 'projects/a/global/networks/b';

      Network.formatName_ = function(compute, name) {
        Network.formatName_ = formatName_;

        assert.strictEqual(compute, COMPUTE);
        assert.strictEqual(name, NETWORK_NAME);

        return formattedName;
      };

      var network = new Network(COMPUTE, NETWORK_NAME);
      assert(network.formattedName, formattedName);
    });

    it('should inherit from ServiceObject', function(done) {
      var computeInstance = extend({}, COMPUTE, {
        createNetwork: {
          bind: function(context) {
            assert.strictEqual(context, computeInstance);
            done();
          }
        }
      });

      var network = new Network(computeInstance, NETWORK_NAME);
      assert(network instanceof ServiceObject);

      var calledWith = network.calledWith_[0];

      assert.strictEqual(calledWith.parent, computeInstance);
      assert.strictEqual(calledWith.baseUrl, '/global/networks');
      assert.strictEqual(calledWith.id, NETWORK_NAME);
      assert.deepEqual(calledWith.methods, {
        create: true,
        exists: true,
        get: true,
        getMetadata: true
      });
    });
  });

  describe('formatName_', function() {
    it('should format the name', function() {
      var formattedName_ = Network.formatName_(COMPUTE, NETWORK_NAME);
      assert.strictEqual(formattedName_, NETWORK_FULL_NAME);
    });
  });

  describe('createFirewall', function() {
    it('should make the correct call to Compute', function(done) {
      var name = 'firewall-name';
      var config = { a: 'b', c: 'd' };
      var expectedConfig = extend({}, config, {
        network: network.formattedName
      });

      network.compute.createFirewall = function(name_, config_, callback) {
        assert.strictEqual(name_, name);
        assert.deepEqual(config_, expectedConfig);
        callback();
      };

      network.createFirewall(name, config, done);
    });
  });

  describe('createSubnetwork', function() {
    it('should call region.createSubnetwork correctly', function(done) {
      var name = 'subnetwork-name';
      var region = {};
      var config = {
        a: 'b',
        c: 'd',
        region: REGION_NAME
      };

      var expectedConfig = extend({}, config, {
        network: network.formattedName
      });
      delete expectedConfig.region;

      network.compute.region = function(name) {
        assert.strictEqual(name, REGION_NAME);
        return region;
      };

      region.createSubnetwork = function(name_, config, callback) {
        assert.strictEqual(name_, name);
        assert.deepEqual(config, expectedConfig);

        callback(); // done();
      };

      network.createSubnetwork(name, config, done);
    });
  });

  describe('delete', function() {
    it('should call ServiceObject.delete', function(done) {
      FakeServiceObject.prototype.delete = function() {
        assert.strictEqual(this, network);
        done();
      };

      network.delete();
    });

    describe('error', function() {
      var error = new Error('Error.');
      var apiResponse = { a: 'b', c: 'd' };

      beforeEach(function() {
        FakeServiceObject.prototype.delete = function(callback) {
          callback(error, apiResponse);
        };
      });

      it('should return an error if the request fails', function(done) {
        network.delete(function(err, operation, apiResponse_) {
          assert.strictEqual(err, error);
          assert.strictEqual(operation, null);
          assert.strictEqual(apiResponse_, apiResponse);
          done();
        });
      });

      it('should not require a callback', function() {
        assert.doesNotThrow(function() {
          network.delete();
        });
      });
    });

    describe('success', function() {
      var apiResponse = {
        name: 'op-name'
      };

      beforeEach(function() {
        FakeServiceObject.prototype.delete = function(callback) {
          callback(null, apiResponse);
        };
      });

      it('should execute callback with Operation & Response', function(done) {
        var operation = {};

        network.compute.operation = function(name) {
          assert.strictEqual(name, apiResponse.name);
          return operation;
        };

        network.delete(function(err, operation_, apiResponse_) {
          assert.ifError(err);
          assert.strictEqual(operation_, operation);
          assert.strictEqual(operation_.metadata, apiResponse);
          assert.strictEqual(apiResponse_, apiResponse);
          done();
        });
      });

      it('should not require a callback', function() {
        assert.doesNotThrow(function() {
          network.delete();
        });
      });
    });
  });

  describe('firewall', function() {
    it('should return a Firewall with the correct metadata', function() {
      var name = 'firewall-name';
      var firewall = {};

      network.compute.firewall = function(name_) {
        assert.strictEqual(name_, name);
        return firewall;
      };

      var firewallInstance = network.firewall(name);
      assert.deepEqual(firewallInstance.metadata, {
        network: network.formattedName
      });
    });
  });

  describe('getFirewalls', function() {
    it('should make the correct call to Compute', function(done) {
      var options = { a: 'b', c: 'd' };
      var expectedOptions = extend({}, options, {
        filter: 'network eq .*' + network.formattedName
      });

      network.compute.getFirewalls = function(options, callback) {
        assert.deepEqual(options, expectedOptions);
        callback();
      };

      network.getFirewalls(options, done);
    });

    it('should not require options', function(done) {
      network.compute.getFirewalls = function(options, callback) {
        callback();
      };

      network.getFirewalls(done);
    });
  });

  describe('getFirewallsStream', function() {
    it('should call to getFirewallsStream correctly', function(done) {
      var options = { a: 'b', c: 'd' };
      var expectedOptions = extend({}, options, {
        filter: 'network eq .*' + network.formattedName
      });

      network.compute.getFirewallsStream = function(options) {
        assert.deepEqual(options, expectedOptions);
        done();
      };

      network.getFirewallsStream(options);
    });

    it('should not require options', function(done) {
      network.compute.getFirewallsStream = function() {
        done();
      };

      network.getFirewallsStream();
    });

    it('should return a stream', function(done) {
      var fakeStream = {};

      network.compute.getFirewallsStream = function() {
        setImmediate(done);
        return fakeStream;
      };

      var stream = network.getFirewallsStream();
      assert.strictEqual(stream, fakeStream);
    });
  });

  describe('getSubnetworks', function() {
    it('should call to compute.getSubnetworks correctly', function(done) {
      var options = { a: 'b', c: 'd' };
      var expectedOptions = extend({}, options, {
        filter: 'network eq .*' + network.formattedName
      });

      network.compute.getSubnetworks = function(options, callback) {
        assert.deepEqual(options, expectedOptions);
        callback();
      };

      network.getSubnetworks(options, done);
    });

    it('should not require options', function(done) {
      network.compute.getSubnetworks = function(options, callback) {
        callback();
      };

      network.getSubnetworks(done);
    });
  });

  describe('getSubnetworksStream', function() {
    it('should call to getSubnetworksStream correctly', function(done) {
      var options = { a: 'b', c: 'd' };
      var expectedOptions = extend({}, options, {
        filter: 'network eq .*' + network.formattedName
      });

      network.compute.getSubnetworksStream = function(options) {
        assert.deepEqual(options, expectedOptions);
        done();
      };

      network.getSubnetworksStream(options);
    });

    it('should not require options', function(done) {
      network.compute.getSubnetworksStream = function() {
        done();
      };

      network.getSubnetworksStream();
    });

    it('should return a stream', function(done) {
      var fakeStream = {};

      network.compute.getSubnetworksStream = function() {
        setImmediate(done);
        return fakeStream;
      };

      var stream = network.getSubnetworksStream();
      assert.strictEqual(stream, fakeStream);
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="shared_user_label" translatable="false">Maps With Me</string>

  <!-- FB -->
  <string name="fb_app_id" translatable="false">185237551520383</string>

  <!-- App names -->
  <string name="facebook" translatable="false">Facebook</string>
  <string name="twitter" translatable="false">Twitter</string>
  <string name="google" translatable="false">Google</string>
  <string name="openstreetmap" translatable="false">OpenStreetMap</string>

  <!-- Font names -->
  <string name="robotoLight" translatable="false">sans-serif-light</string>
  <string name="robotoRegular" translatable="false">sans-serif</string>
  <string name="robotoCondensed" translatable="false">sans-serif-condensed</string>
  <!-- roboto thin (android 4.2)-->
  <string name="robotoThin" translatable="false">sans-serif-thin</string>
  <!--  roboto medium (android 5.0)-->
  <string name="robotoMedium" translatable="false">sans-serif-medium</string>

  <!--  Prefs -->
  <string name="pref_send_statistics" translatable="false">AllowStat</string>
  <string name="pref_munits" translatable="false">MeasurementUnits</string>
  <string name="pref_storage" translatable="false">Storage</string>
  <string name="pref_show_zoom_buttons" translatable="false">ZoomButtonsEnabled</string>
  <string name="pref_play_services" translatable="false">PlayServicesEnabled</string>
  <string name="pref_about" translatable="false">AboutMapsWithMe</string>
  <string name="pref_rate_app" translatable="false">RateApp</string>
  <string name="pref_help" translatable="false">Help</string>
  <string name="pref_copyright" translatable="false">Copyright</string>
  <string name="pref_report_bug" translatable="false">ReportBug</string>
  <string name="pref_community" translatable="false">Community</string>
  <string name="pref_like_fb" translatable="false">LikeFb</string>
  <string name="pref_follow_twitter" translatable="false">FollowTwitter</string>
  <string name="pref_contact" translatable="false">ContactUs</string>
  <string name="pref_subscribe" translatable="false">Subscribe</string>
  <string name="pref_settings" translatable="false">Settings</string>
  <string name="pref_file_name" translatable="false">MapsMePrefs</string>
  <string name="pref_map_style" translatable="false">MapStyle</string>
  <string name="pref_tts_enabled" translatable="false">TtsEnabled</string>
  <string name="pref_tts_language" translatable="false">TtsLanguage</string>
  <string name="pref_autodownload" translatable="false">AutoDownloadMap</string>
  <string name="pref_3d" translatable="false">3D</string>
  <string name="pref_3d_buildings" translatable="false">3DBuildings</string>
  <string name="pref_track_record" translatable="false">TrackRecord</string>
  <string name="pref_showcase_switched_on" translatable="false">DisplayShowcase</string>
  <string name="pref_osm_profile" translatable="false">Osm profile</string>
  <string name="pref_auto_zoom" translatable="false">AutoZoom</string>
  <string name="pref_route_network" translatable="false">RegulatoryNetwork</string>

  <string name="pref_vehicle_enabled" translatable="false">VehicleEnabled</string>
  <string name="pref_vehicle_length" translatable="false">VehicleLength</string>
  <string name="pref_vehicle_width" translatable="false">VehicleWidth</string>
  <string name="pref_vehicle_height" translatable="false">VehicleHeight</string>
  <string name="pref_vehicle_weight" translatable="false">VehicleWeight</string>

  <string name="notification_ticker_ltr" translatable="false">%1$s: %2$s</string>
  <string name="notification_ticker_rtl" translatable="false">%2$s :%1$s</string>

  <!-- "Report a problem" predefined texts -->
  <string name="problem_does_not_exist" translatable="false">The amenity has gone or never existed. This is an auto-generated note from MAPS.ME application: a user reports a POI that is visible on a map (which can be a month old), but cannot be found on the ground.</string>

  <!-- UI themes -->
  <string name="theme_default" translatable="false">default</string>
  <string name="theme_night" translatable="false">night</string>
  <string name="theme_auto" translatable="false">auto</string>

  <!-- Tags -->
  <string name="tag_menu_collapse" translatable="false">collapse</string>
  <string name="tag_height_limited" translatable="false">height limited</string>
</resources>


text:
require_relative 'spec_helper'

describe SelfML do

  subject { SelfML }
  let(:fixtures) { load_fixture "strings" }

  describe "Strings" do

    it "is a verbatim string" do
    end

    it "is a bracketed string" do
    end

    it "is a backtick string" do
    end

    it "parses example correctly" do
      assert_equal subject.parse(fixtures[:input]).to_s, fixtures[:output]
    end

  end

end


text:
import tornado.ioloop
import tornado.web

import skynet.config as CONFIG
from skynet.routes.auth import AuthRoute
from grey.routes.auth import AuthRoute

def main(debug = True, port = CONFIG.PORT):
    application = tornado.web.Application([
        AuthRoute
    ], debug = debug
     , autoreload = debug)

    application.listen(port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()


text:
from django.core.management.base import BaseCommand

from runs.runkeeper import pull_all_users_runs_from_runkeeper

class Command(BaseCommand):
    help = 'Updates runs of all users that have registered with runkeeper'

    def handle(self, *args, **options):
        pull_all_users_runs_from_runkeeper()
        print 'Successfully updated runs for all users'


text: typedef Interrupt<TIMER1_CAPT_vect_num> TIMER1_CAPTInterrupt;


text:
describe('Array#indexOf()', function () {
    beforeEach(function () {
        this.ary = [1,2,3];
    });
    it('should return index when the value is present', function () {
        var who = 'ariya', two = 2;
        assert(this.ary.indexOf(who) === two);
    });
    it('should return -1 when the value is not present', function () {
        var minusOne = -1, two = 2;
        assert.ok(this.ary.indexOf(two) === minusOne, 'THIS IS AN ASSERTION MESSAGE');
    });
});


text:
ASSIMILATE! ASSIMILATE!
=======================
Ubuntu version.

Let's install:

* git
* vim-nox
* tree
* ghc-7.8.*
* J

Steps
-----
Preliminaries:

    sudo apt-get install git
    sudo apt-get install software-properties-common

The next steps should follow either method A or method B.  I did A then B and I'm not sure which worked.

Method A:
---------
Install via a PPA

    sudo add-apt-repository ppa:hvr/ghc
    sudo apt-get update
    sudo apt-get install ghc

Method B:
---------
Install via the experimental repositories

1. modify `/etc/apt/sources.list` so it looks something like this:

    $ cat /etc/apt/sources.list
    deb http://ftp.debian.org/debian experimental main contrib non-free
    deb-src http://ftp.debian.org/debian experimental main contrib non-free
    deb http://ports.ubuntu.com/ubuntu-ports/ trusty main restricted universe multiverse
    deb-src http://ports.ubuntu.com/ubuntu-ports/ trusty main restricted universe multiverse
    deb http://ports.ubuntu.com/ubuntu-ports/ trusty-updates main restricted universe multiverse
    deb-src http://ports.ubuntu.com/ubuntu-ports/ trusty-updates main restricted universe multiverse
    deb http://ports.ubuntu.com/ubuntu-ports/ trusty-security main restricted universe multiverse
    deb-src http://ports.ubuntu.com/ubuntu-ports/ trusty-security main restricted universe multiverse

2. Update and install the right version of GHC

    sudo apt-get update
    sudo apt-get -t experimental install ghc

The whole reason for this GHC insanity is to install the Elm compiler.  More prerequisites:

    sudo apt-get install zlib1g-dev
    sudo apt-get install cabal
    cabal update
    cabal install cabal-install


text:
function [accuracy] = nFoldValidation(features,genres,n,K)

numClasses = 5;
featureSet = size(features);
setSize = featureSet(1);
testSetSize = round(setSize/n);
trainSetSize = setSize - testSetSize;

positives = 0;

% randomize the songs sequence
randomPositions = randi(setSize,setSize,1);

% confusionMatrices = zeros(numClasses,numClasses,10);

for i=1:n

    testData = features(randomPositions(i*testSetSize-testSetSize+1:i*testSetSize),:);
    testLabels = genres(randomPositions(i*testSetSize-testSetSize+1:i*testSetSize),:);

    if i==n
        trainData  = features(randomPositions(1:i*testSetSize-testSetSize),:);
        trainLabels = genres(randomPositions(1:i*testSetSize-testSetSize));
    else
        if i==1
           trainData = features(randomPositions(i*testSetSize+1:setSize),:);
           trainLabels = genres(randomPositions(i*testSetSize+1:setSize));
        else
            trainData = features(randomPositions(i*testSetSize+1:setSize),:);
            trainLabels = genres(randomPositions(i*testSetSize+1:setSize));
            trainData = [trainData;features(randomPositions(1:i*testSetSize-testSetSize),:)];
            trainLabels = [trainLabels;genres(randomPositions(1:i*testSetSize-testSetSize))];
        end
    end

    mean_trainData = mean(trainData);
    std_trainData = std(trainData);

    trainData = (trainData - repmat(mean_trainData,trainSetSize,1)) ./ repmat(std_trainData,trainSetSize,1);
    testData = (testData - repmat(mean_trainData,testSetSize,1)) ./ repmat(std_trainData,testSetSize,1);

    %Run the classifier
    estimatedClasses = myKnn(testData, trainData, trainLabels, K);

    %confusion Matrix
%     confusionMatrices(:,:,i) = confusionmat(testLabels,estimatedClasses);

    %count positives
    for j=1:length(testLabels)
        if (estimatedClasses(j) == testLabels(j))
            positives = positives + 1;
        end
    end

    %do the confusion Matrix and visualize data
end
    accuracy = (positives*100)/(n*testSetSize); %return accuracy in percentage
%     confusionMatrix = mean(confusionMatrices,3);
end


text:
/* dCodes Framework: (c) TemplateAccess */
// <![CDATA[
  $(function() {
	  //graceful degradation
	  $('#dc_slideout').find('ul').css({'left':'-660px'}).siblings('.dc_slideout-right').css({'left':'200px'});

	  var $arrow = $('#dc_slideout').find('.dc_slideout-right');
	  var $menu  = $('#dc_slideout').find('ul');
	  $arrow.bind('mouseenter',function(){
		  var $this = $(this);
		  $this.stop().animate({'left':'160px'},50);
		  $menu.stop().animate({'left':'202px'},500,function(){
			  $(this).find('a')
			  .unbind('mouseenter,mouseleave')
			  .bind('mouseenter',function(){$(this).addClass('hover');})
			  .bind('mouseleave',function(){$(this).removeClass('hover');});
		  });
	  });
	  $menu.bind('mouseleave',function(){
		  var $this = $(this);
		  $this.stop().animate({'left':'-660px'},500,function(){$arrow.stop().animate({'left':'200px'},500);});
	  });
  });

// ]]>


text:
@interface UMOpus : NSObject

+ (void)setAudioEnable:(BOOL)isEnabled;
+ (UMOpus *)sharedInstance;

- (NSData *)wavToOpus:(NSData *)data;
- (BOOL)isAudioEnabled;
@end


text:
package org.openkilda.testing.tools;

import org.openkilda.testing.model.topology.TopologyDefinition.TraffGen;
import org.openkilda.testing.service.traffexam.OperationalException;
import org.openkilda.testing.service.traffexam.TraffExamService;
import org.openkilda.testing.service.traffexam.model.Address;
import org.openkilda.testing.service.traffexam.model.ArpData;
import org.openkilda.testing.service.traffexam.model.LldpData;
import org.openkilda.testing.service.traffexam.model.Vlan;
import org.openkilda.testing.service.traffexam.networkpool.Inet4ValueException;

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

public class ConnectedDevice implements AutoCloseable {

    private Address address;
    private TraffExamService examService;

    public ConnectedDevice(TraffExamService examService, TraffGen tg, List<Integer> vlanId) throws OperationalException,
            Inet4ValueException {
        List<Vlan> vlanIds = new ArrayList<Vlan>();
        for (int i = 0; i < vlanId.size(); i++) {
            Vlan vlan = new Vlan(vlanId.get(i));
            vlanIds.add(vlan);
        }
        this.examService = examService;
        address = examService.allocateFreeAddress(examService.hostByName(tg.getName()), vlanIds);
    }

    public void sendLldp(LldpData data) {
        examService.sendLldp(address, data);
    }

    public void sendArp(ArpData data) {
        examService.sendArp(address, data);
    }

    @Override
    public void close() {
        examService.releaseAddress(address);
    }
}


text:
<?php

/**
 * @task config     Configuring Repository Engines
 * @task internal   Internals
 */
abstract class PhabricatorRepositoryEngine extends Phobject {

  private $repository;
  private $verbose;

  /**
   * @task config
   */
  public function setRepository(PhabricatorRepository $repository) {
    $this->repository = $repository;
    return $this;
  }

  /**
   * @task config
   */
  protected function getRepository() {
    if ($this->repository === null) {
      throw new PhutilInvalidStateException('setRepository');
    }

    return $this->repository;
  }

  /**
   * @task config
   */
  public function setVerbose($verbose) {
    $this->verbose = $verbose;
    return $this;
  }

  /**
   * @task config
   */
  public function getVerbose() {
    return $this->verbose;
  }

  public function getViewer() {
    return PhabricatorUser::getOmnipotentUser();
  }

  protected function newRepositoryLock(
    PhabricatorRepository $repository,
    $lock_key,
    $lock_device_only) {

    $lock_parts = array();
    $lock_parts[] = $lock_key;
    $lock_parts[] = $repository->getID();

    if ($lock_device_only) {
      $device = AlmanacKeys::getLiveDevice();
      if ($device) {
        $lock_parts[] = $device->getID();
      }
    }

    $lock_name = implode(':', $lock_parts);
    return PhabricatorGlobalLock::newLock($lock_name);
  }

  /**
   * Verify that the "origin" remote exists, and points at the correct URI.
   *
   * This catches or corrects some types of misconfiguration, and also repairs
   * an issue where Git 1.7.1 does not create an "origin" for `--bare` clones.
   * See T4041.
   *
   * @param   PhabricatorRepository Repository to verify.
   * @return  void
   */
  protected function verifyGitOrigin(PhabricatorRepository $repository) {
    try {
      list($remotes) = $repository->execxLocalCommand(
        'remote show -n origin');
    } catch (CommandException $ex) {
      throw new PhutilProxyException(
        pht(
          'Expected to find a Git working copy at path "%s", but the '.
          'path exists and is not a valid working copy. If you remove '.
          'this directory, the daemons will automatically recreate it '.
          'correctly. Phabricator will not destroy the directory for you '.
          'because it can not be sure that it does not contain important '.
          'data.',
          $repository->getLocalPath()),
        $ex);
    }

    $matches = null;
    if (!preg_match('/^\s*Fetch URL:\s*(.*?)\s*$/m', $remotes, $matches)) {
      throw new Exception(
        pht(
          "Expected '%s' in '%s'.",
          'Fetch URL',
          'git remote show -n origin'));
    }

    $remote_uri = $matches[1];
    $expect_remote = $repository->getRemoteURI();

    if ($remote_uri == 'origin') {
      // If a remote does not exist, git pretends it does and prints out a
      // made up remote where the URI is the same as the remote name. This is
      // definitely not correct.

      // Possibly, we should use `git remote --verbose` instead, which does not
      // suffer from this problem (but is a little more complicated to parse).
      $valid = false;
      $exists = false;
    } else {
      $normal_type_git = PhabricatorRepositoryURINormalizer::TYPE_GIT;

      $remote_normal = id(new PhabricatorRepositoryURINormalizer(
        $normal_type_git,
        $remote_uri))->getNormalizedPath();

      $expect_normal = id(new PhabricatorRepositoryURINormalizer(
        $normal_type_git,
        $expect_remote))->getNormalizedPath();

      $valid = ($remote_normal == $expect_normal);
      $exists = true;
    }

    if (!$valid) {
      if (!$exists) {
        // If there's no "origin" remote, just create it regardless of how
        // strongly we own the working copy. There is almost no conceivable
        // scenario in which this could do damage.
        $this->log(
          pht(
            'Remote "origin" does not exist. Creating "origin", with '.
            'URI "%s".',
            $expect_remote));
        $repository->execxLocalCommand(
          'remote add origin %P',
          $repository->getRemoteURIEnvelope());

        // NOTE: This doesn't fetch the origin (it just creates it), so we won't
        // know about origin branches until the next "pull" happens. That's fine
        // for our purposes, but might impact things in the future.
      } else {
        if ($repository->canDestroyWorkingCopy()) {
          // Bad remote, but we can try to repair it.
          $this->log(
            pht(
              'Remote "origin" exists, but is pointed at the wrong URI, "%s". '.
              'Resetting origin URI to "%s.',
              $remote_uri,
              $expect_remote));
          $repository->execxLocalCommand(
            'remote set-url origin %P',
            $repository->getRemoteURIEnvelope());
        } else {
          // Bad remote and we aren't comfortable repairing it.
          $message = pht(
            'Working copy at "%s" has a mismatched origin URI, "%s". '.
            'The expected origin URI is "%s". Fix your configuration, or '.
            'set the remote URI correctly. To avoid breaking anything, '.
            'Phabricator will not automatically fix this.',
            $repository->getLocalPath(),
            $remote_uri,
            $expect_remote);
          throw new Exception($message);
        }
      }
    }
  }

  /**
   * @task internal
   */
  protected function log($pattern /* ... */) {
    if ($this->getVerbose()) {
      $console = PhutilConsole::getConsole();
      $argv = func_get_args();
      array_unshift($argv, "%s\n");
      call_user_func_array(array($console, 'writeOut'), $argv);
    }
    return $this;
  }

}


text:
from django.shortcuts import render_to_response
from django.template import RequestContext
from apps.tools.models import Tool

def show_tool(request, tool_slug):
    tool = Tool.objects.get(slug=tool_slug)
    return render_to_response(
        'show_tool.html',
        {'tool': tool},
        context_instance=RequestContext(request)
    )

def show_all(request):
    tools = Tool.objects.all().order_by('status')
    return render_to_response(
        'show_all.html',
        {'tools': tools},
        context_instance=RequestContext(request)
    )


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

<title>org.apache.jmeter.plugin Class Hierarchy (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.jmeter.plugin

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.jmeter.plugin.PluginManager

Interface Hierarchy

org.apache.jmeter.plugin.JMeterPlugin

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev

Next

Frames

No Frames

All Classes

Copyright © 1998-2016 Apache Software Foundation. All Rights Reserved.


text:
MACRO(COPY_FILE_IF_CHANGED in_dir in_file out_file target)
    IF(${in_file} IS_NEWER_THAN ${out_file})
        #MESSAGE("${target} copy: ${in_dir}/${in_file} -> ${out_file}")
    	ADD_CUSTOM_COMMAND (
            TARGET     ${target}
            POST_BUILD
    	    COMMAND    ${CMAKE_COMMAND} -E copy ${in_dir}/${in_file} ${out_file}
    	)
	ENDIF(${in_file} IS_NEWER_THAN ${out_file})
ENDMACRO(COPY_FILE_IF_CHANGED)

MACRO(COPY_FILE_INTO_DIRECTORY_IF_CHANGED in_dir in_file out_dir target)
	GET_FILENAME_COMPONENT(file_name ${in_file} NAME)
	COPY_FILE_IF_CHANGED(${in_dir} ${in_file} ${out_dir}/${file_name}
${target})
ENDMACRO(COPY_FILE_INTO_DIRECTORY_IF_CHANGED)

#Copies all the files from in_file_list into the out_dir.
# sub-trees are ignored (files are stored in same out_dir)
MACRO(COPY_FILES_INTO_DIRECTORY_IF_CHANGED in_dir in_file_list out_dir target)
    FOREACH(in_file ${in_file_list})
        #MESSAGE("${target} copy: ${in_dir}/${in_file} -> ${out_dir}")
	COPY_FILE_INTO_DIRECTORY_IF_CHANGED(${in_dir} ${in_file} ${out_dir} ${target})
    ENDFOREACH(in_file)
ENDMACRO(COPY_FILES_INTO_DIRECTORY_IF_CHANGED)

#Copy all files and directories in in_dir to out_dir.
# Subtrees remain intact.
MACRO(COPY_DIRECTORY_IF_CHANGED in_dir out_dir target)
    #message("Copying directory ${in_dir}")
    FILE(GLOB_RECURSE in_file_list ${in_dir}/*)
	FOREACH(in_file ${in_file_list})
	    if(NOT ${in_file} MATCHES ".svn")
    		STRING(REGEX REPLACE ${in_dir} ${out_dir} out_file ${in_file})
    		COPY_FILE_IF_CHANGED(${in_dir} ${in_file} ${out_file} ${target})
    	endif(NOT ${in_file} MATCHES ".svn")
	ENDFOREACH(in_file)
ENDMACRO(COPY_DIRECTORY_IF_CHANGED)


text:
#pragma once
#include <aws/clouddirectory/CloudDirectory_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CloudDirectory
{
namespace Model
{
  class AWS_CLOUDDIRECTORY_API DeleteSchemaResult
  {
  public:
    DeleteSchemaResult();
    DeleteSchemaResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DeleteSchemaResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline const Aws::String& GetSchemaArn() const{ return m_schemaArn; }

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline void SetSchemaArn(const Aws::String& value) { m_schemaArn = value; }

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline void SetSchemaArn(Aws::String&& value) { m_schemaArn = std::move(value); }

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline void SetSchemaArn(const char* value) { m_schemaArn.assign(value); }

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline DeleteSchemaResult& WithSchemaArn(const Aws::String& value) { SetSchemaArn(value); return *this;}

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline DeleteSchemaResult& WithSchemaArn(Aws::String&& value) { SetSchemaArn(std::move(value)); return *this;}

    /**
     *
The input ARN that is returned as part of the response. For more information,
     * see arns.

     */
    inline DeleteSchemaResult& WithSchemaArn(const char* value) { SetSchemaArn(value); return *this;}

  private:
    Aws::String m_schemaArn;
  };

} // namespace Model
} // namespace CloudDirectory
} // namespace Aws


text:
package com.jcwhatever.nucleus.npc.traits.particles;

import com.jcwhatever.nucleus.npc.traits.NpcTraitPack;
import com.jcwhatever.nucleus.providers.npc.INpc;
import com.jcwhatever.nucleus.providers.npc.traits.NpcTrait;
import com.jcwhatever.nucleus.providers.npc.traits.NpcTraitType;

import org.bukkit.Effect;
import org.bukkit.Location;

/**
 * Ender particle effect.
 */
public class EnderParticlesTrait extends NpcTraitType {

    /**
     * Constructor.
     */
    public EnderParticlesTrait() {
        super(NpcTraitPack.getPlugin(), "EnderParticles");
    }

    @Override
    protected NpcTrait createTrait(INpc npc) {
        return new EnderParticles(this);
    }

    public static class EnderParticles extends ParticlesTrait {

        /**
         * Constructor.
         *
         * @param type The parent type that instantiated the trait.
         */
        protected EnderParticles(NpcTraitType type) {
            super(type);
        }

        @Override
        protected void onEffect(Location location) {
            location.getWorld().playEffect(location, Effect.ENDER_SIGNAL, 0);
        }
    }
}


text:
import leon.annotation.extern
// import leon.lang._

object ClassHierarchy {

  // Example of class hierarchy
  abstract class Top

  case class One(x: Int) extends Top

  abstract class Derived extends Top {
    def sum: Int
  }

  case class Two(x: Int, y: Int) extends Derived {
    def sum: Int = x + y // can overflow
  }

  case class Three(x: Int, y: Int, z: Int) extends Derived {
    def sum: Int = x + y + z // can overflow
  }

  def foo = {
    val x = One(1)
    val y = Two(1, 2)
    bar(x, y)
  }

  def bar(one: One, d: Derived) = one.x + d.sum // can overflow

  def fun(b: Top) = b.isInstanceOf[One]
  def gun(b: Top) = {
    require(b.isInstanceOf[One])
    b.asInstanceOf[One].x
  }

  def _main(): Int = {
    val one = One(42)
    if (foo == 4 && fun(one) && gun(one) == 42) 0
    else 1
  } ensuring { _ == 0 }

  @extern
  def main(args: Array[String]): Unit = _main()

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>The nova.auth.fakeldap Module — nova 2012.2.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/tweaks.css" type="text/css" />

    <link rel="top" title="nova 2012.2.1 documentation" href="../index.html" />
    <link rel="up" title="<no title>" href="autoindex.html" />
    <link rel="next" title="The nova.block_device Module" href="nova.block_device.html" />
    <link rel="prev" title="The nova.api.validator Module" href="nova.api.validator.html" />

OpenStack

Home

Projects

User Stories

Community

Blog

Wiki

Documentation

The <tt class="xref py py-mod docutils literal">nova.auth.fakeldap</tt> Module¶

Fake LDAP server for test harness.

This class does very little error checking, and knows nothing about ldap
class definitions.  It implements the minimum emulation of the python ldap
library to work with nova.

class <tt class="descname">FakeLDAP</tt>¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

Fake LDAP connection.

<tt class="descname">add_s</tt><big>(</big>dn, attr<big>)</big>¶

Add an object with the specified attributes at dn.

<tt class="descname">delete_s</tt><big>(</big>dn<big>)</big>¶

Remove the ldap object at specified dn.

<tt class="descname">modify_s</tt><big>(</big>dn, attrs<big>)</big>¶

Modify the object at dn using the attribute list.

<col class="field-name" />
<col class="field-body" />

Parameters:

dn – a dn

attrs –
a list of tuples in the following form:

([MOD_ADD | MOD_DELETE | MOD_REPACE], attribute, value)

<tt class="descname">modrdn_s</tt><big>(</big>dn, newrdn<big>)</big>¶

<tt class="descname">search_s</tt><big>(</big>dn, scope, query=None, fields=None<big>)</big>¶

Search for all matching objects under dn using the query.

Args:
dn – dn to search under
scope – only SCOPE_BASE and SCOPE_SUBTREE are supported
query – query to filter objects by
fields – fields to return. Returns all fields if not specified

<tt class="descname">simple_bind_s</tt><big>(</big>dn, password<big>)</big>¶

This method is ignored, but provided for compatibility.

<tt class="descname">unbind_s</tt><big>(</big><big>)</big>¶

This method is ignored, but provided for compatibility.

exception <tt class="descname">NO_SUCH_OBJECT</tt>¶

Bases: <tt class="xref py py-class docutils literal">exceptions.Exception</tt>

Duplicate exception class from real LDAP module.

exception <tt class="descname">OBJECT_CLASS_VIOLATION</tt>¶

Bases: <tt class="xref py py-class docutils literal">exceptions.Exception</tt>

Duplicate exception class from real LDAP module.

exception <tt class="descname">SERVER_DOWN</tt>¶

Bases: <tt class="xref py py-class docutils literal">exceptions.Exception</tt>

Duplicate exception class from real LDAP module.

class <tt class="descname">Store</tt>¶

Bases: <tt class="xref py py-class docutils literal">object</tt>

classmethod <tt class="descname">instance</tt><big>(</big><big>)</big>¶

<tt class="descname">initialize</tt><big>(</big>_uri<big>)</big>¶

Opens a fake connection with an LDAP server.

Previous topic

The <tt class="docutils literal docutils literal docutils literal">nova.api.validator</tt> Module

Next topic

The <tt class="docutils literal">nova.block_device</tt> Module

This Page

Show Source

Quick search

              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

              Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

nova 2012.2.1 documentation »

Developer Guide »

<no title> »

        © Copyright 2010-present, OpenStack, LLC.
      Last updated on Thu Nov 1 16:11:51 2012, commit 4ed8d3e.
      Created using Sphinx 1.1.3.


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : 16.06.2016, 11:50:32
    Author     : Kilrogg
*/

/*
Position and percentage dimensions from field width and height
*/
.soccerfield-player {
    position: absolute;
    width: 12%;
    height: 10%;
}

.soccerfield-field-field-img {
    width:100%;
    height: 100%;
    position:absolute;
    top: 0px;
    left:0px;
}

/*
player img
*/
.soccerfield-player .soccerfield-player-img {
    display:block;
    position: absolute;
    z-index: 100;
    margin-right: 2px;
}

/*
player name
*/
.soccerfield-player span {
}

/*
GoalKeeper
*/
.soccerfield-player.posX-GK {
    left:5%;
}
/*
Back
*/
.soccerfield-player.posX-B {
    left: 20%;
}
/*
Defending midfielder
*/
.soccerfield-player.posX-DM {
    left: 35%;
}

/*
Midfielder
*/
.soccerfield-player.posX-M {
    left:50%;
}
/*
Attacking midfielder
*/
.soccerfield-player.posX-AM {
    left: 65%
}
/*
Forward
*/
.soccerfield-player.posX-F {
    left: 80%;
}
/*
Left
*/
.soccerfield-player.posY-L {
    top: 5%;
}
/*
Left-center
*/
.soccerfield-player.posY-LC {
    top: 25%
}
/*
Center
*/
.soccerfield-player.posY-C {
    top:45%;
}
/*
Right-center
*/
.soccerfield-player.posY-RC {
    bottom:30%;
}
/*
Right
*/
.soccerfield-player.posY-R {
    bottom:10%;
}


text:
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace WooCommerceNET.WooCommerce.v3
{
    [DataContract]
    public class Report : v2.Report { }

    [DataContract]
    public class SalesReport : v2.SalesReport { }

    [DataContract]
    public class TopSellersReport : v2.TopSellersReport { }

    [DataContract]
    public class CouponsTotals
    {
        /// <summary>
        /// An alphanumeric identifier for the resource.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string slug { get; set; }

        /// <summary>
        /// Coupon type name.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string name { get; set; }

        /// <summary>
        /// Amount of coupons.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string total { get; set; }
    }

    [DataContract]
    public class CustomersTotals
    {
        /// <summary>
        /// An alphanumeric identifier for the resource.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string slug { get; set; }

        /// <summary>
        /// Customer type name.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string name { get; set; }

        /// <summary>
        /// Amount of customers.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string total { get; set; }
    }

    [DataContract]
    public class OrdersTotals
    {
        /// <summary>
        /// An alphanumeric identifier for the resource.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string slug { get; set; }

        /// <summary>
        /// Orders type name.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string name { get; set; }

        /// <summary>
        /// Amount of orders.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string total { get; set; }
    }

    [DataContract]
    public class ProductsTotals
    {
        /// <summary>
        /// An alphanumeric identifier for the resource.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string slug { get; set; }

        /// <summary>
        /// Product type name.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string name { get; set; }

        /// <summary>
        /// Amount of products.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string total { get; set; }
    }

    [DataContract]
    public class ReviewsTotals
    {
        /// <summary>
        /// An alphanumeric identifier for the resource.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string slug { get; set; }

        /// <summary>
        /// Review type name.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string name { get; set; }

        /// <summary>
        /// Amount of reviews.
        /// read-only
        /// </summary>
        [DataMember(EmitDefaultValue = false)]
        public string total { get; set; }
    }
}


text:
BOOST_AUTO_TEST_SUITE(getarg_tests)

static void
ResetArgs(const std::string& strArg)
{
    std::vector<std::string> vecArg;
    boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);

    // Insert dummy executable name:
    vecArg.insert(vecArg.begin(), "testbitcoin");

    // Convert to char*:
    std::vector<const char*> vecChar;
    BOOST_FOREACH(std::string& s, vecArg)
        vecChar.push_back(s.c_str());

    ParseParameters(vecChar.size(), &vecChar[0]);
}

BOOST_AUTO_TEST_CASE(boolarg)
{
    ResetArgs("-eac");
    BOOST_CHECK(GetBoolArg("-eac"));
    BOOST_CHECK(GetBoolArg("-eac", false));
    BOOST_CHECK(GetBoolArg("-eac", true));

    BOOST_CHECK(!GetBoolArg("-fo"));
    BOOST_CHECK(!GetBoolArg("-fo", false));
    BOOST_CHECK(GetBoolArg("-fo", true));

    BOOST_CHECK(!GetBoolArg("-eaco"));
    BOOST_CHECK(!GetBoolArg("-eaco", false));
    BOOST_CHECK(GetBoolArg("-eaco", true));

    ResetArgs("-eac=0");
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", false));
    BOOST_CHECK(!GetBoolArg("-eac", true));

    ResetArgs("-eac=1");
    BOOST_CHECK(GetBoolArg("-eac"));
    BOOST_CHECK(GetBoolArg("-eac", false));
    BOOST_CHECK(GetBoolArg("-eac", true));

    // New 0.6 feature: auto-map -nosomething to !-something:
    ResetArgs("-noeac");
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", false));
    BOOST_CHECK(!GetBoolArg("-eac", true));

    ResetArgs("-noeac=1");
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", false));
    BOOST_CHECK(!GetBoolArg("-eac", true));

    ResetArgs("-eac -noeac");  // -eac should win
    BOOST_CHECK(GetBoolArg("-eac"));
    BOOST_CHECK(GetBoolArg("-eac", false));
    BOOST_CHECK(GetBoolArg("-eac", true));

    ResetArgs("-eac=1 -noeac=1");  // -eac should win
    BOOST_CHECK(GetBoolArg("-eac"));
    BOOST_CHECK(GetBoolArg("-eac", false));
    BOOST_CHECK(GetBoolArg("-eac", true));

    ResetArgs("-eac=0 -noeac=0");  // -eac should win
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", false));
    BOOST_CHECK(!GetBoolArg("-eac", true));

    // New 0.6 feature: treat -- same as -:
    ResetArgs("--eac=1");
    BOOST_CHECK(GetBoolArg("-eac"));
    BOOST_CHECK(GetBoolArg("-eac", false));
    BOOST_CHECK(GetBoolArg("-eac", true));

    ResetArgs("--noeac=1");
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", false));
    BOOST_CHECK(!GetBoolArg("-eac", true));

}

BOOST_AUTO_TEST_CASE(stringarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-eac", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-eac", "eleven"), "eleven");

    ResetArgs("-eac -bar");
    BOOST_CHECK_EQUAL(GetArg("-eac", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-eac", "eleven"), "");

    ResetArgs("-eac=");
    BOOST_CHECK_EQUAL(GetArg("-eac", ""), "");
    BOOST_CHECK_EQUAL(GetArg("-eac", "eleven"), "");

    ResetArgs("-eac=11");
    BOOST_CHECK_EQUAL(GetArg("-eac", ""), "11");
    BOOST_CHECK_EQUAL(GetArg("-eac", "eleven"), "11");

    ResetArgs("-eac=eleven");
    BOOST_CHECK_EQUAL(GetArg("-eac", ""), "eleven");
    BOOST_CHECK_EQUAL(GetArg("-eac", "eleven"), "eleven");

}

BOOST_AUTO_TEST_CASE(intarg)
{
    ResetArgs("");
    BOOST_CHECK_EQUAL(GetArg("-eac", 11), 11);
    BOOST_CHECK_EQUAL(GetArg("-eac", 0), 0);

    ResetArgs("-eac -bar");
    BOOST_CHECK_EQUAL(GetArg("-eac", 11), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);

    ResetArgs("-eac=11 -bar=12");
    BOOST_CHECK_EQUAL(GetArg("-eac", 0), 11);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);

    ResetArgs("-eac=NaN -bar=NotANumber");
    BOOST_CHECK_EQUAL(GetArg("-eac", 1), 0);
    BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
}

BOOST_AUTO_TEST_CASE(doubledash)
{
    ResetArgs("--eac");
    BOOST_CHECK_EQUAL(GetBoolArg("-eac"), true);

    ResetArgs("--eac=verbose --bar=1");
    BOOST_CHECK_EQUAL(GetArg("-eac", ""), "verbose");
    BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
}

BOOST_AUTO_TEST_CASE(boolargno)
{
    ResetArgs("-noeac");
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", true));
    BOOST_CHECK(!GetBoolArg("-eac", false));

    ResetArgs("-noeac=1");
    BOOST_CHECK(!GetBoolArg("-eac"));
    BOOST_CHECK(!GetBoolArg("-eac", true));
    BOOST_CHECK(!GetBoolArg("-eac", false));

    ResetArgs("-noeac=0");
    BOOST_CHECK(GetBoolArg("-eac"));
    BOOST_CHECK(GetBoolArg("-eac", true));
    BOOST_CHECK(GetBoolArg("-eac", false));

    ResetArgs("-eac --noeac");
    BOOST_CHECK(GetBoolArg("-eac"));

    ResetArgs("-noeac -eac"); // eac always wins:
    BOOST_CHECK(GetBoolArg("-eac"));
}

BOOST_AUTO_TEST_SUITE_END()


text:
using System;
using System.Collections.Generic;

namespace OpenLinq
{
	public static partial class Enumerable
	{
		public static bool All<T>(this IEnumerable<T> source, Func<T, bool> predicate)
		{
			if (source == null) {
				throw new ArgumentNullException ("source");
			}
			if (predicate == null) {
				throw new ArgumentNullException ("predicate");
			}
			return AllImp (source, predicate);
		}

		private static bool AllImp<T>(this IEnumerable<T> source, Func<T, bool> predicate)
		{
			foreach (var item in source) {
				if(!predicate(item)){
					return false;
				}
			}
			return true;
		}
	}
}