text:
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from . import github
import json
import os
import requests
import six.moves.configparser
import urllib.error
import urllib.parse
import urllib.request

class IssueHandler(object):
    '''
    This plugin facilitates sending issues to github, when
    an item is prefixed with '@mention-bot'.

    It will also write items to the issues stream, as well
    as reporting it to github
    '''

    URL = 'https://api.github.com/repos/{}/{}/issues'
    CHARACTER_LIMIT = 70
    CONFIG_FILE = '~/.github-auth.conf'

    def __init__(self):
        self.repo_name = github.get_repo()
        self.repo_owner = github.get_repo_owner()

    def usage(self):
        return '''
            This plugin will allow users to flag messages
            as being issues with Zulip by using te prefix '@mention-bot'.

            Before running this, make sure to create a stream
            called "issues" that your API user can send to.

            Also, make sure that the credentials of the github bot have
            been typed in correctly, that there is a personal access token
            with access to public repositories ONLY,
            and that the repository name is entered correctly.

            Check ~/.github-auth.conf, and make sure there are
            github_repo = <repo_name>  (The name of the repo to post to)
            github_repo_owner = <repo_owner>  (The owner of the repo to post to)
            github_username = <username>  (The username of the GitHub bot)
            github_token = <oauth_token>   (The personal access token for the GitHub bot)
            '''

    def handle_message(self, message, client, state_handler):

        original_content = message['content']
        original_sender = message['sender_email']

        temp_content = 'by {}:'.format(original_sender,)
        new_content = temp_content + original_content
        # gets the repo url
        url_new = self.URL.format(self.REPO_OWNER, self.REPO_NAME)

        # signs into github using the provided username and password
        session = github.auth()

        issue_title = message['content'].strip()
        issue_content = ''
        new_issue_title = ''
        for part_of_title in issue_title.split():
            if len(new_issue_title) < self.CHARACTER_LIMIT:
                new_issue_title += '{} '.format(part_of_title)
            else:
                issue_content += '{} '.format(part_of_title)

        new_issue_title = new_issue_title.strip()
        issue_content = issue_content.strip()
        new_issue_title += '...'

        # Creates the issue json, that is transmitted to the github api servers
        issue = {
            'title': new_issue_title,
            'body': '{} **Sent by [{}](https://chat.zulip.org/#) from zulip**'.format(issue_content, original_sender),
            'assignee': '',
            'milestone': 'none',
            'labels': [''],
        }
        # Sends the HTTP post request
        r = session.post(url_new, json.dumps(issue))

        if r.ok:
            # sends the message onto the 'issues' stream so it can be seen by zulip users
            client.send_message(dict(
                type='stream',
                to='issues',
                subject=message['sender_email'],
                # Adds a check mark so that the user can verify if it has been sent
                content='{} :heavy_check_mark:'.format(new_content),
            ))
            return
            # This means that the issue has not been sent
            # sends the message onto the 'issues' stream so it can be seen by zulip users
            client.send_message(dict(
                type='stream',
                to='issues',
                subject=message['sender_email'],
                # Adds a cross so that the user can see that it has failed, and provides a link to a
                # google search that can (hopefully) direct them to the error
                content='{} :x: Code: [{}](https://www.google.com/search?q=Github HTTP {} Error {})'
                        .format(new_content, r.status_code, r.status_code, r.content),
            ))

handler_class = IssueHandler


text:
Sylius Team
===========

Sylius Team members have the following roles (in an alphabetical order):

Architect
~~~~~~~~~

* Defines and publishes :doc:`the Release Cycle <release-cycle>`
* Contributes to the roadmap with architectural issues

This role is currently held by:

* **Kamil Kokot** (`pamil`_)

Core Team Member
~~~~~~~~~~~~~~~~

* Reviews and merges pull requests
* Triages and reacts to issues
* Engages the community contributors and gathers feedback from them

This role is currently held by:

* **Łukasz Chruściel** (`lchrusciel`_)
* **Kamil Kokot** (`pamil`_)
* **Szymon Kulczyński** (`kulczy`_)
* **Grzegorz Sadowski** (`GSadee`_)
* **Mateusz Zalewski** (`Zales0123`_)

CrowdIn Magician
~~~~~~~~~~~~~~~~

* Maintains translations and integration with `CrowdIn`_
* Curates proofreaders team

This role is currently held by:

* **Adam Kasperczak** (`AdamKasp`_)

Demon
~~~~~

* Deploys and maintains our public demos (`demo.sylius.com`_, `master.demo.sylius.com`_)

This role is currently held by:

* **Łukasz Chruściel** (`lchrusciel`_)
* **Mateusz Zalewski** (`Zales0123`_)

Documentation Mechanic
~~~~~~~~~~~~~~~~~~~~~~

* Maintains and configures documentation setup on Read The Docs

This role is currently held by:

* **Tomasz Sut** (`Tomanhez`_)

Documentation Warden
~~~~~~~~~~~~~~~~~~~~

* Reacts to documentation-related issues and pull requests
* Writes and updates the documentation
* Defines information architecture used in the documentation

This role is currently held by:

* **Kamil Kokot** (`pamil`_)
* **Magdalena Sadowska** (`CoderMaggie`_)

Gardener
~~~~~~~~

* Releases new versions of Sylius (`Sylius`_, `Sylius-Standard`_, `PluginSkeleton`_ repositories)

This role is currently held by:

* **Kamil Kokot** (`pamil`_)

Product Owner
~~~~~~~~~~~~~

* Builds and refines the Product Backlog
* Gathers feedback from all stakeholders

This role is currently held by:

* **Magdalena Sadowska** (`CoderMaggie`_)

Protector of the Realm
~~~~~~~~~~~~~~~~~~~~~~

* Creates and publishes security procedures
* Handles and evaluates security issues

This role is currently held by:

* **Kamil Kokot** (`pamil`_)

Roadmapper
~~~~~~~~~~

* Creates and iterates over `the Sylius Roadmap`_

This role is currently held by:

* **Paweł Jędrzejewski** (`pjedrzejewski`_)

.. _`AdamKasp`: https://github.com/AdamKasp/
.. _`CoderMaggie`: https://github.com/CoderMaggie/
.. _`CrowdIn`: https://crowdin.com/project/sylius
.. _`demo.sylius.com`: https://demo.sylius.com/
.. _`GSadee`: https://github.com/GSadee/
.. _`kulczy`: https://github.com/kulczy/
.. _`lchrusciel`: https://github.com/lchrusciel/
.. _`master.demo.sylius.com`: https://master.demo.sylius.com/
.. _`pamil`: https://github.com/pamil/
.. _`pjedrzejewski`: https://github.com/pjedrzejewski/
.. _`PluginSkeleton`: https://github.com/Sylius/PluginSkeleton
.. _`Sylius-Standard`: https://github.com/Sylius/Sylius-Standard
.. _`Sylius`: https://github.com/Sylius/Sylius
.. _`the Sylius Roadmap`: https://sylius.com/roadmap/
.. _`Tomanhez`: https://github.com/Tomanhez/
.. _`Zales0123`: https://github.com/Zales0123/

redpajama_set_name: RedPajamaGithub


text:
{% extends 'layouts/default.html' %}
{% block content %}
  <div data-ui-view flex layout="row"></div>
  <script type="text/javascript">
    window.user = {{user|json|safe}};
    window.modules = null;
  </script>
{% endblock %}


text:
package org.apache.catalina.ha.authenticator;

import java.security.Principal;

import org.apache.catalina.Container;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Session;
import org.apache.catalina.SessionListener;
import org.apache.catalina.authenticator.SingleSignOn;
import org.apache.catalina.authenticator.SingleSignOnEntry;
import org.apache.catalina.ha.CatalinaCluster;
import org.apache.catalina.ha.ClusterValve;
import org.apache.catalina.tribes.Channel;
import org.apache.catalina.tribes.tipis.AbstractReplicatedMap.MapOwner;
import org.apache.catalina.tribes.tipis.ReplicatedMap;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;

/**
 * A Valve that supports a "single sign on" user experience on
 * each nodes of a cluster, where the security identity of a user who successfully
 * authenticates to one web application is propagated to other web applications and
 * to other nodes cluster in the same security domain.  For successful use, the following
 * requirements must be met:
 *

 *
This Valve must be configured on the Container that represents a
 *     virtual host (typically an implementation of Host).

 *
The Realm that contains the shared user and role
 *     information must be configured on the same Container (or a higher
 *     one), and not overridden at the web application level.

 *
The web applications themselves must use one of the standard
 *     Authenticators found in the
 *     org.apache.catalina.authenticator package.

 *

 *
 * @author Fabien Carrion
 */
public class ClusterSingleSignOn extends SingleSignOn implements ClusterValve, MapOwner {

    private static final StringManager sm =
            StringManager.getManager(ClusterSingleSignOn.class.getPackage().getName());

    // -------------------------------------------------------------- Properties

    private CatalinaCluster cluster = null;
    @Override
    public CatalinaCluster getCluster() { return cluster; }
    @Override
    public void setCluster(CatalinaCluster cluster) {
        this.cluster = cluster;
    }

    private long rpcTimeout = 15000;
    public long getRpcTimeout() {
        return rpcTimeout;
    }
    public void setRpcTimeout(long rpcTimeout) {
        this.rpcTimeout = rpcTimeout;
    }

    private int mapSendOptions =
            Channel.SEND_OPTIONS_SYNCHRONIZED_ACK | Channel.SEND_OPTIONS_USE_ACK;
    public int getMapSendOptions() {
        return mapSendOptions;
    }
    public void setMapSendOptions(int mapSendOptions) {
        this.mapSendOptions = mapSendOptions;
    }

    private boolean terminateOnStartFailure = false;
    public boolean getTerminateOnStartFailure() {
        return terminateOnStartFailure;
    }

    public void setTerminateOnStartFailure(boolean terminateOnStartFailure) {
        this.terminateOnStartFailure = terminateOnStartFailure;
    }

    // ---------------------------------------------------- SingleSignOn Methods

    @Override
    protected boolean associate(String ssoId, Session session) {
        boolean result = super.associate(ssoId, session);
        if (result) {
            ((ReplicatedMap<String,SingleSignOnEntry>) cache).replicate(ssoId, true);
        }
        return result;
    }

    @Override
    protected boolean update(String ssoId, Principal principal, String authType,
            String username, String password) {
        boolean result = super.update(ssoId, principal, authType, username, password);
        if (result) {
            ((ReplicatedMap<String,SingleSignOnEntry>) cache).replicate(ssoId, true);
        }
        return result;
    }

    @Override
    protected SessionListener getSessionListener(String ssoId) {
        return new ClusterSingleSignOnListener(ssoId);
    }

    // -------------------------------------------------------- MapOwner Methods

    @Override
    public void objectMadePrimary(Object key, Object value) {
        // NO-OP
    }

    // ------------------------------------------------------- Lifecycle Methods

    /**
     * Start this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected synchronized void startInternal() throws LifecycleException {

        // Load the cluster component, if any
        try {
            if(cluster == null) {
                Container host = getContainer();
                if(host instanceof Host) {
                    if(host.getCluster() instanceof CatalinaCluster) {
                        setCluster((CatalinaCluster) host.getCluster());
                    }
                }
            }
            if (cluster == null) {
                throw new LifecycleException(sm.getString("clusterSingleSignOn.nocluster"));
            }

            ClassLoader[] cls = new ClassLoader[] { this.getClass().getClassLoader() };

            ReplicatedMap<String,SingleSignOnEntry> cache = new ReplicatedMap<>(
                    this, cluster.getChannel(), rpcTimeout, cluster.getClusterName() + "-SSO-cache",
                    cls, terminateOnStartFailure);
            cache.setChannelSendOptions(mapSendOptions);
            this.cache = cache;
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            throw new LifecycleException(sm.getString("clusterSingleSignOn.clusterLoad.fail"), t);
        }

        super.startInternal();
    }

    /**
     * Stop this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected synchronized void stopInternal() throws LifecycleException {

        super.stopInternal();

        if (getCluster() != null) {
            ((ReplicatedMap<?,?>) cache).breakdown();
        }
    }
}


text:
#ifndef OP_DCACHE_H
#define OP_DCACHE_H

#include <linux/sched.h>
#include <linux/unistd.h>
#include <linux/mman.h>
#include <linux/file.h>

#include "oprofile.h"

extern uint op_dname_top;
extern struct qstr **op_dname_stack;
extern char * op_pool_pos;
extern char * op_pool_start;
extern char * op_pool_end;

uint do_hash(struct dentry * dentry, struct vfsmount * vfsmnt, struct dentry * root, struct vfsmount * rootmnt);

inline static uint alloc_in_pool(char const * str, uint len);
inline static int add_hash_entry(struct op_hash_index * entry, uint parent, char const * name, uint len);
inline static uint name_hash(char const * name, uint len, uint parent);

inline static uint name_hash(char const * name, uint len, uint parent)
{
	uint hash=0;

	while (len--)
		hash = (hash + (name[len] << 4) + (name[len] >> 4)) * 11;

	return (hash ^ parent) % OP_HASH_MAP_NR;
}

/* empty ascending dname stack */
inline static void push_dname(struct qstr * dname)
{
	op_dname_stack[op_dname_top] = dname;
	if (op_dname_top != DNAME_STACK_MAX)
		op_dname_top++;
	else
		printk(KERN_ERR "oprofile: overflowed dname stack !\n");
}

inline static struct qstr * pop_dname(void)
{
	if (op_dname_top == 0)
		return NULL;

	return op_dname_stack[--op_dname_top];
}

inline static uint alloc_in_pool(char const * str, uint len)
{
	char * place = op_pool_pos;
	if (op_pool_pos + len + 1 >= op_pool_end)
		return 0;

	strcpy(place, str);
	op_pool_pos += len + 1;
	return place - op_pool_start;
}

inline static char * get_from_pool(uint index)
{
	return op_pool_start + index;
}

inline static int add_hash_entry(struct op_hash_index * entry, uint parent, char const * name, uint len)
{
	entry->name = alloc_in_pool(name, len);
	if (!entry->name)
		return -1;
	entry->parent = parent;
	return 0;
}

#endif /* OP_DCACHE_H */


text:
require "rails_helper"

describe EnrollmentAction::RenewalComparisonHelper do
  subject { Class.new { extend EnrollmentAction::RenewalComparisonHelper } }

  describe "#any_renewal_candidates?" do
    let(:enrollment_event) { double }
    let(:same_carrier_candidates) { [] }
    let(:other_carrier_candidates) { [] }

    before do
      allow(subject).to receive(:same_carrier_renewal_candidates).with(enrollment_event).and_return(same_carrier_candidates)
      allow(subject).to receive(:other_carrier_renewal_candidates).with(enrollment_event).and_return(other_carrier_candidates)
    end

    it "returns false" do
      expect(subject.any_renewal_candidates?(enrollment_event)).to be_falsey
    end

    context "with same carrier candidates" do
      let(:same_carrier_candidates) { [:candidate] }
      it "returns true" do
        expect(subject.any_renewal_candidates?(enrollment_event)).to be_truthy
      end
    end

    context "with other carrier candidates" do
      let(:other_carrier_candidates) { [:candidate] }
      it "returns true" do
        expect(subject.any_renewal_candidates?(enrollment_event)).to be_truthy
      end
    end
  end

  describe "#carrier_requires_simple_renewal" do
    let(:carrier) { instance_double(Carrier, :id => 1, :requires_simple_renewal? => false) }
    let(:plan) { instance_double(Plan, :id => 1, :carrier_id => 1) }
    let(:is_shop?) { false }
    let(:policy_cv) { double()}
    let(:enrollment_event) { instance_double(ExternalEvents::EnrollmentEventNotification,
                              :existing_plan => plan,
                              :is_shop? => is_shop?,
                              :policy_cv => policy_cv
                               )}
    before :each do
      allow(plan).to receive(:carrier).and_return(carrier)
      allow(subject).to receive(:extract_plan).with(policy_cv).and_return(plan)
    end

    it "returns false" do
      expect(subject.carrier_requires_simple_renewal?(enrollment_event)).to be_falsey
    end

    it "returns true" do
      allow(carrier).to receive(:requires_simple_renewal?).and_return(true)
      expect(subject.carrier_requires_simple_renewal?(enrollment_event)).to be_truthy
    end
  end

  describe "#same_carrier_renewal_candidates" do
    let(:is_shop?) { false }
    let(:policy_cv) { double()}
    let(:enrollment_event) { instance_double(ExternalEvents::EnrollmentEventNotification,
                              :is_shop? => is_shop?,
                              :policy_cv => policy_cv
                               )}
    let(:plan) { instance_double(Plan) }
    let(:policy) { instance_double(Policy) }
    let(:subscriber_person) { double(:policies => [policy]) }
    before do
      allow(subject).to receive(:extract_ivl_policy_details).with(policy_cv).
        and_return([plan, subscriber_person, :subscriber_id, :subscriber_start])
      allow(subject).to receive(:ivl_renewal_candidate?).with(policy, plan, :subscriber_id, :subscriber_start, true).
        and_return(true)
    end
    it "returns true" do
      expect(subject.same_carrier_renewal_candidates(enrollment_event)).to eq([policy])
    end

    context "with an empty subscriber_person" do
      let(:subscriber_person) { nil }
      it "returns an empty array" do
        expect(subject.same_carrier_renewal_candidates(enrollment_event)).to eq([])
      end
    end
    context "if the enrollment event is SHOP" do
      let(:is_shop?) { true }
      before do
        allow(subject).to receive(:shop_renewal_candidates).with(policy_cv, true).and_return([:policy])
      end
      it "checks the shop_renewal_candidates" do
        expect(subject.same_carrier_renewal_candidates(enrollment_event)).to eq([:policy])
      end
    end
  end

  describe "#renewal_dependents_changed?" do
    let(:enrollment_event) { instance_double(ExternalEvents::EnrollmentEventNotification) }
    let(:renewal_candidate) { double }
    let(:dropped) { false }
    let(:added) { false }

    before do
      allow(subject).to receive(:renewal_dependents_added?).
        with(renewal_candidate, enrollment_event).
        and_return(added)
      allow(subject).to receive(:renewal_dependents_dropped?).
        with(renewal_candidate, enrollment_event).
        and_return(dropped)
    end

    it "returns false" do
      expect(subject.renewal_dependents_changed?(renewal_candidate, enrollment_event))
    end

    context "if dependends have been added" do
      let(:added) { true }
      it "returns true" do
        expect(subject.renewal_dependents_changed?(renewal_candidate, enrollment_event))
      end
    end
    context "if dependends have been dropped" do
      let(:dropped) { true }
      it "returns true" do
        expect(subject.renewal_dependents_changed?(renewal_candidate, enrollment_event))
      end
    end
  end

  describe "#renewal_dependents_added?" do
    let(:all_member_ids) { [1,2,3] }
    let(:enrollment_event) { instance_double(ExternalEvents::EnrollmentEventNotification,
                              :all_member_ids => all_member_ids
                              )
                           }
    let(:renewal_candidate) { double(:active_member_ids => [1,2,3]) }

    it "returns false if there are no added ids" do
      expect(subject.renewal_dependents_added?(renewal_candidate, enrollment_event)).to be_falsey
    end

    context "if there are added members" do
      let(:all_member_ids) { [1,2,3,4] }
      it "returns true" do
        expect(subject.renewal_dependents_added?(renewal_candidate, enrollment_event)).to be_truthy
      end
    end

    context "if there are dropped members" do
      let(:all_member_ids) { [1,2] }
      it "returns false" do
        expect(subject.renewal_dependents_added?(renewal_candidate, enrollment_event)).to be_falsey
      end
    end
  end

  describe "#renewal_dependents_dropped?" do
    let(:all_member_ids) { [1,2,3] }
    let(:enrollment_event) { instance_double(ExternalEvents::EnrollmentEventNotification,
                              :all_member_ids => all_member_ids
                              )
                           }
    let(:renewal_candidate) { double(:active_member_ids => [1,2,3]) }

    it "returns false if there are no dropped ids" do
      expect(subject.renewal_dependents_dropped?(renewal_candidate, enrollment_event)).to be_falsey
    end

    context "if there are added members" do
      let(:all_member_ids) { [1,2,3,4] }
      it "returns false" do
        expect(subject.renewal_dependents_dropped?(renewal_candidate, enrollment_event)).to be_falsey
      end
    end

    context "if there are dropped members" do
      let(:all_member_ids) { [1,2] }
      it "returns true" do
        expect(subject.renewal_dependents_dropped?(renewal_candidate, enrollment_event)).to be_truthy
      end
    end
  end

  describe "ivl_renewal_candidate?" do
    let(:subscriber) { instance_double(Enrollee, :m_id => 1)}
    let(:subscriber_id) { 1 }
    let(:is_shop?) { false }
    let(:canceled?) { false }
    let(:terminated?) { false }
    let(:same_carrier) { true }
    let(:old_plan) { instance_double(Plan, :year => 2016, :carrier_id => 1, :coverage_type => :some_type)}
    let(:new_plan) { instance_double(Plan, :year => 2017, :carrier_id => 1, :coverage_type => :some_type) }
    let(:policy) { instance_double(Policy,
                    :is_shop? => is_shop?,
                    :subscriber => subscriber,
                    :plan => old_plan,
                    :canceled? => canceled?,
                    :terminated? => terminated?,
                    :coverage_period => old_coverage_period )
                  }
    let(:subscriber_start) { DateTime.new(2017,1,1) }
    let(:old_coverage_period) { double(:end => subscriber_start - 1.day) }

    it "returns true" do
      expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_truthy
    end

    context "policy is for SHOP" do
      let(:is_shop?) { true }
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "policy subscriber mismatch" do
      let(:subscriber_id) { 2 }
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "plan year mismatch" do
      let(:old_plan) { instance_double(Plan, :year => 2015, :carrier_id => 1, :coverage_type => :some_type)}
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "coverage type mismatch" do
      let(:old_plan) { instance_double(Plan, :year => 2016, :carrier_id => 1, :coverage_type => :different_type)}
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "carrier change but same_carrier is true" do
      let(:old_plan) { instance_double(Plan, :year => 2016, :carrier_id => 2, :coverage_type => :some_type)}
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "carrier unchanged but same_carrier is false" do
      let(:same_carrier) { false }
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "policy cancelled" do
      let(:canceled?) { true }
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "policy terminated" do
      let(:terminated?) { true }
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
    context "start date and end date gap" do
      let(:old_coverage_period) { double(:end => subscriber_start - 2.day) }
      it "returns false" do
        expect(subject.ivl_renewal_candidate?(policy, new_plan, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
  end
  describe "shop_renewal_candidate?" do
    ## receives a policy, plan, employer, subscriber_id, subscriber_start, and a boolean if same carrier
    let(:subscriber) { double(:m_id => 1)}
    let(:employer) { double(id: 1) }
    let(:policy_employer_id) { 1 }
    let(:old_plan) { instance_double(Plan, :year => 2016, :carrier_id => 1, :coverage_type => :some_type)}
    let(:new_plan) { instance_double(Plan, :year => 2017, :carrier_id => 1, :coverage_type => :some_type) }
    let(:same_carrier) { true }
    let(:canceled?) { false }
    let(:terminated?) { false }
    let(:subscriber_id) { 1 }
    let(:subscriber_start) { DateTime.new(2017,1,1) }
    let(:old_coverage_period) { double(:end => subscriber_start - 1.day) }

    let(:policy) { instance_double(Policy,
                    :terminated? => terminated?,
                    :canceled? => canceled?,
                    :subscriber => subscriber,
                    :employer_id => policy_employer_id,
                    :plan => old_plan,
                    :coverage_period => old_coverage_period)
                  }

    it "returns true for the matching cases" do
      expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_truthy
    end

    context "the policy does not include an employer_id" do
      let(:policy_employer_id) { nil }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the policy is cancelled" do
      let(:canceled?) { true }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the policy is terminated" do
      let(:terminated?) { true }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the policy subscriber is blank" do
      let(:subscriber) { nil }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the policy's subscriber member id does not match the new subscriber_id" do
      let(:subscriber) { instance_double(Enrollee, :m_id => 4) }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the policy coverage type changed" do
      let(:new_plan) { instance_double(Plan, :year => 2017, :carrier_id => 1, :coverage_type => :new_type)}
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the employer does not match" do
      let(:policy_employer_id) { 2 }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "the plan years dont align" do
      let(:new_plan) { instance_double(Plan, :year => 2018, :carrier_id => 1, :coverage_type => :some_type)}
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "carrier unchanged but same_carrier is false" do
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, false)).to be_falsey
      end
    end

    context "carrier changed but same_carrier is true" do
      let(:new_plan) { instance_double(Plan, :year => 2017, :carrier_id => 2, :coverage_type => :some_type)}
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end

    context "returns false if there is a gap between coverage end and subscriber_start" do
      let(:old_coverage_period) { double(:end => subscriber_start - 2.day) }
      it "returns false" do
        expect(subject.shop_renewal_candidate?(policy, new_plan, employer, subscriber_id, subscriber_start, same_carrier)).to be_falsey
      end
    end
  end

  describe "shop_renewal_candidates" do
    let(:policy_cv) { double }
    let(:subscriber_enrollee) { instance_double(Enrollee) }
    let(:subscriber_start) { DateTime.new(2017,1,1) }
    let(:subscriber_id) { 1 }
    let(:subscriber_person) { instance_double(Person, :policies => [:policy, :non_eligible_policy]) }
    let(:employer) { instance_double(Employer) }
    let(:plan_year) { double(:end_date => subscriber_start + 1.month) }

    before do
      allow(subject).to receive(:extract_subscriber).with(policy_cv).and_return(subscriber_enrollee)
      allow(subject).to receive(:extract_enrollee_start).with(subscriber_enrollee).and_return(subscriber_start)
      allow(subject).to receive(:extract_member_id).with(subscriber_enrollee).and_return(subscriber_id)
      allow(subject).to receive(:find_employer).with(policy_cv).and_return(:employer)
      allow(subject).to receive(:find_employer_plan_year).with(policy_cv).and_return(plan_year)
      allow(subject).to receive(:extract_enrollee_end).with(subscriber_enrollee).and_return('')
      allow(Person).to receive(:find_by_member_id).with(subscriber_id).and_return(subscriber_person)
      allow(subject).to receive(:extract_plan).with(policy_cv).and_return(:plan)
      allow(subject).to receive(:shop_renewal_candidate?).
        with(:policy, :plan, :employer, 1, subscriber_start, true).and_return(true)
      allow(subject).to receive(:shop_renewal_candidate?).
        with(:non_eligible_policy, :plan, :employer, 1, subscriber_start, true).and_return(false)
    end
    it "sends :shop_renewal_candidate? for each policy and returns a candidate if true" do
      expect(subject).to receive(:shop_renewal_candidate?).
        with(:policy, :plan, :employer, 1, subscriber_start, true).once
      expect(subject.shop_renewal_candidates(policy_cv, true)).to eq([:policy])
    end
  end
end


text:
( function( $ ) {

$.preloadImages([
    "/curer/assets/images/yin-dang-de-yi-tian.png",
    "/curer/assets/images/no-worklog-day.png"
]);

var currentDate = Date.today(),
    worklogs = {},
    template = {
        memberTitle: '
#{name}#{total}
',
        memberWorklog: '
#{hour}
#{comments}

',
        member: '
#{name}
'
    };

$( function() {

    $( window ).bind( "hashchange", function (){
        if( location.hash ) {
            var date =  location.hash.replace( "#", "" );
            currentDate = new Date( date * 1 );
        } else{
            var date = Date.today().getTime();
            location.replace( location.href + '#'+ date );
            return;
        }
        fetchData();
    });

    $( "#btn-prev, #btn-next" ).click( function( e ) {
        e.preventDefault();
        var btn = $( this );
        if ( btn.hasClass( "disabled" )) {
            return;
        }

        var date;
        if ( btn.attr( "id" ) == "btn-next" ) {
            date = currentDate.addDays( 1 );
        } else {
            date = currentDate.addDays( -1 );
        }
        location.hash = '#' + date.getTime();
    });

    $( "#btn-today" ).click( function( e ) {
        e.preventDefault();
        var btn = $( this );

        if ( btn.hasClass( "disabled" )) {
            return;
        }

        var today = Date.today();
        if ( currentDate.getTime() != today.getTime()) {
            currentDate = today;
            location.hash = '#' + currentDate.getTime();
        }
    });

    $( ".worklog" ).live( "mouseenter", function() {
        $( this ).addClass( "over" );
    }).live( "mouseleave", function() {
        $( this ).removeClass( "over" );
    });

    $( "#link-toggle-labels" ).click( function( e ) {
        e.preventDefault();
        var labelsEl = $( ".label-list" ),
            labels = labelsEl.find( "li" ),
            liH = labels.eq( 0 ).outerHeight( true ),
            link = $( this );

        if ( link.hasClass( "expanded" )) {
            labelsEl.css({
                height: liH * 5 - 2
            });
            link.removeClass( "expanded" )
                .text( "显示不常用的" + ( labels.length - 5 ) + "个分类" )
                .siblings( "span" )
                .html( "▼" );
        } else {
            labelsEl.css({
                height: liH * labels.length - 2
            });
            link.addClass( "expanded" )
                .text( "只显示常用的5个分类" )
                .siblings( "span" )
                .html( "▲" );
        }
    });

    if ( $( ".label-list li" ).length > 5 ) {
        $( ".toggle-labels" ).show()
            .find( "#link-toggle-labels" )
            .click();
    } else {
        $( ".toggle-labels" ).hide();
    }

    if ( !teamcola.tour ) {
        if( location.hash ) {
            $( window ).trigger( "hashchange" );
        } else {
            var hash = '#' + currentDate.getTime();
            location.replace( location.href + hash);
        }
    }

});

function fetchData( ) {
    var date = currentDate.getTime();
    if ( worklogs[date] ) {
        loadData( worklogs[date] );
    } else {
        hugeLoading.show();
        $.ajax({
            url: teamcola.api.getWorklog,
            data: {
                data: $.toJSON({
                    start: date,
                    end: date + 86400000,
                    teams: [teamcola.currentTeam]
                })
            },
            success: function( result ) {
                $.extend( worklogs, result.worklogs );
                loadData( worklogs[date] );
                hugeLoading.hide();
            }
        });
    }

    function loadData( data ) {

        var teamWorklog = $( ".team-worklog" ).empty().removeClass( "no-worklog" ),
            noWorklogMembers = [],
            noWorklog = true;

        teamcola.members.sort( function( a, b ) {
            return getTotalHour( data[b.guid] ) - getTotalHour( data[a.guid] );
        });

        $.each( teamcola.members, function( index, member ) {

            if ( data[member.guid] && data[member.guid].length ) {
                noWorklog = false;

                var memberEl = $( '

' )
                        .appendTo( teamWorklog ),
                    titleEl = $( template.memberTitle
                        .replace( /\#\{guid\}/g, member.guid )
                        .replace( /\#\{name\}/g, member.nickname )
                        .replace( /\#\{total\}/g, getTotalHour( data[member.guid] ).toFixed( 1 ))
                        .replace( /\#\{avatar\}/g, member.avatar ))
                        .appendTo( memberEl );

                $.each( data[member.guid], function( index, worklog ) {
                    var hour = ( worklog.end_time - worklog.start_time ) / 3600000;
                        worklogEl = $( template.memberWorklog
                            .replace( /\#\{guid\}/g, worklog.guid )
                            .replace( /\#\{hour\}/g, hour.toFixed( 1 ))
                            .replace( /\#\{start\}/g, ( new Date( worklog.start_time )).toString( "HH:mm" ))
                            .replace( /\#\{end\}/g, ( new Date( worklog.end_time )).toString( "HH:mm" ))
                            .replace( /\#\{comments\}/g, worklog.comments || "" ))
                            .appendTo( memberEl );

                    if ( worklog.comments > 0 ) {
                        worklogEl.find( ".comments" ).removeClass( "no-comment" );
                    } else {
                        worklogEl.find( ".comments" ).addClass( "no-comment" );
                    }

                    var htmlContent = $( worklog.html_content );
                    if ( htmlContent.length == 1 && htmlContent.is( "p" )) {
                        worklogEl.find( ".worklog-content" ).prepend( htmlContent.html());
                    } else {
                        worklogEl.find( ".worklog-content" ).prepend( worklog.html_content );
                    }

                    var periodEl = worklogEl.find( ".period" );
                    periodEl.find( "span" ).css({
                        left: Math.round(( worklog.start_time - date ) / 864000 ) + "%",
                        width: Math.max( 1, ( worklog.end_time - worklog.start_time ) / 86400000 * periodEl.width())
                    });

                    var labelsEl = worklogEl.find( ".labels" );
                    if ( worklog.labels.length ) {
                        $.each( worklog.labels, function( index, label ) {
                            $( '' , {
                                href: "/label/" + label.guid + "/",
                                text: label.name
                            }).appendTo( labelsEl );

                            if ( index != worklog.labels.length - 1 ) {
                                labelsEl.append( ", " );
                            }
                        });
                    } else {
                        labelsEl.hide();
                    }
                });
            } else if ( member.is_active ) {
                noWorklogMembers.push( member );
            }

        });

        var noWorklogEl = $( ".no-worklog-members" ),
            noWorklogList = noWorklogEl.find( ".member-list" ).empty();
        if ( noWorklogMembers.length ) {
            noWorklogEl.show();
            $.each( noWorklogMembers, function( index, member ) {
                $( template.member
                    .replace( /\#\{guid\}/g, member.guid )
                    .replace( /\#\{name\}/g, member.nickname )
                    .replace( /\#\{avatar\}/g, member.avatar ))
                    .appendTo( noWorklogList );
            });
        } else {
            noWorklogEl.hide();
        }

        if ( noWorklog ) {
            teamWorklog.addClass( "no-worklog" );
        } else {
            teamWorklog.removeClass( "no-worklog" );
        }

        if ( Date.today().getTime() == date ) {
            $( "#btn-today, #btn-next" ).addClass( "disabled" );
            teamWorklog.addClass( "new-day" );
        } else {
            $( "#btn-today, #btn-next" ).removeClass( "disabled" );
            teamWorklog.removeClass( "new-day" );
        }

        var weekdays = ["日", "一", "二", "三", "四", "五", "六"];
        $( ".date-control .date" ).text( currentDate.toString( "yyyy年M月d日" ) + " 星期" + weekdays[currentDate.getDay()] );
    }
}

function getTotalHour( logs ) {
    var total = 0;
    $.each( logs, function( index, log ) {
        total += ( log.end_time - log.start_time ) / 3600000;
    });
    return total;
}

})( jQuery );


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

shared_examples_for "a token creator that blocks suspended users" do
  let(:app) { OauthApplication.make! }
  let(:user) { User.make! }
  it "should return a token for a normal user" do
    get :create, format: :json, params: default_params_for_strategy
    json = JSON.parse( response.body )
    expect( json["access_token"] ).not_to be_blank
  end
  it "should return a 403 for a suspended user" do
    user.suspend!
    get :create, format: :json, params: default_params_for_strategy
    expect( response.code ).to eq "403"
  end
end

describe OauthTokensController, "with resource owner password credentials" do
  let(:app) { OauthApplication.make! }
  let(:user) { User.make! }
  let(:default_params_for_strategy) { {
    client_id: app.uid,
    client_secret: app.secret,
    grant_type: "password",
    username: user.login,
    password: user.password
  } }
  it_behaves_like "a token creator that blocks suspended users"
  before { ActionController::Base.allow_forgery_protection = true }
  after { ActionController::Base.allow_forgery_protection = false }
  it "should return a 400 for an incorrect password" do
    get :create, format: :json, params: default_params_for_strategy.merge(
      password: "#{user.password}foo"
    )
    expect( response.code ).to eq "400"
  end

  it "should localize an error response" do
    locale = "fr"
    get :create, format: :json, params: default_params_for_strategy.merge(
      password: "#{user.password}foo",
      locale: locale
    )
    json = JSON.parse( response.body )
    expect( json["error_description"] ).to eq I18n.t( :invalid_grant, scope: [:doorkeeper, :errors, :messages], locale: locale )
  end
end

describe OauthTokensController, "with an authorization code" do
  let(:auth_code) {
    # There has to be a better way to test this, but this works
    Doorkeeper::AccessGrant.create!(
      application: app,
      resource_owner_id: user.id,
      expires_in: 600,
      scopes: "write login",
      redirect_uri: app.redirect_uri
    ).token
  }
  let(:default_params_for_strategy) { {
    client_id: app.uid,
    client_secret: app.secret,
    grant_type: "authorization_code",
    redirect_uri: app.redirect_uri,
    code: auth_code
  } }
  before { ActionController::Base.allow_forgery_protection = true }
  after { ActionController::Base.allow_forgery_protection = false }
  it_behaves_like "a token creator that blocks suspended users"
end


text:
import React from 'react';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import { StaticQuery, graphql } from 'gatsby';
import { ThemeProvider } from 'styled-components';

import Logo from '../Logo';
import Breadcrumb from '../Breadcrumb';
import PageTransition from '../PageTransition';
import BlogLink from '../BlogLink';

import theme from '../../styles/theme';
import Container from '../../styles/Container';
import Header from '../../styles/Header';
import Main from '../../styles/Main';
import GlobalStyle from '../../styles/Global';

const Layout = ({ element, props }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (
      <>
        <Helmet
          title={data.site.siteMetadata.title}
          meta={[
            { name: 'description', content: 'Sample' },
            { name: 'keywords', content: 'sample, something' },
          ]}
        >
          <html lang="en" />
        </Helmet>
        <ThemeProvider theme={theme}>
          <Container>
            <Header>
              <Logo icon />
              <Breadcrumb />
              <BlogLink />
            </Header>
            <PageTransition {...props}>
              <Main>{element}</Main>
            </PageTransition>
            <GlobalStyle />
          </Container>
        </ThemeProvider>
      </>
    )}
  />
);

Layout.propTypes = {
  children: PropTypes.node.isRequired,
};

export default Layout;


text:
.class Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;
.super Ljava/lang/Object;
.source "BluetoothControllerImpl.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "ActuallyCachedState"
.end annotation

# instance fields
.field private mBondState:I

.field private final mDevice:Ljava/lang/ref/WeakReference;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/ref/WeakReference",
            "<",
            "Lcom/android/settingslib/bluetooth/CachedBluetoothDevice;",
            ">;"
        }
    .end annotation
.end field

.field private mMaxConnectionState:I

.field private final mUiHandler:Landroid/os/Handler;

# virtual methods
.method public run()V
    .locals 2

    const/4 v1, 0x1

    iget-object v0, p0, Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;->mDevice:Ljava/lang/ref/WeakReference;

    invoke-virtual {v0}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/settingslib/bluetooth/CachedBluetoothDevice;

    invoke-virtual {v0}, Lcom/android/settingslib/bluetooth/CachedBluetoothDevice;->getBondState()I

    move-result v0

    iput v0, p0, Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;->mBondState:I

    iget-object v0, p0, Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;->mDevice:Ljava/lang/ref/WeakReference;

    invoke-virtual {v0}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/android/settingslib/bluetooth/CachedBluetoothDevice;

    invoke-virtual {v0}, Lcom/android/settingslib/bluetooth/CachedBluetoothDevice;->getMaxConnectionState()I

    move-result v0

    iput v0, p0, Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;->mMaxConnectionState:I

    iget-object v0, p0, Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;->mUiHandler:Landroid/os/Handler;

    invoke-virtual {v0, v1}, Landroid/os/Handler;->removeMessages(I)V

    iget-object v0, p0, Lcom/android/systemui/statusbar/policy/BluetoothControllerImpl$ActuallyCachedState;->mUiHandler:Landroid/os/Handler;

    invoke-virtual {v0, v1}, Landroid/os/Handler;->sendEmptyMessage(I)Z

    return-void
.end method


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ForumModels
{
    public class User
    {
        UserList _userList;

        public string Name { get; set; }

        public string MSDNName { get; set; }
        public string StackOverflowID { get; set; }

        public Scores Scores { get; } = new Scores();

        public async Task CalculateScores(UserList userList)
        {
            Console.WriteLine($"Processing {Name}");

            _userList = userList;

            try {
                await Task.WhenAll(CalculateMSDNScore(), CalculateStackOverflowScores());
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error for user {Name}: " + e);
                throw;
            }
        }

        async Task CalculateMSDNScore()
        {
            if (String.IsNullOrWhiteSpace(MSDNName))
                return;

            string rssXml = await QueryHelpers.GetStringAsync($"https://social.msdn.microsoft.com/Profile/u/activities/feed?displayName={MSDNName}");
            var root = XElement.Parse(rssXml);
            CalculateMSDNScoresFromRss(root);
        }

        void CalculateMSDNScoresFromRss(XElement root)
        {
            XNamespace ns = "";

            var titles = new HashSet<string>();

            foreach (var item in root.Descendants(ns + "item"))
            {
                string pubDate = item.Descendants(ns + "pubDate").FirstOrDefault()?.Value;
                string title = item.Descendants(ns + "title").FirstOrDefault()?.Value;

                // Don't process if title is identical
                if (titles.Contains(title)) continue;

                titles.Add(title);

                var dt = DateTimeOffset.Parse(pubDate);

                int newScore = 0;

                if (title.StartsWith("Quickly answered the question"))
                {
                    newScore += 20;
                }
                else if (title.StartsWith("Answered the question"))
                {
                    newScore += 20;
                }
                else if (title.StartsWith("Contributed a helpful post"))
                {
                    newScore += 10;
                }
                else if (title.StartsWith("Replied to a forums thread"))
                {
                    newScore += 1;
                }

                if (dt > _userList.StartOfPeriod && dt < _userList.EndOfPeriod)
                {
                    Scores.MSDN += newScore;
                }
            }
        }

        async Task CalculateStackOverflowScores()
        {
            if (String.IsNullOrWhiteSpace(StackOverflowID))
                return;

            Scores.StackOverflow = await GetStackOverflowReputation(_userList.StartOfPeriod, _userList.EndOfPeriod, _userList.FirstStackOverflowPost);
        }

        async Task<int> GetStackOverflowReputation(DateTimeOffset start, DateTimeOffset end, int firstPostIdToConsider)
        {
            dynamic items = await QueryHelpers.Query(
                $"/2.2/users/{StackOverflowID}/reputation",
                $"fromdate={start.ToUnixTimeSeconds()}&todate={end.ToUnixTimeSeconds()}");

            int reputation = 0;
            foreach (var item in items)
            {
                // Ignore if the post that the event is attached to is too old
                if (item.post_id < firstPostIdToConsider)
                    continue;

                if (item.vote_type == "up_votes")
                {
                    if (item.post_type == "answer")
                    {
                        reputation += 10;
                    }
                    else
                    {
                        // No points for upvotes on questions
                    }
                }
                else if (item.vote_type == "accepts")
                {
                    reputation += 20;
                }
                else
                {
                    // We ignore bounties
                }
            }

            return reputation;
        }

        public override string ToString()
        {
            return Name;
        }
    }
}


text:
@implementation UIImageView (NBWebCache)

- (void)setLastURLString:(NSString *)lastURLString
{
    objc_setAssociatedObject(self, "key", lastURLString, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)lastURLString
{
    return objc_getAssociatedObject(self, "key");
}

- (void)NB_setImageWithURLString:(NSString *)URLString
{
    // 判断本次地址和上次地址是否一样,如果不一样就取消上次的下载操作
    if (![URLString isEqualToString:self.lastURLString] && self.lastURLString != nil) {

        // 单例取消上次下载操作
        [[DownloadOperationManager sharedManager] cancelWithLastUrlStr:self.lastURLString];
    }

    // 保存本次图片地址 : 当再次点击屏幕时,本次保存的就变成上次的了
    self.lastURLString = URLString;

    // 单例接管下载
    [[DownloadOperationManager sharedManager] downloadWithUrlStr:URLString andFinishedBlock:^(UIImage *image)  {

        // 赋值
        self.image = image;
    }];
}

@end


text:
@interface DiscoveryViewController : CHIBaseViewController

@end


text:
<!DOCTYPE html>
<html>
    <head>
        <title>Testing boiler plate</title>
        <script src="bundle.js"></script>
    <head>
    <body>
    <body>
</html>


text:
<?php namespace CodeIgniter\Filters;

use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\Services;

require __DIR__.'/fixtures/InvalidClass.php';
require __DIR__.'/fixtures/GoogleMe.php';

/**
 * @backupGlobals enabled
 */
class FiltersTest extends \CIUnitTestCase
{
	protected $request;
	protected $response;

	public function __construct()
	{
	    parent::__construct();

		$this->request = Services::request();
		$this->response = Services::response();
	}

	//--------------------------------------------------------------------

	public function setUp()
	{

	}

	//--------------------------------------------------------------------

	public function tearDown()
	{

	}

	//--------------------------------------------------------------------

	public function testProcessMethodDetectsCLI()
	{
		$config = [
			'methods' => [
				'cli' => ['foo']
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);

		$expected = [
			'before' => ['foo'],
			'after'  => []
		];

		$this->assertEquals($expected, $filters->initialize()->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodDetectsGetRequests()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'methods' => [
				'get' => ['foo']
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);

		$expected = [
			'before' => ['foo'],
			'after'  => []
		];

		$this->assertEquals($expected, $filters->initialize()->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodRespectsMethod()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'methods' => [
				'post' => ['foo'],
				'get'  => ['bar']
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);

		$expected = [
			'before' => ['bar'],
			'after'  => []
		];

		$this->assertEquals($expected, $filters->initialize()->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodProcessGlobals()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'globals' => [
				'before' => [
					'foo' => ['bar'],
					'bar'
				],
				'after' => [
					'baz'
				]
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);

		$expected = [
			'before' => [
				'foo' => ['bar'],
				'bar'
			],
			'after'  => ['baz']
		];

		$this->assertEquals($expected, $filters->initialize()->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodProcessGlobalsWithExcept()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'globals' => [
				'before' => [
					'foo' => ['except' => ['admin/*']],
					'bar'
				],
				'after' => [
					'baz'
				]
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);
		$uri = 'admin/foo/bar';

		$expected = [
			'before' => [
				'bar'
			],
			'after'  => ['baz']
		];

		$this->assertEquals($expected, $filters->initialize($uri)->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodProcessesFiltersBefore()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'filters' => [
				'foo' => ['before' => ['admin/*'], 'after' => ['/users/*']]
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);
		$uri = 'admin/foo/bar';

		$expected = [
			'before' => ['foo'],
			'after'  => []
		];

		$this->assertEquals($expected, $filters->initialize($uri)->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodProcessesFiltersAfter()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'filters' => [
				'foo' => ['before' => ['admin/*'], 'after' => ['/users/*']]
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);
		$uri = 'users/foo/bar';

		$expected = [
			'before' => [],
			'after'  => ['foo']
		];

		$this->assertEquals($expected, $filters->initialize($uri)->getFilters());
	}

	//--------------------------------------------------------------------

	public function testProcessMethodProcessesCombined()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'globals' => [
				'before' => [
					'foog' => ['except' => ['admin/*']],
					'barg'
				],
				'after' => [
					'bazg'
				]
			],
			'methods' => [
				'post' => ['foo'],
				'get'  => ['bar']
			],
			'filters' => [
				'foof' => ['before' => ['admin/*'], 'after' => ['/users/*']]
			]
		];
		$filters = new Filters((object)$config, $this->request, $this->response);
		$uri = 'admin/foo/bar';

		$expected = [
			'before' => ['barg', 'bar', 'foof'],
			'after'  => ['bazg']
		];

		$this->assertEquals($expected, $filters->initialize($uri)->getFilters());
	}

	//--------------------------------------------------------------------

	public function testRunThrowsWithInvalidAlias()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'aliases' => [],
			'globals' => [
				'before' => ['invalid'],
				'after' => []
			]
		];

		$filters = new Filters((object)$config, $this->request, $this->response);

		$this->expectException('InvalidArgumentException');
		$uri = 'admin/foo/bar';

		$filters->run($uri);
	}

	//--------------------------------------------------------------------

	public function testRunThrowsWithInvalidClassType()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'aliases' => ['invalid' => 'CodeIgniter\Filters\fixtures\InvalidClass'],
			'globals' => [
				'before' => ['invalid'],
				'after' => []
			]
		];

		$filters = new Filters((object)$config, $this->request, $this->response);

		$this->expectException('RuntimeException');
		$uri = 'admin/foo/bar';

		$filters->run($uri);
	}

	//--------------------------------------------------------------------

	public function testRunDoesBefore()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'],
			'globals' => [
				'before' => ['google'],
				'after' => []
			]
		];

		$filters = new Filters((object)$config, $this->request, $this->response);
		$uri = 'admin/foo/bar';

		$request = $filters->run($uri, 'before');

		$this->assertEquals('http://google.com', $request->url);
	}

	//--------------------------------------------------------------------

	public function testRunDoesAfter()
	{
		$_SERVER['REQUEST_METHOD'] = 'GET';

		$config = [
			'aliases' => ['google' => 'CodeIgniter\Filters\fixtures\GoogleMe'],
			'globals' => [
				'before' => [],
				'after' => ['google']
			]
		];

		$filters = new Filters((object)$config, $this->request, $this->response);
		$uri = 'admin/foo/bar';

		$response = $filters->run($uri, 'after');

		$this->assertEquals('http://google.com', $response->csp);
	}

	//--------------------------------------------------------------------
}


text:
namespace Microsoft.Azure.Management.Batch.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Contains information about the auto-storage account associated with a
    /// Batch account.
    /// </summary>
    public partial class AutoStorageProperties : AutoStorageBaseProperties
    {
        /// <summary>
        /// Initializes a new instance of the AutoStorageProperties class.
        /// </summary>
        public AutoStorageProperties()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the AutoStorageProperties class.
        /// </summary>
        /// <param name="storageAccountId">The resource ID of the storage
        /// account to be used for auto-storage account.</param>
        /// <param name="lastKeySync">The UTC time at which storage keys were
        /// last synchronized with the Batch account.</param>
        public AutoStorageProperties(string storageAccountId, System.DateTime lastKeySync)
            : base(storageAccountId)
        {
            LastKeySync = lastKeySync;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the UTC time at which storage keys were last
        /// synchronized with the Batch account.
        /// </summary>
        [JsonProperty(PropertyName = "lastKeySync")]
        public System.DateTime LastKeySync { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public override void Validate()
        {
            base.Validate();
        }
    }
}


text:
layout: post
comments: true
title: Matlab part 1
---

* [GNU Octave](https://www.gnu.org/software/octave/) is a MATLAB clone! Hail GNU Octave!
* **Getting help**: Use `doc blah` to get help on `blah`. The `blah` can be operators too!
* **Expressions**: example, `5 + 5`, `ans = 10`, `y = sin(pi/2)`.
* Semicolon implies end of statement and that you want to suppress the output. For example: `sin(pi/2);` will calculate `sin(pi/2)` but will not echo the value of it in the terminal, while mere `sin(pi/2)` does echo the value. The same is true for variable assignment, i.e., `x =2;` will not echo, while `x = 2` does.
* **Comments**: `%` can be used to add in line comments. Use `%{ ... %}` for block comments.
* Commonly used operators:

| `+` | Plus, addition |
| `-` | Minus, subtraction |
| `*` | Scalar and matrix multiplication |
| `.*`| Array multiplication operator, element wise multiplication |
| `^` | Scalar and matrix exponentiation operator |
| `.^` | Array exponentiation operator, element wise exponentiation |
| `\` | Left division operator, `A\B` solves the system `Ax = B` |
| `/` | Right division operator, `A/B` solves the system `Bx = A`|
| `.\` | Array left division, `A.\B` does the left division pair wise|
| `./` | Array right division |
| `:` | Produces regularly spaced elements `j:k` is same as `[j j+1 ... j+k]` and `j:i:k` is same as `[j j+i j+2i ... j+mi]` |
| `()` | Parenthesis; encloses function argument; **array indices**; overrides precision|
| `[]` | Brackets; used to define array, e.g., `x = [1 2]`|
| `.` | Decimal point |
| `,` | Separates statements and elements in a row|
| `;` | Separates columns and suppresses display |
| `'` | Used to calculate transpose |
| `.'`| Non-conjugated transpose operator|
| `=` | Assignment operator |

* Special: `ans` represent the most recent answer; `i,j` for complex numbers; `inf` represent Infinity; `NaN` undefined number (not a number); `pi` the number $\pi$.
* *Variable* consist of a letter followed by any number of letters, digits, or underscores and MATLAB is case-sensitive.
* **Creating vectors**:
  * `r = [1 2 3]` and `r = [1, 2, 3]` are the same and are ways in which one can create row vectors.
  * `r = [1; 2; 3]` represent a column vector. `[1; 2; 3] = [1 2 3]'`.
* **Creating Matrices**:
  * `mat = [1 2 3; 4 5 6; 7 8 9]`
* **Commands**:
  * `clc` to clear command window, `clear` to remove variables from memory, `exist` to check whether a variable exist, `global` to declare a variable as global, `quit` to quit MATLAB, `who` to list current variable, `whos` to give a longer display.
* **Formatting and I/O**: `disp` to display contents of an array or a string, `fscanf` for inputs, `fprintf` for printing, `input` for taking input.
* **Commands**:

| `cat` | concatenates arrays|
| `find` | finds indices of nonzero elements|
| `length` | computes the number of elements|
| `linspace`| Creates a regularly spaced vector|
| `max` | Returns the maximum element |
| `min` | Returns the smallest element|
| `prod` | Product of each column |
| `reshape` | Changes the size |
| `sort` | Sorts each column |
| `sum` | sums each column |
| `eye` | Creates an identity matrix |
| `ones` | Creates an array of ones |
| `zeros` | Creates an array of zeros |
| `dot` | Computes the dot product |
| `det` | Computes the determinant of a matrix |
| `ceil` | Computes the ceiling of a number |

* **Plotting**:

| `axis` | Set axis limits |
| `fplot` | intelligent plot of functions, use anonymous function as first input|
| `grid`| displays grid lines|
| `plot`| Generates an $xy$ plot, even for matrices|
| `print`| Prints plot or saves plot into a file |
| `title` | Puts up a title at the top of the plot|
| `xlabel` | Adds an xlabel to the plot|
| `ylabel` | Adds a ylabel to the plot|
| `figure` | Opens up a new window for plot |
| `legend` | Legend placement by mouse |
| `subplot` | Creates plot in sub-windows|
| `bar` | Creates a bar plot|
| `hist` | Creates a histogram|
| `hist3d`| Creates a 3-dimensional histogram |
| `hist2d`| Creates a 2-dimensional histogram |

* **Scripts**
  * Scripts are programs with `.m` extension. One can write a series of commands, but this does not accept input and does not return output.
  * **Functions** are programs in `.m` extension. They can accept input and return output. The file in which the function is written should have the name of the first function in the file. For example, if the name of the first function in the file is `fun`, then the name of the Matlab script should be `fun.m`.
  * Function syntax: `function [x1, x2, ..., xn] = funtion-name(i1, i2, ...,im)`.
* Matlab does not use curly braces to denote scope. Instead for things like `if`, loops, etc, one can make use of the end command to denote the end of the current scope.
* **Loops**:
  * `while`: use `while (expression) ... end`
  * `for`: use `for a = 10:20 .. end`. Here `a = 10:20` is a sample and can be replaced with similar command that suits the need.
  * One can use `break` command to exit from the loop, if required.

* **Some useful functions**:

| `mvnpdf`| Multivariate normal pdf|
| `mvncdf`| Multivariate cumulative cdf|
|


text:
class SuppliersController < ApplicationController
  before_action :set_supplier, only: [:show, :edit, :update, :destroy]

  # GET /suppliers
  # GET /suppliers.json
  def index
    # @suppliers = Supplier.all
    @search = Supplier.ransack(params[:q])
    @suppliers = @search.result
  end

  # GET /suppliers/1
  # GET /suppliers/1.json
  def show
  end

  # GET /suppliers/new
  def new
    @supplier = Supplier.new
  end

  # GET /suppliers/1/edit
  def edit
  end

  # POST /suppliers
  # POST /suppliers.json
  def create
    @supplier = Supplier.new(supplier_params)

    respond_to do |format|
      if @supplier.save
        UserMonitor.create(user: current_user.id, info: "Ha agregado nuevo suplidor: #{@supplier.name}")
        format.html { redirect_to @supplier, notice: 'Supplier was successfully created.' }
        format.json { render :show, status: :created, location: @supplier }
      else
        format.html { render :new }
        format.json { render json: @supplier.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /suppliers/1
  # PATCH/PUT /suppliers/1.json
  def update
    respond_to do |format|
      if @supplier.update(supplier_params)
        format.html { redirect_to @supplier, notice: 'Supplier was successfully updated.' }
        format.json { render :show, status: :ok, location: @supplier }
      else
        format.html { render :edit }
        format.json { render json: @supplier.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /suppliers/1
  # DELETE /suppliers/1.json
  def destroy
    @supplier.destroy
    respond_to do |format|
      format.html { redirect_to suppliers_url, notice: 'Supplier was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_supplier
      @supplier = Supplier.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def supplier_params
      params.require(:supplier).permit(:name, :description, supplier_emails_attributes: [:id, :email, :_destroy],
                                        supplier_phones_attributes: [:id, :phone, :ptype, :_destroy] )
    end
end


text:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
    <!-- appworks script (this will be a 404 during development) -->
    <script src="appworks.min.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
</head>
<body ng-app="starter">
<!--The nav bar that will be updated as we navigate between views.-->
<ion-nav-bar class="bar-stable">
    <ion-nav-back-button>
    </ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</body>
</html>


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2015, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Hannes Hauswedell <hannes.hauswedell@fu-berlin.de>
// ==========================================================================
// Tests for the blast module
// ==========================================================================

#ifndef SEQAN_TESTS_TEST_BLAST_MISC_H_
#define SEQAN_TESTS_TEST_BLAST_MISC_H_

using namespace seqan;

SEQAN_DEFINE_TEST(test_blast_program)
{
    constexpr BlastProgram  n = BlastProgram::BLASTN;
    constexpr BlastProgram  p = BlastProgram::BLASTP;
    constexpr BlastProgram  x = BlastProgram::BLASTX;
    constexpr BlastProgram tn = BlastProgram::TBLASTN;
    constexpr BlastProgram tx = BlastProgram::TBLASTX;

    BlastProgram n2 = BlastProgram::BLASTN;
    BlastProgram p2 = BlastProgram::BLASTP;

    /*** TEST frame information functions ***/
    static_assert(qHasRevComp(n),                           "static assertion failed!");
    static_assert(!qHasRevComp(p),                          "static assertion failed!");
    SEQAN_ASSERT(qHasRevComp(n2));
    SEQAN_ASSERT(!qHasRevComp(p2));

    static_assert(qIsTranslated(x),                         "static assertion failed!");
    static_assert(!qIsTranslated(p),                        "static assertion failed!");

    static_assert(qNumFrames(x) == 6u,                      "static assertion failed!");
    static_assert(qNumFrames(tx) == 6u,                     "static assertion failed!");
    static_assert(qNumFrames(p) == 1u,                      "static assertion failed!");
    static_assert(qNumFrames(n) == 2u,                      "static assertion failed!");

    static_assert(sHasRevComp(tn),                          "static assertion failed!");
    static_assert(!sHasRevComp(n),                          "static assertion failed!");
    static_assert(!sHasRevComp(x),                          "static assertion failed!");
    SEQAN_ASSERT(!sHasRevComp(n2));

    static_assert(!sIsTranslated(x),                        "static assertion failed!");

    static_assert(sNumFrames(x) == 1u,                      "static assertion failed!");
    static_assert(sNumFrames(tx) == 6u,                     "static assertion failed!");

    /*** TEST string functions ***/
    // gcc can do the following, because it provides a constexpr strcmp implementation (not required by the standard)
    // it is not really important, though, just for demonstration purposes:
#if defined(COMPILER_GCC) || defined(COMPILER_LINTEL)
    static_assert(strcmp(_programTagToString(n), "BLASTN") == 0,       "static assertion failed!");
#endif
    SEQAN_ASSERT_EQ(_programTagToString(n2), "BLASTN");
}

SEQAN_DEFINE_TEST(test_blast_context_targs)
{
    {
        BlastIOContext<Blosum62/*, DYNAMIC, DYNAMIC*/> context;

        SEQAN_ASSERT(context.tabularSpec == BlastTabularSpec::UNKNOWN);
        SEQAN_ASSERT(context.blastProgram == BlastProgram::UNKNOWN);

        // these would cause build failures, because for ::DYNAMIC the selectors are not fixed at compile time
//         static_assert(context.blastProgram == BlastProgram::UNKNOWN,    "static assertion failed!");
//         static_assert(context.tabularSpec == BlastTabularSpec::UNKNOWN, "static assertion failed!");

        // we can set them to something else
        context.blastProgram = BlastProgram::BLASTX;
        context.tabularSpec = BlastTabularSpec::COMMENTS;

        SEQAN_ASSERT(context.blastProgram == BlastProgram::BLASTX);
        SEQAN_ASSERT(context.tabularSpec == BlastTabularSpec::COMMENTS);
    }

    {
        BlastIOContext<Blosum62, BlastProgram::BLASTX, BlastTabularSpec::COMMENTS> context;

        SEQAN_ASSERT(context.blastProgram == BlastProgram::BLASTX);
        SEQAN_ASSERT(context.tabularSpec == BlastTabularSpec::COMMENTS);

        // now they work at compile time, too
        static_assert(context.blastProgram == BlastProgram::BLASTX,    "static assertion failed!");
        static_assert(context.tabularSpec == BlastTabularSpec::COMMENTS, "static assertion failed!");

        // setting the same programs at run-time is ok
        context.blastProgram = BlastProgram::BLASTX;
        context.tabularSpec = BlastTabularSpec::COMMENTS;

        // but setting to something else would fail
//         context.blastProgram = BlastProgram::BLASTP;
//         context.tabularSpec = BlastTabularSpec::NO_COMMENTS;
    }

}

#endif  // SEQAN_TESTS_TEST_BLAST_MISC_H_


text:
import { Plugin } from '@ckeditor/ckeditor5-core';

export default class ImageEditing extends Plugin {
    static readonly pluginName: 'ImageEditing';
    init(): void;
}


text:
package com.qualogy.qafe.mgwt.client.activities.scrollwidget;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.qualogy.qafe.mgwt.client.DetailActivity;
import com.qualogy.qafe.mgwt.client.main.ClientFactory;

/**
 * @author Daniel Kurka
 *
 */
public class ScrollWidgetActivity extends DetailActivity {

	private final ClientFactory clientFactory;

	/**
	 *
	 */
	public ScrollWidgetActivity(ClientFactory clientFactory) {
		super(clientFactory.getScrollWidgetView(), "nav");
		this.clientFactory = clientFactory;

	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		super.start(panel, eventBus);
		ScrollWidgetView view = clientFactory.getScrollWidgetView();

		view.getMainButtonText().setText("Nav");
		view.getBackbuttonText().setText("UI");
		view.getHeader().setText("Scroll Widget");

		panel.setWidget(view);
	}

}


text:
/*
 * The DistributedSystem QuickStart Example.
 * This example creates two pools programatically.
 * This example takes the following steps:
 *
 * 1. Create a Geode Cache.
 * 2. Now it creates Pool with poolName1.
 * 3. Adds server(localhost:40404) to pool factory.
 * 4. Creates region "root1" with pool.
 * 5. Put Entries (Key and Value pairs) into the Region.
 * 6. Get Entries from the Region.
 * 7. Invalidate an Entry in the Region.
 * 8. Destroy an Entry in the Region.
 * 9. Now it creates another reagion "root2" with another pool "poolName2",
 * which connects to the server(localhost:40405).
 * 10. Now it do put/get operations.
 * 10. Close the Cache.
 *
 */

// Include the Geode library.
#include <geode/GeodeCppCache.hpp>

// Use the "geode" namespace.
using namespace apache::geode::client;

void distributedsystem(CachePtr cachePtr, char *hostname, int port,
                       char *poolName, char *regionName) {
  // create pool factory to create the pool.
  PoolFactoryPtr poolFacPtr = PoolManager::createFactory();

  // adding host(endpoint) in pool
  poolFacPtr->addServer(hostname, port);

  // enabling subscription on pool
  poolFacPtr->setSubscriptionEnabled(true);

  // creating pool with name "examplePool"
  poolFacPtr->create(poolName);

  RegionFactoryPtr regionFactory = cachePtr->createRegionFactory(CACHING_PROXY);

  LOGINFO("Created the RegionFactory");

  // setting pool to attach with region
  regionFactory->setPoolName(poolName);

  // creating first root region
  RegionPtr regionPtr = regionFactory->create(regionName);

  LOGINFO("Created Region.");

  // Put an Entry (Key and Value pair) into the Region using the direct/shortcut
  // method.
  regionPtr->put("Key1", "Value1");

  LOGINFO("Put the first Entry into the Region");

  // Put an Entry into the Region by manually creating a Key and a Value pair.
  CacheableKeyPtr keyPtr = CacheableInt32::create(123);
  CacheablePtr valuePtr = CacheableString::create("123");
  regionPtr->put(keyPtr, valuePtr);

  LOGINFO("Put the second Entry into the Region");

  // Get Entries back out of the Region.
  CacheablePtr result1Ptr = regionPtr->get("Key1");

  LOGINFO("Obtained the first Entry from the Region");

  CacheablePtr result2Ptr = regionPtr->get(keyPtr);

  LOGINFO("Obtained the second Entry from the Region");

  // Invalidate an Entry in the Region.
  regionPtr->invalidate("Key1");

  LOGINFO("Invalidated the first Entry in the Region");

  // Destroy an Entry in the Region.
  regionPtr->destroy(keyPtr);

  LOGINFO("Destroyed the second Entry in the Region");
}

// The DistributedSystem QuickStart example.
int main(int argc, char **argv) {
  try {
    CacheFactoryPtr cacheFactory = CacheFactory::createCacheFactory();

    LOGINFO("Connected to the Geode Distributed System");

    // Create a Geode Cache.
    CachePtr cachePtr = cacheFactory->create();

    LOGINFO("Created the Geode Cache");

    distributedsystem(cachePtr, (char *)"localhost", 40404, (char *)"poolName1",
                      (char *)"exampleRegion1");
    distributedsystem(cachePtr, (char *)"localhost", 40405, (char *)"poolName2",
                      (char *)"exampleRegion2");

    // Close the Geode Cache.
    cachePtr->close();

    LOGINFO("Closed the Geode Cache");

    return 0;
  }
  // An exception should not occur
  catch (const Exception &geodeExcp) {
    LOGERROR("DistributedSystem Geode Exception: %s", geodeExcp.getMessage());

    return 1;
  }
}


text:
<?php

declare(strict_types=1);

namespace Kreta\TaskManager\Application\DataTransformer\Project;

use Kreta\TaskManager\Domain\Model\Project\Project;

interface ProjectDataTransformer
{
    public function write(Project $project);

    public function read();
}


text:
import sys

# pyside resources
from PySide import QtCore
from PySide.QtGui import *

# grab the autogen UI
from devicetree.gui.console_dialog import Ui_ConsoleDialog

class ConsoleDialog(QDialog, Ui_ConsoleDialog):

    def __init__(self, args, parent=None):
        super(ConsoleDialog, self).__init__(parent)
        self.setupUi(self)

        # adjust the layout to be proper -- the designer doesn't seem to be able to do this...
        self.layout = QVBoxLayout()

        self.layout.addWidget( self.textEdit )
        self.layout.addWidget( self.horizontalLayoutWidget )

        self.setLayout(self.layout)

        # line number
        self.lines = 0

        # cook up the param
        self.textEdit.setReadOnly( True )

    def log(self, data):
        self.textEdit.append(data)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    dlg = ConsoleDialog(sys.argv)
    dlg.show()
    sys.exit(app.exec_())


text:
package org.arquillian.cube.spi.await;

public interface AwaitStrategy {

    boolean await();

}


text:
@interface ZM_WKCookieTool : NSObject
{

}
//1.使用全局的processPool,
@property (nonatomic, strong, readonly) WKProcessPool *processPool;

+ (instancetype)sharedSupport;

//关于Cookie同步
//WKWebView有自己的缓存机制,如果想同步session需要注意一下几个地方
+ (WKWebView *)createSharableWKWebView;

@end


text:
define(['mout/lang/clone'], function(clone) {

    describe('lang/clone', function() {

        it('should not return source object', function() {
            var src = {};
            var result = clone(src);
            expect(result).not.toBe(src);
        });

        it('should copy source properties', function() {
            var src = { test: true };
            var result = clone(src);
            expect(result.test).toBe(true);
        });

        it('should not clone child objects', function() {
            var src = { test: {} };
            var result = clone(src);
            expect(result.test).toBe(src.test);
        });

        it('should clone arrays', function() {
            var src = [1, 2, 3];
            var result = clone(src);
            expect(result).not.toBe(src);
            expect(result).toEqual(src);
        });

        it('should clone RegExps', function() {
            var src = /test/gim;
            var result = clone(src);
            expect(result).not.toBe(src);
            expect(result).toEqual(src);
            expect(result.ignoreCase).toEqual(true);
            expect(result.multiline).toEqual(true);
            expect(result.global).toEqual(true);
        });

        it('should clone Dates', function() {
            var src = new Date();
            var result = clone(src);
            expect(result).not.toBe(src);
            expect(result).toEqual(src);
        });

        it('should not clone objects created with custom constructor', function() {
            function TestType() { }
            var src = new TestType();
            var result = clone(src);
            expect(result).toBe(src);
        });

    });

});


text:
KinectCapture
=============

KinectCapture is a user-friendly modified libfreenect front-end software to capture Kinect raw data.

-----------
Compilation
-----------
KinectCapture requires the following libraries and IDEs to get compiled
a) freenect (modified) according to cameras.h
b) pthread
c) gtk
d) gtkglext
e) gl, glu
f) code-blocks.

--------------
User Interface
--------------
The user-interface consists of the real-time depth and rgb/ir display with optional histogram display for rgb/ir. The menu consists of 'Load Program' item to load a valid program. The lower end of the user interface contains the Write Register, Write CMOS Register, Run program, Brightness Set input options.

-------------------
Keyboard Shortcuts
-------------------
1 - mode 1 (RGB 640X480 8bit + Depth 640X480 8bit).
2 - mode 2 (YUV-RGB 640X480 8bit + Depth 640X480 8bit).
3 - mode 3 (IR 640X480 8bit + Depth 640X480 8bit).
4 - mode 4 (RGB 1280X1024 8bit + Depth 640X480 8bit).
5 - mode 5 (IR 1280X1024 8bit).
6 - mode 6 (IR 1280X1024 10bit).
c - captures current mode.
d - toggles depth display.
e - toggles exposure display.
f - cycles through all modes.
h - toggles histogram display.
m - depth smoothing off.
n - depth smoothing on.
p - toggles projector.
q - switches among multiple kinects.
r - runs loaded program if any.
s - resets angle to 0.
w - increases tilt angle.
x - decreases tilt angle.

----------------------------
Programming in KinectCapture
----------------------------
To load a program in memory, check program mode on the main window.
Goto File menu>Load Program and select the program file.
Only on valid program, the Run button 'r' keyboard shortcut will be enabled.

------------------------
Structure of the program
------------------------
Every program must start with the keyword START and end with the keyword STOP.

Comments are allowed at any line except lines that contain codes. e.g.
% this a demo program.

----------------
Program keywords
----------------
All keywords are case-sensitive. The valid keywords are given below.

START - start of a program.
STOP - end of a program.
PAUSE <milliseconds> - pauses the code for <milliseconds> ms.
MODE <value> - changes the current mode to <value> which must be in 1-6 range.
CAPTURE - captures current mode in memory.
SAVE - saves captured data to raw file format.
PROJECTOR - toggles projector.
BRIGHTNESS <value> - changes the ir brightness to <value> level which must be in 0-50 range.
SWITCH <value> - change current device to kinect number <value> for multiple kinects. (-1 for next kinect)
LOOP <value> - beginning of a loop for <value> times.
END - end of a loop.

------------------------------
Capturing data through program
------------------------------
For example to capture all the depth, rgb and ir images, all the required modes need to be captured. e.g. in 640X480 resolution, one must capture both mode 1/2 (for depth and rgb) and mode 3 (for depth and ir) as in the demo program below.

>
% this a demo program to capture all data
START
% change to mode 1
MODE 1
% pause to stabilize the images
PAUSE 1000
% capture depth and rgb
CAPTURE
% change to mode 3
MODE 3
% pause to stabilize the images
PAUSE 1000
% capture depth and ir, note depth will be overwritten
CAPTURE
% now save the captured data
SAVE
STOP
>

Copyright (c) 2014 Sk. Mohammadul Haque

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 details and updates, visit http://mohammadulhaque.alotspace.com


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.17379
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TicTacToe.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TicTacToe.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Запущенная копия программы или брандмаузер блокирует порт, необходимый для работы программы.
        /// </summary>
        internal static string Game_Init_Port_Is_No_Available {
            get {
                return ResourceManager.GetString("Game_Init_Port_Is_No_Available", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Произошло отключение от клиента соперника.
        /// </summary>
        internal static string Game_ProtocolOnErrorMessage_ClientAborted {
            get {
                return ResourceManager.GetString("Game_ProtocolOnErrorMessage_ClientAborted", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to 27015.
        /// </summary>
        internal static string Port {
            get {
                return ResourceManager.GetString("Port", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Connection... {0}.
        /// </summary>
        internal static string Protocol_PostGoGame_Connection {
            get {
                return ResourceManager.GetString("Protocol_PostGoGame_Connection", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Вы играете крестиками.
        /// </summary>
        internal static string TTTForm_YouGameDagger {
            get {
                return ResourceManager.GetString("TTTForm_YouGameDagger", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Вы играете ноликами.
        /// </summary>
        internal static string TTTForm_YouGameZero {
            get {
                return ResourceManager.GetString("TTTForm_YouGameZero", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Ваш ход!.
        /// </summary>
        internal static string TTTForm_YouTurn {
            get {
                return ResourceManager.GetString("TTTForm_YouTurn", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Введен некорректный IP адресс.
        /// </summary>
        internal static string UIGameTTT_CreateGame_IP_Not_Correct {
            get {
                return ResourceManager.GetString("UIGameTTT_CreateGame_IP_Not_Correct", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Ничья!.
        /// </summary>
        internal static string UIGameTTT_Drawn {
            get {
                return ResourceManager.GetString("UIGameTTT_Drawn", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Предложение игры от клиента с IP .
        /// </summary>
        internal static string UIGameTTT_OnGoNewGame_Client_with_IP {
            get {
                return ResourceManager.GetString("UIGameTTT_OnGoNewGame_Client_with_IP", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Новая игра.
        /// </summary>
        internal static string UIGameTTT_OnGoNewGame_NewGame {
            get {
                return ResourceManager.GetString("UIGameTTT_OnGoNewGame_NewGame", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Предупреждение.
        /// </summary>
        internal static string UIGameTTT_OnGoNewGameWarn {
            get {
                return ResourceManager.GetString("UIGameTTT_OnGoNewGameWarn", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Вы проиграли.
        /// </summary>
        internal static string UIGameTTT_You_Miss {
            get {
                return ResourceManager.GetString("UIGameTTT_You_Miss", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Вы победили!.
        /// </summary>
        internal static string UIGameTTT_You_Win {
            get {
                return ResourceManager.GetString("UIGameTTT_You_Win", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Не корректный формат IP.
        /// </summary>
        internal static string UINewGame_ConnectButtonClick_IncorrectIPFormat {
            get {
                return ResourceManager.GetString("UINewGame_ConnectButtonClick_IncorrectIPFormat", resourceCulture);
            }
        }
    }
}


text:
import random
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from trees.ddt import *
sns.set_style('white')

S = 1

increment = 0.001

times = np.arange(0, 1 + increment, increment).tolist()

def get_time(t):
    return times[int(t / increment)]

class Node(object):
    def __init__(self, path, time, parent, leaf=False):
        self.path = path
        self.parent = parent
        self.leaf = leaf
        self.children = []
        self.time = time

    def sample_point(self):
        r = random.random()
        total_count = float(self.leaf_count())
        for i, c in enumerate(self.children):
            leaf_count = c.leaf_count()
            if r > leaf_count / total_count:
                continue
            diverge = random.random() > df.no_divergence(times[self.time], times[c.time], leaf_count)
            if diverge:
                time = times.index(get_time(df.sample(times[self.time], times[c.time], leaf_count)[0]))
                path = c.get_path()
                first_path = path[:time]
                motion = brownian_motion(first_path[-1], (times[time], 1.0))
                new_path = first_path + motion
                while len(new_path) > len(times):
                    new_path = new_path[1:]
                assert len(new_path) == len(times), (len(new_path), len(times))
                node = Node(None, time, self)
                leaf = Node(new_path, -1, node, True)
                node.children.append(leaf)
                node.children.append(c)
                c.parent = node
                self.children[i] = node
                return leaf
            return c.sample_point()

    def get_path(self):
        if self.leaf:
            return self.path
        else:
            return self.left.get_path()[:self.time + 1]

    def leaf_count(self):
        if self.leaf:
            return 1
        return sum([c.leaf_count() for c in self.children])

    @property
    def location(self):
        return self.get_path()[-1]

    @property
    def left(self):
        return self.children[0]

    @property
    def right(self):
        return self.children[1]

    def __repr__(self):
        if self.leaf:
            return "Node(%f, %f)" % (times[self.time], self.get_path()[-1])
        return "Node(%f, %f, %s)" % (times[self.time], self.get_path()[-1], '(%s)' % ', '.join(str(c) for c in self.children))

def brownian_motion(start, time_interval):
    start_time, end_time = time_interval
    vals = [start]
    for i in np.arange(start_time, end_time, increment):
        vals.append(np.random.normal(loc=vals[-1], scale=np.sqrt(S) * increment))
    return vals

df = Inverse(c = 0.7)

root = Node(None, 0, None)
x1 =  Node(brownian_motion(0, (0, 1)), len(times) - 1, root, leaf=True)
root.children.append(x1)

wat = [x1, root.sample_point(), root.sample_point(), root.sample_point()]

def get_path(point):
    return point.path

def plot_node(node):
    if node.leaf:
        plt.plot(times, node.path, alpha=0.5, color=current_palette[0])
        plt.plot(1.0, node.get_path()[-1], 'o', color='black')
        return
    for c in node.children:
        plot_node(c)
    plt.plot(times[node.time], node.get_path()[-1], 'o', color='black')

current_palette = sns.color_palette()
plot_node(root)
plt.xlabel('Time')
plt.savefig('out/ddt.png', bbox_inches='tight')


text:
module AI.Planning.Swarm.SandError where

portError = "This port number can be cause a port conflict: "