text:
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Configuration;
using System.Data.Services.Client;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using biz.dfch.CS.Entity.LifeCycleManager.Contracts.Entity;
using biz.dfch.CS.Entity.LifeCycleManager.Contracts.Executors;
using biz.dfch.CS.Entity.LifeCycleManager.Contracts.Loaders;
using biz.dfch.CS.Entity.LifeCycleManager.Controller;
using biz.dfch.CS.Entity.LifeCycleManager.Logging;
using biz.dfch.CS.Entity.LifeCycleManager.Model;
using biz.dfch.CS.Entity.LifeCycleManager.UserData;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CalloutDefinition = biz.dfch.CS.Entity.LifeCycleManager.CumulusCoreService.CalloutDefinition;
using Job = biz.dfch.CS.Entity.LifeCycleManager.CumulusCoreService.Job;
using StateChangeLock = biz.dfch.CS.Entity.LifeCycleManager.CumulusCoreService.StateChangeLock;
using System.Web;

[assembly: InternalsVisibleTo("biz.dfch.CS.Entity.LifeCycleManager.Tests")]
namespace biz.dfch.CS.Entity.LifeCycleManager
{
    // DFTODO implement entity hierarchy
    // DFTODO implement ACL
    // DFTODO Modify plugin interface to provide a factory
    public class LifeCycleManager
    {
        private const String CALLOUT_JOB_TYPE = "CalloutData";
        private const String CORE_ENDPOINT_URL_KEY = "LifeCycleManager.Endpoint.Core";
        private static String _tenantIdHeaderKey = ConfigurationManager.AppSettings["TenantId.Header.Key"];
        private static Object _lock = new Object();
        private static String _username = ConfigurationManager.AppSettings["LifeCycleManager.Service.Core.User"];
        private static String _password = ConfigurationManager.AppSettings["LifeCycleManager.Service.Core.Password"];

        private static IStateMachineConfigLoader _staticStateMachineConfigLoader = null;
        private static ICalloutExecutor _staticCalloutExecutor = null;

        [Import(typeof(IStateMachineConfigLoader))]
        internal IStateMachineConfigLoader _stateMachineConfigLoader;

        [Import(typeof (ICalloutExecutor))]
        internal ICalloutExecutor _calloutExecutor;

        private CumulusCoreService.Core _coreService;
        private StateMachine.StateMachine _stateMachine;
        private EntityController _entityController;
        private String _entityType;

        public LifeCycleManager(IAuthenticationProvider authenticationProvider, String entityType)
        {
            Debug.WriteLine("Create new instance of LifeCycleManager for entityType '{0}'", entityType);
            _entityType = entityType;

            lock (_lock)
            {
                if (null == _staticStateMachineConfigLoader)
                {
                    LoadAndComposeParts();
                    _staticStateMachineConfigLoader = _stateMachineConfigLoader;
                    _staticCalloutExecutor = _calloutExecutor;
                }
                else
                {
                    _stateMachineConfigLoader = _staticStateMachineConfigLoader;
                    _calloutExecutor = _staticCalloutExecutor;
                }
            }
            _coreService = new CumulusCoreService.Core(new Uri(ConfigurationManager.AppSettings[CORE_ENDPOINT_URL_KEY]));
            _coreService.BuildingRequest += CoreServiceOnBuildingRequest;

            _entityController = new EntityController(authenticationProvider);
            _stateMachine = new StateMachine.StateMachine();
            ConfigureStateMachine(entityType);
        }

        private void CoreServiceOnBuildingRequest(object sender, BuildingRequestEventArgs buildingRequestEventArgs)
        {
            var tenantId = HttpContext.Current.Request.Headers.Get(_tenantIdHeaderKey);
            buildingRequestEventArgs.Headers.Add(_tenantIdHeaderKey, tenantId);
        }

        private void LoadAndComposeParts()
        {
            var assemblyCatalog = new AggregateCatalog();

            // Adds all the parts found in the given directory
            var folder = ConfigurationManager.AppSettings["LifeCycleManager.ExtensionsFolder"];
            Debug.WriteLine("Loading assemblies from folder: {0}", folder);
            try
            {
                if (!Path.IsPathRooted(folder))
                {
                    folder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder);
                }
                assemblyCatalog.Catalogs.Add(new DirectoryCatalog(folder));
            }
            catch (Exception ex)
            {
                Trace.WriteLine("WARNING: Loading extensions from '{0}' FAILED.\n{1}", folder, ex.Message);
            }
            finally
            {
                assemblyCatalog.Catalogs.Add(new AssemblyCatalog(typeof(LifeCycleManager).Assembly));
            }

            var _container = new CompositionContainer(assemblyCatalog);

            try
            {
                Debug.WriteLine("Composing MEF parts...");
                _container.ComposeParts(this);
                Debug.WriteLine("Composition MEF parts successfully completed!");
            }
            catch (CompositionException compositionException)
            {
                Trace.WriteLine(compositionException.ToString());
            }
        }

        private void ConfigureStateMachine(String entityType)
        {
            Debug.WriteLine("Configuring state machine for entityType '{0}'", entityType);
            String config;
            lock (_lock)
            {
                config = _stateMachineConfigLoader.LoadConfiguration(entityType);
            }

            if (null != config)
            {
                try
                {
                    _stateMachine.SetupStateMachine(config);
                }
                catch (JsonReaderException e)
                {
                    Debug.WriteLine("Error occurred while parsing state machine configuraiton for entity type '{0}' : {1}",
                        entityType,
                        e.Message);
                    throw new ArgumentException("Invalid state machine configuration", e);
                }
            }
        }

        public void RequestStateChange(Uri entityUri, String entity, String condition, String tenantId)
        {
            Debug.WriteLine("Got state change request for entity with URI: '{0}' and condition: '{1}'", entityUri, condition);

            CheckForExistingStateChangeLock(entityUri);
            var preCalloutDefinition = LoadCalloutDefinition(condition, entityUri, tenantId,
                Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString());
            CreateStateChangeLockForEntity(entityUri);

            String token = null;
            if (null == preCalloutDefinition)
            {
                DoPostCallout(entityUri, entity, condition, tenantId);
            }
            else
            {
                try
                {
                    var calloutData = CreatePreCalloutData(entityUri, entity, condition);
                    token = CreateJob(entityUri, tenantId, calloutData);
                    lock (_lock)
                    {
                        _calloutExecutor.ExecuteCallout(preCalloutDefinition.Parameters, calloutData);
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine("An error occurred while preparing or executing pre '{0}' callout for entity with id '{1}'",
                        condition,
                        entityUri.ToString());
                    if (null != token)
                    {
                        ChangeJobState(token, JobStateEnum.Failed);
                    }
                    DeleteStateChangeLockOfEntity(entityUri);
                    throw new InvalidOperationException(e.Message);
                }
            }
        }

        private void DoPostCallout(Uri entityUri, String entity, String condition, String tenantId)
        {
            CalloutData postCalloutData = null;
            String token = null;
            try
            {
                var postCalloutDefinition = LoadCalloutDefinition(condition, entityUri, tenantId,
                    Model.CalloutDefinition.CalloutDefinitionType.Post.ToString());
                ChangeEntityState(entityUri, entity, condition);
                if (null != postCalloutDefinition)
                {
                    postCalloutData = CreatePostCalloutData(entityUri, entity, condition);
                    token = CreateJob(entityUri, tenantId, postCalloutData);
                    lock (_lock)
                    {
                        _calloutExecutor.ExecuteCallout(postCalloutDefinition.Parameters, postCalloutData);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("An error occurred while preparing or executing post '{0}' callout for entity with id '{1}'",
                    condition,
                    entityUri.ToString());
                if (null != token)
                {
                    ChangeJobState(token, JobStateEnum.Failed);
                }
                if (postCalloutData != null)
                {
                    SetEntityState(entityUri, entity, postCalloutData.OriginalState);
                }
                DeleteStateChangeLockOfEntity(entityUri);
                throw new InvalidOperationException(e.Message);
            }
        }

        private void CheckForExistingStateChangeLock(Uri entityUri)
        {
            SetCoreServiceCredentialsBasedOnConfigValues();
            var scl = _coreService.StateChangeLocks
               .Where(l => l.EntityId == entityUri.ToString())
               .FirstOrDefault();

            if (null != scl)
            {
                Debug.WriteLine("State of entity '{0}' can not be changed because the entity is locked for state changes", entityUri.ToString());
                throw new InvalidOperationException();
            }
        }

        private void CreateStateChangeLockForEntity(Uri entityUri)
        {
            SetCoreServiceCredentialsBasedOnConfigValues();
            _coreService.AddToStateChangeLocks(
                new StateChangeLock
                {
                    EntityId = entityUri.ToString()
                }
            );
            _coreService.SaveChanges();
            Debug.WriteLine("Created state change lock for entity with id '{0}'", entityUri);
        }

        private void SetEntityState(Uri entityUri, String entity, String stateToSet)
        {
            Debug.WriteLine("Set state of entity with id '{0}' to '{1}'", entityUri, stateToSet);
            var obj = JObject.Parse(entity);
            obj["State"] = stateToSet;
            _entityController.UpdateEntity(entityUri, JsonConvert.SerializeObject(obj));
        }

        public void Next(Uri entityUri, String entity, String tenantId)
        {
            Debug.WriteLine("Request next state for entity with Uri: '{0}", entityUri);
            RequestStateChange(entityUri, entity, _stateMachine.ContinueCondition, tenantId);
        }

        public void Cancel(Uri entityUri, String entity, String tenantId)
        {
            Debug.WriteLine("Request cancel condition for entity with Uri: '{0}", entityUri);
            RequestStateChange(entityUri, entity, _stateMachine.CancelCondition, tenantId);
        }

        public void OnAllowCallback(Job job)
        {
            var parameters = JsonConvert.DeserializeObject<CalloutData>(job.Parameters);

            var entityUri = new Uri(job.ReferencedItemId);

            ChangeJobState(job.Token, JobStateEnum.Finished);
            if (parameters.Type == Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString())
            {
                Debug.WriteLine("Process allow POST action callback for job with id '{0}'", job.Id);
                DoPostCallout(entityUri, LoadEntity(entityUri), parameters.Action, job.TenantId);
            }
            else if (parameters.Type == Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
            {
                Debug.WriteLine("Process allow PRE action callback for job with id '{0}'", job.Id);
                DeleteStateChangeLockOfEntity(entityUri);
            }
        }

        public void OnDeclineCallback(Job job)
        {
            var parameters = JsonConvert.DeserializeObject<CalloutData>(job.Parameters);

            var entityUri = new Uri(job.ReferencedItemId);

            if (parameters.Type == Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString())
            {
                Debug.WriteLine("Process deny POST action callback for job with id '{0}' - finish job and unlock entity",
                    job.Id);
            }
            else if (parameters.Type == Model.CalloutDefinition.CalloutDefinitionType.Post.ToString())
            {
                Debug.WriteLine("Process deny PRE action callback for job with id '{0}' - Reset state, finish job and unlock entity",
                    job.Id);
                SetEntityState(entityUri, LoadEntity(entityUri), parameters.OriginalState);
            }
            ChangeJobState(job.Token, JobStateEnum.Canceled);
            DeleteStateChangeLockOfEntity(entityUri);
        }

        private String LoadEntity(Uri entityUri)
        {
            return _entityController.LoadEntity(entityUri);
        }

        private void DeleteStateChangeLockOfEntity(Uri entityUri)
        {
            var entityUriAsString = entityUri.ToString();
            Debug.WriteLine("Deleting StateChangeLock for entity '{0}'", entityUriAsString);
            SetCoreServiceCredentialsBasedOnConfigValues();
            var scl = _coreService.StateChangeLocks
                .Where(l => l.EntityId == entityUriAsString).Single();
            _coreService.DeleteObject(scl);
            _coreService.SaveChanges();
            Debug.WriteLine("StateChangeLock for entity with id '{0}' deleted", entityUriAsString);
        }

        private CalloutDefinition LoadCalloutDefinition(String condition, Uri entityUri, String tenantId, String calloutType)
        {
            Debug.WriteLine("Loading {0} callout definition of tenant '{1}' for condition '{2}' and entity of type '{3}' with id '{4}'",
                calloutType,
                tenantId,
                condition,
                _entityType,
                entityUri.ToString());

            var identity = (WindowsIdentity) HttpContext.Current.User.Identity;
            _coreService.Credentials = CredentialCache.DefaultCredentials;

            using (var impersonationContext = identity.Impersonate())
            {
                return _coreService.CalloutDefinitions.Where(
                    c =>
                        (c.CalloutType == calloutType
                         || c.CalloutType == Model.CalloutDefinition.CalloutDefinitionType.PreAndPost.ToString())
                        && tenantId == c.TenantId
                        && (entityUri.ToString() == c.EntityId
                            || _entityType == c.EntityType)
                        && new Regex(c.Condition).IsMatch(condition)).FirstOrDefault();
            }
        }

        private CalloutData CreatePreCalloutData(Uri entityUri, String entity, String condition)
        {
            return CreateCalloutData(entityUri, entity, condition,
                Model.CalloutDefinition.CalloutDefinitionType.Pre.ToString());
        }

        private CalloutData CreatePostCalloutData(Uri entityUri, String entity, String condition)
        {
            return CreateCalloutData(entityUri, entity, condition,
                Model.CalloutDefinition.CalloutDefinitionType.Post.ToString());
        }

        private CalloutData CreateCalloutData(Uri entityUri, String entity, String condition, String calloutType)
        {
            var obj = JObject.Parse(entity);
            var originalState = (String)obj["State"];
            var tenantId = (String) obj["Tid"];

            return new CalloutData
            {
                Type = calloutType,
                EntityType = _entityType,
                TenantId = tenantId,
                Action = condition,
                EntityId = entityUri.ToString(),
                OriginalState = originalState,
                UserId = CurrentUserDataProvider.GetCurrentUsername(),
                CallbackUrl = CreateCallbackUrl(entityUri.ToString())
            };
        }

        private String CreateCallbackUrl(String entityUri)
        {
            StringBuilder sb = new StringBuilder();

            using (SHA256 hash = SHA256Managed.Create())
            {
                Encoding enc = Encoding.UTF8;
                Byte[] result = hash.ComputeHash(enc.GetBytes(entityUri));

                foreach (Byte b in result)
                    sb.Append(b.ToString("x2"));
            }

            var token = sb.ToString();

            return String.Format("{0}/Jobs({1})", ConfigurationManager.AppSettings[CORE_ENDPOINT_URL_KEY], token);
        }

        private void ChangeEntityState(Uri entityUri, String entity, String condition)
        {
            var obj = JObject.Parse(entity);
            var entityState = (String)obj["State"];
            _stateMachine.SetupStateMachine(_stateMachine.GetStringRepresentation(), entityState);
            var newState = _stateMachine.ChangeState(condition);
            SetEntityState(entityUri, entity, newState);
        }

        private String CreateJob(Uri entityUri, String tenantId, CalloutData calloutData)
        {
            var token = calloutData.CallbackUrl.Split('(', ')')[1];
            SetCoreServiceCredentialsBasedOnConfigValues();
            _coreService.AddToJobs(new Job
            {
                State = JobStateEnum.Running.ToString(),
                Type = CALLOUT_JOB_TYPE,
                Parameters = JsonConvert.SerializeObject(calloutData),
                ReferencedItemId = entityUri.ToString(),
                TenantId = tenantId,
                Token = token
            });
            _coreService.SaveChanges();
            return token;
        }

        private void ChangeJobState(String token, JobStateEnum newJobState)
        {
            SetCoreServiceCredentialsBasedOnConfigValues();
            var job = GetRunningJob(token);

            job.State = newJobState.ToString();
            _coreService.UpdateObject(job);
            _coreService.SaveChanges();
            Debug.WriteLine("Changed state of job with id '{0}' to '{1}'", job.Id, newJobState);
        }

        private Job GetRunningJob(String token)
        {
            SetCoreServiceCredentialsBasedOnConfigValues();
            return _coreService.Jobs.Where(
                    j =>
                        token == j.Token
                        && CALLOUT_JOB_TYPE == j.Type
                        && JobStateEnum.Running.ToString() == j.State).Single();
        }

        private void SetCoreServiceCredentialsBasedOnConfigValues()
        {
            _coreService.Credentials = new NetworkCredential(_username, _password);
        }
    }
}


text:
package org.keycloak.testsuite.drone;

import org.arquillian.extension.recorder.screenshooter.ScreenshooterConfiguration;
import org.arquillian.extension.recorder.screenshooter.event.ScreenshooterExtensionConfigured;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;

/**
 * Disable screenshots for HTMLUnitDriver as it doesn't work
 *
 * @author Marek Posolda
 */
public class HtmlUnitScreenshots {

    protected final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(HtmlUnitScreenshots.class);

    @Inject
    private Instance<ScreenshooterConfiguration> configuration;

    public void configureExtension(@Observes ScreenshooterExtensionConfigured event) {
        ScreenshooterConfiguration conf = configuration.get();

        if (System.getProperty("browser", "htmlUnit").equals("htmlUnit")) {
            conf.setProperty("takeWhenTestFailed", "false");
            log.info("Screenshots disabled as htmlUnit is used");
        } else {
            log.info("Screenshots are enabled");
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.texxel.data;

import java.util.HashMap;
import java.util.Set;

import com.github.texxel.data.exceptions.*;

/**
 * A High level interface that lets data be read in from a data file. The class
 * is readonly.
 */
public class DataIn {

    final PData root;
    final PData pData;
    final HashMap<String, Object> references;
    final HashMap<String, Object> cache;

    public DataIn(PData data) {
        this(data, new HashMap<String, Object>(), data);
    }

    DataIn(PData section, HashMap<String, Object> references, PData root ) {
        this.references = references;
        this.pData = section;
        this.root = root;
        cache = new HashMap<>();
    }

    /**
     * Gets an unmodifiable set of all the keys that are in this section of the data
     * @return the data keys
     */
    public Set<String> keys() {
        return pData.keys();
    }

    /**
     * Tests if this section has a specific key
     * @param key the key to test for
     * @return true if the data has the key
     */
    public boolean has( String key ) {
        return pData.contains(key);
    }

    /**
     * Reads out an Object from the Data. WARNING: the returned object may not
     * be initialised yet. Therefore, NEVER call any methods on the object or
     * let anyone else call methods (including methods like toString() or
     * hashCode()). It is only safe to call methods on the object once
     * deserialization has finished.
     * @param type the class that should be read
     * @param key where to read the object from
     * @return the created object
     * @throws MissingDataException if there is no value at the specified location
     * @throws WrongTypeException if the object at the specified location is of the incorrect type
     * @throws InvalidDataException if the data type is not supported
     * @throws DataSerializationException if there was any issue in constructing the object
     */
    public <T> T read (Class<T> type, String key) {
        return PrimitiveConverter.read(key, type, this);
    }

    /**
     * Reads out an object from the Data. If any error occurs during the read or
     * the data is missing, then the bup is returned. This is the exact same
     * result as calling {@link #read(Class, String)} and catching any exceptions.
     * @param type the class that is wanted
     * @param bup the object to return if the class is not okay
     * @return the object read or bup
     * @see {@link #read(Class, String)}
     */
    public <T> T read (Class<T> type, String key, T bup) {
        try {
            return read(type, key);
        } catch (DataException e) {
            return bup;
        }
    }

    public long readLong(String key) {
        return pData.getLong(key);
    }

    public long readLong(String key, long bup) {
        if (pData.getType(key) == PData.Type.LONG)
            return pData.getLong(key);
        return bup;
    }
    public int readInt(String key) {
        return (int)readLong(key);
    }

    public int readInt(String key, int bup) {
        return (int)readLong(key, bup);
    }

    public double readDouble(String key) {
        return pData.getDouble(key);
    }

    public double readDouble(String key, double bup) {
        PData.Type type = pData.getType(key);
        if (type == PData.Type.DOUBLE)
            return pData.getDouble(key);
        if (type == PData.Type.LONG)
            return pData.getLong(key);
        return bup;
    }

    public float readFloat(String key) {
        return (float)readDouble(key);
    }

    public float readFloat(String key, float bup) {
        return (float)readDouble(key, bup);
    }

    public boolean readBoolean(String key) {
        return pData.getBoolean(key);
    }

    public boolean readBoolean(String key, boolean bup) {
        if (pData.getType(key) == PData.Type.BOOLEAN)
            return pData.getBoolean(key);
        return bup;
    }

    public String readString(String key) {
        return pData.getString(key);
    }

    public String readString(String key, String bup) {
        if (pData.getType(key) == PData.Type.STRING)
            return pData.getString(key);
        return bup;
    }

    /**
     * Reads a section of data out.
     * @param key the place to read the section from
     * @return the read section
     * @throws MissingDataException if the section is not present
     * @throws WrongTypeException if the key does not contain a data section
     */
    public DataIn readSection(String key) {
        return read(DataIn.class, key);
    }
}


text:
"""
Copyright 2021 Dean Hall.  See LICENSE for details.

The Text User Interface state machine
"""

import logging

from asciimatics.exceptions import ResizeScreenError, StopApplication
from asciimatics.scene import Scene
from asciimatics.screen import Screen
import farc

from heymac.ui import MsgsModel, RadioStngsModel, StatusModel
from heymac.utl import IdentModel
from tui_ident import IdentView
from tui_msgs import MsgsView
from tui_status import StatusView
from tui_stngs import RadioStngsView

UI_ANIMATE_PERIOD = 0.050  # Taken from asciimatics screen.py

class TxtUiHsm(farc.Ahsm):
    def __init__(self, phy_hsm, lnk_hsm):
        """Language-specific initialization."""
        super().__init__()
        self._ident_model = IdentModel()
        self._msgs_model = MsgsModel(lnk_hsm)
        self._status_model = StatusModel(phy_hsm, lnk_hsm)
        self._stngs_model = RadioStngsModel(phy_hsm)

    @farc.Hsm.state
    def _initial(self, event):
        """PseudoState: _initial

        State machine framework initialization
        """
        farc.Signal.register("_UI_KEYCODE")
        self._tmout_evt = farc.TimeEvent("_UI_TMOUT")
        self._one_sec_evt = farc.TimeEvent("_UI_ONE_SEC")
        farc.Framework.subscribe("GPS_GPRMC", self)
        return self.tran(self._running)

    @farc.Hsm.state
    def _running(self, event):
        """State: _running

        Application init and running.
        """
        sig = event.signal
        if sig == farc.Signal.ENTRY:
            logging.debug("UI._running")
            self._tmout_evt.post_in(self, 0)
            self._one_sec_evt.post_every(self, 1.0)
            self._prev_tick = farc.Framework._event_loop.time()

            if (self._ident_model.device_cred_exists()
                    and self._ident_model.personal_cert_exists()):
                start_scene = None
            else:
                start_scene = Scene([], -1, name="Identity")
            self._new_screen(start_scene)
            return self.handled(event)

        elif sig == farc.Signal._UI_TMOUT:
            try:
                self._screen.draw_next_frame()

            except ResizeScreenError as e:
                self._new_screen(e.scene)

            except StopApplication:
                self._screen.close()
                return self.tran(self._exiting)

            # Iterate immediately if this step took too long
            now = farc.Framework._event_loop.time()
            if now > self._prev_tick + UI_ANIMATE_PERIOD:
                self._tmout_evt.post_in(self, 0)
                self._prev_tick = now

            # otherwise iterate one period later
            else:
                self._prev_tick += UI_ANIMATE_PERIOD
                self._tmout_evt.post_at(self, self._prev_tick)
            return self.handled(event)

        elif sig == farc.Signal._UI_ONE_SEC:
            self._msgs_view.update_ui()
            return self.handled(event)

        elif sig == farc.Signal.GPS_GPRMC:
            self._status_view.update_gps(event.value)
            return self.handled(event)

        elif sig == farc.Signal.EXIT:
            self._tmout_evt.disarm()
            self._one_sec_evt.disarm()
            return self.handled(event)

        return self.super(self.top)

    @farc.Hsm.state
    def _exiting(self, event):
        sig = event.signal
        if sig == farc.Signal.ENTRY:
            logging.debug("UI._exiting")
            farc.Framework.stop()
            return self.handled(event)

        return self.super(self.top)

    def _new_screen(self, start_scene):
        screen = Screen.open()
        screen.clear()
        self._msgs_view = MsgsView(
            screen,
            self._msgs_model,
            self._ident_model,
            self._stngs_model,
            self._status_model)
        self._ident_view = IdentView(screen, self._ident_model)
        self._stngs_view = RadioStngsView(screen, self._stngs_model)
        self._status_view = StatusView(screen, self._stngs_model)
        scenes = [
            Scene([self._msgs_view], -1, name="Messages"),
            Scene([self._ident_view], -1, name="Identity"),
            Scene([self._stngs_view], -1, name="Settings"),
            Scene([self._status_view], -1, name="Status"),
        ]
        screen.set_scenes(scenes, start_scene=start_scene)
        self._screen = screen


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;

class ecommerceDataUser extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'customers';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['customers_id', 'user_registered', 'organization_name', 'first_name', 'middle_name', 'last_name', 'email_address', 'login_name', 'login_password', 'phone_number', 'city', 'country'], 'required'],
            [['customers_id'], 'integer'],
            [['user_registered'], 'safe'],
            [['organization_name', 'first_name', 'middle_name', 'last_name', 'email_address', 'login_name', 'login_password', 'phone_number', 'city', 'country'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'customers_id' => 'Customers Id',
            'user_registered' => 'User Registered',
			'organization_name' => 'Organization Name',
			'first_name' => 'First Name',
			'middle_name' => 'Middle Name',
			'last_name' => 'Last Name',
            'email_address' => 'Email Address',
            'login_name' => 'Login Name',
			'login_password' => 'Login Password',
            'phone_number' => 'Phone Number',
			'city' => 'City',
            'country' => 'Country',
        ];
    }

    public function findDataUser(){
        $sql = "SELECT customers_id, user_registered, organization_name, first_name, middle_name, last_name, email_address, login_name, login_password, phone_number, city, country
                FROM customers";

        return self::findBySql($sql)->asArray()->all();
    }

}


text:
package org.apache.hadoop.hdfs.server.datanode;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.server.datanode.FSDataset.ActiveFile;
import org.apache.hadoop.hdfs.server.datanode.FSDataset.FSVolume;

/**
 * Maintains the replicas map.
 */
class VolumeMap {

  // Map of block Id to DatanodeBlockInfo, indexed by namespace
  private Map<Integer, Map<Block, DatanodeBlockInfo>> namespaceMap;
  private Map<Integer, Map<Block, ActiveFile>> ongoingCreates;

  VolumeMap(int numNamespaces) {
    namespaceMap = new HashMap<Integer, Map<Block, DatanodeBlockInfo>>(numNamespaces);
    ongoingCreates = new HashMap<Integer, Map<Block, ActiveFile>>(numNamespaces);
  }

  /**
   * Returns an immutable instance of the volume map for a given namespace.
   * @param namespaceID the namespaceID for which the volume map needs to be
   * returned.
   */
  public Map <Block, DatanodeBlockInfo> getNamespaceMap(int namespaceID) {
    return Collections.unmodifiableMap(namespaceMap.get(namespaceID));
  }

  synchronized Integer[] getNamespaceList() {
    return namespaceMap.keySet().toArray(
        new Integer[namespaceMap.keySet().size()]);
  }

  private void checkBlock(Block b) {
    if (b == null) {
      throw new IllegalArgumentException("Block is null");
    }
  }

  synchronized int removeUnhealthyVolumes(Collection<FSVolume> failed_vols) {
    int removed_blocks = 0;

    for (Integer namespaceId : namespaceMap.keySet()) {
      Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
      Iterator<Entry<Block, DatanodeBlockInfo>> dbi = m.entrySet().iterator();
      while (dbi.hasNext()) {
        Entry<Block, DatanodeBlockInfo> entry = dbi.next();
        for (FSVolume v : failed_vols) {
          if (entry.getValue().getVolume() == v) {
            DataNode.LOG.warn("removing block " + entry.getKey().getBlockId()
                + " from vol " + v.toString() + ", form namespace: "
                + namespaceId);
            dbi.remove();
            removed_blocks++;
            break;
          }
        }
      }
    }
    return removed_blocks;
  }

  /**
   * Get the meta information of the replica that matches both block id and
   * generation stamp
   *
   * @param namespaceId
   * @param block
   *          block with its id as the key
   * @return the replica's meta information
   * @throws IllegalArgumentException
   *           if the input block or block pool is null
   */
  DatanodeBlockInfo get(int namespaceId, Block block) {
    checkBlock(block);
    synchronized(this){
      Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
      return m != null ? m.get(block) : null;
    }
  }

  /**
   * Add a replica's meta information into the map
   *
   * @param namespaceId
   * @param replicaInfo
   *          a replica's meta information
   * @return previous meta information of the replica
   * @throws IllegalArgumentException
   *           if the input parameter is null
   */
  DatanodeBlockInfo add(int namespaceId, Block block,
      DatanodeBlockInfo replicaInfo) {
    checkBlock(block);
    synchronized(this){
      Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
      return m.put(block, replicaInfo);
    }
  }

  DatanodeBlockInfo update(int namespaceId, Block oldB, Block newB) {
    Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
    if (m == null) {
      return null;
    }

    DatanodeBlockInfo bi = m.remove(oldB);
    if (bi != null) {
      m.put(newB, bi);
    }
    return bi;
  }

  /**
   * Remove the replica's meta information from the map that matches the input
   * block's id and generation stamp
   *
   * @param namespaceId
   * @param block
   *          block with its id as the key
   * @return the removed replica's meta information
   * @throws IllegalArgumentException
   *           if the input block is null
   */
  DatanodeBlockInfo remove(int namespaceId, Block block) {
    checkBlock(block);
    synchronized(this){
      Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
      return m != null ? m.remove(block) : null;
    }
  }

  /**
   * Get the size of the map for given namespace
   *
   * @param namespaceId
   * @return the number of replicas in the map
   */
  synchronized int size(int namespaceId) {
    Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
    return m != null ? m.size() : 0;
  }

  synchronized void initNamespace(int namespaceId) {
    Map<Block, DatanodeBlockInfo> m = namespaceMap.get(namespaceId);
    if(m != null){
      return;
    }
    m = new HashMap<Block, DatanodeBlockInfo>();
    namespaceMap.put(namespaceId, m);
    Map<Block, ActiveFile> oc = new HashMap<Block, ActiveFile>();
    ongoingCreates.put(namespaceId, oc);
  }

  synchronized void removeNamespace(int namespaceId){
    namespaceMap.remove(namespaceId);
    ongoingCreates.remove(namespaceId);
  }

  // for ongoing creates

  ActiveFile getOngoingCreates(int namespaceId, Block block) {
    checkBlock(block);
    synchronized(this){
      Map<Block, ActiveFile> m = ongoingCreates.get(namespaceId);
      return m != null ? m.get(block) : null;
    }
  }

  ActiveFile removeOngoingCreates(int namespaceId, Block block) {
    checkBlock(block);
    synchronized(this){
      Map<Block, ActiveFile> m = ongoingCreates.get(namespaceId);
      return m != null ? m.remove(block) : null;
    }
  }

  ActiveFile addOngoingCreates(int namespaceId, Block block, ActiveFile af) {
    checkBlock(block);
    synchronized(this){
      Map<Block, ActiveFile> m = ongoingCreates.get(namespaceId);
      return m.put(block, af);
    }
  }

  public synchronized String toString() {
    String ret = "VolumeMap: ";
    for (Integer namespaceId : namespaceMap.keySet()) {
      ret += namespaceMap.get(namespaceId).toString();
      ret += "\n---\n";
      ret += ongoingCreates.get(namespaceId).toString();
    }
    return ret;
  }
}


text:
package com.netflix.kayenta.datadog.canary;

import com.netflix.kayenta.canary.CanaryScope;
import com.netflix.kayenta.canary.CanaryScopeFactory;
import org.springframework.stereotype.Component;

@Component
public class DatadogCanaryScopeFactory implements CanaryScopeFactory {
  @Override
  public boolean handles(String serviceType) {
    return "datadog".equals(serviceType);
  }

  @Override
  public CanaryScope buildCanaryScope(CanaryScope scope) {
    return scope;
  }
}


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

namespace _03.MinMaxSumAverageNNumbers
{
    class Program
    {
        static void Main()
        {
            int n;
            string[] numbers;
            bool isInteger = true;
            int minimal = int.MaxValue;
            int maximal = int.MinValue;
            Console.Write("Enter a sequence of numbers delimited with \",\":");
            numbers = (Console.ReadLine()).Split(',');
            int[] intNumbers = new int[numbers.Length];
            for (int i = 0; i < (numbers.Length); i++)
            {
                isInteger = int.TryParse(numbers[i], out intNumbers[i]);
                if (isInteger == false)
                {
                    break;
                }
            }
            if (isInteger)
            {
                for (int i = 0; i < numbers.Length; i++)
                {
                    if (intNumbers[i] < minimal)
                    {
                        minimal = intNumbers[i];
                    }
                    if (intNumbers[i] > maximal)
                    {
                        maximal = intNumbers[i];
                    }
                }
                Console.WriteLine("minimal={0}", minimal);
                Console.WriteLine("maximal={0}", maximal);
            }
            else
            {
                Console.WriteLine("Not a valid entry! Some of the entries are not integer!");
            }
        }
    }
}


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

namespace Chiro.Voorbeeld.Net35Algemeen
{
	class Program
	{
		internal class Bier
		{
			public string Naam { get; set; }
			public double Alcohol { get; set; }
		}

		static void Main(string[] args)
		{
			// Initialisatie: Onderstaande lijn
			Bier b1 = new Bier {Naam = "Hopus", Alcohol = 8.3};
			// is equivalent met

			//   Bier b1 = new Bier();
			//   b1.Naam = "Hopus";
			//   b1.Alcohol = 8.3;

			// Je kan ook in de declaratie 'Bier' vervangen door 'var'
			var b2 = new Bier {Naam = "Barbãr", Alcohol = 8};
			// is equivalent met

			//   Bier b2 = new Bier {Naam = "Barbãr", Alcohol = 8};
			// De compiler leidt zelf af dat het type van b2 'Bier' moet zijn.

			Bier b3 = b2; // de compiler weet dat het dezelfde types zijn, en doet dus niet moeilijk.

			// Je kan 'var' ook gebruiken voor 'anonieme types'.  Deze kan je wel enkel
			// binnen hun scope blijven gebruiken.

			var bierinfo = new {Naam = b2.Naam, Omschrijving = String.Format("{0} ({1}%)", b2.Naam, b2.Alcohol)};

			// 'bierinfo' heeft nu property's Naam en Omschrijving.  Het type van bierinfo is
			// automatisch gegenereerd.  Je kan de velden accessen op de verwachte manier:

			Console.WriteLine(String.Format("Naam: {0}", bierinfo.Naam));
			Console.WriteLine(String.Format("Omschrijving: {0}", bierinfo.Omschrijving));

			// Eens kijken wat het type van bierinfo is: (niet dat het ertoe doet)

			Console.WriteLine(String.Format("Naam van het 'anonieme type': {0}", bierinfo.GetType()));

			Console.ReadLine();
		}
	}
}


text:
Application for generating Minecraft banners.

## Includes

* A web server/page showing the variations of Minecraft banners, as SVG approximations (`mcweb`).
* A commandline application for evolving Minecraft banners with genetic algorithms (`evolve`).
* Go code for generating a random SVG banner and rendering it as PNG by using `rsvg-convert` (`random`).

## Original goal

* Given an image, get the steps for creating the closest looking Minecraft banner. This goal is a work in progress, since the evolution is not rapid enough. Perhaps using smaller images when rendering from SVG, or another algorithm, would work.

## General information

* Version: 2.0.1
* License: MIT


text:
title: "Can I easily transition from self-hosted to Cloud or vice-versa?"
meta_title: "Can I easily transition from self-hosted to Cloud or vice-versa? - FAQ"
meta_description: "Yes, absolutely. You own your data, models, code, and artifacts whether you are using Polyaxon CE, Polyaxon Cloud, or Polyaxon EE."
featured: false
custom_excerpt: "Yes, absolutely. You own your data, models, code, and artifacts whether you are using Polyaxon CE, Polyaxon Cloud, or Polyaxon EE."
author:
  name: "Polyaxon"
  slug: "Polyaxon"
  website: "https://polyaxon.com"
  twitter: "polyaxonAI"
  github: "polyaxon"
visibility: public
status: published
tags:
  - billing
---

Yes, absolutely. You own your data, models, code, and artifacts whether you are using Polyaxon CE, Polyaxon Cloud, or Polyaxon EE.

The difference between Polyaxon Cloud and Polyaxon EE is the control plane. In both cases, the workload, data, logs, metrics, models, artifacts, and all sensitive secrets and config-maps are managed by a Polyaxon Agent running on a different cluster/namespace.

In Polyaxon Cloud we manage the control plane, in Polyaxon EE the customer manages the control plane, in both cases the customer manages the Agent deployments (data plane).

We designed our control plane to meet the strict standards and to allow users to achieve several use-cases: data locality, federated training, federated job scheduling, support for custom networking on each Agent, namespacing and isolation, multi-cluster scaling options ...


text:
package jsettlers.graphics.utils;

import jsettlers.common.action.EActionType;
import jsettlers.common.action.Action;
import jsettlers.graphics.ui.UIInput;

public class FocusAction extends Action {

	private final UIInput input;

	public FocusAction(UIInput input) {
		super(EActionType.FOCUS);
		this.input = input;
	}

	public UIInput getInput() {
		return input;
	}

}


text:
package org.apache.camel;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marks a parameter as being an injection point of a property of an {@link org.apache.camel.Exchange}
 *
 * @see org.apache.camel.Exchange#getProperty(String)
 */
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target({ElementType.PARAMETER })
public @interface ExchangeProperty {

    /**
     * Name of the property
     */
    String value();
}


text:
module RikiEngine
  module RiWikiHistoryHelper
    require 'differ'

    def do_show_history
      article = Article.where(name: @article)
      @snapshots = []

      if article.empty?
        crash
      else
        article = article.first
        snapshots = Snapshot.where(article_id: article.id)

        return if snapshots.nil?
        snapshots.each do |snapshot|
          author = get_username_or_deleted snapshot.author_id

          @snapshots.append({
                                author: author,
                                created: snapshot.created_at,
                                id: snapshot.id,
                            })
        end
      end
    end

    def get_snapshot_text(id)
      diff = ''

      if id > -1
        diff = Snapshot.where(id: id)
        if diff.empty?
          diff = ''
        else
          diff = diff.first.wiki_text
        end
      end

      diff
    end

    def do_show_diff
      diff_first = get_snapshot_text @diff_first.to_i
      diff_second = get_snapshot_text @diff_second.to_i

      diff = Differ.diff_by_line(diff_second, diff_first)
      @diff = diff.format_as(:html).to_s
      @diff.gsub! "\r", ''
    end

  end
end


text:
@interface FlickrGroupClient : BDBOAuth1RequestOperationManager

+ (FlickrGroupClient *)instance;

- (void)saveAccessToken:(BDBOAuthToken *)accessToken;

- (void)removeAccessToken;

- (BDBOAuthToken *)getAccessToken;

- (void)saveUser:(User *)currentUser;

- (void)removeUser;

- (User *)getCurrentUser;

- (void)logout;

- (void)login;

- (NSString *)getBuddyIconUrlWithFarm:(NSString *)farm server:(NSString *)server id:(NSString *)id;

#pragma mark client methods

- (AFHTTPRequestOperation *)currentUserWithSuccess:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                           failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)getUserInfoWithUserId:(NSString *)userId
                                          success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                          failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)getGroupsWithUserId:(NSString *)userId
                                          success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                          failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)searchGroupsWithKeyword:(NSString *)keyword
                                            success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                            failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)joinGroupWithGroupId:(NSString *)groupId
                                            success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                         failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)leaveGroupWithGroupId:(NSString *)groupId
                                          success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                          failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)getGroupDetailWithGroupId:(NSString *)groupId
                                        success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                              failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)getGroupTopicsWithGroupId:(NSString *)groupId
                                        countPerPage:(NSInteger)countPerPage
                                              pageNum:(NSInteger)pageNum
                                              success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                              failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)getTopicDetailsWithTopicId:(NSString *)topicId
                                               success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                               failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)getTopicRepliesWithTopicId:(NSString *)topicId
                                          countPerPage:(NSInteger)countPerPage
                                               pageNum:(NSInteger)pageNum
                                               success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                               failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)addTopicReplyWithTopicId:(NSString *)topicId
                                             message:(NSString *)message
                                             success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                             failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

- (AFHTTPRequestOperation *)addTopicWithGroupId:(NSString *)groupId
                                        subject:(NSString *)subject
                                        message:(NSString *)message
                                        success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                        failure:(void (^) (AFHTTPRequestOperation *operation, NSError *error))failure;

@end


text:
using System.Linq;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.Utilities;

namespace FallenSoD.NPCs
{
    [AutoloadHead]
    public class IbaNPC : ModNPC
    {
        public override string Texture
        {
            get
            {
                return "FallenSoD/NPCs/IbaNPC";
            }
        }

        public override bool Autoload(ref string name)
        {
            name = "Priestess of the Calamity";
            return mod.Properties.Autoload;
        }

        public override void SetStaticDefaults()
        {
            DisplayName.SetDefault("Priestess of the Calamity");
            Main.npcFrameCount[npc.type] = 25;
            NPCID.Sets.ExtraFramesCount[npc.type] = 9;
            NPCID.Sets.AttackFrameCount[npc.type] = 4;
            NPCID.Sets.DangerDetectRange[npc.type] = 700;
            NPCID.Sets.AttackType[npc.type] = 0;
            NPCID.Sets.AttackTime[npc.type] = 90;
            NPCID.Sets.AttackAverageChance[npc.type] = 30;
            NPCID.Sets.HatOffsetY[npc.type] = 4;
        }

        public override void SetDefaults()
        {
            npc.townNPC = true;
            npc.friendly = true;
            npc.width = 18;
            npc.height = 40;
            npc.aiStyle = 7;
            npc.damage = 500;
            npc.defense = 55;
            npc.lifeMax = 400;
            npc.HitSound = SoundID.NPCHit1;
            npc.DeathSound = SoundID.NPCDeath1;
            npc.knockBackResist = 0.5f;
            animationType = NPCID.Guide;
        }

        public static bool TownSpawn()
        {
            if (Main.hardMode)
                return false;
            else
                return false;
        }

        public override string TownNPCName()
        {
            switch (WorldGen.genRand.Next(4))
            {
                case 0:
                    return "Ibalia";
                default:
                    return "Iba";
            }
        }

        public override string GetChat()
        {
            int Dryad = NPC.FindFirstNPC(NPCID.Dryad);
            if (Dryad >= 0 && Main.rand.Next(4) == 0)
            {
                return "This " + Main.npc[Dryad].GivenName + " ... How do we get rid of her? She is trying to 'cleanse' me!";
            }
            switch (Main.rand.Next(4))
            {
                case 0:
                    return "I hope Kazajirr isn't that much of a deal for you. He really tends to be hot-headded.";
                case 1:
                    return "This world has to be corrupt for you to be the true Lord of the Calamity";
                case 2:
                    return "Ever heard of the 'Knights of the Calamity'? They are quite a Chaotic bunch. They will try to kill you even if you are their next Lord.";
                case 3:
                    return "You probably ask yourself 'Why am I now the next Lord of the Calamity?' Well, I don't know!";
                case 4:
                    return "... What? Why are you staring at me?!";
                default:
                    return "Ah, Hello my Lord. Why I'm calling you my Lord? Well, I serve you dummy!";
            }
        }

        public override void SetChatButtons(ref string button, ref string button2)
        {
            button = Lang.inter[28].Value;
        }

        public override void OnChatButtonClicked(bool firstButton, ref bool shop)
        {
            if (firstButton)
            {
                shop = true;
            }
        }

        public override void SetupShop(Chest shop, ref int nextSlot)
        {
            shop.item[nextSlot].SetDefaults(ItemID.CorruptSeeds);
            nextSlot++;
            shop.item[nextSlot].SetDefaults(ItemID.CrimsonSeeds);
            nextSlot++;
        }
        public override void TownNPCAttackStrength(ref int damage, ref float knockback)
        {
            damage = 20;
            knockback = 4f;
        }

        public override void TownNPCAttackCooldown(ref int cooldown, ref int randExtraCooldown)
        {
            cooldown = 30;
            randExtraCooldown = 30;
        }

        public override void TownNPCAttackProj(ref int projType, ref int attackDelay)
        {
            projType = mod.ProjectileType("SparklingBall");
            attackDelay = 1;
        }

        public override void TownNPCAttackProjSpeed(ref float multiplier, ref float gravityCorrection, ref float randomOffset)
        {
            multiplier = 12f;
            randomOffset = 2f;
        }
    }
}


text:
<?php

namespace Codeages\Biz\Framework\Tests\Example\Service;

interface ExampleService
{

    public function test1();

    public function test2();

}


text:
using System;
using System.IO;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Threading;
using SvnBridge.Interfaces;
using SvnBridge.Net;
using SvnBridge.SourceControl;
using SvnBridge.Utility;
using SvnBridge.Infrastructure;
using System.Collections;
using SvnBridge.Cache;
using System.Collections.Generic;
using SvnBridge.Protocol;
using SvnBridge.Nodes;
using System.Xml;
using CodePlex.TfsLibrary.RepositoryWebSvc;

namespace SvnBridge.RequestHandlers.SAWSHandlers
{
    public class SAWSPropFindHandler : SAWSHandlerBase
    {
        protected override void Handle(IHttpContext context, TFSSourceControlProvider sourceControlProvider)
        {
            IHttpRequest request = context.Request;
            IHttpResponse response = context.Response;
            PropFindData propfind = Helper.DeserializeXml<PropFindData>(request.InputStream);
            try
            {
                string requestPath = GetPath(request);
                string depthHeader = request.Headers["Depth"];
                string labelHeader = request.Headers["Label"];

                SetResponseSettings(response, "text/xml; charset=\"utf-8\"", Encoding.UTF8, 207);

                if (request.Headers["Label"] != null)
                {
                    response.AppendHeader("Vary", "Label");
                }

                if (propfind.AllProp != null && requestPath.EndsWith("/!svn/vcc/default"))
                {
                    HandleAllPropVccDefault(sourceControlProvider, requestPath, response.OutputStream);
                }
                else if (propfind.AllProp != null)
                {
                    HandleAllProp(sourceControlProvider, requestPath, response.OutputStream);
                }
                else if (propfind.Prop != null)
                {
                    HandleProp(sourceControlProvider, requestPath, depthHeader, labelHeader, propfind.Prop, response.OutputStream);
                }
                else
                {
                    throw new InvalidOperationException("Only <allprop> and <prop> are currently supported.");
                }
            }
            catch (FileNotFoundException)
            {
                WriteFileNotFoundResponse(request, response);
            }
            catch
            {
                RequestCache.Items["RequestBody"] = propfind;
                throw;
            }
        }

        private void HandleAllPropVccDefault(TFSSourceControlProvider sourceControlProvider, string requestPath, Stream stream)
        {
            // TODO:
            int latestVersion = GetSDKObject().GetLastestVersionNum(requestPath);
            Guid id = Guid.NewGuid();
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"DAV:\">\n");
                writer.Write("<D:response xmlns:lp1=\"DAV:\" xmlns:lp2=\"http://subversion.tigris.org/xmlns/dav/\">\n");
                writer.Write("<D:href>" + GetLocalPath("/!svn/vcc/default") + "</D:href>\n");
                writer.Write("<D:propstat>\n");
                writer.Write("<D:prop>\n");
                writer.Write("<lp1:checked-in><D:href>" + GetLocalPath("/!svn/bln/" + latestVersion) + "</D:href></lp1:checked-in>\n");
                writer.Write("<lp2:repository-uuid>" + id + "</lp2:repository-uuid>\n");
                writer.Write("<D:supportedlock>\n");
                writer.Write("<D:lockentry>\n");
                writer.Write("<D:lockscope><D:exclusive/></D:lockscope>\n");
                writer.Write("<D:locktype><D:write/></D:locktype>\n");
                writer.Write("</D:lockentry>\n");
                writer.Write("</D:supportedlock>\n");
                writer.Write("<D:lockdiscovery/>\n");
                writer.Write("</D:prop>\n");
                writer.Write("<D:status>HTTP/1.1 200 OK</D:status>\n");
                writer.Write("</D:propstat>\n");
                writer.Write("</D:response>\n");
                writer.Write("</D:multistatus>\n");
            }
        }
        private ItemMetaData GetItems(TFSSourceControlProvider sourceControlProvider,
                                     int version,
                                     string path,
                                     Recursion recursion,
                                     bool loadPropertiesFromFile)
        {
            return QueryItems(path, version, recursion);
        }

        private FolderMetaData GetFolderInfo(TFSSourceControlProvider sourceControlProvider,
                                                    string depth,
                                                    string path,
                                                    int? version,
                                                    bool loadPropertiesFromFile)
        {
            if (depth == "0")
            {
                FolderMetaData folderInfo = new FolderMetaData();
                ItemMetaData item =
                    GetItems(sourceControlProvider, version.HasValue ? version.Value : -1, path, Recursion.None, loadPropertiesFromFile);
                folderInfo.Items.Add(item);
                return folderInfo;
            }
            else if (depth == "1")
            {
                FolderMetaData data =
                    (FolderMetaData)GetItems(sourceControlProvider, version.HasValue ? version.Value : -1, path, Recursion.OneLevel, loadPropertiesFromFile);
                return data;
            }
            else
            {
                throw new InvalidOperationException(String.Format("Depth not supported: {0}", depth));
            }
        }

        private void HandleAllProp(TFSSourceControlProvider sourceControlProvider, string requestPath, Stream outputStream)
        {
            int revision;
            string path;
            bool bcPath = false;
            if (requestPath.StartsWith("/!svn/bc"))
            {
                bcPath = true;
                revision = int.Parse(requestPath.Split('/')[3]);
                path = requestPath.Substring("/!svn/bc/".Length + revision.ToString().Length);
            }
            else
            {
                const string latestVersion = "Repository.Latest.Version";
                if (RequestCache.Items[latestVersion] != null)
                {
                    revision = (int)RequestCache.Items[latestVersion];
                }
                else
                {
                    revision = GetSDKObject().GetLastestVersionNum(requestPath);
                }
            //    revision = sourceControlProvider.GetItems(-1, requestPath, Recursion.None).Revision;
                path = requestPath;
            }

            ItemMetaData item = GetItems(sourceControlProvider, revision, path, Recursion.None, true);

            if (item == null)
            {
                if (IsSvnRequestForProjectCreation(path, revision, sourceControlProvider))
                {
                    item = GetItems(sourceControlProvider, revision, "", Recursion.None, true);
                    item.Name = "trunk";
                }

                if (item == null)
                    throw new FileNotFoundException("There is no item " + requestPath + " in revision " + revision);
            }

            using (StreamWriter writer = new StreamWriter(outputStream))
            {
                if (item.ItemType == ItemType.Folder)
                {
                    WriteAllPropForFolder(writer, requestPath, item, bcPath, sourceControlProvider);
                }
                else
                {
                 //   WriteAllPropForItem(writer, requestPath, item, sourceControlProvider.ReadFile(item), sourceControlProvider);
                    WriteAllPropForItem(writer, requestPath, item, new byte[1], sourceControlProvider);
                }
            }
        }

        private void WriteAllPropForFolder(TextWriter writer, string requestPath, ItemMetaData item, bool bcPath, TFSSourceControlProvider sourceControlProvider)
        {
            writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            if (bcPath)
            {
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"DAV:\">\n");
            }
            else
            {
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns2=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns1=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns0=\"DAV:\">\n");
            }
            writer.Write("<D:response xmlns:S=\"http://subversion.tigris.org/xmlns/svn/\" xmlns:C=\"http://subversion.tigris.org/xmlns/custom/\" xmlns:V=\"http://subversion.tigris.org/xmlns/dav/\" xmlns:lp1=\"DAV:\" xmlns:lp2=\"http://subversion.tigris.org/xmlns/dav/\">\n");
            writer.Write("<D:href>" + Helper.Encode(requestPath) + "/</D:href>\n");
            writer.Write("<D:propstat>\n");
            writer.Write("<D:prop>\n");
            foreach (var prop in item.Properties)
            {
                if (prop.Key.StartsWith("svn:"))
                {
                    writer.Write("<S:" + prop.Key.Substring(4) + ">" + prop.Value + "</S:" + prop.Key.Substring(4) + ">\n");
                }
                else
                {
                    writer.Write("<C:" + prop.Key + ">" + prop.Value + "</C:" + prop.Key + ">\n");
                }
            }
            writer.Write("<lp1:getcontenttype>text/html; charset=UTF-8</lp1:getcontenttype>\n");
            writer.Write("<lp1:getetag>W/\"" + item.Revision + "//" + Helper.EncodeB(item.Name) + "\"</lp1:getetag>\n");
            writer.Write("<lp1:creationdate>" + Helper.FormatDate(item.LastModifiedDate) + "</lp1:creationdate>\n");
            writer.Write("<lp1:getlastmodified>" + Helper.FormatDateB(item.LastModifiedDate) + "</lp1:getlastmodified>\n");
            string svrVerLocalPath = GetLocalPath("/!svn/ver/" + item.Revision + "/" + Helper.Encode(item.Name, true));
            writer.Write("<lp1:checked-in><D:href>" + svrVerLocalPath + "</D:href></lp1:checked-in>\n");
            writer.Write("<lp1:version-controlled-configuration><D:href>" + VccPath + "</D:href></lp1:version-controlled-configuration>\n");
            writer.Write("<lp1:version-name>" + item.Revision + "</lp1:version-name>\n");
            writer.Write("<lp1:creator-displayname>" + item.Author + "</lp1:creator-displayname>\n");
            if (item.Name != "")
            {
                writer.Write("<lp2:baseline-relative-path>" + Helper.EncodeB(item.Name) + "</lp2:baseline-relative-path>\n");
            }
            else
            {
                writer.Write("<lp2:baseline-relative-path/>\n");
            }
            writer.Write("<lp2:repository-uuid>" + Guid.NewGuid() + "</lp2:repository-uuid>\n");
            writer.Write("<lp2:deadprop-count>" + item.Properties.Count + "</lp2:deadprop-count>\n");
            writer.Write("<lp1:resourcetype><D:collection/></lp1:resourcetype>\n");
            writer.Write("<D:lockdiscovery/>\n");
            writer.Write("</D:prop>\n");
            writer.Write("<D:status>HTTP/1.1 200 OK</D:status>\n");
            writer.Write("</D:propstat>\n");
            writer.Write("</D:response>\n");
            writer.Write("</D:multistatus>\n");
        }

        private void WriteAllPropForItem(TextWriter writer, string requestPath, ItemMetaData item, byte[] itemData, TFSSourceControlProvider sourceControlProvider)
        {
            writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"DAV:\">\n");
            writer.Write("<D:response xmlns:S=\"http://subversion.tigris.org/xmlns/svn/\" xmlns:C=\"http://subversion.tigris.org/xmlns/custom/\" xmlns:V=\"http://subversion.tigris.org/xmlns/dav/\" xmlns:lp1=\"DAV:\" xmlns:lp2=\"http://subversion.tigris.org/xmlns/dav/\">\n");
            writer.Write("<D:href>" + Helper.Encode(requestPath) + "</D:href>\n");
            writer.Write("<D:propstat>\n");
            writer.Write("<D:prop>\n");
            writer.Write("<lp1:getcontentlength>" + itemData.Length + "</lp1:getcontentlength>\n");
            writer.Write("<lp1:getcontenttype>text/plain</lp1:getcontenttype>\n");
            writer.Write("<lp1:getetag>\"" + item.Revision + "//" + Helper.EncodeB(item.Name) + "\"</lp1:getetag>\n");
            writer.Write("<lp1:creationdate>" + Helper.FormatDate(item.LastModifiedDate) + "</lp1:creationdate>\n");
            writer.Write("<lp1:getlastmodified>" + Helper.FormatDateB(item.LastModifiedDate) + "</lp1:getlastmodified>\n");
            string svnVerLocalPath = GetLocalPath("/!svn/ver/" + item.Revision + "/" + Helper.Encode(item.Name, true));
			writer.Write("<lp1:checked-in><D:href>" + svnVerLocalPath + "</D:href></lp1:checked-in>\n");
            writer.Write("<lp1:version-controlled-configuration><D:href>" + VccPath + "</D:href></lp1:version-controlled-configuration>\n");
            writer.Write("<lp1:version-name>" + item.Revision + "</lp1:version-name>\n");
            writer.Write("<lp1:creator-displayname>" + item.Author + "</lp1:creator-displayname>\n");
            writer.Write("<lp2:baseline-relative-path>" + Helper.EncodeB(item.Name) + "</lp2:baseline-relative-path>\n");
            writer.Write("<lp2:md5-checksum>" + Helper.GetMd5Checksum(itemData) + "</lp2:md5-checksum>\n");
            writer.Write("<lp2:repository-uuid>" + Guid.NewGuid() + "</lp2:repository-uuid>\n");
            writer.Write("<lp2:deadprop-count>0</lp2:deadprop-count>\n");
            writer.Write("<lp1:resourcetype/>\n");
            writer.Write("<D:supportedlock>\n");
            writer.Write("<D:lockentry>\n");
            writer.Write("<D:lockscope><D:exclusive/></D:lockscope>\n");
            writer.Write("<D:locktype><D:write/></D:locktype>\n");
            writer.Write("</D:lockentry>\n");
            writer.Write("</D:supportedlock>\n");
            writer.Write("<D:lockdiscovery/>\n");
            writer.Write("</D:prop>\n");
            writer.Write("<D:status>HTTP/1.1 200 OK</D:status>\n");
            writer.Write("</D:propstat>\n");
            writer.Write("</D:response>\n");
            writer.Write("</D:multistatus>\n");
        }

        private void HandleProp(TFSSourceControlProvider sourceControlProvider, string requestPath, string depthHeader, string labelHeader, PropData data, Stream outputStream)
        {
            if (requestPath == Constants.SvnVccPath)
            {
                WriteVccResponse(sourceControlProvider, requestPath, labelHeader, data, outputStream);
            }
            else if (requestPath.StartsWith("/!svn/bln/"))
            {
                WriteBlnResponse(requestPath, data, outputStream);
            }
            else if (requestPath.StartsWith("/!svn/bc/"))
            {
                WriteBcResponse(sourceControlProvider, requestPath, depthHeader, data, outputStream);
            }
            else if (requestPath.StartsWith("/!svn/wrk/"))
            {
                WriteWrkResponse(sourceControlProvider, requestPath, depthHeader, data, outputStream);
            }
            else
            {
                WritePathResponse(sourceControlProvider, requestPath, depthHeader, data, outputStream);
            }
        }

        private void WriteVccResponse(TFSSourceControlProvider sourceControlProvider,
                                      string requestPath,
                                      string label,
                                      PropData data,
                                      Stream outputStream)
        {

            string path;
            string[] pa = requestPath.Split('/');
            if (pa.Length <= 4) path = "/";
            else path = pa[4];
            int version = 0;
            const string latestVersion = "Repository.Latest.Version";
            if (RequestCache.Items[latestVersion] != null)
            {
                version = (int)RequestCache.Items[latestVersion];
            }
            else
            {
                version = GetSDKObject().GetLastestVersionNum(path);
            }

            INode node = new SvnVccDefaultNode(sourceControlProvider, requestPath, label, version);

            using (StreamWriter writer = new StreamWriter(outputStream))
            {
                writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"DAV:\">\n");
                WriteProperties(node, data.Properties, writer);
                writer.Write("</D:multistatus>\n");
            }
        }

        private void WriteBlnResponse(string requestPath,
                                      PropData data,
                                      Stream outputStream)
        {
            INode node = new SvnBlnNode(requestPath, int.Parse(requestPath.Substring(10)));

            using (StreamWriter writer = new StreamWriter(outputStream))
            {
                writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"DAV:\">\n");
                WriteProperties(node, data.Properties, writer);
                writer.Write("</D:multistatus>\n");
            }
        }

        private void WriteBcResponse(TFSSourceControlProvider sourceControlProvider,
                                     string requestPath,
                                     string depthHeader,
                                     PropData data,
                                     Stream outputStream)
        {
            int version = int.Parse(requestPath.Split('/')[3]);
            string path = requestPath.Substring(9 + version.ToString().Length);
            bool setTrunkAsName = false;

         //   if (!sourceControlProvider.ItemExists(Helper.Decode(path), version))
            if(!GetSDKObject().FileExists(Helper.Decode(path), version))
            {
                if (!IsSvnRequestForProjectCreation(path, version, sourceControlProvider))
                    throw new FileNotFoundException();
                path = "";
                setTrunkAsName = true;
            }

            FolderMetaData folderInfo = GetFolderInfo(sourceControlProvider, depthHeader, path, version, false);
            if (setTrunkAsName)
                folderInfo.Name = "trunk";

            using (StreamWriter writer = new StreamWriter(outputStream))
            {
                writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");

                WriteMultiStatusStart(writer, data.Properties);

                if (depthHeader == "1")
                {
                    INode node = new BcFileNode(version, folderInfo, sourceControlProvider);

                    WriteProperties(node, data.Properties, writer, folderInfo.ItemType == ItemType.Folder);
                }

                foreach (ItemMetaData item in folderInfo.Items)
                {
                    INode node = new BcFileNode(version, item, sourceControlProvider);

                    WriteProperties(node, data.Properties, writer, item.ItemType == ItemType.Folder);
                }

                writer.Write("</D:multistatus>\n");
            }
        }

        private void WritePathResponse(TFSSourceControlProvider sourceControlProvider,
                                       string requestPath,
                                       string depth,
                                       PropData data,
                                       Stream outputStream)
        {
         //   if (!sourceControlProvider.ItemExists(Helper.Decode(requestPath), -1))

            if(!GetSDKObject().FileExists(Helper.Decode(requestPath), -1))
            {
                throw new FileNotFoundException("Unable to find file '" + requestPath + "'in the source control repository",
                                                requestPath);
            }

            FolderMetaData folderInfo = GetFolderInfo(sourceControlProvider, depth, requestPath, null, true);

            using (StreamWriter writer = new StreamWriter(outputStream))
            {
                writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");

                WriteMultiStatusStart(writer, data.Properties);

                foreach (ItemMetaData item in folderInfo.Items)
                {
                    INode node = new FileNode(item, sourceControlProvider);

                    WriteProperties(node, data.Properties, writer, item.ItemType == ItemType.Folder);
                }

                writer.Write("</D:multistatus>\n");
            }
        }

        private void WriteWrkResponse(TFSSourceControlProvider sourceControlProvider,
                                       string requestPath,
                                       string depth,
                                       PropData data,
                                       Stream outputStream)
        {
            string activityId = requestPath.Split('/')[3];
            if (depth != "0")
            {
                throw new InvalidOperationException(String.Format("Depth not supported: {0}", depth));
            }
            string path = requestPath.Substring(11 + activityId.Length);
            // ItemMetaData item = sourceControlProvider.GetItemInActivity(activityId, Helper.Decode(path));
            ItemMetaData item = null;
            if (GetSDKObject().FileExists(Helper.Decode(path), -1))
            {
                item = new ItemMetaData();
                item.Name = path;
                item.ItemRevision = GetSDKObject().GetLastestVersionNum(item.Name);
                GetSDKObject().GetFileModifiedDate(item.Name, out item.LastModifiedDate);
            }

            if (item == null)
            {
                throw new FileNotFoundException("Unable to find file '" + path + "'in the specified activity", path);
            }

            using (StreamWriter writer = new StreamWriter(outputStream))
            {
                writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
                WriteMultiStatusStart(writer, data.Properties);
                INode node = new FileNode(item, sourceControlProvider);
                WriteProperties(node, data.Properties, writer, item.ItemType == ItemType.Folder);
                writer.Write("</D:multistatus>\n");
            }
        }

        private void WriteMultiStatusStart(TextWriter writer, List<XmlElement> properties)
        {
            if (properties.Count > 1 ||
               (properties.Count == 1 && properties[0].LocalName == "deadprop-count") ||
               (properties.Count == 1 && properties[0].LocalName == "md5-checksum"))
            {
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns1=\"http://subversion.tigris.org/xmlns/dav/\" xmlns:ns0=\"DAV:\">\n");
            }
            else
            {
                writer.Write("<D:multistatus xmlns:D=\"DAV:\" xmlns:ns0=\"DAV:\">\n");
            }
        }

        private void WriteProperties(INode node, List<XmlElement> properties, TextWriter output)
        {
            WriteProperties(node, properties, output, false);
        }

        private void WriteProperties(INode node, List<XmlElement> properties, TextWriter output, bool isFolder)
        {
            bool writeGetContentLengthForFolder = isFolder && PropertiesContains(properties, "getcontentlength");

            output.Write("<D:response xmlns:lp1=\"DAV:\"");
            if (!(properties.Count == 1 && properties[0].LocalName == "resourcetype"))
            {
                output.Write(" xmlns:lp2=\"http://subversion.tigris.org/xmlns/dav/\"");
            }
            if (writeGetContentLengthForFolder)
            {
                output.Write(" xmlns:g0=\"DAV:\"");
            }
            output.Write(">\n");
			output.Write("<D:href>" + Helper.UrlEncodeIfNeccesary(node.Href(this)) + "</D:href>\n");

            XmlDocument doc = new XmlDocument();
            List<string> propertyResults = new List<string>();

            foreach (XmlElement prop in properties)
            {
                XmlElement property = doc.CreateElement(prop.LocalName, prop.NamespaceURI);
                if (!(isFolder && prop.LocalName == "getcontentlength"))
                {
                    propertyResults.Add(node.GetProperty(this, property));
                }
            }

            output.Write("<D:propstat>\n");
            output.Write("<D:prop>\n");
            foreach (string propertyResult in propertyResults)
            {
                output.Write(propertyResult + "\n");
            }
            output.Write("</D:prop>\n");
            output.Write("<D:status>HTTP/1.1 200 OK</D:status>\n");
            output.Write("</D:propstat>\n");

            if (writeGetContentLengthForFolder)
            {
                output.Write("<D:propstat>\n");
                output.Write("<D:prop>\n");
                output.Write("<g0:getcontentlength/>\n");
                output.Write("</D:prop>\n");
                output.Write("<D:status>HTTP/1.1 404 Not Found</D:status>\n");
                output.Write("</D:propstat>\n");
            }

            output.Write("</D:response>\n");
        }

        private static bool PropertiesContains(IEnumerable<XmlElement> properties,
                                               string propertyName)
        {
            foreach (XmlElement property in properties)
            {
                if (property.LocalName == propertyName)
                {
                    return true;
                }
            }

            return false;
        }

        private bool IsSvnRequestForProjectCreation(string requestPath, int version, TFSSourceControlProvider sourceControlProvider)
        {
            requestPath = Helper.Decode(requestPath);

            bool isSvnPath = (requestPath.Equals("/trunk", StringComparison.OrdinalIgnoreCase)
                              || requestPath.Equals("/branches", StringComparison.OrdinalIgnoreCase)
                              || requestPath.Equals("/tags", StringComparison.OrdinalIgnoreCase));

            return true;
         //   return isSvnPath && version == sourceControlProvider.GetEarliestVersion(string.Empty);
        }
    }
}


text:
<?php
class SelectionTopic extends JY_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('topic_model', 'topic');
	}

	public function selectionTopicList() {
		$data['crumbs'] = $this->createCrumbs(array('selectiontopic/selectionTopicList' => '精选帖列表'));

		$pageSize = (int)$this->input->get('pageSize', TRUE);
		$pageNo =  (int)$this->input->get('pageNo', TRUE);
		$topicState =  (int)$this->input->get('topicState', TRUE);

		//默认值
		$pageNo = $pageNo <= 0 ? 1 : $pageNo;
		$pageSize = ($pageSize > 0 && $pageSize <= 50) ? $pageSize : 10;

		$pageInfo = $this->topic->getSelectionTopicList($pageSize, $pageNo, $topicState);

		if ($pageInfo) {
			$data['pageNo'] = $pageNo;
			$data['pageSize'] = $pageSize;
			$data['topicState'] = $topicState;
			$data['selectionTopicList'] = $pageInfo['selectionTopicList'];
			$data['totalPages'] = $pageInfo['totalPages'];
		}

		$data['pageUrl'] = "/selectionTopic/selectionTopicList?";
		if (isset($topicState)) $data['pageUrl'] .= 'topicState=' . $topicState;
		$this->load->view('selectionTopicList', $data);
	}

	public function reserveTopicList() {
		$data['crumbs'] = $this->createCrumbs(array('selectiontopic/reserveTopicList' => '预约精选列表'));

		$pageSize = (int)$this->input->get('pageSize', TRUE);
		$pageNo =  (int)$this->input->get('pageNo', TRUE);
		$isSend = (int)$this->input->get('isSend', TRUE);

		$redis = $this->createRedis('action');
		$isOpen = (int)$redis->get('selectionTopic:reserve:open');
		$redis->close();

		//默认值
		$pageNo = $pageNo <= 0 ? 1 : $pageNo;
		$pageSize = ($pageSize > 0 && $pageSize <= 50) ? $pageSize : 10;

		$pageInfo = $this->topic->getReserveTopicList($pageSize, $pageNo, $isSend);

		if ($pageInfo) {
			$data['pageNo'] = $pageNo;
			$data['pageSize'] = $pageSize;
			$data['isOpen'] = $isOpen;
			$data['isSend'] = $isSend;
			$data['reserveTopicList'] = $pageInfo['reserveTopicList'];
			$data['totalPages'] = $pageInfo['totalPages'];
		}

		$data['pageUrl'] = "/selectionTopic/reserveTopicList?";
		$data['pageUrl'] .= "isSend=$isSend";
		$this->load->view('reserve/reserveTopicList', $data);
	}

	public function doSendAction() {
		$setOpen = (int)$this->input->get('setOpen', TRUE);

		$redis = $this->createRedis('action');
		$result = $redis->set('selectionTopic:reserve:open', $setOpen);
		if ($result) {
			echo "0";
		} else {
			echo "999";
		}
	}

	/*public function saveSelectionTopic() {

		$topicID = (int)$this->input->post('topicID', TRUE);
		$locIdx = (int)$this->input->post('locIdx', TRUE);
		$offlineTime = $this->input->post('offlineTime', TRUE);
		$onlineTime = $this->input->post('onlineTime', TRUE);

		$errorMessage = array();

		$check = $this->checkJumpID(4, $topicID);
		$isExistTopicID = $this->topic->isExistSelectionTopicID($topicID);
		if ($check !== TRUE) {
			array_push($errorMessage, array('messageText' => $check));
			$data['message'] = array('error' => $errorMessage);
		} else if ($isExistTopicID) {
			array_push($errorMessage, array('messageText' => '不能插入已经存在的帖子ID'));
			$data['message'] = array('error' => $errorMessage);
		} else if ($locIdx <= 0 || $locIdx >= 51) {
			array_push($errorMessage, array('messageText' => '插入的位置不正确'));
			$data['message'] = array('error' => $errorMessage);

		} else if (strtotime($offlineTime) < time() || strtotime($offlineTime) < strtotime($onlineTime)) {
			array_push($errorMessage, array('messageText' => '失效时间设置错误'));
			$data['message'] = array('error' => $errorMessage);
		} else {

			$data['topicID'] = $topicID;
			$data['onlineTime'] = $onlineTime;
			$data['offlineTime'] = $offlineTime;
			$data['addTime'] = date('Y-m-d H:i:s');
			$data['locIdx'] = $locIdx;

			$result= $this->topic->saveSelectionTopic($data);

			if ($result) {
				array_push($errorMessage, array('messageText' => '保存成功!'));
				$data['message'] = array('success' => $errorMessage);
			} else {
				array_push($errorMessage, array('messageText' => '提交失败!'));
				$data['message'] = array('error' => $errorMessage);
			}

		}
		$this->load->view('message', $data);
	}*/

	public function deleteSelectionTopic() {

		$id = (int)$this->input->get('id', TRUE);
		$result = $this->topic->deleteSelectionTopic($id);
		if ($result) {
			echo "0";
		} else {
			echo "999";
		}

	}

	public function deleteReserveTopic() {
		$id = (int)$this->input->get('id', TRUE);
		$result = $this->topic->deleteReserveTopic($id);
		if ($result) {
			echo "0";
		} else {
			echo "999";
		}
	}

	/*public function editSelectionTopic() {
		$data['crumbs'] = $this->createCrumbs(array('message/msgEdit' => '编辑精选贴'));
		$this->load->view('selectionTopicEdit', $data);
	}*/

	public function setSelectionTopicState() {
		$state = (int)$this->input->get('state', TRUE);
		$id = (int)$this->input->get('id', TRUE);
		if ($id > 0) {
			$result = $this->topic->setTopicSelectState($id, $state);
			if ($result) {
				echo "0";
			} else {
				echo "999";
			}
		} else {
			echo "777";
		}
	}

}


text:
package com.drug.platform.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * Created by Yaochao on 2015/7/14.
 */
public class BytesHelper {

    /**
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     *
     * @param hexStr
     * @return
     */
    public static byte[] hexToBytes(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static byte[] readFromInputStream(InputStream inputStream) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int n = 0;
        while ((n = inputStream.read(buf)) > 0) {
            out.write(buf, 0, n);
        }
        out.flush();
        out.close();
        return out.toByteArray();
    }
}


text:
layout: post
title:  "Mart Bülteni: Öne çıkan Konuşmacıları Duyurmaya Devam Ediyoruz"
date:   2015-02-17 09:00:00
isStaticPost: false
---

Mart bültenine hoş geldiniz :) Bu bültende sizlere gelişmelerden bahsedeceğiz. Ayrıca bazı ücretsiz Android programlama kaynakları ve siteleri paylaşacağız.

* [Turkcell Geleceği Yazanlar Android Eğitimleri](https://gelecegiyazanlar.turkcell.com.tr/konu/android)
* [Programlama Defteri:](http://www.programlamadefteri.com/android-programlama-dersleri) Android geliştirme ortamının kurulumu, ilk Android uygulaması geliştirme, Listview, Özel Listview, SQLLite veritabanı işlemleri gibi konuların anlatıldığı 17 dersin olduğu bir site.
* [Androidce:](http://androidce.blogspot.com.tr/) Yeni başlayanlar için bir çok blog yazısı olan bir site.
* [Unity 3D Android Oyun Yapımı](https://www.youtube.com/watch?v=2xxqCefW2g4) anlatan bir video dersi.
* [Android ile ilgili 21 adet video dersi](https://www.youtube.com/playlist?list=PL5Kp8m5lL8isKrO52KYH5DR6BylEZKc1C)
* [Android Uygulamalı Dersler ve Bilgi Paylaşım Platformu](http://www.androidevreni.com/)
* [Android Weekly:](http://androidweekly.net/) Her hafta seçilmiş Android ile ilgili blog yazıların paylaşıldığı ve açık kaynak kütüphanelerin tanıtıldığı platform.
* [Android ikon oluşturucu:](http://romannurik.github.io/AndroidAssetStudio/icons-launcher.html) Hazır Android ikonlarını kolayca değişik boyutlarda oluşturun.
* [TechnoTalkative:](http://www.technotalkative.com/) Çeşitli Android programlama ile ilgili yazıların olduğu bir site.
* [Codepath Android:](https://github.com/codepath/android_guides/wiki) Android için güzel bir kaynak.

Etkin katılım çağrısı hala açık. [Buradan]({{ site.baseurl }}/blog/share-your-knowledge-and-experience-in-add/) konuşmacı olmak için başvurabilirsiniz.

Sizi dinliyoruz. ADD'de ne görmek istiyorsunuz? Lütfen düşünce ve önerilerinizi [bu form](https://docs.google.com/forms/d/16RB2PM-ifAxv4HqTOXWO72DlgYEEWc0f9SB921smTBs/viewform) ile paylaşın.

AGG'ye kayıt olan katılımcı sayısı **1175**'yi geçti. Kayıt olmak için acele edin ve [bu form](http://www.eventbrite.com/e/android-developer-days-2015-registration-14846274607) doldurun. Katılım hala ücretsiz :)

    Mobil ve web geliştiricisi olan Tim Messerschmidt,  bunun yanısıra Braintree'de  Geliştirici İlişkilerinin Başkanı olarak bilgi ve tecrübelerini paylaşıyor. Birçok start up  inkübatör ve hızlandırıcı oluşumunda danışmanlık yapan Tim'in  tutkusu start uplar.Tim Paypal 'a katılmadan önce Neofonie ve Samsung da birçok mobil projeye odaklandı. Boş zamanlarında geliştirici odaklı konularda çalışma grupları  kurup yönlendiren Tim aynı zamanda açık kaynak projelere de katkı sağlıyor. The Mobile Developer's Guide to the Galaxy yazarlarından biri olan Tim'in bunlara ek olarak dergilerde bir çok makalesi bulunmaktadır.

	Abhisek Devkota CyanogenMod kurucularının yürüttüğü Cyanogen Inc.'de proje ve topluluk yöneticisidir. CyanogenMod projesi son kullanıcılara daha fazla güvenlik, özelleştirme ve fonksiyonellik sunmayı amaçlayan, tüm dünyadan gönüllü geliştiriciler tarafından yürütülen açık kaynak bir dağıtımdır.

    UX ve Design tutkusu olan Wiebe Elsinga bir Android geliştiricisi olmakla beraber, android üzerine bir  GDE (Google Developer Expert) olarak kabul edilmiştir. GDG Dutch Android Kullanıcı grubu organizatörlerinden biri olan Wiebe Itude Mobile şirketinde çalışmaktadır.  Temelde bir EntrepreNerd olmakla beraber, mobil uygulama geliştirme ve dizayn üzerine odaklanmıştır.

	Markus Eisele, Red Hat'de Geliştirici Savunucusu olarak çalışmaktadır ve JBoss Middleware konusuna odaklanmıştır.14 yıldan fazla bir zamandır değişik sağlayıcılardan Java EE sunucuları ile çalışmaktadır ve dünyanın değişik yerlerinde Java EE konuları üzerine konferanslarda sunumlar yapmaktadır. Kendisi baş danışman olarak değişik müşteriler ile  Java EE uygulamaları ve çözümleri üzerine çalışmıştır. Ayrıca üretken bir blogcu,yazar ve Java EE konuları üzerine değişik kitaplarda teknik editördür. German DOAG e.V. aktif üyelerindendir ve iJUG e.V. temsilcidir. Toplulukta Java Şampiyonu olarak bilinmektedir.

	Cyril Mottier, Captain Train'de yazılım mühendisidir ve Android Google Geliştirici Uzmanıdır. Dizayn ve teknoloji konularında tutkuludur, Android'i çok sever ve çok  yetenekli bir mühendistir. Android topluluklarında aktif olarak yer almaktadır ve  bilgilerini blog yazarak, açık kaynak kodlu projeler geliştirerek ve konuşmalar yaparak paylaşmaktadır. Sloganı: Az ama çok iyi yap

    Prajyot Mainkar Hindistandaki app engineering üzerine bir firma olan  Androcid Media Pvt. de çalışmaktadır. Hindistandaki en eski gruplardan olan Goa Android Kullanıcı Grubu Organizatörüdür. Android Geliştirici olan Prajyot Droidcon India,GDG Devfest, Silcon India Mobile  da dahil olmak üzere pek çok konferansa konuşmacı olarak katılmıştır. Android topluluğunda aktif rol almakla beraber, Android geliştiricileri yeni,rekabetçi ve iyi uygulamalar geliştirmeleri için yönlendirmektir. Droidcon India,GDG Devfest,Silicon India Mobile Conference gibi bir çok etkinlikte konuşmacı olmuştur.

    Orhan Obut, Berlin'de Rocket-Internet'de android gelistiricisi olarak calismaktadir. Android development ve acik-kaynak konusunda oldukca hevesli oldugundan, bu konularda kendini mumkun oldugu kadar gelistirmeye calismaktadir. Acik-kaynak konusunda da surekli olarak destek vermektedir. Mobil alisveristen mobil bankaciliga cesitli bir cok konuda gelistirme yapmistir. Surekli olarak yazilim prensiplerini, en iyi pratiklerini uygulamayi ve ogrendiklerini de digerleriyle paylasmayi hedeflemektedir.

AGG'yi destekleyen [sponsorlar]({{ site.baseurl }}/sponsors) sayısı 28'e ulaştı. Sponsor olma fırsatını kaçırmayın.

AGG'yi bir blog yazısı veya istediğiniz bir şekilde destekleyebilirsiniz. Yaptığınızda bize haber verin ve logonuzu destekleyenler arasına koyalım.

2.indir.com Mobil Uygulama Ödülleri finalistleri uygulamalarını Android Geliştirici Günleri'nde tanıtacaklar. Yarışmaya başvurular hala açık ve 20 Nisan başvurular için son gün. Kazananlar 23 Mayıs'ta indir.com tarafından Bahçeşehir Üniversitesi'nde düzenlenecek olan Mobil Etkinlikte duyurulacaktır. Kazanlara bir çok güzel ödül verilecektir. Detaylar için [burayı](http://www.indir.com/yarisma/) tıklayınız.

Organizatör GDG sayısı 57'ye ulaştı.[Organizatörler]({{ site.baseurl }}/organizers) dünyanın bir çok değişik şehir ve ülkesinden.

#####Sponsorlar
Güncel sponsorlar için lütfen bu sayfaya[bu sayfaya]({{ site.baseurl }}/sponsors) bakın. Tüm sponsorlar haber bülteninin email versiyonunda burada listelenmektedir.


text:
"""Constants for reference_checkpoint."""

from ml_collections import config_dict

from diplomacy.environment import province_order
from diplomacy.network import network

def get_config() -> config_dict.ConfigDict:
  """Returns network config."""
  config = config_dict.ConfigDict()
  config.network_class = network.Network
  config.network_kwargs = config_dict.create(
      rnn_ctor=network.RelationalOrderDecoder,
      rnn_kwargs=dict(
          adjacency=network.normalize_adjacency(
              province_order.build_adjacency(
                  province_order.get_mdf_content(
                      province_order.MapMDF.STANDARD_MAP))),
          filter_size=64,
          num_cores=4,
      ),
      name="delta",
      num_players=7,
      area_mdf=province_order.MapMDF.BICOASTAL_MAP,
      province_mdf=province_order.MapMDF.STANDARD_MAP,
      is_training=False,
      shared_filter_size=160,
      player_filter_size=160,
      num_shared_cores=12,
      num_player_cores=3,
      value_mlp_hidden_layer_sizes=(256,),
      actions_since_last_moves_embedding_size=10)
  return config


text:
package com.intel.analytics.bigdl.dllib.utils.tf.loaders

import java.nio.ByteOrder

import com.intel.analytics.bigdl.Module
import com.intel.analytics.bigdl.dllib.nn.{Pack => PackOps}
import com.intel.analytics.bigdl.dllib.nn.abstractnn.{AbstractModule, Activity}
import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.dllib.utils.tf.Context
import org.tensorflow.framework.NodeDef

import scala.reflect.ClassTag

class Pack extends TensorflowOpsLoader {
  override def build[T: ClassTag](nodeDef: NodeDef, byteOrder: ByteOrder,
    context: Context[T])(implicit ev: TensorNumeric[T]): Module[T] = {
    val dim = nodeDef.getAttrMap.get("axis").getI.toInt + 1
    PackOps[T](dim).asInstanceOf[AbstractModule[Activity, Activity, T]]
  }
}


text: litte part of my dev'life


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Ellipse Tests</title>
    <link rel="stylesheet" href="../../lib/qunit/qunit.css">