text:
404 ERROR

Sorry, the page you're trying to visit is not available.

redpajama_set_name: RedPajamaGithub


text:
from time import time
from typing import Optional

from slack_sdk.errors import SlackApiError, SlackTokenRotationError
from slack_sdk.web import WebClient
from slack_sdk.oauth.installation_store import Installation, Bot

class TokenRotator:
    client: WebClient
    client_id: str
    client_secret: str

    def __init__(
        self, *, client_id: str, client_secret: str, client: Optional[WebClient] = None
    ):
        self.client = client if client is not None else WebClient(token=None)
        self.client_id = client_id
        self.client_secret = client_secret

    def perform_token_rotation(
        self,
        *,
        installation: Installation,
        minutes_before_expiration: int = 120,  # 2 hours by default
    ) -> Optional[Installation]:
        """Performs token rotation if the underlying tokens (bot / user) are expired / expiring.

        Args:
            installation: the current installation data
            minutes_before_expiration: the minutes before the token expiration

        Returns:
            None if no rotation is necessary for now.
        """

        # TODO: make the following two calls in parallel for better performance

        # bot
        rotated_bot: Optional[Bot] = self.perform_bot_token_rotation(
            bot=installation.to_bot(),
            minutes_before_expiration=minutes_before_expiration,
        )

        # user
        rotated_installation: Optional[Installation] = self.perform_user_token_rotation(
            installation=installation,
            minutes_before_expiration=minutes_before_expiration,
        )

        if rotated_bot is not None:
            if rotated_installation is None:
                rotated_installation = Installation(**installation.to_dict())
            rotated_installation.bot_token = rotated_bot.bot_token
            rotated_installation.bot_refresh_token = rotated_bot.bot_refresh_token
            rotated_installation.bot_token_expires_at = rotated_bot.bot_token_expires_at

        return rotated_installation

    def perform_bot_token_rotation(
        self,
        *,
        bot: Bot,
        minutes_before_expiration: int = 120,  # 2 hours by default
    ) -> Optional[Bot]:
        """Performs bot token rotation if the underlying bot token is expired / expiring.

        Args:
            bot: the current bot installation data
            minutes_before_expiration: the minutes before the token expiration

        Returns:
            None if no rotation is necessary for now.
        """
        if bot.bot_token_expires_at is None:
            return None
        if bot.bot_token_expires_at > time() + minutes_before_expiration * 60:
            return None

        try:
            refresh_response = self.client.oauth_v2_access(
                client_id=self.client_id,
                client_secret=self.client_secret,
                grant_type="refresh_token",
                refresh_token=bot.bot_refresh_token,
            )
            if refresh_response.get("token_type") != "bot":
                return None

            refreshed_bot = Bot(**bot.to_dict())
            refreshed_bot.bot_token = refresh_response.get("access_token")
            refreshed_bot.bot_refresh_token = refresh_response.get("refresh_token")
            refreshed_bot.bot_token_expires_at = int(time()) + int(
                refresh_response.get("expires_in")
            )
            return refreshed_bot

        except SlackApiError as e:
            raise SlackTokenRotationError(e)

    def perform_user_token_rotation(
        self,
        *,
        installation: Installation,
        minutes_before_expiration: int = 120,  # 2 hours by default
    ) -> Optional[Bot]:
        """Performs user token rotation if the underlying user token is expired / expiring.

        Args:
            installation: the current installation data
            minutes_before_expiration: the minutes before the token expiration

        Returns:
            None if no rotation is necessary for now.
        """
        if installation.user_token_expires_at is None:
            return None
        if installation.user_token_expires_at > time() + minutes_before_expiration * 60:
            return None

        try:
            refresh_response = self.client.oauth_v2_access(
                client_id=self.client_id,
                client_secret=self.client_secret,
                grant_type="refresh_token",
                refresh_token=installation.user_refresh_token,
            )

            if refresh_response.get("token_type") != "user":
                return None

            refreshed_installation = Installation(**installation.to_dict())
            refreshed_installation.user_token = refresh_response.get("access_token")
            refreshed_installation.user_refresh_token = refresh_response.get(
                "refresh_token"
            )
            refreshed_installation.user_token_expires_at = int(time()) + int(
                refresh_response.get("expires_in")
            )
            return refreshed_installation

        except SlackApiError as e:
            raise SlackTokenRotationError(e)


text:
<md-dialog aria-label="{{ 'Health Check' | translate }}"  ng-cloak>
  <form>
    <md-toolbar>

Health Check Results

        <md-button class="md-icon-button" ng-click="cancel()">
          <md-icon md-svg-src="img/icons/ic_close_24px.svg" aria-label="{{ 'Close dialog' | translate }}"></md-icon>
        </md-button>

    </md-toolbar>
    <md-dialog-content>

        <md-table-container>

                Description
                Passed

                Internet Check

                    <md-icon md-menu-origin md-font-icon="check_circle" class="s48">check_circle</md-icon>

                    <md-icon md-menu-origin md-font-icon="error_outline" class="s48">error_outline</md-icon>

                DNS Check

                    <md-icon md-menu-origin md-font-icon="check_circle" class="s48">check_circle</md-icon>

                    <md-icon md-menu-origin md-font-icon="error_outline" class="s48">error_outline</md-icon>
                    <translate>The box cannot resolve hostnames. Please check your DNS settings.</translate>

                MTU Check

                    <md-icon md-menu-origin md-font-icon="check_circle" class="s48">check_circle</md-icon>

                    <md-icon md-menu-origin md-font-icon="error_outline" class="s48">error_outline</md-icon>

                Connected to CT

                    <md-icon md-menu-origin md-font-icon="check_circle" class="s48">check_circle</md-icon>

                    <md-icon md-menu-origin md-font-icon="error_outline" class="s48">error_outline</md-icon>
                    <translate>Cannot communicate with CT. Please reboot.</translate>

                Splash Pages

                    <md-icon md-menu-origin md-font-icon="check_circle" class="s48">check_circle</md-icon>

                    <md-icon md-menu-origin md-font-icon="error_outline" class="s48">error_outline</md-icon>
                    <translate>Splash pages aren't active. This is OK if you're not using a captive portal</translate>

                In Sync

                    <md-icon md-menu-origin md-font-icon="check_circle" class="s48">check_circle</md-icon>

                    <md-icon md-menu-origin md-font-icon="error_outline" class="s48">error_outline</md-icon>
                    <translate>The box is out of sync. Resync or reboot to get updated configs.</translate>

        </md-table-container>

    </md-dialog-content>
    <md-dialog-actions layout="row">

      <md-button ng-click="close()">
        <translate>
          Close
        </translate>
      </md-button>
    </md-dialog-actions>
  </form>
</md-dialog>


text:
(function(){
    var isActive = true;
    var unreadCount = 0;
    var originalTitle = document.title
    $(window).blur(function () {
        isActive = false;
    })
    $(window).focus(function () {
        isActive = true;
        unreadCount = 0;
        document.title = "kyoppie";
    })
    $.extend({
        addUnreadCount: function(count){
            if(!count) count = 1
            if (!isActive) {
                unreadCount += count;
                document.title = "(" + unreadCount + ") "+originalTitle;
            }
        }
    })
})()


text:
FROM centos:7

RUN yum update -y
RUN yum install -y sudo curl wget unzip
RUN yum install yum-utils –y
RUN yum install -y python36 python36-libs python36-devel python36-pip

RUN mkdir /app
WORKDIR /app

COPY grpc-mate-python.tar /app
RUN tar xvf /app/grpc-mate-python.tar -C /app
RUN pip3 install -r /app/requirements.txt
ENV PYTHONPATH=.

EXPOSE 8080

CMD ["python3","server/server.py"]
#COPY entrypoint.sh /entrypoint.sh
#RUN chmod +x /entrypoint.sh
#ENTRYPOINT ["/entrypoint.sh"]


text:
package com.zyw.horrarndoo.yizhi.global;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

import com.tencent.bugly.crashreport.CrashReport;
import com.zyw.horrarndoo.sdk.global.GlobalApplication;

/**
 * Created by Horrarndoo on 2017/9/6.
 * <p>
 */

public class MyApplication extends GlobalApplication {
    //这个key是自己在聚合数据申请的key,需要自己去聚合数据申请
    public static final String JU_HE_APP_KEY = "799b785ba7b97223be80534651dd0d63";
    public static int SCREEN_WIDTH = -1;
    public static int SCREEN_HEIGHT = -1;
    public static float DIMEN_RATE = -1.0F;
    public static int DIMEN_DPI = -1;
    public static MyApplication app;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        //初始化屏幕宽高
        getScreenSize();

        CrashReport.initCrashReport(getApplicationContext(), "c73ecc54da", false);
    }

    public void getScreenSize() {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        Display display = windowManager.getDefaultDisplay();
        display.getMetrics(dm);
        DIMEN_RATE = dm.density / 1.0F;
        DIMEN_DPI = dm.densityDpi;
        SCREEN_WIDTH = dm.widthPixels;
        SCREEN_HEIGHT = dm.heightPixels;
        if (SCREEN_WIDTH > SCREEN_HEIGHT) {
            int t = SCREEN_HEIGHT;
            SCREEN_HEIGHT = SCREEN_WIDTH;
            SCREEN_WIDTH = t;
        }
    }
}


text:
package org.kie.aries.blueprint.factorybeans;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.kie.api.KieBase;
import org.kie.api.builder.ReleaseId;
import org.kie.api.command.Command;
import org.kie.api.event.KieRuntimeEventManager;
import org.kie.api.event.process.ProcessEventListener;
import org.kie.api.event.rule.AgendaEventListener;
import org.kie.api.event.rule.RuleRuntimeEventListener;
import org.kie.api.logger.KieRuntimeLogger;
import org.kie.api.runtime.Calendars;
import org.kie.api.runtime.Channel;
import org.kie.api.runtime.CommandExecutor;
import org.kie.api.runtime.Environment;
import org.kie.api.runtime.Globals;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.KieSessionConfiguration;
import org.kie.api.runtime.ObjectFilter;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.api.runtime.process.WorkItemManager;
import org.kie.api.runtime.rule.Agenda;
import org.kie.api.runtime.rule.AgendaFilter;
import org.kie.api.runtime.rule.EntryPoint;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.LiveQuery;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.ViewChangedEventListener;
import org.kie.api.time.SessionClock;
import org.kie.aries.blueprint.namespace.BlueprintContextHelper;

public class KieSessionResolver extends AbstractKieObjectsResolver implements KieSession, StatelessKieSession {

    private KieSession kieSession;
    private StatelessKieSession statelessKieSession;

    private final List<KieListenerAdaptor> listeners;
    private final List<KieLoggerAdaptor> loggers;
    private final List<?> commands;
    private final KSessionOptions kSessionOptions;

    public KieSessionResolver( ReleaseId releaseId, List<KieListenerAdaptor> listeners, List<KieLoggerAdaptor> loggers, List<?> commands, KSessionOptions kSessionOptions ) {
        super( releaseId );
        this.listeners = listeners;
        this.loggers = loggers;
        this.commands = commands;
        this.kSessionOptions = kSessionOptions;
    }

    @Override
    public Object init(BlueprintContextHelper context) {
        return getSession();
    }

    private synchronized Object getSession() {
        boolean stateless = isStateless();
        if (stateless) {
            if (statelessKieSession != null) {
                return statelessKieSession;
            }
        } else {
            if (kieSession != null) {
                return kieSession;
            }
        }

        Object obj;
        if (stateless) {
            statelessKieSession = newStatelessSession(kSessionOptions.getkBaseRef(), releaseId, null);
            obj = statelessKieSession;
        } else {
            kieSession = newStatefulSession(kSessionOptions.getkBaseRef(), releaseId, null);
            KieSessionFactoryBeanHelper.executeCommands(kieSession, commands);
            obj = kieSession;
        }

        KieSessionFactoryBeanHelper.addListeners((KieRuntimeEventManager) obj, listeners);
        KieSessionFactoryBeanHelper.attachLoggers((KieRuntimeEventManager) obj, loggers);

        return obj;
    }

    private boolean isStateless() {
        return "stateless".equalsIgnoreCase(kSessionOptions.getType());
    }

    private KieSession getKieSession() {
        return ((KieSession) getSession());
    }

    private StatelessKieSession getStatelessKieSession() {
        return ((StatelessKieSession) getSession());
    }

    @Override
    public int getId() {
        return getKieSession().getId();
    }

    @Override
    public long getIdentifier() {
        return getKieSession().getIdentifier();
    }

    @Override
    public void dispose() {
        getKieSession().dispose();
    }

    @Override
    public void destroy() {
        getKieSession().destroy();
    }

    @Override
    public <T> T execute(Command<T> command) {
        return ((CommandExecutor) getSession()).execute(command);
    }

    @Override
    public <T extends SessionClock> T getSessionClock() {
        return getKieSession().getSessionClock();
    }

    @Override
    public void setGlobal(String identifier, Object value) {
        if (isStateless()) {
            getStatelessKieSession().setGlobal(identifier, value);
        } else {
            getKieSession().setGlobal(identifier, value);
        }
    }

    @Override
    public Object getGlobal(String identifier) {
        return getKieSession().getGlobal(identifier);
    }

    @Override
    public Globals getGlobals() {
        if (isStateless()) {
            return getStatelessKieSession().getGlobals();
        } else {
            return getKieSession().getGlobals();
        }
    }

    @Override
    public Calendars getCalendars() {
        return getKieSession().getCalendars();
    }

    @Override
    public Environment getEnvironment() {
        return getKieSession().getEnvironment();
    }

    @Override
    public KieBase getKieBase() {
        if (isStateless()) {
            return getStatelessKieSession().getKieBase();
        } else {
            return getKieSession().getKieBase();
        }
    }

    @Override
    public void registerChannel(String name, Channel channel) {
        if (isStateless()) {
            getStatelessKieSession().registerChannel(name, channel);
        } else {
            getKieSession().registerChannel(name, channel);
        }
    }

    @Override
    public void unregisterChannel(String name) {
        if (isStateless()) {
            getStatelessKieSession().unregisterChannel(name);
        } else {
            getKieSession().unregisterChannel(name);
        }
    }

    @Override
    public Map<String, Channel> getChannels() {
        if (isStateless()) {
            return getStatelessKieSession().getChannels();
        } else {
            return getKieSession().getChannels();
        }
    }

    @Override
    public KieSessionConfiguration getSessionConfiguration() {
        return getKieSession().getSessionConfiguration();
    }

    @Override
    public void halt() {
        getKieSession().halt();
    }

    @Override
    public Agenda getAgenda() {
        return getKieSession().getAgenda();
    }

    @Override
    public EntryPoint getEntryPoint(String name) {
        return getKieSession().getEntryPoint(name);
    }

    @Override
    public Collection<? extends EntryPoint> getEntryPoints() {
        return getKieSession().getEntryPoints();
    }

    @Override
    public QueryResults getQueryResults(String query, Object... arguments) {
        return getKieSession().getQueryResults(query, arguments);
    }

    @Override
    public LiveQuery openLiveQuery(String query, Object[] arguments, ViewChangedEventListener listener) {
        return getKieSession().openLiveQuery(query, arguments, listener);
    }

    @Override
    public String getEntryPointId() {
        return getKieSession().getEntryPointId();
    }

    @Override
    public FactHandle insert(Object object) {
        return getKieSession().insert(object);
    }

    @Override
    public void retract(FactHandle handle) {
        getKieSession().retract(handle);
    }

    @Override
    public void delete(FactHandle handle) {
        getKieSession().delete(handle);
    }

    @Override
    public void delete(FactHandle handle, FactHandle.State fhState) {
        getKieSession().delete(handle, fhState);
    }

    @Override
    public void update(FactHandle handle, Object object) {
        getKieSession().update(handle, object);
    }

    @Override
    public void update(FactHandle handle, Object object, String... modifiedProperties) {
        getKieSession().update(handle, object, modifiedProperties);
    }

    @Override
    public FactHandle getFactHandle(Object object) {
        return getKieSession().getFactHandle(object);
    }

    @Override
    public Object getObject(FactHandle factHandle) {
        return getKieSession().getObject(factHandle);
    }

    @Override
    public Collection<? extends Object> getObjects() {
        return getKieSession().getObjects();
    }

    @Override
    public Collection<? extends Object> getObjects(ObjectFilter filter) {
        return getKieSession().getObjects(filter);
    }

    @Override
    public <T extends FactHandle> Collection<T> getFactHandles() {
        return getKieSession().getFactHandles();
    }

    @Override
    public <T extends FactHandle> Collection<T> getFactHandles(ObjectFilter filter) {
        return getKieSession().getFactHandles(filter);
    }

    @Override
    public long getFactCount() {
        return getKieSession().getFactCount();
    }

    @Override
    public KieRuntimeLogger getLogger() {
        return getKieSession().getLogger();
    }

    @Override
    public void addEventListener(ProcessEventListener listener) {
        getKieSession().addEventListener(listener);
    }

    @Override
    public void removeEventListener(ProcessEventListener listener) {
        getKieSession().removeEventListener(listener);
    }

    @Override
    public Collection<ProcessEventListener> getProcessEventListeners() {
        return getKieSession().getProcessEventListeners();
    }

    @Override
    public ProcessInstance startProcess(String processId) {
        return getKieSession().startProcess(processId);
    }

    @Override
    public ProcessInstance startProcess(String processId, Map<String, Object> parameters) {
        return getKieSession().startProcess(processId, parameters);
    }

    @Override
    public ProcessInstance createProcessInstance(String processId, Map<String, Object> parameters) {
        return getKieSession().createProcessInstance(processId, parameters);
    }

    @Override
    public ProcessInstance startProcessInstance(long processInstanceId) {
        return getKieSession().startProcessInstance(processInstanceId);
    }

    @Override
    public void signalEvent(String type, Object event) {
        getKieSession().signalEvent(type, event);
    }

    @Override
    public void signalEvent(String type, Object event, long processInstanceId) {
        getKieSession().signalEvent(type, event, processInstanceId);
    }

    @Override
    public Collection<ProcessInstance> getProcessInstances() {
        return getKieSession().getProcessInstances();
    }

    @Override
    public ProcessInstance getProcessInstance(long processInstanceId) {
        return getKieSession().getProcessInstance(processInstanceId);
    }

    @Override
    public ProcessInstance getProcessInstance(long processInstanceId, boolean readonly) {
        return getKieSession().getProcessInstance(processInstanceId, readonly);
    }

    @Override
    public void abortProcessInstance(long processInstanceId) {
        getKieSession().abortProcessInstance(processInstanceId);
    }

    @Override
    public WorkItemManager getWorkItemManager() {
        return getKieSession().getWorkItemManager();
    }

    @Override
    public void addEventListener(RuleRuntimeEventListener listener) {
        getKieSession().addEventListener(listener);
    }

    @Override
    public void removeEventListener(RuleRuntimeEventListener listener) {
        getKieSession().removeEventListener(listener);
    }

    @Override
    public Collection<RuleRuntimeEventListener> getRuleRuntimeEventListeners() {
        return getKieSession().getRuleRuntimeEventListeners();
    }

    @Override
    public void addEventListener(AgendaEventListener listener) {
        getKieSession().addEventListener(listener);
    }

    @Override
    public void removeEventListener(AgendaEventListener listener) {
        getKieSession().removeEventListener(listener);
    }

    @Override
    public Collection<AgendaEventListener> getAgendaEventListeners() {
        return getKieSession().getAgendaEventListeners();
    }

    @Override
    public int fireAllRules() {
        return getKieSession().fireAllRules();
    }

    @Override
    public int fireAllRules(int max) {
        return getKieSession().fireAllRules(max);
    }

    @Override
    public int fireAllRules(AgendaFilter agendaFilter) {
        return getKieSession().fireAllRules(agendaFilter);
    }

    @Override
    public int fireAllRules(AgendaFilter agendaFilter, int max) {
        return getKieSession().fireAllRules(agendaFilter, max);
    }

    @Override
    public void fireUntilHalt() {
        getKieSession().fireUntilHalt();
    }

    @Override
    public void fireUntilHalt(AgendaFilter agendaFilter) {
        getKieSession().fireUntilHalt(agendaFilter);
    }

    @Override
    public void submit(AtomicAction action) {
        getKieSession().submit(action);
    }

    @Override
    public <T> T getKieRuntime(Class<T> cls) {
        return getKieSession().getKieRuntime(cls);
    }

    @Override
    public void execute(Object object) {
        getStatelessKieSession().execute(object);
    }

    @Override
    public void execute(Iterable objects) {
        getStatelessKieSession().execute(objects);
    }

    @Override
    public ProcessInstance startProcessFromNodeIds(String processId, Map<String, Object> params, String... nodeId) {
        return getKieSession().startProcessFromNodeIds(processId, params, nodeId);
    }
}


text:
ACCEPTED

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

#### Published in
Mycol. Pap. 175: 75 (1999)

#### Original name
Oxodeora K.D. Hyde & P.F. Cannon

### Remarks
null


text:
<ion-view view-title={{title}}>
  <ion-content>

        <input type="text" placeholder="{{title}}" ng-model="shop[property]">

      <button class="button button-energized button-block" ng-click="save()" >保存</button>

  </ion-content>

</ion-view>


text:
'use strict';

angular.module('bojApp')
  .factory('Slider', function (localStorageService) {
    var slides = [
      {
        title: 'Software Architecture',
        image: 'images/slider/architecture.jpg',
        quote: 'Architecture is the fundamental organization of a system embodied in its components, their relationships to each other and to the environment, and the principles guiding its design and evolution.',
        author: 'IEEE 1471'
      },
      {
        title: 'Object-oriented Design',
        image: 'images/slider/design.jpg',
        quote: 'Analysis and design have been summarized in the phrase "do the right thing (analysis), and do the thing right (design)". (...) During object-oriented design, there is an emphasis on defining software objects and how they collaborate to fulfill the requirements.',
        author: 'Craig Larman'
      },
      {
        title: 'Functional Programming',
        image: 'images/slider/functional_programming.jpg',
        quote: 'Functional programming is a programming paradigm (...) that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions.',
        author: 'Wikipedia'
      },
      {
        title: 'Innovation',
        image: 'images/slider/innovation.jpg',
        quote: 'Without tradition, art is a flock of sheep without a shepherd. Without innovation, it is a corpse.',
        author: 'Winston Churchill'
      },
      {
        title: 'The Internet',
        image: 'images/slider/internet.jpg',
        quote: 'An internet (spelled with a lower case i) is a network that is composed of a number of smaller computer networks. The Internet (spelled with an upper case I) is an internet that is vastly larger than any other internet and can be considered to be the ultimate internet.',
        author: 'The Linux Information Project'
      },
      {
        title: 'Software Patterns',
        image: 'images/slider/patterns.jpg',
        quote: 'A pattern is primarily a way to chunk up advice about a topic. Chunking is important because there\'s such a huge amount of knowledge you need to write software. As a result there needs be ways to divide knowledge up so you don\'t need to remember it all - what you need is to be able to get at a particular chunk of knowledge when you need it. Only then do you need details.',
        author: 'Martin Fowler'
      },
      {
        title: 'The Bounds of Java Newsletter',
        image: 'images/slider/newsletter.jpg',
        quote: 'A newsletter in which Java\'s edge concepts and advanced tricks are introduced and explored in depth. Software architecture and patterns, object-oriented design principles and functional programming techniques are covered and analyzed in a way that (I hope) is both innovative and enjoyable.',
        author: 'Federico Peralta Schaffner'
      }
    ];
    return {
      storeIndex: function (index) {
        localStorageService.set('Slider.currentIndex', index);
      },
      slides: slides,
      direction: 'left',
      currentIndex: localStorageService.get('Slider.currentIndex') || Math.floor(Math.random() * slides.length)
    };
  });


text:
import copy
from operator import add
import types

from .vendor import six
from .vendor.lexicon import Lexicon

from .parser import Context, Argument
from .tasks import Task

class Collection(object):
    """
    A collection of executable tasks.
    """
    def __init__(self, *args, **kwargs):
        """
        Create a new task collection/namespace.

        `.Collection` offers a set of methods for building a collection of
        tasks from scratch, plus a convenient constructor wrapping said API.

        **The method approach**

        May initialize with no arguments and use methods (e.g.
        `.add_task`/`.add_collection`) to insert objects::

            c = Collection()
            c.add_task(some_task)

        If an initial string argument is given, it is used as the default name
        for this collection, should it be inserted into another collection as a
        sub-namespace::

            docs = Collection('docs')
            docs.add_task(doc_task)
            ns = Collection()
            ns.add_task(top_level_task)
            ns.add_collection(docs)
            # Valid identifiers are now 'top_level_task' and 'docs.doc_task'
            # (assuming the task objects were actually named the same as the
            # variables we're using :))

        For details, see the API docs for the rest of the class.

        **The constructor approach**

        All ``*args`` given to `.Collection` (besides the optional first 'name'
        argument) are expected to be `.Task` or `.Collection` instances which
        will be passed to `.add_task`/`.add_collection` as appropriate. Module
        objects are also valid (as they are for `.add_collection`). For
        example, the below snippet results in the same two task identifiers as
        the one above::

            ns = Collection(top_level_task, Collection('docs', doc_task))

        If any ``**kwargs`` are given, the keywords are used as the initial
        name arguments for the respective values::

            ns = Collection(
                top_level_task=some_other_task,
                docs=Collection(doc_task)
            )

        That's exactly equivalent to::

            docs = Collection(doc_task)
            ns = Collection()
            ns.add_task(some_other_task, 'top_level_task')
            ns.add_collection(docs, 'docs')

        See individual methods' API docs for details.
        """
        # Initialize
        self.tasks = Lexicon()
        self.collections = Lexicon()
        self.default = None
        self.name = None
        self._configuration = {}
        # Name if applicable
        args = list(args)
        if args and isinstance(args[0], six.string_types):
            self.name = args.pop(0)
        # Dispatch args/kwargs
        for arg in args:
            self._add_object(arg)
        # Dispatch kwargs
        for name, obj in six.iteritems(kwargs):
            self._add_object(obj, name)

    def _add_object(self, obj, name=None):
        if isinstance(obj, Task):
            method = self.add_task
        elif isinstance(obj, (Collection, types.ModuleType)):
            method = self.add_collection
        else:
            raise TypeError("No idea how to insert %r!" % type(obj))
        return method(obj, name=name)

    @classmethod
    def from_module(self, module):
        """
        Return a new `.Collection` created from ``module``.

        Inspects ``module`` for any `.Task` instances and adds them to a new
        `.Collection`, returning it. If any explicit namespace collections
        exist (named ``ns`` or ``namespace``) they are preferentially loaded
        instead.

        When the implicit/default collection is generated, it will be named
        after the module's ``__name__`` attribute, or its last dotted section
        if it's a submodule. (I.e. it should usually map to the actual ``.py``
        filename.)

        Explicitly given collections will only be given that module-derived
        name if they don't already have a valid ``.name`` attribute.
        """
        module_name = module.__name__.split('.')[-1]
        # See if the module provides a default NS to use in lieu of creating
        # our own collection.
        for candidate in ('ns', 'namespace'):
            obj = getattr(module, candidate, None)
            if obj and isinstance(obj, Collection):
                if not obj.name:
                    obj.name = module_name
                return obj
        # Failing that, make our own collection from the module's tasks.
        tasks = filter(
            lambda x: isinstance(x[1], Task),
            vars(module).items()
        )
        collection = Collection(module_name)
        for name, task in tasks:
            collection.add_task(name=name, task=task)
        return collection

    def add_task(self, task, name=None):
        """
        Adds ``Task`` ``task`` to this collection.

        The name the task is bound with is taken, in order, from:

        * The ``name`` kwarg;
        * If that is not given, the task object's ``name`` attribute;
        * If that is empty, the task object's wrapped callable's ``.func_name``
          attribute.
        """
        if name is None:
            if task.name:
                name = task.name
            elif hasattr(task.body, 'func_name'):
                name = task.body.func_name
            elif hasattr(task.body, '__name__'):
                name = task.__name__
            else:
                raise ValueError("Could not obtain a name for this task!")
        if name in self.collections:
            raise ValueError("Name conflict: this collection has a sub-collection named %r already" % name)
        self.tasks[name] = task
        for alias in task.aliases:
            self.tasks.alias(alias, to=name)
        if task.is_default:
            if self.default:
                msg = "'%s' cannot be the default because '%s' already is!"
                raise ValueError(msg % (name, self.default))
            self.default = name

    def add_collection(self, coll, name=None):
        # Handle module-as-collection
        if isinstance(coll, types.ModuleType):
            coll = Collection.from_module(coll)
        # Ensure we have a name, or die trying
        name = name or coll.name
        if not name:
            raise ValueError("Non-root collections must have a name!")
        # Test for conflict
        if name in self.tasks:
            raise ValueError("Name conflict: this collection has a task named %r already" % name)
        # Insert
        self.collections[name] = coll

    def __getitem__(self, name=None):
        """
        Returns task named ``name``. Honors aliases and subcollections.

        If this collection has a default task, it is returned when ``name`` is
        empty or ``None``. If empty input is given and no task has been
        selected as the default, ValueError will be raised.

        Tasks within subcollections should be given in dotted form, e.g.
        'foo.bar'. Subcollection default tasks will be returned on the
        subcollection's name.
        """
        # Default task for this collection itself
        if not name:
            if self.default:
                return self[self.default]
            else:
                raise ValueError("This collection has no default task.")
        # Non-default tasks within subcollections
        if '.' in name:
            parts = name.split('.')
            coll = parts.pop(0)
            rest = '.'.join(parts)
            return self.collections[coll][rest]
        # Default task for subcollections (via empty-name lookup)
        if name in self.collections:
            return self.collections[name]['']
        # Regular task lookup
        return self.tasks[name]

    def __contains__(self, name):
        try:
            task = self[name]
            return True
        except KeyError:
            return False

    def to_contexts(self):
        """
        Returns all contained tasks and subtasks as a list of parser contexts.
        """
        result = []
        for primary, aliases in six.iteritems(self.task_names):
            task = self[primary]
            result.append(Context(
                name=primary, aliases=aliases, args=task.get_arguments()
            ))
        return result

    def subtask_name(self, collection_name, task_name):
        return "%s.%s" % (collection_name, task_name)

    @property
    def task_names(self):
        """
        Return all task identifiers for this collection as a dict.

        Specifically, a dict with the primary/"real" task names as the key, and
        any aliases as a list value.
        """
        ret = {}
        # Our own tasks get no prefix, just go in as-is: {name: [aliases]}
        for name, task in six.iteritems(self.tasks):
            ret[name] = task.aliases
        # Subcollection tasks get both name + aliases prefixed
        for coll_name, coll in six.iteritems(self.collections):
            for task_name, aliases in six.iteritems(coll.task_names):
                # Cast to list to handle Py3 map() 'map' return value,
                # so we can add to it down below if necessary.
                aliases = list(map(
                    lambda x: self.subtask_name(coll_name, x),
                    aliases
                ))
                # Tack on collection name to alias list if this task is the
                # collection's default.
                if coll.default and coll.default == task_name:
                    aliases += (coll_name,)
                ret[self.subtask_name(coll_name, task_name)] = aliases
        return ret

    @property
    def configuration(self):
        """
        Return this collection's configuration options as a dict.

        Child/inner collections' configurations are merged on top of this
        collection's (so the inner collections will override the parent
        collection when conflicts arise.) Multiple child collections'
        configurations are merged in alphabetical order by attached name (thus
        childs with 'later' names will win.)

        .. note::
            Merging uses ``copy.deepcopy`` to prevent state bleed.
        """
        ret = copy.deepcopy(self._configuration)
        for key in sorted(self.collections.keys()):
            ret.update(copy.deepcopy(self.collections[key].configuration))
        return ret

    def configure(self, options):
        """
        Merge ``options`` dict into this collection's `.configuration`.

        Options configured this way will be available to all
        :doc:`contextualized tasks </concepts/context>`. It is recommended to
        use unique keys to avoid potential clashes with other config options

        For example, if you were configuring a Sphinx docs build target
        directory, it's better to use a key like ``'sphinx.target'`` than
        simply ``'target'``.

        :param options: An object implementing the dictionary protocol.
        :returns: ``None``.
        """
        self._configuration.update(options)


text:
use rustc_serialize;
use rustc_serialize::Decodable;
use libcoinche::{cards, bid, pos};

/// An event about a player.
#[derive(Clone,Debug)]
pub enum PlayerEvent {
    /// A player made a new bid in the auction.
    Bidded(cards::Suit, bid::Target),
    /// A player coinched the current bid in the auction.
    Coinched,
    /// A player passed in the auction.
    Passed,
    /// A player played a card.
    CardPlayed(cards::Card),
}

impl rustc_serialize::Encodable for PlayerEvent {
    fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        match self {
            &PlayerEvent::Bidded(suit, target) => {
                s.emit_struct("PlayerEvent", 3, |s| {
                    try!(encode_field!(s, "type", 0, "Bidded"));
                    try!(encode_field!(s, "suit", 1, suit));
                    try!(encode_field!(s, "target", 2, target));
                    Ok(())
                })
            }
            &PlayerEvent::Coinched => {
                s.emit_struct("PlayerEvent",
                              1,
                              |s| encode_field!(s, "type", 0, "Coinched"))
            }
            &PlayerEvent::Passed => {
                s.emit_struct("PlayerEvent", 1, |s| encode_field!(s, "type", 0, "Passed"))
            }
            &PlayerEvent::CardPlayed(card) => {
                s.emit_struct("PlayerEvent", 2, |s| {
                    try!(encode_field!(s, "type", 0, "CardPlayed"));
                    try!(encode_field!(s, "card", 1, card));
                    Ok(())
                })
            }
        }
    }
}

impl rustc_serialize::Decodable for PlayerEvent {
    fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
        d.read_struct("PlayerEvent", 0, |d| {
            match try!(d.read_struct_field("type", 0, |d| d.read_str())).as_ref() {
                "Bidded" => {
                    let suit = try!(d.read_struct_field("suit", 1, |d| cards::Suit::decode(d)));
                    let target = try!(d.read_struct_field("target", 2, |d| bid::Target::decode(d)));
                    Ok(PlayerEvent::Bidded(suit, target))
                }
                "CardPlayed" => {
                    let card = try!(d.read_struct_field("card", 1, |d| cards::Card::decode(d)));
                    Ok(PlayerEvent::CardPlayed(card))
                }
                "Passed" => Ok(PlayerEvent::Passed),
                "Coinched" => Ok(PlayerEvent::Coinched),
                _ => Err(d.error("unknown event type")),
            }
        })
    }
}

/// Represents an event that can happen during the game.
#[derive(Clone,Debug)]
pub enum EventType {
    /// Special event indicating the server expects the player to take an action.
    YourTurn,

    /// The party is cancelled. Contains an optional explanation.
    PartyCancelled(String),

    /// A player did something!
    FromPlayer(pos::PlayerPos, PlayerEvent),

    /// Bid over: contains the contract and the author
    BidOver(bid::Contract),
    /// The bid was cancelled, probably because no one bidded anything.
    /// A new game is probably on its way.
    BidCancelled,

    /// Trick over: contains the winner
    TrickOver {
        winner: pos::PlayerPos,
    },

    /// New game: contains the first player, and the player's hand.
    /// For internal use only, it is never sent on the network.
    NewGame {
        first: pos::PlayerPos,
        hands: [cards::Hand; 4],
    },
    /// New game event, translated for each player.
    NewGameRelative {
        first: pos::PlayerPos,
        hand: cards::Hand,
    },

    /// Game over: contains scores
    GameOver {
        points: [i32; 2],
        winner: pos::Team,
        scores: [i32; 2],
    },
}

impl EventType {
    /// Returns a version of the event from the point of view of a given player.
    /// It returns a direct clone of the event for most event types,
    /// except for a NewGame, where it only returns the player's hand.
    pub fn relativize(&self, from: pos::PlayerPos) -> Self {
        match self {
            &EventType::NewGame { first, hands } => {
                EventType::NewGameRelative {
                    first: first,
                    hand: hands[from as usize],
                }
            }
            _ => self.clone(),
        }
    }
}

// Ugly serialization...
impl rustc_serialize::Encodable for EventType {
    fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        match self {
            &EventType::PartyCancelled(ref msg) => {
                s.emit_struct("Event", 2, |s| {
                    try!(encode_field!(s, "type", 0, "PartyCancelled"));
                    try!(encode_field!(s, "msg", 1, msg));
                    Ok(())
                })
            }
            &EventType::YourTurn => {
                s.emit_struct("Event", 1, |s| encode_field!(s, "type", 0, "YourTurn"))
            }
            &EventType::BidCancelled => {
                s.emit_struct("Event", 1, |s| encode_field!(s, "type", 0, "BidCancelled"))
            }
            &EventType::BidOver(ref contract) => {
                s.emit_struct("Event", 2, |s| {
                    try!(encode_field!(s, "type", 0, "BidOver"));
                    try!(encode_field!(s, "contract", 1, contract));
                    Ok(())
                })
            }
            &EventType::TrickOver { winner } => {
                s.emit_struct("Event", 2, |s| {
                    try!(encode_field!(s, "type", 0, "TrickOver"));
                    try!(encode_field!(s, "winner", 1, winner));
                    Ok(())
                })
            }
            &EventType::FromPlayer(pos, ref event) => {
                s.emit_struct("Event", 3, |s| {
                    try!(encode_field!(s, "type", 0, "FromPlayer"));
                    try!(encode_field!(s, "pos", 1, pos));
                    try!(encode_field!(s, "event", 2, event));
                    Ok(())
                })
            }
            &EventType::NewGame { first, ref hands } => {
                s.emit_struct("Event", 3, |s| {
                    // Should rarely happen
                    try!(encode_field!(s, "type", 0, "NewGameGlobal"));
                    try!(encode_field!(s, "first", 1, first));
                    try!(encode_field!(s, "hands", 2, hands));
                    Ok(())
                })
            }
            &EventType::NewGameRelative { first, ref hand } => {
                s.emit_struct("Event", 3, |s| {
                    try!(encode_field!(s, "type", 0, "NewGame"));
                    try!(encode_field!(s, "first", 1, first));
                    try!(encode_field!(s, "cards", 2, hand));
                    Ok(())
                })
            }
            &EventType::GameOver { points, winner, scores } => {
                s.emit_struct("Event", 4, |s| {
                    try!(encode_field!(s, "type", 0, "GameOver"));
                    try!(encode_field!(s, "points", 1, points));
                    try!(encode_field!(s, "winner", 2, winner));
                    try!(encode_field!(s, "scores", 3, scores));
                    Ok(())
                })
            }
        }
    }
}

impl rustc_serialize::Decodable for EventType {
    fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> {
        d.read_struct("PlayerEvent", 0, |d| {
            match try!(d.read_struct_field("type", 0, |d| d.read_str())).as_ref() {
                "BidCancelled" => Ok(EventType::BidCancelled),
                "YourTurn" => Ok(EventType::YourTurn),
                "BidOver" => {
                    let contract = try!(decode_field!(d, "contract", 1));
                    Ok(EventType::BidOver(contract))
                }
                "TrickOver" => {
                    let winner = try!(decode_field!(d, "winner", 1));
                    Ok(EventType::TrickOver { winner: winner })
                }
                "FromPlayer" => {
                    let pos = try!(decode_field!(d, "pos", 1));
                    let event = try!(decode_field!(d, "event", 2));
                    Ok(EventType::FromPlayer(pos, event))
                }
                "PartyCancelled" => {
                    let msg = try!(decode_field!(d, "msg", 1));
                    Ok(EventType::PartyCancelled(msg))
                }
                "GameOver" => {
                    let points = try!(decode_field!(d, "points", 1));
                    let winner = try!(decode_field!(d, "winner", 2));
                    let scores = try!(decode_field!(d, "scores", 3));
                    Ok(EventType::GameOver {
                        points: points,
                        winner: winner,
                        scores: scores,
                    })
                }
                "NewGame" => {
                    let first = try!(decode_field!(d, "first", 1));
                    let cards = try!(decode_field!(d, "cards", 2));
                    Ok(EventType::NewGameRelative {
                        first: first,
                        hand: cards,
                    })
                }
                _ => Err(d.error("unknown event type")),
            }
        })
    }
}

/// Represents an event happening to the game.
#[derive(Clone,Debug,RustcEncodable,RustcDecodable)]
pub struct Event {
    /// Actual event
    pub event: EventType,
    /// Event ID
    pub id: usize,
}


text:
package com.planet_ink.coffee_mud.Locales;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class DesertGrid extends StdGrid
{
	@Override public String ID(){return "DesertGrid";}
	public DesertGrid()
	{
		super();
		name="the desert";
		basePhyStats.setWeight(2);
		recoverPhyStats();
		climask=Places.CLIMASK_HOT|CLIMASK_DRY;
	}
	@Override public int domainType(){return Room.DOMAIN_OUTDOORS_DESERT;}

	@Override public String getGridChildLocaleID(){return "Desert";}
	@Override public List<Integer> resourceChoices(){return Desert.roomResources;}
}


text:
<?php

namespace App\Language\Front\English\Account;

class Affiliate {
	public static function lang() {
		// heading
		$_['lang_heading_title']             = 'Affiliate';

		// text
		$_['lang_text_account']              = 'Dashboard';
		$_['lang_text_affiliate']            = 'Affiliate Settings';
		$_['lang_text_general']              = 'General Details';
		$_['lang_text_success']              = 'Success: You have successfully updated your affiliate settings.';
		$_['lang_text_cheque']               = 'Check';
		$_['lang_text_paypal']               = 'PayPal';
		$_['lang_text_bank']                 = 'Bank Transfer';
		$_['lang_text_description']          = 'You can create affiliate referrals through three different strategies.

You can simply send traffic to your base affiliate url: %s

You can send traffic to a specific product using the product links you create below.

You can refer someone who creates a customer account, and that customer will be yours for life.

Product links and base affiliate tracking cookies are set for a time period of one year, after which the cookie is deleted and a new affiliate can be set for that visitor.

If on the other hand, a given visitor chooses to create an account, if your tracking cookie is found you will be set as their referrer and you will automatically receive a commission on every sale they complete, provided you have an active affiliate status.';
		$_['lang_text_code']                 = 'Your Tracking Code:';
		$_['lang_text_generator']            = 'Tracking Link Generator:
Type in the name of a product you would like to link to.';
		$_['lang_text_link']                 = 'Tracking Link:';
		$_['lang_text_balance']              = 'Your current balance is:';
		$_['lang_text_empty']                = 'You do not have any commissions.';
		$_['lang_text_enroll_now']           = 'Hi %s,

It looks like you didn\'t enroll as an Affiliate when you signed up.

No worries, you can enroll right now with the click of Enroll button below.';
		$_['lang_text_terms']                = 'I have read and agree to the %s';
		$_['lang_text_build']                = 'Build URL';

		// entry
		$_['lang_entry_slug']                = 'Vanity URL:
Set a vanity url for your affiliate link. Make sure you DO NOT use spaces, use hyphens (-) and click the Build button to check for uniqueness.';
		$_['lang_entry_company']             = 'Company Name:';
		$_['lang_entry_website']             = 'Website:';
		$_['lang_entry_status']              = 'Status:
Here you can disable or enable your own affiliate account.
**NOTE: If you disable your account you will no longer receive affiliate commissions.';
		$_['lang_entry_tax_id']              = 'Tax ID:
Your SSN or Employer Tax ID number.';
		$_['lang_entry_payment']             = 'Payment Method:';
		$_['lang_entry_cheque']              = 'Check Name:';
		$_['lang_entry_paypal']              = 'PayPal Email:';
		$_['lang_entry_bank_name']           = 'Bank Name:';
		$_['lang_entry_bank_branch_number']  = 'ABA/BSB number (Branch Number):';
		$_['lang_entry_bank_swift_code']     = 'SWIFT Code:';
		$_['lang_entry_bank_account_name']   = 'Account Name:';
		$_['lang_entry_bank_account_number'] = 'Account Number:';

		// column
		$_['lang_column_date_added']         = 'Date Added';
		$_['lang_column_description']        = 'Description';
		$_['lang_column_amount']             = 'Amount (%s)';

		// tab
		$_['lang_tab_general']               = 'General';
		$_['lang_tab_tracking']              = 'Tracking Codes';
		$_['lang_tab_payment']               = 'Payment Info';
		$_['lang_tab_commission']            = 'Commissions';

		// button
		$_['lang_button_save']               = 'Save Settings';

		// error
		$_['lang_error_warning']             = 'Warning: Please check the form carefully for errors.';
		$_['lang_error_slug']                = 'Warning: You must set a vanity URL for your affiliate settings.';
		$_['lang_error_slug_found']          = 'ERROR: The vanity URL %s is already in use, please use a different one in the input field.';
		$_['lang_error_tax_id']              = 'Tax ID required.';
		$_['lang_error_payment']             = 'Payment method is required.';
		$_['lang_error_cheque']              = 'If payment method is check, a check name is required.';
		$_['lang_error_paypal']              = 'If payment method is PayPal, a PayPal email account is required.';
		$_['lang_error_bank_name']           = 'If payment method is bank, a bank name is required.';
		$_['lang_error_account_name']        = 'If payment method is bank, a bank account name is required.';
		$_['lang_error_account_number']      = 'If payment is bank, a bank account number is required.';
		$_['lang_error_agree']               = 'Warning: You must agree to the %s.';

		return $_;
	}
}


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * Class Product
 *
 * @package App\Models
 * @mixin \Eloquent
 * @property-read \App\Models\Customer $customer
 * @property int $id
 * @property int $customer_id
 * @property string $transaction_id 微信支付订单号
 * @property string $out_trade_no 商户订单号
 * @property string $appid 公众账号ID
 * @property string $mch_id 商户号
 * @property string $device_info 设备号
 * @property string $nonce_str 随机字符串
 * @property string $sign 签名
 * @property string $result_code 业务结果
 * @property string $err_code 错误代码
 * @property string $err_code_des 错误代码描述
 * @property string $openid 用户标识
 * @property string $is_subscribe 是否关注公众账号
 * @property string $trade_type 交易类型
 * @property string $bank_type 付款银行
 * @property int $total_fee 订单金额
 * @property int $settlement_total_fee 应结订单金额
 * @property string $fee_type 货币种类
 * @property int $cash_fee 现金支付金额
 * @property string $cash_fee_type 现金支付货币类型
 * @property int $coupon_fee 代金券金额
 * @property int $coupon_count 代金券使用数量
 * @property string $attach 商家数据包
 * @property string $time_end 支付完成时间
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereAppid($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereAttach($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereBankType($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereCashFee($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereCashFeeType($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereCouponCount($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereCouponFee($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereCustomerId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereDeviceInfo($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereErrCode($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereErrCodeDes($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereFeeType($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereIsSubscribe($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereMchId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereNonceStr($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereOpenid($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereOutTradeNo($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereResultCode($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereSettlementTotalFee($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereSign($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereTimeEnd($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereTotalFee($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereTradeType($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereTransactionId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\WxPaymentDetail whereUpdatedAt($value)
 */
class WxPaymentDetail extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'wx_payment_details';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'transaction_id',
        'out_trade_no',
        'appid',
        'mch_id',
        'device_info',
        'nonce_str',
        'sign',
        'result_code',
        'err_code',
        'openid',
        'is_subscribe',
        'trade_type',
        'bank_type',
        'total_fee',
        'settlement_total_fee',
        'fee_type',
        'cash_fee',
        'cash_fee_type',
        'coupon_fee',
        'coupon_count',
        'time_end'
    ];

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }
}


text:
@interface AddOrEditBehaviorController () <UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
@end

@implementation AddOrEditBehaviorController
{
  NSArray *sortedArray_;
  NSDictionary *categoryDictionary_;
  UIPickerView *picker_;
}

- (void)awakeFromNib
{
  categoryDictionary_ = [Behavior getAllCategoryDictionary];
  sortedArray_ = [[categoryDictionary_ allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSNumber *number1, NSNumber *number2) {
    return [number2 compare:number1];
  }];
}

- (void)startInputName
{
  [self.nameTextField becomeFirstResponder];
}

- (void)viewDidLoad
{
  [super viewDidLoad];
  NSNumber *rank;
  NSString *title;
  NSString *nameText = @"";
  if (self.editingBehavior) {
    title = @"修改项目";
    nameText = self.editingBehavior.name;
    rank = self.editingBehavior.rank;
  } else {
    title = @"添加新项目";
    rank = [NSNumber numberWithInt:((MainViewController *) self.presentingViewController).selectedIndex == 0 ? 1 : -1];
  }
  self.navigationItem.title = title;

  UIView *const view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

  view.backgroundColor = [UIColor groupTableViewBackgroundColor];

  self.nameTextField.text = nameText;

  //build rank text filed
  self.rankTextField.text = [categoryDictionary_ objectForKey:rank];
  picker_ = [self getPickerViewSelectedName:self.rankTextField.text inSource:categoryDictionary_];
  self.rankTextField.inputView = picker_;
}

- (void)viewDidAppear:(BOOL)animated
{
  [super viewDidAppear:animated];
  [self startInputName];
}

- (UIPickerView *)getPickerViewSelectedName:(NSString *)selectedName inSource:(NSDictionary *)dict {
  CGFloat const pickerHeight = 216;
  UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, pickerHeight)];
  picker.delegate = self;
  picker.dataSource = self;
  picker.showsSelectionIndicator = YES;
  [picker selectRow:[self getRowOfCategory:selectedName fromDict:dict] inComponent:0 animated:NO];
  return picker;
}

- (int)getRowOfCategory:(NSString *)categoryName fromDict:(NSDictionary *)dict {
  for (int i = 0; i < sortedArray_.count; i++) {
    if ([[dict objectForKey:[sortedArray_ objectAtIndex:i]] isEqual:categoryName]) {
      return i;
    }
  }
  return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return 40;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
  [self.rankTextField becomeFirstResponder];
  return YES;
}

//TODO: refactor to be a separate controller for pickerview
#pragma mask - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
  return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  return [Behavior getAllCategoryDictionary].count;
}

#pragma mask - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  return [categoryDictionary_ objectForKey:[sortedArray_ objectAtIndex:row]];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
  self.rankTextField.text = [categoryDictionary_ objectForKey:[sortedArray_ objectAtIndex:[pickerView selectedRowInComponent:0]]];
}

- (IBAction)save:(id)sender
{
  NSManagedObjectContext *context = [NSManagedObjectContext defaultContext];
  NSString *behaviorName = self.nameTextField.text;

  if ([behaviorName isBlank]) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"项目名称不能为空" delegate:nil cancelButtonTitle:@"明了" otherButtonTitles:nil];
    [alert show];
    return;
  }

  if (nil == self.editingBehavior || (![self.editingBehavior.name isEqualToString:self.nameTextField.text])) {
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Behavior"];
    [request setPredicate:[NSPredicate predicateWithFormat:@"name == %@", behaviorName]];
    __block NSUInteger count;
    [context performBlockAndWait:^{
      count = [context countForFetchRequest:request error:nil];
    }];
    if (count > 0) {
      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"已存在同名项目,请修改名称" delegate:nil cancelButtonTitle:@"明了" otherButtonTitles:nil];
      [alert show];
      return;
    }
  }

  Behavior *behavior = nil;
  if (self.editingBehavior) {
    behavior = self.editingBehavior;
  }
  else {
    behavior = [NSEntityDescription insertNewObjectForEntityForName:@"Behavior" inManagedObjectContext:context];
    behavior.isCustomised = [NSNumber numberWithBool:YES];
    [behavior increaseEventForDate:[[NSDate date] dateWithoutTime]];
  }

  behavior.name = behaviorName;
  behavior.rank = [sortedArray_ objectAtIndex:(NSUInteger) [picker_ selectedRowInComponent:0]];
  behavior.timestamp = [NSDate date];
  [context save];

  MainViewController *controller = (MainViewController *) self.presentingViewController;
  [self dismissViewControllerAnimated:YES completion:^{
    [controller behaviorDidSave:behavior];
  }];
}

- (IBAction)cancel:(id)sender
{
  [self dismissViewControllerAnimated:YES completion:nil];
}

@end


text:
<ion-header>

  <ion-toolbar>
    <ion-title>Inset List</ion-title>
  </ion-toolbar>

</ion-header>

<ion-content class="outer-content">

  <div>
    <ion-fab top center>
      <button ion-fab><ion-icon name="add"></ion-icon></button>
    </ion-fab>
  </div>
  <ion-fab bottom center>
    <button ion-fab><ion-icon name="close"></ion-icon></button>
  </ion-fab>

  <ion-list inset no-lines>

    <ion-list-header>
      List Header 1
    </ion-list-header>

    <a ion-item href="#">
      <ion-icon name="alarm" item-left></ion-icon>
      List Link Item 1
    </a>

    <ion-item>
      <ion-label>Toggle</ion-label>
      <ion-toggle checked="true"></ion-toggle>
    </ion-item>

    <ion-item>
      <ion-label>Checkbox</ion-label>
      <ion-checkbox checked="true"></ion-checkbox>
    </ion-item>

    <ion-item>
      <ion-icon name="boat" item-left></ion-icon>
      List Button Item 1
    </ion-item>

  </ion-list>

  <ion-list inset no-lines>
      <ion-list-header>
          List header 2
      </ion-list-header>
      <ion-item>
          <ion-icon name="list" item-left></ion-icon>
          item 1
      </ion-item>
  </ion-list>

  <ion-list>
    <ion-list-header>
        List header 3
    </ion-list-header>
    <ion-item>
        <ion-icon name="list" item-left></ion-icon>
        item 1
    </ion-item>
  </ion-list>

  <ion-list inset no-lines>
    <ion-list-header>
        List header 4
    </ion-list-header>
    <ion-item>
        <ion-icon name="list" item-left></ion-icon>
        item 1
    </ion-item>
  </ion-list>

  <ion-list inset>

    <ion-item>
      Inset List, No Header
      <button ion-button outline item-right>View</button>
    </ion-item>

    <ion-item>
      List Item 1
    </ion-item>

    <ion-item>
      List Item 2
    </ion-item>

    <ion-item text-wrap>
      This is a multiline content within a list that should
      take up multiple lines and stuff.
    </ion-item>

  </ion-list>

  <ion-list inset>

    <ion-item>
      Inset List, no header, no items
    </ion-item>

  </ion-list>

</ion-content>


text:
namespace browser_sync {
namespace internal {

std::string GetComputerName() {
  char computer_name[MAX_COMPUTERNAME_LENGTH + 1];
  DWORD size = sizeof(computer_name);
  if (GetComputerNameA(computer_name, &size))
    return computer_name;
  return std::string();
}

}  // namespace internal
}  // namespace browser_sync


text:
require "myexam_6/version"

module Myexam6
  # Your code goes here...
end


text:
import { Module } from 'cerebral'

import * as sequences from './sequences'

export default (urlParams) => {
  return Module({
    signals: {
      fieldChanged: sequences.changeField,
      loginFormSubmitted: sequences.signinUser,
      registerFormSubmitted: sequences.registerUser,
      emailFormSubmitted: sequences.requestPasswordReset,
      passwordFormSubmitted: sequences.updatePassword,
      logoutButtonClicked: sequences.logoutUser,
    },

    state: {
      email: '',
      nickname: '',
      isAdmin: false,
      authenticated: false,
      token: {},
      api: {
        '@id': urlParams['@id'],
      },
      loginForm: {
        email: {
          value: '',
          validationRules: ['isEmail'],
          isRequired: true,
        },
        password: {
          value: '',
          validationRules: ['minLength:5'],
          isRequired: true,
        },
        showErrors: false,
        isLoading: false,
      },
      registerForm: {
        nickname: {
          value: '',
          validationRules: ['minLength:3'],
          isRequired: true,
        },
        email: {
          value: '',
          validationRules: ['isEmail'],
          isRequired: true,
        },
        password: {
          value: '',
          validationRules: ['minLength:5'],
          isRequired: true,
        },
        confirmPassword: {
          value: '',
          validationRules: ['equalsField:user.registerForm.password'],
          isRequired: true,
        },
        showErrors: false,
        isLoading: false,
      },
      emailForm: {
        email: {
          value: '',
          validationRules: ['isEmail'],
          isRequired: true,
        },
        showErrors: false,
        isLoading: false,
      },
      passwordForm: {
        password: {
          value: '',
          validationRules: ['minLength:5'],
          isRequired: true,
        },
        confirmPassword: {
          value: '',
          validationRules: ['equalsField:user.passwordForm.password'],
          isRequired: true,
        },
        showErrors: false,
        isLoading: false,
      },
    },
  })
}


text:
Python coding guidelines
========================

PEP8
~~~~

We ask that all Python contributions adhere to the `PEP8 <http://www.python.org/dev/peps/pep-0008/>`_ style guide, apart from the restriction on line length (E501) and some minor docstring-related issues.
The list of PEP8 violations to ignore is in the ``tox.ini`` file, under the ``[flake8]`` header.
You might want to configure the flake8 linter in your editor/IDE to use the configuration in this file.

In addition, import lines should be sorted according to `isort <http://timothycrosley.github.io/isort/>`_ 4.2.5 rules. If you have installed Wagtail's testing dependencies (``pip install -e .[testing]``), you can check your code by running ``make lint``.

Django compatibility
~~~~~~~~~~~~~~~~~~~~

Wagtail is written to be compatible with multiple versions of Django. Sometimes, this requires running one piece of code for recent version of Django, and another piece of code for older versions of Django. In these cases, always check which version of Django is being used by inspecting ``django.VERSION``:

.. code-block:: python

    import django

    if django.VERSION >= (1, 9):
        # Use new attribute
        related_field = field.rel
    else:
        # Use old, deprecated attribute
        related_field = field.related

Always compare against the version using greater-or-equals (``>=``), so that code for newer versions of Django is first.

Do not use a ``try ... except`` when seeing if an object has an attribute or method introduced in a newer versions of Django, as it does not clearly express why the ``try ... except`` is used. An explicit check against the Django version makes the intention of the code very clear.

.. code-block:: python

    # Do not do this
    try:
        related_field = field.rel
    except AttributeError:
        related_field = field.related

If the code needs to use something that changed in a version of Django many times, consider making a function that encapsulates the check:

.. code-block:: python

    import django

    def related_field(field):
        if django.VERSION >= (1, 9):
            return field.rel
        else:
            return field.related

If a new function has been introduced by Django that you think would be very useful for Wagtail, but is not available in older versions of Django that Wagtail supports, that function can be copied over in to Wagtail. If the user is running a new version of Django that has the function, the function should be imported from Django. Otherwise, the version bundled with Wagtail should be used. A link to the Django source code where this function was taken from should be included:

.. code-block:: python

    import django

    if django.VERSION >= (1, 9):
        from django.core.validators import validate_unicode_slug
    else:
        # Taken from https://github.com/django/django/blob/1.9/django/core/validators.py#L230
        def validate_unicode_slug(value):
            # Code left as an exercise to the reader
            pass

Tests
~~~~~

Wagtail has a suite of tests, which we are committed to improving and expanding. See :ref:`testing`.

We run continuous integration at `travis-ci.org/wagtail/wagtail <https://travis-ci.org/wagtail/wagtail>`_ to ensure that no commits or pull requests introduce test failures. If your contributions add functionality to Wagtail, please include the additional tests to cover it; if your contributions alter existing functionality, please update the relevant tests accordingly.


text:
package org.dhira.core.optimize.stepfunctions

import org.deeplearning4j.optimize.api.StepFunction

object StepFunctions {
  private val DEFAULT_STEP_FUNCTION_INSTANCE: Nothing = new Nothing
  private val GRADIENT_STEP_FUNCTION_INSTANCE: Nothing = new Nothing
  private val NEGATIVE_DEFAULT_STEP_FUNCTION_INSTANCE: Nothing = new Nothing
  private val NEGATIVE_GRADIENT_STEP_FUNCTION_INSTANCE: Nothing = new Nothing

  def createStepFunction(stepFunction: Nothing): Nothing = {
    if (stepFunction == null) return null
    if (stepFunction.isInstanceOf[Nothing]) return DEFAULT_STEP_FUNCTION_INSTANCE
    if (stepFunction.isInstanceOf[Nothing]) return GRADIENT_STEP_FUNCTION_INSTANCE
    if (stepFunction.isInstanceOf[Nothing]) return NEGATIVE_DEFAULT_STEP_FUNCTION_INSTANCE
    if (stepFunction.isInstanceOf[Nothing]) return NEGATIVE_GRADIENT_STEP_FUNCTION_INSTANCE
    throw new RuntimeException("unknown step function: " + stepFunction)
  }
}

class StepFunctions {
  private def this() {
    this()
  }
}


text:
/*
 * Copyright (c) 2015 Spotify AB
 *
 * 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.
 */
package com.spotify.missinglink.datamodel;

public class VoidTypeDescriptor implements TypeDescriptor {

  public static final VoidTypeDescriptor voidTypeDescriptor = new VoidTypeDescriptor();

  private VoidTypeDescriptor() {}

  @Override
  public String toString() {
    return "void";
  }
}


text:
import React, { Component } from 'react'
import ReactDOM             from 'react-dom'
import styles               from './CommandWindow.scss'
import config               from 'config'
import { Button }           from 'antd'
import electron             from 'electron'
import { store }            from 'index.js'
import { removeWindow }     from 'lagniappe/actions/command'

const ElectronMenu = electron.remote.Menu

export default class CommandWindow extends Component
{
    scrollToBottom()
    {
        const node = ReactDOM.findDOMNode(this.consoleBottom)
        // This will be false if we're not currently rendering this window
        if(!node) return
        node.scrollIntoView({behavior: "smooth"})
    }

    componentDidMount()
    {
        this.scrollToBottom()
    }

    componentDidUpdate(prevProps, prevState)
    {
        // Only scroll to the bottom if new lines were added
        if(this.props.lines.length > prevProps.lines.length)
            this.scrollToBottom()
    }

    contextMenu()
    {
        const menu = [{
                label: 'Copy',
                role: 'copy',
            }, {
                label: 'Paste',
                role: 'paste',
            }, {
                type: 'separator',
            }, {
                label: 'Select all',
                role: 'selectall',
        }]
        if(!this.props.finished)
        {
            menu.push({type: 'separator'})
            menu.push({
                label: 'Stop Command',
                click: this.handleKill.bind(this)
            })
        }
        menu.push({type: 'separator'})
        menu.push({
            label: 'Close Window',
            click: this.handleRemove.bind(this)
        })
        return ElectronMenu.buildFromTemplate(menu)
    }

    handleRemove()
    {
        const id = this.props.id
        store.dispatch(removeWindow(id))
        this.handleKill()
    }

    handleContext(e)
    {
        e.preventDefault()
        this.contextMenu().popup()
    }

    handleKill()
    {
        if(config.processes[this.props.id])
        {
            config.processes[this.props.id].kill()
            delete config.processes[this.props.id]
        }
    }

    renderLines()
    {
        let lines = []
        let i = 0
        return this.props.lines.map( line =>
{line}
 )
    }

    render()
    {
        if(!this.props.active) return false
        const title = this.props.title
        const lines = this.renderLines()
        const windowId = this.props.id
        const contextHandler = this.handleContext.bind(this)

        return (

                    {lines}

 { this.consoleBottom = el }}>

        )
    }
}


text:
<!DOCTYPE html>

  <title>BST Runtime</title>

BST search, insert, and delete operations
        typically run in time O(d). What is d?

<var>"The depth of the appropriate node in the tree"</var>

<var>"The number of divisions at each level"</var>

<var>"The number of entries in each node"</var>

<var>"The number of nodes in the tree"</var>

<var>"The total number of entries in all the nodes of the tree"</var>

Think about a given insert or search operation.

How many nodes get looked at?

The operation moves down the tree, looking at a node at
          each level that it visits.

So the total work is the number of nodes that it visits,
          which is the same as the depth of the last node.


text:
<!DOCTYPE html>

    <title>hawkular-directives</title>
    <base href='/'>
    <meta charset="UTF8">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse-1">
          Toggle navigation

        </button>

              Brian Johnson

                Log Out

        <hawkular-topbar ng-controller="Topbar.TopbarController"></hawkular-topbar>

        <hawkular-sidebar ng-controller="Sidebar.SidebarController"></hawkular-sidebar>

    <link rel="stylesheet" href="dist/hawkular-ui-components-directives.css" />


text:
#pragma once

struct Stats {
  int32_t collection_success;
  int32_t collection_skipped;
  int32_t collection_failed;
  int32_t collection_total;

  uint32_t success;
  uint32_t skipped;
  uint32_t failed;
  uint32_t total;

  Stats() :
    collection_success(0),
    collection_skipped(0),
    collection_failed(0),
    collection_total(0),
    success(0),
    skipped(0),
    failed(0),
    total(0)
  { }
};