text:
package uk.ac.ebi.subs.api.services;

import org.hamcrest.collection.IsEmptyCollection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import uk.ac.ebi.subs.data.component.Team;
import uk.ac.ebi.tsc.aap.client.exception.AAPException;
import uk.ac.ebi.tsc.aap.client.model.Domain;
import uk.ac.ebi.tsc.aap.client.model.Profile;
import uk.ac.ebi.tsc.aap.client.model.User;
import uk.ac.ebi.tsc.aap.client.repo.DomainService;
import uk.ac.ebi.tsc.aap.client.repo.ProfileService;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

@RunWith(SpringRunner.class)
public class UserTeamServiceTest {

    private UserTeamService userTeamService;

    @MockBean
    private DomainService domainService;

    @MockBean
    private ProfileService profileService;

    @MockBean
    private UserAuthoritiesService userAuthoritiesService;

    private static final String USER_TOKEN = "JWT.ABC.123";

    @Before
    public void setup() {
        userTeamService = new UserTeamService(domainService, profileService, userAuthoritiesService);
        userTeamService.setTeamNamePrefix("subs.");
    }

    @Test
    public void whenUserTokenIsOutdated_ThenItWontShowTheFreslyAddedDomains() {
        when(domainService.getMyDomains(USER_TOKEN)).thenReturn(generateDomains());
        when(profileService.getDomainProfile(anyString(), anyString())).thenAnswer(
            invocation -> {
                Object argument = invocation.getArguments()[0];
                if (argument.equals("TestDomain_4_reference")) {
                    throw new AAPException("message");
                } else {
                    return generateProfile();
                }
            }
        );

        List<Team> teams = userTeamService.userTeams(USER_TOKEN);

        assertThat(teams, not(IsEmptyCollection.empty()));
        assertThat(teams.size(), is(4));
        assertThat(teams, not(hasItem(Team.build("subs.4"))));
    }

    private Collection<Domain> generateDomains() {
        Collection<Domain> domains = new HashSet<>();

        for (int i = 0; i < 5; i++) {
            Domain domain = getDomain(i);
            domains.add(domain);
        }

        return domains;
    }

    private Domain getDomain(int domainId) {
        return new Domain("subs." + domainId, "TestDomain_" + domainId + "_description", "TestDomain_" + domainId + "_reference");
    }

    private Profile generateProfile() {
        User user = new User("userName", "email", "userReference", "fullName", Collections.emptySet());
        return new Profile("reference", user, getDomain(1), Collections.emptyMap());
    }
}


text:
layout: post
title: "The Python Challenge"
published: true
tags: [Python, Ruby]
---

The [Python Challenge](http://www.pythonchallenge.com) is a great way to practise some varied programming challenges.

There are lots of different stages and clever ways to solve the puzzles.

Try it now!

redpajama_set_name: RedPajamaGithub


text:
package com.portalmgr.common;

/**
 * 常量池
 * @author duwk
 * @date: 日期:2016-12-29 时间:上午10:30:38
 */
public class ClientConstantPool {

	public static final String SESSION_KEY = "LoginBean";
	//验证码
	public static final String VALID_CODE_SESSION_KEY = "valid_code";

}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>TimeEvaluator Constructor ()</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

TimeEvaluator Constructor ()

 Create a new evaluator using the DEFAULT_INTERVAL time threshold in seconds.

        [Visual Basic]

Overloads Public Sub New()

        [C#]

public TimeEvaluator();

Remarks

 Create a new evaluator using the DEFAULT_INTERVAL time threshold in seconds.

 This evaluator will trigger if the specified time period Interval has passed since last check.

See Also

TimeEvaluator Class | log4net.Core Namespace | TimeEvaluator Constructor Overload List

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
package org.apache.sling.resourceresolver.impl.helper;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.util.Map;

import org.apache.sling.api.resource.PersistableValueMap;
import org.apache.sling.api.resource.ValueMap;
import org.junit.Test;

@SuppressWarnings("deprecation")
public class RedirectResourceTest {

    @Test public void testRedirectResource() {

        final String path = "/redir/path";
        final String target = "/redir/target";
        final int status = 999;
        final RedirectResource res = new RedirectResource(null, path, target,
            status);

        assertEquals(path, res.getPath());
        assertEquals(RedirectResource.RT_SLING_REDIRECT, res.getResourceType());

        final Map<?, ?> map = res.adaptTo(Map.class);
        assertNotNull("Expected Map adapter", map);
        assertEquals(target, map.get(RedirectResource.PROP_SLING_TARGET));
        assertEquals(status, ((Integer) map.get(RedirectResource.PROP_SLING_STATUS)).intValue());

        final ValueMap valueMap = res.adaptTo(ValueMap.class);
        assertNotNull("Expected ValueMap adapter", valueMap);
        assertEquals(target, valueMap.get(RedirectResource.PROP_SLING_TARGET));
        assertEquals(status, ((Integer) valueMap.get(RedirectResource.PROP_SLING_STATUS)).intValue());
        assertEquals(status, valueMap.get(RedirectResource.PROP_SLING_STATUS, Integer.class).intValue());

        final PersistableValueMap persistableValueMap = res.adaptTo(PersistableValueMap.class);
        assertNull("Unexpected PersistableValueMap adapter",
            persistableValueMap);
    }
}


text:
function MessageListView(list, table_name, collapse_messages) {
    this.list = list;
    this.collapse_messages = collapse_messages;
    this._rows = {};
    this.message_containers = {};
    this.table_name = table_name;
    if (this.table_name) {
        this.clear_table();
    }
    this._message_groups = [];

    // Half-open interval of the indices that define the current render window
    this._render_win_start = 0;
    this._render_win_end = 0;
}

(function () {

function mention_button_refers_to_me(elem) {
    var user_id = $(elem).attr('data-user-id');
    if ((user_id === '*') || people.is_my_user_id(user_id)) {
        return true;
    }

    // Handle legacy markdown that was rendered before we cut
    // over to using data-user-id.
    var email = $(elem).attr('data-user-email');
    if (email === '*' || people.is_current_user(email)) {
        return true;
    }

    return false;
}

function stringify_time(time) {
    if (page_params.twenty_four_hour_time) {
        return time.toString('HH:mm');
    }
    return time.toString('h:mm TT');
}

function same_day(earlier_msg, later_msg) {
    if (earlier_msg === undefined || later_msg === undefined) {
        return false;
    }
    var earlier_time = new XDate(earlier_msg.msg.timestamp * 1000);
    var later_time = new XDate(later_msg.msg.timestamp * 1000);

    return earlier_time.toDateString() === later_time.toDateString();
}

function same_sender(a, b) {
    if (a === undefined || b === undefined) {
        return false;
    }
    return util.same_sender(a.msg, b.msg);
}

function same_recipient(a, b) {
    if (a === undefined || b === undefined) {
        return false;
    }
    return util.same_recipient(a.msg, b.msg);
}

function add_display_time(group, message_container, prev) {
    var time = new XDate(message_container.msg.timestamp * 1000);

    if (prev !== undefined) {
        var prev_time = new XDate(prev.msg.timestamp * 1000);
        if (time.toDateString() !== prev_time.toDateString()) {
            // NB: show_date is HTML, inserted into the document without escaping.
            group.show_date = (timerender.render_date(time, prev_time))[0].outerHTML;
        }
    } else {
        group.show_date = (timerender.render_date(time))[0].outerHTML;
    }

    if (message_container.timestr === undefined) {
        message_container.timestr = stringify_time(time);
    }
}

function populate_group_from_message_container(group, message_container) {
    group.is_stream = message_container.msg.is_stream;
    group.is_private = message_container.msg.is_private;

    if (group.is_stream) {
        group.background_color = stream_data.get_color(message_container.msg.stream);
        group.color_class = stream_color.get_color_class(group.background_color);
        group.invite_only = stream_data.get_invite_only(message_container.msg.stream);
        group.subject = message_container.msg.subject;
        group.match_subject = message_container.msg.match_subject;
        group.stream_url = message_container.stream_url;
        group.topic_url = message_container.topic_url;
        var sub = stream_data.get_sub(message_container.msg.stream);
        if (sub === undefined) {
            // Hack to handle unusual cases like the tutorial where
            // the streams used don't actually exist in the subs
            // module.  Ideally, we'd clean this up by making the
            // tutorial populate subs.js "properly".
            group.stream_id = -1;
        } else {
            group.stream_id = sub.stream_id;
        }
    } else if (group.is_private) {
        group.pm_with_url = message_container.pm_with_url;
        group.display_reply_to = message_store.get_pm_full_names(message_container.msg);
    }
    group.display_recipient = message_container.msg.display_recipient;
    group.always_visible_topic_edit = message_container.msg.always_visible_topic_edit;
    group.on_hover_topic_edit = message_container.msg.on_hover_topic_edit;
    group.subject_links = message_container.msg.subject_links;

    var time = new XDate(message_container.msg.timestamp * 1000);
    var date_element = timerender.render_date(time)[0];

    group.date = date_element.outerHTML;
}

MessageListView.prototype = {
    // Number of messages to render at a time
    _RENDER_WINDOW_SIZE: 400,
    // Number of messages away from edge of render window at which we
    // trigger a re-render
    _RENDER_THRESHOLD: 50,

    _add_msg_timestring: function MessageListView___add_msg_timestring(message_container) {
        if (message_container.msg.last_edit_timestamp !== undefined) {
            // Add or update the last_edit_timestr
            var last_edit_time = new XDate(message_container.msg.last_edit_timestamp * 1000);
            message_container.last_edit_timestr =
                (timerender.render_date(last_edit_time))[0].textContent
                + " at " + stringify_time(last_edit_time);
        }
    },

    add_subscription_marker: function MessageListView__add_subscription_marker(
                                group, last_msg_container, first_msg_container) {
        if (last_msg_container !== undefined &&
            first_msg_container.msg.historical !== last_msg_container.msg.historical) {
            group.bookend_top = true;
            if (first_msg_container.msg.historical) {
                group.unsubscribed = first_msg_container.msg.stream;
                group.bookend_content =
                    this.list.unsubscribed_bookend_content(first_msg_container.msg.stream);
            } else {
                group.subscribed = first_msg_container.msg.stream;
                group.bookend_content =
                    this.list.subscribed_bookend_content(first_msg_container.msg.stream);
            }
        }
    },

    build_message_groups: function MessageListView__build_message_groups(message_containers) {
        function start_group() {
            return {
                message_containers: [],
                message_group_id: _.uniqueId('message_group_'),
            };
        }

        var self = this;
        var current_group = start_group();
        var new_message_groups = [];
        var prev;

        function add_message_container_to_group(message_container) {
            if (same_sender(prev, message_container)) {
                prev.next_is_same_sender = true;
            }
            current_group.message_containers.push(message_container);
        }

        function finish_group() {
            if (current_group.message_containers.length > 0) {
                populate_group_from_message_container(current_group,
                                                      current_group.message_containers[0]);
                current_group
                   .message_containers[current_group.message_containers.length - 1]
                   .include_footer = true;
                new_message_groups.push(current_group);
            }
        }

        _.each(message_containers, function (message_container) {
            var message_reactions = reactions.get_message_reactions(message_container.msg);
            message_container.msg.message_reactions = message_reactions;
            message_container.include_recipient = false;
            message_container.include_footer    = false;

            if (same_recipient(prev, message_container) && self.collapse_messages &&
                prev.msg.historical === message_container.msg.historical &&
                same_day(prev, message_container)) {
                add_message_container_to_group(message_container);
            } else {
                finish_group();
                current_group = start_group();
                add_message_container_to_group(message_container);

                message_container.include_recipient = true;
                message_container.subscribed = false;
                message_container.unsubscribed = false;

                // This home_msg_list condition can be removed
                // once we filter historical messages from the
                // home view on the server side (which requires
                // having an index on UserMessage.flags)
                if (self.list !== home_msg_list) {
                    self.add_subscription_marker(current_group, prev, message_container);
                }

                if (message_container.msg.stream) {
                    message_container.stream_url =
                        narrow.by_stream_uri(message_container.msg.stream);
                    message_container.topic_url =
                        narrow.by_stream_subject_uri(message_container.msg.stream,
                                                     message_container.msg.subject);
                } else {
                    message_container.pm_with_url =
                        message_container.msg.pm_with_url;
                }
            }

            add_display_time(current_group, message_container, prev);

            message_container.include_sender = true;
            if (!message_container.include_recipient &&
                !prev.status_message &&
                same_sender(prev, message_container)) {
                message_container.include_sender = false;
            }

            message_container.sender_is_bot = people.sender_is_bot(message_container.msg);

            self._add_msg_timestring(message_container);

            message_container.small_avatar_url = people.small_avatar_url(message_container.msg);
            if (message_container.msg.stream !== undefined) {
                message_container.background_color =
                    stream_data.get_color(message_container.msg.stream);
            }

            message_container.contains_mention =
                notifications.speaking_at_me(message_container.msg);
            message_container.msg.unread = unread.message_unread(message_container.msg);
            self._maybe_format_me_message(message_container);

            prev = message_container;
        });

        finish_group();

        return new_message_groups;
    },

    join_message_groups: function MessageListView__join_message_groups(first_group, second_group) {
        // join_message_groups will combine groups if they have the
        // same_recipient on the same_day and the view supports collapsing
        // otherwise it may add a subscription_marker if required.
        // It returns true if the two groups were joined in to one and
        // the second_group should be ignored.
        if (first_group === undefined || second_group === undefined) {
            return false;
        }
        var last_msg_container = _.last(first_group.message_containers);
        var first_msg_container = _.first(second_group.message_containers);

        // Join two groups into one.
        if (this.collapse_messages && same_recipient(last_msg_container, first_msg_container) &&
            same_day(last_msg_container, first_msg_container) &&
            last_msg_container.msg.historical === first_msg_container.msg.historical) {
            if (!last_msg_container.status_message && !first_msg_container.msg.is_me_message
                && same_sender(last_msg_container, first_msg_container)) {
                first_msg_container.include_sender = false;
            }
            if (same_sender(last_msg_container, first_msg_container)) {
                last_msg_container.next_is_same_sender = true;
            }
            first_group.message_containers =
                first_group.message_containers.concat(second_group.message_containers);
            return true;
        // Add a subscription marker
        } else if (this.list !== home_msg_list &&
                   last_msg_container.msg.historical !== first_msg_container.msg.historical) {
            first_group.bookend_bottom = true;
            this.add_subscription_marker(first_group, last_msg_container, first_msg_container);
        }
        return false;
    },

    merge_message_groups: function MessageListView__merge_message_groups(new_message_groups,
                                                                         where) {
        // merge_message_groups takes a list of new messages groups to add to
        // this._message_groups and a location where to merge them currently
        // top or bottom. It returns an object of changes which needed to be
        // rendered in to the page. The types of actions are append_group,
        // prepend_group, rerender_group, append_message.
        //
        // append_groups are groups to add to the top of the rendered DOM
        // prepend_groups are group to add to the bottom of the rendered DOM
        // rerender_groups are group that should be updated in place in the DOM
        // append_messages are messages which should be added to the last group in the DOM
        // rerender_messages are messages which should be updated in place in the DOM

        var message_actions = {
            append_groups: [],
            prepend_groups: [],
            rerender_groups: [],
            append_messages: [],
            rerender_messages: [],
        };
        var first_group;
        var second_group;

        if (where === 'top') {
            first_group = _.last(new_message_groups);
            second_group = _.first(this._message_groups);
            if (this.join_message_groups(first_group, second_group)) {
                // join_message_groups moved the old message to the end of the
                // new group. We need to replace the old rendered message
                // group. So we will reuse its ID.

                first_group.message_group_id = second_group.message_group_id;
                message_actions.rerender_groups.push(first_group);

                // Swap the new group in
                this._message_groups.shift();
                this._message_groups.unshift(first_group);

                new_message_groups = _.initial(new_message_groups);
            } else if (!same_day(second_group.message_containers[0],
                       first_group.message_containers[0])) {
                // The groups did not merge, so we need up update the date row for the old group
                add_display_time(
                    second_group,
                    _.first(second_group.message_containers),
                    _.last(first_group.message_containers)
                );
                // We could add an action to update the date row, but for now rerender the group.
                message_actions.rerender_groups.push(second_group);
            }
            message_actions.prepend_groups = new_message_groups;
            this._message_groups = new_message_groups.concat(this._message_groups);
        } else {
            first_group = _.last(this._message_groups);
            second_group = _.first(new_message_groups);
            if (this.join_message_groups(first_group, second_group)) {
                // rerender the last message
                message_actions.rerender_messages.push(
                    first_group.message_containers[
                        first_group.message_containers.length
                        - second_group.message_containers.length - 1]
                );
                message_actions.append_messages = _.first(new_message_groups).message_containers;
                new_message_groups = _.rest(new_message_groups);
            } else if (first_group !== undefined && second_group !== undefined) {
                var last_msg_container = _.last(first_group.message_containers);
                var first_msg_container = _.first(second_group.message_containers);

                if (same_day(last_msg_container, first_msg_container)) {
                    // Clear the date if it is the same as the last group
                    second_group.show_date = undefined;
                }
            }
            message_actions.append_groups = new_message_groups;
            this._message_groups = this._message_groups.concat(new_message_groups);
        }

        return message_actions;
    },

    _post_process_dom_messages: function MessageListView___post_process_dom_messages(dom_messages) {
        // _post_process_dom_messages adds applies some extra formating to messages
        // and stores them in self._rows and sends an event that the message is
        // complete. _post_process_dom_messages should be a list of DOM nodes not
        // jQuery objects.

        var self = this;
        _.each(dom_messages, function (dom_message) {
            if (!_.isElement(dom_message)) {
                blueslip.warn('Only DOM nodes can be passed to _post_process_messages');
            }
            var row = $(dom_message);

            // Save DOM elements by id into self._rows for O(1) lookup
            if (row.hasClass('message_row')) {
                self._rows[row.attr('zid')] = dom_message;
            }

            if (row.hasClass('mention')) {
                row.find('.user-mention').each(function () {
                    // We give special highlights to the mention buttons
                    // that refer to the current user.
                    if (mention_button_refers_to_me(this)) {
                        $(this).addClass('user-mention-me');
                    }
                });
            }

            var id = rows.id(row);
            message_edit.maybe_show_edit(row, id);

            var e = $.Event('message_rendered.zulip', {target: row});
            try {
                $(document).trigger(e);
            } catch (ex) {
                blueslip.error('Problem with message rendering',
                               {message_id: rows.id($(row))},
                               ex.stack);
            }
        });
    },

    _get_message_template: function MessageListView___get_message_template(message_container) {
        var msg_reactions = reactions.get_message_reactions(message_container.msg);
        message_container.msg.message_reactions = msg_reactions;
        var msg_to_render = _.extend(message_container, {
            table_name: this.table_name,
        });
        return templates.render('single_message', msg_to_render);
    },

    render: function MessageListView__render(messages, where, messages_are_new) {
        // This function processes messages into chunks with separators between them,
        // and templates them to be inserted as table rows into the DOM.

        if (messages.length === 0 || this.table_name === undefined) {
            return;
        }

        var list = this.list; // for convenience
        var table_name = this.table_name;
        var table = rows.get_table(table_name);
        // we we record if last_message_was_selected before updating the table
        var last_message_was_selected = rows.id(rows.last_visible()) === list.selected_id();
        var orig_scrolltop_offset;
        var message_containers;

        var self = this;

        // The messages we are being asked to render are shared with between
        // all messages lists. To prevent having both list views overwriting
        // each others data we will make a new message object to add data to
        // for rendering.
        message_containers = _.map(messages, function (message) { return {msg: message}; });

        function save_scroll_position() {
            if (orig_scrolltop_offset === undefined && self.selected_row().length > 0) {
                orig_scrolltop_offset = self.selected_row().offset().top;
            }
        }

        function restore_scroll_position() {
            if (list === current_msg_list && orig_scrolltop_offset !== undefined) {
                message_viewport.set_message_offset(orig_scrolltop_offset);
                list.reselect_selected_id();
            }
        }

        // This function processes messages into chunks with separators between them,
        // and templates them to be inserted as table rows into the DOM.

        if (message_containers.length === 0 || this.table_name === undefined) {
            return;
        }

        var new_message_groups = this.build_message_groups(message_containers, this.table_name);
        var message_actions = this.merge_message_groups(new_message_groups, where);
        var new_dom_elements = [];
        var rendered_groups;
        var dom_messages;
        var last_message_row;
        var last_group_row;

        _.each(message_containers, function (message_container) {
            self.message_containers[message_container.msg.id] = message_container;
        });

        // Render new message groups on the top
        if (message_actions.prepend_groups.length > 0) {
            save_scroll_position();

            rendered_groups = $(templates.render('message_group', {
                message_groups: message_actions.prepend_groups,
                use_match_properties: self.list.filter.is_search(),
                table_name: self.table_name,
            }));

            dom_messages = rendered_groups.find('.message_row');
            new_dom_elements = new_dom_elements.concat(rendered_groups);

            self._post_process_dom_messages(dom_messages.get());

            // The date row will be included in the message groups or will be
            // added in a rerenderd in the group below
            table.find('.recipient_row').first().prev('.date_row').remove();
            table.prepend(rendered_groups);
            condense.condense_and_collapse(dom_messages);
        }

        // Rerender message groups
        if (message_actions.rerender_groups.length > 0) {
            save_scroll_position();

            _.each(message_actions.rerender_groups, function (message_group) {
                var old_message_group = $('#' + message_group.message_group_id);
                // Remove the top date_row, we'll re-add it after rendering
                old_message_group.prev('.date_row').remove();

                rendered_groups = $(templates.render('message_group', {
                    message_groups: [message_group],
                    use_match_properties: self.list.filter.is_search(),
                    table_name: self.table_name,
                }));

                dom_messages = rendered_groups.find('.message_row');
                // Not adding to new_dom_elements it is only used for autoscroll

                self._post_process_dom_messages(dom_messages.get());
                old_message_group.replaceWith(rendered_groups);
                condense.condense_and_collapse(dom_messages);
            });
        }

        // Rerender message rows
        if (message_actions.rerender_messages.length > 0) {
            _.each(message_actions.rerender_messages, function (message_container) {
                var old_row = self.get_row(message_container.msg.id);
                var row = $(self._get_message_template(message_container));
                self._post_process_dom_messages(row.get());
                old_row.replaceWith(row);
                condense.condense_and_collapse(row);
                list.reselect_selected_id();
            });
        }

        // Insert new messages in to the last message group
        if (message_actions.append_messages.length > 0) {
            last_message_row = table.find('.message_row:last').expectOne();
            last_group_row = rows.get_message_recipient_row(last_message_row);
            dom_messages = $(_.map(message_actions.append_messages, function (message_container) {
                return self._get_message_template(message_container);
            }).join('')).filter('.message_row');

            self._post_process_dom_messages(dom_messages.get());
            last_group_row.append(dom_messages);

            new_dom_elements = new_dom_elements.concat(dom_messages);
        }

        // Add new message groups to the end
        if (message_actions.append_groups.length > 0) {
            // Remove the trailing bookend; it'll be re-added after we do our rendering
            self.clear_trailing_bookend();

            rendered_groups = $(templates.render('message_group', {
                message_groups: message_actions.append_groups,
                use_match_properties: self.list.filter.is_search(),
                table_name: self.table_name,
            }));

            dom_messages = rendered_groups.find('.message_row');
            new_dom_elements = new_dom_elements.concat(rendered_groups);

            self._post_process_dom_messages(dom_messages.get());
            table.append(rendered_groups);
            condense.condense_and_collapse(dom_messages);
        }

        restore_scroll_position();

        var last_message_group = _.last(self._message_groups);
        if (last_message_group !== undefined) {
            list.last_message_historical =
                _.last(last_message_group.message_containers).msg.historical;
        }

        var stream_name = narrow.stream();
        if (stream_name !== undefined) {
            // If user narrows to a stream, doesn't update
            // trailing bookend if user is subscribed.
            var sub = stream_data.get_sub(stream_name);
            if (sub === undefined || !sub.subscribed) {
                list.update_trailing_bookend();
            }
        }

        if (list === current_msg_list) {
            // Update the fade.

            var get_element = function (message_group) {
                // We don't have a MessageGroup class, but we can at least hide the messy details
                // of rows.js from compose_fade.  We provide a callback function to be lazy--
                // compose_fade may not actually need the elements depending on its internal
                // state.
                var message_row = self.get_row(message_group.message_containers[0].msg.id);
                return rows.get_message_recipient_row(message_row);
            };

            compose_fade.update_rendered_message_groups(new_message_groups, get_element);
        }

        if (list === current_msg_list && messages_are_new) {
            self._maybe_autoscroll(new_dom_elements, last_message_was_selected);
        }
    },

    _maybe_autoscroll: function MessageListView__maybe_autoscroll(rendered_elems,
                                                                  last_message_was_selected) {
        // If we are near the bottom of our feed (the bottom is visible) and can
        // scroll up without moving the pointer out of the viewport, do so, by
        // up to the amount taken up by the new message.
        var new_messages_height = 0;
        var id_of_last_message_sent_by_us = -1;

        // C++ iterators would have made this less painful
        _.each(rendered_elems.reverse(), function (elem) {
            // Sometimes there are non-DOM elements in rendered_elems; only
            // try to get the heights of actual trs.
            if (elem.is("div")) {
                new_messages_height += elem.height();
                // starting from the last message, ignore message heights that weren't sent by me.
                if (id_of_last_message_sent_by_us > -1) {
                    return;
                }
                var row_id = rows.id(elem);
                // check for `row_id` NaN in case we're looking at a date row or bookend row
                if (row_id > -1 &&
                    people.is_current_user(this.get_message(row_id).sender_email)) {
                    id_of_last_message_sent_by_us = rows.id(elem);
                }
            }
        }, this);

        // autoscroll_forever: if we're on the last message, keep us on the last message
        if (last_message_was_selected && page_params.autoscroll_forever) {
            this.list.select_id(this.list.last().id, {from_rendering: true});
            navigate.scroll_to_selected();
            this.list.reselect_selected_id();
            return;
        }

        var selected_row = this.selected_row();
        var last_visible = rows.last_visible();

        // Make sure we have a selected row and last visible row. (defensive)
        if (!(selected_row && (selected_row.length > 0) && last_visible)) {
            return;
        }

        var selected_row_offset = selected_row.offset().top;
        var info = message_viewport.message_viewport_info();
        var available_space_for_scroll = selected_row_offset - info.visible_top;

        var rows_offset = rows.last_visible().offset().top - this.list.selected_row().offset().top;

        // autoscroll_forever: if we've sent a message, move pointer at least that far.
        if (page_params.autoscroll_forever && id_of_last_message_sent_by_us > -1 &&
            rows_offset < (message_viewport.height())) {
            this.list.select_id(id_of_last_message_sent_by_us, {from_rendering: true});
            navigate.scroll_to_selected();
            return;
        }

        // Don't scroll if we can't move the pointer up.
        if (available_space_for_scroll <= 0) {
            return;
        }

        if (new_messages_height <= 0) {
            return;
        }

        // This next decision is fairly debatable.  For a big message that
        // would push the pointer off the screen, we do a partial autoscroll,
        // which has the following implications:
        //    a) user sees scrolling (good)
        //    b) user's pointer stays on screen (good)
        //    c) scroll amount isn't really tied to size of new messages (bad)
        //    d) all the bad things about scrolling for users who want messages
        //       to stay on the screen
        var scroll_amount = new_messages_height;

        if (scroll_amount > available_space_for_scroll) {
            scroll_amount = available_space_for_scroll;
        }

        // Let's work our way back to whether the user was already dealing
        // with messages off the screen, in which case we shouldn't autoscroll.
        var bottom_last_visible = last_visible.offset().top + last_visible.height();
        var bottom_old_last_visible = bottom_last_visible - new_messages_height;
        var bottom_viewport = info.visible_top + info.visible_height;

        // Exit if the user was already past the bottom.
        if (bottom_old_last_visible > bottom_viewport) {
            return;
        }

        // Ok, we are finally ready to actually scroll.
        message_viewport.system_initiated_animate_scroll(scroll_amount);
    },

    clear_rendering_state: function MessageListView__clear_rendering_state(clear_table) {
        if (clear_table) {
            this.clear_table();
        }
        this.list.last_message_historical = false;

        this._render_win_start = 0;
        this._render_win_end = 0;
    },

    update_render_window: function MessageListView__update_render_window(selected_idx,
                                                                         check_for_changed) {
        var new_start = Math.max(selected_idx - this._RENDER_WINDOW_SIZE / 2, 0);
        if (check_for_changed && new_start === this._render_win_start) {
            return false;
        }

        this._render_win_start = new_start;
        this._render_win_end = Math.min(this._render_win_start + this._RENDER_WINDOW_SIZE,
                                        this.list.num_items());
        return true;
    },

    maybe_rerender: function MessageListView__maybe_rerender() {
        if (this.table_name === undefined) {
            return false;
        }

        var selected_idx = this.list.selected_idx();

        // We rerender under the following conditions:
        // * The selected message is within this._RENDER_THRESHOLD messages
        //   of the top of the currently rendered window and the top
        //   of the window does not abut the beginning of the message
        //   list
        // * The selected message is within this._RENDER_THRESHOLD messages
        //   of the bottom of the currently rendered window and the
        //   bottom of the window does not abut the end of the
        //   message list
        if (! (((selected_idx - this._render_win_start < this._RENDER_THRESHOLD)
                && (this._render_win_start !== 0)) ||
               ((this._render_win_end - selected_idx <= this._RENDER_THRESHOLD)
                && (this._render_win_end !== this.list.num_items())))) {
            return false;
        }

        if (!this.update_render_window(selected_idx, true)) {
            return false;
        }

        this.rerender_preserving_scrolltop();
        return true;
    },

    rerender_preserving_scrolltop: function MessageListView__rerender_preserving_scrolltop() {
        // scrolltop_offset is the number of pixels between the top of the
        // viewable window and the selected message
        var scrolltop_offset;
        var selected_row = this.selected_row();
        var selected_in_view = (selected_row.length > 0);
        if (selected_in_view) {
            scrolltop_offset = selected_row.offset().top;
        }

        this.clear_table();
        this.render(this.list.all_messages().slice(this._render_win_start, this._render_win_end), 'bottom');

        // If we could see the newly selected message, scroll the
        // window such that the newly selected message is at the
        // same location as it would have been before we
        // re-rendered.
        if (selected_in_view) {
            if (this.selected_row().length === 0 && this.list.selected_id() > -1) {
                this.list.select_id(this.list.selected_id(), {use_closest: true});
            }
            // Must get this.list.selected_row() again since it is now a new DOM element
            message_viewport.scrollTop(
                message_viewport.scrollTop() +
                    this.selected_row().offset().top - scrolltop_offset);
        }
    },

    _rerender_header: function MessageListView__maybe_rerender_header(message_containers) {
        // Given a list of messages that are in the **same** message group,
        // rerender the header / recipient bar of the messages
        if (message_containers.length === 0) {
            return;
        }

        var first_row = this.get_row(message_containers[0].msg.id);

        // We may not have the row if the stream or topic was muted
        if (first_row.length === 0) {
            return;
        }

        var recipient_row = rows.get_message_recipient_row(first_row);
        var header = recipient_row.find('.message_header');

        var group = {message_containers: message_containers};
        populate_group_from_message_container(group, message_containers[0]);

        var rendered_recipient_row = $(templates.render('recipient_row', group));

        header.replaceWith(rendered_recipient_row);
    },

    _rerender_message: function MessageListView___rerender_message(message_container) {
        var row = this.get_row(message_container.msg.id);
        var was_selected = this.list.selected_message() === message_container.msg;

        // Re-render just this one message
        this._add_msg_timestring(message_container);
        this._maybe_format_me_message(message_container);

        var rendered_msg = $(this._get_message_template(message_container));
        this._post_process_dom_messages(rendered_msg.get());
        row.replaceWith(rendered_msg);

        if (was_selected) {
            this.list.select_id(message_container.msg.id);
        }
    },

    rerender_messages: function MessageListView__rerender_messages(messages) {
        var self = this;

        // Convert messages to list messages
        var message_containers = _.map(messages, function (message) {
            return self.message_containers[message.id];
        });
        // We may not have the message_container if the stream or topic was muted
        message_containers = _.reject(message_containers, function (message_container) {
            return message_container === undefined;
        });

        var message_groups = [];
        var current_group = [];
        _.each(message_containers, function (message_container) {
            if (current_group.length === 0 ||
                same_recipient(current_group[current_group.length - 1], message_container)) {
                current_group.push(message_container);
            } else {
                message_groups.push(current_group);
                current_group = [];
            }
            self._rerender_message(message_container);
        });
        if (current_group.length !== 0) {
            message_groups.push(current_group);
        }
        _.each(message_groups, function (messages_in_group) {
            self._rerender_header(messages_in_group);
        });
    },

    append: function MessageListView__append(messages, messages_are_new) {
        var cur_window_size = this._render_win_end - this._render_win_start;
        if (cur_window_size < this._RENDER_WINDOW_SIZE) {
            var slice_to_render = messages.slice(0, this._RENDER_WINDOW_SIZE - cur_window_size);
            this.render(slice_to_render, 'bottom', messages_are_new);
            this._render_win_end += slice_to_render.length;
        }

        // If the pointer is high on the page such that there is a
        // lot of empty space below and the render window is full, a
        // newly received message should trigger a rerender so that
        // the new message, which will appear in the viewable area,
        // is rendered.
        this.maybe_rerender();
    },

    prepend: function MessageListView__prepend(messages) {
        this._render_win_start += messages.length;
        this._render_win_end += messages.length;

        var cur_window_size = this._render_win_end - this._render_win_start;
        if (cur_window_size < this._RENDER_WINDOW_SIZE) {
            var msgs_to_render_count = this._RENDER_WINDOW_SIZE - cur_window_size;
            var slice_to_render = messages.slice(messages.length - msgs_to_render_count);
            this.render(slice_to_render, 'top', false);
            this._render_win_start -= slice_to_render.length;
        }
    },

    rerender_the_whole_thing: function MessageListView__rerender_the_whole_thing() {
        // TODO: Figure out if we can unify this with this.list.rerender().
        this.clear_rendering_state(true);
        this.update_render_window(this.list.selected_idx(), false);
        this.render(this.list.all_messages().slice(this._render_win_start, this._render_win_end), 'bottom');
    },

    clear_table: function MessageListView_clear_table() {
        // We do not want to call .empty() because that also clears
        // jQuery data.  This does mean, however, that we need to be
        // mindful of memory leaks.
        rows.get_table(this.table_name).children().detach();
        this._rows = {};
        this._message_groups = [];
        this.message_containers = {};
    },

    get_row: function MessageListView_get_row(id) {
        return $(this._rows[id]);
    },

    clear_trailing_bookend: function MessageListView_clear_trailing_bookend() {
        var trailing_bookend = rows.get_table(this.table_name).find('.trailing_bookend');
        trailing_bookend.remove();
    },

    render_trailing_bookend: function MessageListView_render_trailing_bookend(
                                trailing_bookend_content, subscribed) {
        var rendered_trailing_bookend = $(templates.render('bookend', {
            bookend_content: trailing_bookend_content,
            trailing: true,
            subscribed: subscribed,
        }));
        rows.get_table(this.table_name).append(rendered_trailing_bookend);
    },

    selected_row: function MessageListView_selected_row() {
        return this.get_row(this.list.selected_id());
    },

    get_message: function MessageListView_get_message(id) {
        return this.list.get(id);
    },

    change_message_id: function MessageListView_change_message_id(old_id, new_id) {
        if (this._rows[old_id] !== undefined) {
            var row = this._rows[old_id];
            delete this._rows[old_id];

            row.setAttribute('zid', new_id);
            row.setAttribute('id', this.table_name + new_id);
            $(row).removeClass('local');
            this._rows[new_id] = row;
        }

        if (this.message_containers[old_id] !== undefined) {
            var message_container = this.message_containers[old_id];
            delete this.message_containers[old_id];
            this.message_containers[new_id] = message_container;
        }

    },

    _maybe_format_me_message: function MessageListView__maybe_format_me_message(message_container) {
        if (message_container.msg.is_me_message) {
            // Slice the '<p>/me ' off the front, and '</p>' off the end
            message_container.status_message = message_container.msg.content.slice(4 + 3, -4);
            message_container.include_sender = true;
        } else {
            message_container.status_message = false;
        }
    },
};

}());

if (typeof module !== 'undefined') {
    module.exports = MessageListView;
}


text:
package com.concert.repository.redis;

/**
 * Created by himanshu.virmani on 04/06/16.
 */
public class KeyUtils {
}


text:
layout: page
title: About
permalink: /about/
---
![smax48]({{ site.baseurl }}/images/max_au_2009.jpg)

Hi, my name is Maxim Chuvilyaev. I am a software developer and solution architect on the Microsoft.NET platform.
I've also had a lot of experience with other technologies like Java, RDBMS, BI systems and more.

Currently I live and work in Melbourne, Australia.

This blog is mainly about software development and related topics.

### Hobbies

Travel - Europe, Russia, Asia, South America and Australia

Scuba diving - Egypt, Malaysia and Australia

Cross-country and downhill skiing - wherever and whenever possible and Australia :-)

Martial arts - TSKSR, Fudoshin Ryu

### Contact me

[{{ site.footer-links.email }}](mailto:{{ site.footer-links.email }})


text:
<?php

namespace Wiki;

use Zend\Mvc\ModuleRouteListener, Zend\Config, Zend\Config\Reader\Yaml;

class Module extends \Psycle\Ext\Module\AbstractModule
{
    public function onBootstrap($e)
    {
        $e->getApplication()->getServiceManager()->get('translator');
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        return $this->_getConfig(__DIR__, array('SKIN_NAME' => $this->getWikiConfig()->skin));
    }

    /**
     *
     * @return Zend\Config\Config
     */
    public function getWikiConfig()
    {
        $dir = __DIR__;
        $replacements = array('CURRENT_MODULE_PATH' => $dir);
        $reader = new Yaml('Symfony\Component\Yaml\Yaml::parse');

        $config = new Config\Config($reader->fromFile($dir . '/config/wiki.config.yml', true), true);
        $constantProcessor = new Config\Processor\Constant();
        $config = $constantProcessor->process($config);
        $tokenProcessor = new Config\Processor\Token($replacements);
        $config = $tokenProcessor->process($config);

        return $config;
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}


text:
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
%GRADIENTDESCENT Performs gradient descent to learn theta
%   theta = GRADIENTDESENT(X, y, theta, alpha, num_iters) updates theta by
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples
J_history = zeros(num_iters, 1);

for iter = 1:num_iters

    % ====================== YOUR CODE HERE ======================
    % Instructions: Perform a single gradient step on the parameter vector
    %               theta.
    %
    % Hint: While debugging, it can be useful to print out the values
    %       of the cost function (computeCost) and gradient here.
    %
deri1=(1/m)*sum(X*theta-y);
deri2=(1/m)*(transpose(X(:,2))*(X*theta-y));
temp0=theta(1)-alpha*deri1;
temp1=theta(2)-alpha*deri2;
theta(1)=temp0;
theta(2)=temp1;

    % ============================================================

    % Save the cost J in every iteration
    J_history(iter) = computeCost(X, y, theta);

end

end


text:
// Including SDKDDKVer.h defines the highest available Windows platform.

// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
#include <WinSDKVer.h>
//Win7 Platform Update were included in Win8 SDK headers, so minimum version is Win8 (0x0602)
#define _WIN7_PLATFORM_UPDATE
#define _WIN32_WINNT  0x0602
#define WINVER        0x0602
#define NTDDI_VERSION 0x06020000
#include <SDKDDKVer.h>


text:
                    Home (current)

Menu


text:
// Copyright 2020 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Unit tests for the app service.
 */

import { TestBed } from '@angular/core/testing';

import { AppConstants } from 'app.constants';
import { AppService } from 'services/app.service';

describe('App Service', () => {
  let appService: AppService;

  beforeEach(() => {
    appService = TestBed.get(AppService);
  });

  describe('querying the app for Machine Learning classifiers', () => {
    const initialValue = AppConstants.ENABLE_ML_CLASSIFIERS;

    afterAll(() => {
      // This throws "Cannot assign to 'ENABLE_ML_CLASSIFIERS' because it
      // is a read-only property.". We need to suppress this error because
      // we need to change the value of 'ENABLE_ML_CLASSIFIERS' for testing
      // purposes.
      // @ts-expect-error
      AppConstants.ENABLE_ML_CLASSIFIERS = initialValue;
    });

    it('should return true if AppConstants.ENABLE_ML_CLASSIFIERS is true',
      () => {
        // This throws "Cannot assign to 'ENABLE_ML_CLASSIFIERS' because it
        // is a read-only property.". We need to suppress this error because
        // we need to change the value of 'ENABLE_ML_CLASSIFIERS' for testing
        // purposes.
        // @ts-expect-error
        AppConstants.ENABLE_ML_CLASSIFIERS = true;
        expect(appService.isMachineLearningClassificationEnabled()).toBeTrue();
      });

    it('should return false if AppConstants.ENABLE_ML_CLASSIFIERS is false',
      () => {
        // This throws "Cannot assign to 'ENABLE_ML_CLASSIFIERS' because it
        // is a read-only property.". We need to suppress this error because
        // we need to change the value of 'ENABLE_ML_CLASSIFIERS' for testing
        // purposes.
        // @ts-expect-error
        AppConstants.ENABLE_ML_CLASSIFIERS = false;
        expect(appService.isMachineLearningClassificationEnabled()).toBeFalse();
      });
  });
});


text:
SELECT DISTINCT state AS abbreviation INTO state FROM address WHERE state IS NOT NULL;
ALTER TABLE state MODIFY abbreviation NOT NULL;
ALTER TABLE state ADD PRIMARY KEY (abbreviation);
ALTER TABLE address ADD CONSTRAINT FK_ADDRESS_STATE FOREIGN KEY (state) REFERENCES state (abbreviation);


text:
#ifndef __GST_AUDIO_CHEB_BAND_H__
#define __GST_AUDIO_CHEB_BAND_H__

#include <gst/gst.h>
#include <gst/base/gstbasetransform.h>
#include <gst/audio/audio.h>
#include <gst/audio/gstaudiofilter.h>

#include "audiofxbaseiirfilter.h"

G_BEGIN_DECLS
#define GST_TYPE_AUDIO_CHEB_BAND            (gst_audio_cheb_band_get_type())
#define GST_AUDIO_CHEB_BAND(obj)            (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIO_CHEB_BAND,GstAudioChebBand))
#define GST_IS_AUDIO_CHEB_BAND(obj)         (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIO_CHEB_BAND))
#define GST_AUDIO_CHEB_BAND_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST((klass) ,GST_TYPE_AUDIO_CHEB_BAND,GstAudioChebBandClass))
#define GST_IS_AUDIO_CHEB_BAND_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass) ,GST_TYPE_AUDIO_CHEB_BAND))
#define GST_AUDIO_CHEB_BAND_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS((obj) ,GST_TYPE_AUDIO_CHEB_BAND,GstAudioChebBandClass))
typedef struct _GstAudioChebBand GstAudioChebBand;
typedef struct _GstAudioChebBandClass GstAudioChebBandClass;

struct _GstAudioChebBand
{
  GstAudioFXBaseIIRFilter parent;

  gint mode;
  gint type;
  gint poles;
  gfloat lower_frequency;
  gfloat upper_frequency;
  gfloat ripple;

  /* < private > */
  GMutex lock;
};

struct _GstAudioChebBandClass
{
  GstAudioFXBaseIIRFilterClass parent;
};

GType gst_audio_cheb_band_get_type (void);

G_END_DECLS
#endif /* __GST_AUDIO_CHEB_BAND_H__ */


text:
const path = require('path')
const moduleAlias = require('module-alias')

moduleAlias.addAlias('quasar', path.join(__dirname, '..'))

require('@quasar/app/bin/quasar-build')


text:
<?php
// *********************************************************************************************************************************
//
// curl.php
//
// This test illustrates how to use the fmCURL class directly.
//
// *********************************************************************************************************************************
//
// Copyright (c) 2017 Mark DeNyse
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// *********************************************************************************************************************************

require_once 'startup.inc.php';

$curl = new fmCURL();

$curlResult = $curl->curl('https://www.example.com');

if (! $curl->getIsError($curlResult)) {
   fmLogger($curlResult);
}
else {
   $errorInfo = $curl->getErrorInfo($curlResult);
   fmLogger('Error = '. $errorInfo['code'] .' Message = '. $errorInfo['message']);
}

?>
<!DOCTYPE html>

      <meta charset="utf-8" />
      <title>fmPDA ♥</title>
      <link href="../css/normalize.css" rel="stylesheet" />
      <link href="../css/styles.css" rel="stylesheet" />

         fmPDA ♥

         fmCURL GET

         Introduction
         Version History
         Examples
         Download

      <?php echo fmGetLog(); ?>


text:
// [[[[INFO>
// Copyright 2015 Epicycle (http://epicycle.org, https://github.com/open-epicycle)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information check https://github.com/open-epicycle/Epicycle.Math-cs
// ]]]]

using System;
using System.Collections.Generic;
using System.Linq;

namespace Epicycle.Math.Geometry.Polytopes
{
    public class TransformedPolysurface : IPolysurface
    {
        public TransformedPolysurface(IPolysurface localSurface, RotoTranslation3 localToGlobal)
        {
            _localSurface = localSurface;
            _localToGlobal = localToGlobal;

            _vertexCollection = new VertexCollection(this);
            _edgeCollection = new EdgeCollection(this);
            _faceCollection = new FaceCollection(this);

            _undirectedComparer = new UndirectedEdgeComparerImpl(this);
        }

        private readonly IPolysurface _localSurface;
        private readonly RotoTranslation3 _localToGlobal;

        private readonly VertexCollection _vertexCollection;
        private readonly EdgeCollection _edgeCollection;
        private readonly FaceCollection _faceCollection;

        private readonly UndirectedEdgeComparerImpl _undirectedComparer;

        public IPolysurface LocalSurface
        {
            get { return _localSurface; }
        }

        public RotoTranslation3 LocalToGlobal
        {
            get { return _localToGlobal; }
        }

        public IReadOnlyCollection<IPolysurfaceVertex> Vertices
        {
            get { return _vertexCollection; }
        }

        public IReadOnlyCollection<IPolysurfaceEdge> Edges
        {
            get { return _edgeCollection; }
        }

        public IReadOnlyCollection<IPolysurfaceFace> Faces
        {
            get { return _faceCollection; }
        }

        public IPolysurfaceEdge GetEdge(IPolysurfaceVertex source, IPolysurfaceVertex target)
        {
            var nativeSource = (TransformedVertex)source;
            var nativeTarget = (TransformedVertex)target;

            return new TransformedEdge(_localSurface.GetEdge(nativeSource.LocalVertex, nativeTarget.LocalVertex), this);
        }

        public IEqualityComparer<IPolysurfaceEdge> UndirectedEdgeComparer
        {
            get { return _undirectedComparer; }
        }

        private sealed class UndirectedEdgeComparerImpl : IEqualityComparer<IPolysurfaceEdge>
        {
            public UndirectedEdgeComparerImpl(TransformedPolysurface parent)
            {
                _parent = parent;
            }

            private readonly TransformedPolysurface _parent;

            public bool Equals(IPolysurfaceEdge x, IPolysurfaceEdge y)
            {
                var nativeX = (TransformedEdge)x;
                var nativeY = (TransformedEdge)y;

                return
                    nativeX.Parent == nativeY.Parent &&
                    LocalComparer.Equals(nativeX.LocalEdge, nativeY.LocalEdge);
            }

            public int GetHashCode(IPolysurfaceEdge edge)
            {
                var nativeEdge = (TransformedEdge)edge;

                return nativeEdge.Parent.GetHashCode() ^ LocalComparer.GetHashCode(nativeEdge.LocalEdge);
            }

            private IEqualityComparer<IPolysurfaceEdge> LocalComparer
            {
                get { return _parent._localSurface.UndirectedEdgeComparer; }
            }
        }

        #region data implementation

        private sealed class VertexCollection : IReadOnlyCollection<IPolysurfaceVertex>
        {
            public VertexCollection(TransformedPolysurface parent)
            {
                _parent = parent;
            }

            private readonly TransformedPolysurface _parent;

            public int Count
            {
                get { return LocalVertices.Count; }
            }

            public IEnumerator<IPolysurfaceVertex> GetEnumerator()
            {
                return LocalVertices.Select(v => (IPolysurfaceVertex)new TransformedVertex(v, _parent)).GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            private IReadOnlyCollection<IPolysurfaceVertex> LocalVertices
            {
                get { return _parent._localSurface.Vertices; }
            }
        }

        private sealed class EdgeCollection : IReadOnlyCollection<IPolysurfaceEdge>
        {
            public EdgeCollection(TransformedPolysurface parent)
            {
                _parent = parent;
            }

            private readonly TransformedPolysurface _parent;

            public int Count
            {
                get { return LocalEdges.Count; }
            }

            public IEnumerator<IPolysurfaceEdge> GetEnumerator()
            {
                return LocalEdges.Select(v => (IPolysurfaceEdge)new TransformedEdge(v, _parent)).GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            private IReadOnlyCollection<IPolysurfaceEdge> LocalEdges
            {
                get { return _parent._localSurface.Edges; }
            }
        }

        private sealed class FaceCollection : IReadOnlyCollection<IPolysurfaceFace>
        {
            public FaceCollection(TransformedPolysurface parent)
            {
                _parent = parent;
            }

            private readonly TransformedPolysurface _parent;

            public int Count
            {
                get { return LocalFaces.Count; }
            }

            public IEnumerator<IPolysurfaceFace> GetEnumerator()
            {
                return LocalFaces.Select(v => (IPolysurfaceFace)new TransformedFace(v, _parent)).GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }

            private IReadOnlyCollection<IPolysurfaceFace> LocalFaces
            {
                get { return _parent._localSurface.Faces; }
            }
        }

        private sealed class TransformedVertex : IPolysurfaceVertex, IEquatable<TransformedVertex>
        {
            public TransformedVertex(IPolysurfaceVertex localVertex, TransformedPolysurface parent)
            {
                _localVertex = localVertex;
                _parent = parent;
            }

            private readonly IPolysurfaceVertex _localVertex;
            private readonly TransformedPolysurface _parent;

            public IPolysurfaceVertex LocalVertex
            {
                get { return _localVertex; }
            }

            public Vector3 Point
            {
                get { return _parent._localToGlobal.Apply(_localVertex.Point); }
            }

            public int Order
            {
                get { return _localVertex.Order; }
            }

            public IEnumerable<IPolysurfaceEdge> Edges
            {
                get { return _localVertex.Edges.Select(edge => (IPolysurfaceEdge)new TransformedEdge(edge, _parent)); }
            }

            #region equality

            public bool Equals(IPolysurfaceVertex other)
            {
                return Equals(other as TransformedVertex);
            }

            public bool Equals(TransformedVertex that)
            {
                return
                    that != null &&
                    this._localVertex.Equals(that._localVertex) &&
                    this._parent == that._parent;
            }

            public override bool Equals(object obj)
            {
                return Equals(obj as TransformedVertex);
            }

            public override int GetHashCode()
            {
                return _parent.GetHashCode() ^ _localVertex.GetHashCode();
            }

            #endregion
        }

        private sealed class TransformedEdge : IPolysurfaceEdge, IEquatable<TransformedEdge>
        {
            public TransformedEdge(IPolysurfaceEdge localEdge, TransformedPolysurface parent)
            {
                _localEdge = localEdge;
                _parent = parent;
            }

            private readonly IPolysurfaceEdge _localEdge;
            private readonly TransformedPolysurface _parent;

            #region properties

            public IPolysurfaceEdge LocalEdge
            {
                get { return _localEdge; }
            }

            public TransformedPolysurface Parent
            {
                get { return _parent; }
            }

            public IPolysurfaceVertex Source
            {
                get { return new TransformedVertex(_localEdge.Source, _parent); }
            }

            public IPolysurfaceVertex Target
            {
                get { return new TransformedVertex(_localEdge.Target, _parent); }
            }

            public IPolysurfaceFace RightFace
            {
                get { return new TransformedFace(_localEdge.RightFace, _parent); }
            }

            public IPolysurfaceFace LeftFace
            {
                get { return new TransformedFace(_localEdge.LeftFace, _parent); }
            }

            public IPolysurfaceEdge Reversed
            {
                get { return new TransformedEdge(_localEdge.Reversed, _parent); }
            }

            #endregion

            #region equality

            public bool Equals(IPolysurfaceEdge other)
            {
                return Equals(other as TransformedEdge);
            }

            public bool Equals(TransformedEdge that)
            {
                return
                    that != null &&
                    this._localEdge.Equals(that._localEdge) &&
                    this._parent == that._parent;
            }

            public override bool Equals(object obj)
            {
                return Equals(obj as TransformedEdge);
            }

            public override int GetHashCode()
            {
                return _parent.GetHashCode() ^ _localEdge.GetHashCode();
            }

            #endregion
        }

        private sealed class TransformedFace : IPolysurfaceFace, IEquatable<TransformedFace>
        {
            public TransformedFace(IPolysurfaceFace localFace, TransformedPolysurface parent)
            {
                _localFace = localFace;
                _parent = parent;
            }

            private readonly IPolysurfaceFace _localFace;
            private readonly TransformedPolysurface _parent;

            public IPolygon3 Polygon
            {
                get { return _parent._localToGlobal.Apply(_localFace.Polygon); }
            }

            public Vector3 Normal
            {
                get { return _parent._localToGlobal.Rotation.Apply(_localFace.Normal); }
            }

            public int Order
            {
                get { return _localFace.Order; }
            }

            public IEnumerable<IPolysurfaceEdge> Edges
            {
                get { return _localFace.Edges.Select(edge => (IPolysurfaceEdge)new TransformedEdge(edge, _parent)); }
            }

            #region equality

            public bool Equals(IPolysurfaceFace other)
            {
                return Equals(other as TransformedFace);
            }

            public bool Equals(TransformedFace that)
            {
                return
                    that != null &&
                    this._localFace.Equals(that._localFace) &&
                    this._parent == that._parent;
            }

            public override bool Equals(object obj)
            {
                return Equals(obj as TransformedFace);
            }

            public override int GetHashCode()
            {
                return _parent.GetHashCode() ^ _localFace.GetHashCode();
            }

            #endregion
        }

        #endregion
    }
}


text:
#ifndef CONTEXT_H
#define CONTEXT_H
#if !defined(INTERNAL) || !defined(EXTERNAL)
# error Missing amalgamation macros
#endif

#include <stddef.h>

enum target {
    TARGET_PREPROCESS,
    TARGET_IR_DOT,
    TARGET_ASM,
    TARGET_OBJ,
    TARGET_EXE
};

enum cstd {
    STD_C89,
    STD_C99,
    STD_C11
};

/* Global information about translation unit. */
INTERNAL struct context {
    int errors;
    int verbose;
    int suppress_warning;
    unsigned int pic : 1;            /* position independent code */
    unsigned int debug : 1;          /* Generate debug information. */
    unsigned int no_common : 1;      /* Don't use COMMON symbols. */
    unsigned int no_sse : 1;         /* Don't use SSE instructions. */
    unsigned int pedantic : 1;
    unsigned int nostdinc : 1;
    enum target target;
    enum cstd standard;
} context;

/*
 * Output diagnostics info to stdout. No-op if context.verbose is not
 * set.
 */
INTERNAL void verbose(const char *, ...);

/*
 * Output warning to stderr. No-op if context.suppress_warning is set.
 */
INTERNAL void warning(const char *, ...);

/* Output error to stderr. */
INTERNAL void error(const char *, ...);

#endif


text:
/**
 * This file is part of the CernVM File System
 *
 * Symmetric encryption/decryption of small pieces of text.  Plain text and
 * cipher text are stored in std::string.  Uses cbc mode, there is no inherent
 * integrity check.  The cipher text should only be used in a data structure
 * that is itself protected by a digital signature, HMAC, or similar.
 *
 * The initialization vector is transferred together with the cipher text.  It
 * is constructed from the HMAC of the key and nonce.
 */

#ifndef CVMFS_CRYPTO_ENCRYPT_H_
#define CVMFS_CRYPTO_ENCRYPT_H_

#include <pthread.h>

#include <map>
#include <string>

#include "crypto/hash.h"
#include "gtest/gtest_prod.h"
#include "util/export.h"
#include "util/single_copy.h"

namespace cipher {

enum Algorithms {
  kAes256Cbc = 0,
  kNone,  // needs to be last
};

/**
 * Encapsulates a small non-copyable piece of pinned memory.  Is actively set to
 * zero on destruction.
 */
class CVMFS_EXPORT Key : SingleCopy {
 public:
  static const unsigned kMaxSize = 64;

  static Key *CreateRandomly(const unsigned size);
  static Key *CreateFromFile(const std::string &path);
  static Key *CreateFromString(const std::string &key);
  bool SaveToFile(const std::string &path);
  ~Key();

  unsigned size() const { return size_; }
  const unsigned char *data() const { return data_; }
  std::string ToBase64() const;

 private:
  Key() : data_(NULL), size_(0)  { }
  unsigned char *data_;
  unsigned size_;
};

/**
 * Allows to access keys by identifiers.  This might at some point move into a
 * separate compilation unit.
 */
class CVMFS_EXPORT AbstractKeyDatabase {
 public:
  virtual ~AbstractKeyDatabase() { }
  virtual bool StoreNew(const Key *key, std::string *id) = 0;
  virtual const Key *Find(const std::string &id) = 0;
};

class CVMFS_EXPORT MemoryKeyDatabase : SingleCopy, public AbstractKeyDatabase {
 public:
  MemoryKeyDatabase();
  virtual ~MemoryKeyDatabase();
  virtual bool StoreNew(const Key *key, std::string *id);
  virtual const Key *Find(const std::string &id);

 private:
  pthread_mutex_t *lock_;
  std::map<std::string, const Key *> database_;
};

/**
 * The interface for an encryption algorithm.  Uses a simple envelope with a one
 * byte prefix: the first 4 bits are the envelope version (currently 0), the
 * second 4 bits are the encryption algorithm and refers to Algorithms.
 */
class CVMFS_EXPORT Cipher {
 public:
  static Cipher *Create(const Algorithms a);
  virtual ~Cipher() { }

  bool Encrypt(const std::string &plaintext, const Key &key,
               std::string *ciphertext);
  static bool Decrypt(const std::string &ciphertext, const Key &key,
                      std::string *plaintext);

  virtual std::string name() const = 0;
  virtual Algorithms algorithm() const = 0;
  virtual unsigned key_size() const = 0;
  virtual unsigned iv_size() const = 0;
  virtual unsigned block_size() const = 0;

 protected:
  Cipher() { }
  virtual std::string DoEncrypt(const std::string &plaintext,
                                const Key &key) = 0;
  virtual std::string DoDecrypt(const std::string &ciphertext,
                                const Key &key) = 0;
};

/**
 * Uses OpenSSL EVP_... format.  The IV is created from the system time.
 */
class CVMFS_EXPORT CipherAes256Cbc : public Cipher {
  FRIEND_TEST(T_Encrypt, Aes_256_Cbc_Iv);

 public:
  static const unsigned kKeySize = 256/8;
  static const unsigned kIvSize = 128/8;
  static const unsigned kBlockSize = 128/8;

  virtual ~CipherAes256Cbc() { }

  virtual std::string name() const { return "AES-256-CBC"; }
  virtual Algorithms algorithm() const { return kAes256Cbc; }
  virtual unsigned key_size() const { return kKeySize; }
  virtual unsigned iv_size() const { return kIvSize; }
  virtual unsigned block_size() const { return kBlockSize; }

 protected:
  virtual std::string DoEncrypt(const std::string &plaintext, const Key &key);
  virtual std::string DoDecrypt(const std::string &ciphertext, const Key &key);

 private:
  shash::Md5 GenerateIv(const Key &key);
};

/**
 * No encryption, plaintext and ciphertext are identical.  For testing.
 */
class CVMFS_EXPORT CipherNone : public Cipher {
 public:
  virtual ~CipherNone() { }

  virtual std::string name() const { return "FOR TESTING ONLY"; }
  virtual Algorithms algorithm() const { return kNone; }
  virtual unsigned key_size() const { return 256/8; }
  virtual unsigned iv_size() const { return 128/8; }
  virtual unsigned block_size() const { return 128/8; }

 protected:
  virtual std::string DoEncrypt(const std::string &plaintext, const Key &key);
  virtual std::string DoDecrypt(const std::string &ciphertext, const Key &key);
};

}  // namespace cipher

#endif  // CVMFS_CRYPTO_ENCRYPT_H_


text:
package io.getlime.security.powerauth.util.otp;

/**
 * The {@code Otp} class contains parsed components from user-provided activation, or recovery
 * code. You can use methods from {@link OtpUtil} class to fill this object with a valid data.
 */
public class Otp {

    /**
     * If object is constructed from an activation code, then property contains just a code, without a signature part.
     * If object is constructed from a recovery code, then property contains just a code, without an optional "R:" prefix.
     */
    public final String activationCode;
    /**
     * Signature calculated from {@link #activationCode}. The value is typically optional for cases,
     * when the user re-typed activation code manually.
     *
     * If object is constructed from a recovery code, then the activation signature part is always empty.
     */
    public final String activationSignature;

    /**
     * Dummy constructor. The object is initialized in the JNI code.
     */
    public Otp() {
        this.activationCode = null;
        this.activationSignature = null;
    }

    //
    // Getters for compatibility with older codes
    //
    public String getActivationCode() {
        return activationCode;
    }

    public String getActivationSignature() {
        return activationSignature;
    }

}


text:
<?php

/**
 * @namespace
 */
namespace Bluz\Router;

use Bluz\Exception;

/**
 * Exception
 *
 * @category Bluz
 * @package  Router
 *
 * @author   Anton Shevchuk
 * @created  03.07.12 11:12
 */
class RouterException extends Exception
{
}


text:
module Viewpoint::EWS::Types
  class MeetingCancellation
    include Viewpoint::EWS
    include Viewpoint::EWS::Types
    include Viewpoint::EWS::Types::Item
  end
end


text:
class CaseinCreateAdminUsers < ActiveRecord::Migration

  def self.up
    create_table :casein_admin_users do |t|
      t.string    :login, :null => false
      t.string    :name
      t.string    :email
      t.integer   :access_level, :null => false, :default => 0
      t.string    :crypted_password, :null => false
      t.string    :password_salt, :null => false
      t.string    :persistence_token
      t.string    :single_access_token
      t.string    :perishable_token
      t.integer   :login_count, :null => false, :default => 0
      t.integer   :failed_login_count, :null => false, :default => 0
      t.datetime  :last_request_at
      t.datetime  :current_login_at
      t.datetime  :last_login_at
      t.string    :current_login_ip
      t.string    :last_login_ip
      t.string    :time_zone
      t.timestamps
    end
  end

  def self.down
    drop_table :casein_admin_users
  end

end


text:
HWND FAR PASCAL CreateMDIDialogParam( HINSTANCE hInstance,
									  LPCSTR lpTemplateName,
									  int x, int y, int cx, int cy);

void WINAPI OpenNotifyWindow(LPSTR confName, LPSTR topicName, LPSTR subject, LPSTR msg)
{
HWND hwndMDIFlist;
HWND confWindow;
HWND topicWindow;
HWND subjectWindow;
HWND messageWindow;
//HWND  amWindows[7];
int i;
//HINSTANCE hInst;

//	GetAmeolWindows((HWND *)&amWindows);
//	BringWindowToTop(amWindows[1]);

//	hwndMDIFlist = (HWND)SendMessage(lpGlobals->hwndAmeol, 2026, 0, 0);
//	hInst = (HINSTANCE)GetWindowLong(GetParent(amWindows[4]), GWL_HINSTANCE);
//	if(hInst)
//	{
//		hwndMDIFlist = CreateMDIDialogParam( hInst, "amctl_saywndcls", 10, 10, 630, 470);
		hwndMDIFlist = StdMDIDialogBoxFrame( lpGlobals->hInst, "amctl_saywndcls", 10, 10, 630, 470);

		if(IsWindow(hwndMDIFlist))
		{
			confWindow    = GetDlgItem(hwndMDIFlist, 6061); // Conference;
			topicWindow	  = GetDlgItem(hwndMDIFlist, 6006); // Topic
			subjectWindow = GetDlgItem(hwndMDIFlist, 5009); // Subject;
			messageWindow = GetDlgItem(hwndMDIFlist, 6031); // Message Text;

			i = ComboBox_FindStringExact(confWindow,  0, confName);
				ComboBox_SetCurSel(confWindow, i);
			i = ComboBox_FindStringExact(topicWindow, 0, topicName);
				ComboBox_SetCurSel(topicWindow, i);

			Edit_SetText(messageWindow, msg);
			Edit_SetText(subjectWindow, subject);
		}
//	}
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="cleartype" content="on">

<link rel="apple-touch-icon-precomposed" sizes="144x144"
	href="img/touch/apple-touch-icon-144x144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114"
	href="img/touch/apple-touch-icon-114x114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72"
	href="img/touch/apple-touch-icon-72x72-precomposed.png">
<link rel="apple-touch-icon-precomposed"
	href="img/touch/apple-touch-icon-57x57-precomposed.png">
<link rel="shortcut icon" href="img/touch/apple-touch-icon.png">

<meta name="msapplication-TileImage"
	content="img/touch/apple-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#222222">

<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/smashtik.css">

Smashtik Video exercise

SuperDog (Zoe's first film)

						<video width="350" height="280" controls poster="media/poster.jpg">

							<source src="media/super_perro_primera_pel_cula_de_zoe_.mp4"
								type="video/mp4">

							<source src="media/super_perro_primera_pel_cula_de_zoe_.ogv"
								type="video/ogg">

							<source src="media/super_perro_primera_pel_cula_de_zoe_.webm"
								type="video/webm">

							Download
								Video from here.
						</video>

				Content: Sed placerat accumsan ligula. Aliquam
				felis magna, congue quis, tempus eu, aliquam vitae, ante. Cras neque
				justo, ultrices at, rhoncus a, facilisis eget, nisl. Quisque vitae
				pede. Nam et augue. Sed a elit. Ut vel massa. Suspendisse nibh pede,
				ultrices vitae, ultrices nec, mollis non, nibh. In sit amet pede
				quis leo vulputate hendrerit. Cras laoreet leo et justo auctor
				condimentum. Integer id enim. Suspendisse egestas, dui ac egestas
				mollis, libero orci hendrerit lacus, et malesuada lorem neque ac
				libero. Morbi tempor pulvinar pede. Donec vel elit. Expand column

				Left Sidebar: Integer velit. Vestibulum nisi nunc,
				accumsan ut, vehicula sit amet, porta a, mi. Nam nisl tellus,
				placerat eget, posuere eget, egestas eget, dui. Pellentesque
				habitant morbi tristique senectus et netus et malesuada fames ac
				turpis egestas. In elementum urna a eros. Integer iaculis. Maecenas
				vel elit. Expand column

				Right Sidebar: Integer velit. Vestibulum nisi nunc,
				accumsan ut, vehicula sit amet, porta a, mi. Nam nisl tellus,
				placerat eget, posuere eget, egestas eget, dui. Pellentesque
				habitant morbi tristique senectus et netus et malesuada fames ac
				turpis egestas. In elementum urna a eros. Integer iaculis. Maecenas
				vel elit. Expand column

			Footer: Mus elit Morbi mus enim lacus at quis Nam
			eget morbi. Et semper urna urna non at cursus dolor vestibulum neque
			enim. Tellus interdum at laoreet laoreet lacinia lacinia sed Quisque
			justo quis. Hendrerit scelerisque lorem elit orci tempor tincidunt
			enim Phasellus dignissim tincidunt. Nunc vel et Sed nisl Vestibulum
			odio montes Aliquam volutpat pellentesque. Ut pede sagittis et quis
			nunc gravida porttitor ligula.


text:
var express = require('express');
var router = express.Router();
var bullet= require('../models/Bullets.js');

/* GET home page. */
router.post('/addBullet', function(req, res, next) {
  var newBullet=new bullet({
    name: req.body.name,
    dateOfCreation: req.body.dateOfCreation,
    lastUpdate: req.body.lastUpdate,
    color: req.body.color,
    content: req.body.content
  });

  bullet.addBullet(newBullet,(err,bullet)=>{
    if(err){
      res.json({succsess: false, msg:'Failed to add bullet  <br>'+err});
    }
    else{
      res.json({succsess: true, msg:'Bullet added',id:bullet.id});
    }
  });

});
router.post('/getAllBullets', function(req, res, next) {
  bullet.getAllBullets((err,bullets)=>{
    if(err){
      res.json({succsess: false, msg:'Failed to get bullets'+err});
    }
    else{
      res.json({succsess: true, bullets:bullets});
    }
  });

});

router.post('/removeBullet',function(req,res,next){
  let id=req.body.id;
  bullet.removeBullet(id,(err,bullet)=>{
    if(err){
      res.json({succsess: false, msg:'Failed to remove bullet'+err});
    }
    else{
      res.json({succsess: true, msg:'Bullet removed Seccessfully'});
    }
  });
});

router.post('/addNewContentToBullet',function(req,res,next){

  bullet.addNewContentToBullet(req.body.bulletID,{"_content":req.body.contentValue,"_updateTime":req.body.contentUpdateTime},(err,dbRes)=>{
    if(err){  res.json({seccess:false,msg:'Failed to add new content to the bullet'});}
    else   res.json({seccess:true,msg:'new content added to the bullet'});
  });
  bullet.updateLastUpdate(req.body.bulletID,req.body.contentUpdateTime,(err,dbRes)=>{
    if(err){  res.json({seccess:false,msg:'Failed to add new content to the bullet'});}
    else   res.json({seccess:true,msg:'new content added to the bullet'});
  });

});

router.post('/updatenewName',function(req,res,next){
  let id=req.body.bulletID;
  let newName =req.body.newName;

  bullet.updateNewName(id,newName,(err,dbres)=>{
    if(err){  res.json({seccess:false,msg:'Failed to Update name'});}
    else   res.json({seccess:true,msg:'new name seccessfully updated'});
  });

});

router.post('/updateTodayContentOfBullet',function(req,res,next){
  let error=false;
    bullet.updateTodayContentOfBullet(req.body.bulletID,{"_content":req.body.contentValue,"_updateTime":req.body.contentUpdateTime},(err,dbRes)=>{
      if(err) error=true;
    });

    bullet.updateLastUpdate(req.body.bulletID,req.body.contentUpdateTime,(err,dbRes)=>{
      if(err||error){  res.json({seccess:false,msg:'Failed to add new content to the bullet'});}
      else   res.json({seccess:true,msg:'new content added to the bullet'});
    });

  });

router.post('/getTime',function(req,res,next){
  let date=new Date();
  res.json({
    year: date.getFullYear(),
    mounth: (date.getMonth()+1),
    day:date.getDate()
  });
});

module.exports = router;


text:
// ***********************************************************************
// Assembly         : CoBuilder.Common
// Author           : Alex Bradley
// Created          : 05-27-2016
//
// Last Modified By : Alex Bradley
// Last Modified On : 07-20-2016
// ***********************************************************************
// <copyright file="Mapper.cs" company="AB Consulting">
//     Copyright © AB Consulting 2016
// </copyright>
// <summary></summary>
// ***********************************************************************
using System.Collections.Generic;
using CoBuilder.Common.Domain;
using CoBuilder.Common.Infrastructure;
using CoBuilder.Common.Interfaces;

namespace CoBuilder.Common.Logic
{
    /// <summary>
    /// Class Mapper.
    /// </summary>
    /// <seealso cref="CoBuilder.Common.Interfaces.IMapper" />
    /// <seealso cref="CoBuilder.Common.Logic.IConfigurator" />
    public class Mapper : IMapper, IConfigurator
    {
        /// <summary>
        /// The _config
        /// </summary>
        private readonly IConfiguration _config;

        /// <summary>
        /// Initializes a new instance of the <see cref="Mapper"/> class.
        /// </summary>
        /// <param name="config">The configuration.</param>
        public Mapper(IConfiguration config)
        {
            _config = config;
        }

        /// <summary>
        /// ps the set identifiers.
        /// </summary>
        /// <param name="bimProduct">The bim product.</param>
        /// <returns>IEnumerable<System.String>.</returns>
        public IEnumerable<string> PSetIdentifiers(BimProduct bimProduct)
        {
            return new List<string> {_config.Structure.Root.Value.Identifier + bimProduct.Id};
        }

        /// <summary>
        /// Generates the project set.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <returns>ProjectPropertySetInfo.</returns>
        public ProjectPropertySetInfo GenerateProjectSet(ISession session)
        {
            return new ProjectPropertySetInfo
            {
                DisplayName = "CBProject",
                Identifier = "CBProject",
                ContactId = session.CurrentUser.ContactId,
                Username = session.CurrentUser.Username,
                WorkplaceName = session.CurrentWorkplaceName
            };
        }

        /// <summary>
        /// Maps the specified bim product.
        /// </summary>
        /// <param name="bimProduct">The bim product.</param>
        /// <returns>IEnumerable<PropertySetInfo>.</returns>
        public IEnumerable<PropertySetInfo> Map(BimProduct bimProduct)
        {
            var root = _config.Structure.Root;
            var rootPSet = MapPSet(root.Value, bimProduct);

            foreach (var child in root.Children)
            {
                if (child.Value.Include)
                {
                    var property = MapProperty(child.Value, bimProduct);
                    if (property == null) continue;
                    rootPSet.AddProperty(property);
                }
            }

            return new List<PropertySetInfo> {rootPSet};
        }

        /// <summary>
        /// Maps the property.
        /// </summary>
        /// <param name="info">The information.</param>
        /// <param name="product">The product.</param>
        /// <returns>PropertyInfo.</returns>
        private PropertyInfo MapProperty(ConfigInfo info, BimProduct product)
        {
            var value = typeof (BimProduct).GetProperty(info.Name).GetValue(product);
            if (value == null) return null;
            var result = new PropertyInfo
            {
                DisplayName = info.DisplayName,
                Identifier = info.Identifier,
                Units = null,
                Value = value.ToString()
            };

            return result;
        }

        /// <summary>
        /// Maps the p set.
        /// </summary>
        /// <param name="info">The information.</param>
        /// <param name="product">The product.</param>
        /// <returns>PropertySetInfo.</returns>
        private PropertySetInfo MapPSet(ConfigInfo info, BimProduct product)
        {
            return new PropertySetInfo
            {
                DisplayName = info.DisplayName,
                Identifier = info.Identifier + product.Id
            };
        }
    }
}


text:
package com.gooddata.dataload;

import static com.gooddata.JsonMatchers.serializesToJson;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.text.MatchesPattern.matchesPattern;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.testng.annotations.Test;

import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;

public class OutputStageTest {

    private static final String SCHEMA_URI = "/gdc/datawarehouse/instances/instanceId/schemas/default";
    private static final String SELF_LINK = "/gdc/dataload/projects/projectId/outputStage";
    private static final String SQL_DIFF =  "/gdc/dataload/projects/projectId/outputStage/sqlDiff";
    private static final String PROCESS_URI = "/gdc/projects/projectId/dataload/processes/processId";
    private static final String CLIENT_ID = "clientId";
    private static final String OUTPUT_STAGE_PREFIX = "outputStagePrefix";

    private static final Map<String, String> LINKS = new LinkedHashMap<String, String>() {{
        put("self", SELF_LINK);
        put("outputStageDiff", SQL_DIFF);
        put("dataloadProcess", PROCESS_URI);
    }};

    @Test
    public void testDeserializationAllFields() throws Exception {
        final InputStream stream = getClass().getResourceAsStream("/dataload/outputStageAllFields.json");
        final OutputStage outputStage = new ObjectMapper().readValue(stream, OutputStage.class);

        assertThat(outputStage.getSchemaUri(), is(equalTo(SCHEMA_URI)));
        assertThat(outputStage.getClientId(), is(equalTo(CLIENT_ID)));
        assertThat(outputStage.getOutputStagePrefix(), is(equalTo(OUTPUT_STAGE_PREFIX)));
        assertThat(outputStage.getLinks(), is(equalTo(LINKS)));
        assertThat(outputStage.getUri(), is(equalTo(SELF_LINK)));
        assertThat(outputStage.getOutputStageDiffUri(), is(equalTo(SQL_DIFF)));
        assertThat(outputStage.getDataloadProcessUri(), is(equalTo(PROCESS_URI)));
        assertThat(outputStage.hasSchemaUri(), is(true));
        assertThat(outputStage.hasClientId(), is(true));
        assertThat(outputStage.hasOutputStagePrefix(), is(true));
    }

    @Test
    public void testDeserialization() throws Exception {
        final InputStream stream = getClass().getResourceAsStream("/dataload/outputStage.json");
        final OutputStage outputStage = new ObjectMapper().readValue(stream, OutputStage.class);

        assertThat(outputStage.getSchemaUri(), is(nullValue()));
        assertThat(outputStage.getClientId(), is(nullValue()));
        assertThat(outputStage.getOutputStagePrefix(), is(nullValue()));
        assertThat(outputStage.getUri(), is(equalTo(SELF_LINK)));
        assertThat(outputStage.getOutputStageDiffUri(), is(equalTo(SQL_DIFF)));
        assertThat(outputStage.getDataloadProcessUri(), is(nullValue()));
        assertThat(outputStage.hasSchemaUri(), is(false));
        assertThat(outputStage.hasClientId(), is(false));
        assertThat(outputStage.hasOutputStagePrefix(), is(false));
    }

    @Test
    public void testSerializationAfterDeserialization() throws Exception {
        final InputStream stream = getClass().getResourceAsStream("/dataload/outputStage.json");
        final OutputStage outputStage = new ObjectMapper().readValue(stream, OutputStage.class);

        outputStage.setSchemaUri(SCHEMA_URI);
        outputStage.setClientId(CLIENT_ID);
        outputStage.setOutputStagePrefix(OUTPUT_STAGE_PREFIX);
        assertThat(outputStage, serializesToJson("/dataload/outputStageNoProcess.json"));
    }

    @Test
    public void testToStringFormat() throws Exception {
        final InputStream stream = getClass().getResourceAsStream("/dataload/outputStage.json");
        final OutputStage outputStage = new ObjectMapper().readValue(stream, OutputStage.class);

        assertThat(outputStage.toString(), matchesPattern(OutputStage.class.getSimpleName() + "\\[.*\\]"));
    }
}


text:
package yarpc

import "go.uber.org/yarpc/yarpcerrors"

// IsBadRequestError returns true on an error returned by RPC clients if the
// request was rejected by YARPC because it was invalid.
//
// 	res, err := client.Call(...)
// 	if yarpc.IsBadRequestError(err) {
// 		fmt.Println("invalid request:", err)
// 	}
//
// Deprecated: use yarpcerrors.FromError(err).Code() == yarpcerrors.CodeInvalidArgument instead.
func IsBadRequestError(err error) bool {
	return yarpcerrors.FromError(err).Code() == yarpcerrors.CodeInvalidArgument
}

// IsUnexpectedError returns true on an error returned by RPC clients if the
// server panicked or failed with an unhandled error.
//
// 	res, err := client.Call(...)
// 	if yarpc.IsUnexpectedError(err) {
// 		fmt.Println("internal server error:", err)
// 	}
//
// Deprecated: use yarpcerrors.FromError(err).Code() == yarpcerrors.CodeInternal instead.
func IsUnexpectedError(err error) bool {
	return yarpcerrors.FromError(err).Code() == yarpcerrors.CodeInternal
}

// IsTimeoutError returns true on an error returned by RPC clients if the given
// error is a TimeoutError.
//
// 	res, err := client.Call(...)
// 	if yarpc.IsTimeoutError(err) {
// 		fmt.Println("request timed out:", err)
// 	}
//
// Deprecated: use yarpcerrors.FromError(err).Code() == yarpcerrors.CodeDeadlineExceeded instead.
func IsTimeoutError(err error) bool {
	return yarpcerrors.FromError(err).Code() == yarpcerrors.CodeDeadlineExceeded
}