text:
<?php
namespace api\modules\v1\controllers;
use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use api\modules\v1\models\Country;
use api\modules\v1\models\WatchUser;
use yii\db\Exception;
use api\util\DataService;
use common\models\WatchUserRegister;
use yii\helpers\Json;
use common\models\WatchUserInfo;

use yii\helpers\FileHelper;

class UserDeviceController extends ActiveController
{
    public $modelClass = 'api\modules\v1\models\WatchUser';
    private $appid = "10103";
    private $appkey = "m2wCuSkTXkqZqMny";

    public function actions() {

    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        #定义返回格式是:JSON
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actionSearch(){
//         Yii::error('test','api');

        $post = Yii::$app->request->post();
        $one = null;
        if (isset($post['name'])){
            $one = Country::findOne(['code'=>$post['name']]);
        }
        return $one;
    }

    /**
     * 接收米家转发的数据
     */
    public function actionReceiveData(){
        $request = Yii::$app->request;
        $path = isset( $_SERVER ['REQUEST_URI'] ) ? $_SERVER ['REQUEST_URI'] : '';
        $nonce = $_REQUEST["_nonce"];
        $method = $request->method;
        $dataStr = isset( $_REQUEST ['data'] ) ? $_REQUEST['data'] : '';
        $didStr = isset( $_REQUEST ['did'] ) ? "&did={$_REQUEST['did']}" : '';
        $signature = $_REQUEST['signature'];
        $dataService = new DataService($this->appid, $this->appkey);
        $jsonstr = $dataService->decrypt($_REQUEST['data'],$path,$signature,$nonce,$method,$didStr);
//         $jsonstr = '{"create_time":1501637897870,"data":{"did":"blt.3.ofr2qom48400","key":"steps","time":1501603200,"type":"user_info","uid":430208357,"value":"{\"count\":1179,\"end\":1501637771,\"start\":1501603200}"},"id":"2672916397","type":"set_user_device_data"}';
        $dataArray = Json::decode($jsonstr, true);
        //log data
        if (YII_ENV_PROD){
            //写入原始接口数据
            $this->writeApiData($jsonstr);
//             $logPath = Yii::getAlias('@app').'/userdata.html';
//             file_put_contents($logPath, date('Y-m-d H:i:s')."===".$jsonstr."\r\n
", FILE_APPEND|LOCK_EX);
        }
        $result = [
            'code'=>0,
            'result'=>[],
            'message'=>'ok'
        ];

        $data = $dataArray['data'];
        $value = null;
        if (isset($data['value']))
            $value = is_array($data['value']) ? $data['value'] : Json::decode(stripslashes($data['value']),true);
        //执行事务
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();

        //设备注册信息
        if (isset($data['key']) && $data['key'] == 'user_register'){
            if (!empty($value)){
//                 $register = is_array($data['value']) ? $data['value'] : Json::decode(stripslashes($data['value']),true);
                $watchRegister = new WatchUserRegister();
                $watchRegister->uid = $data['uid'];
                $watchRegister->did = $data['did'];
                $watchRegister->register_time = $value['time'];
                $watchRegister->save();
            }
        }

        //保存用户信息
        if (isset($data['key']) && $data['key'] == 'user'){
            if (!empty($value)){
                try {
                    //$value = is_string($data['value']) ? Json::decode(stripslashes($data['value']),true) : $data['value'];
                    $user = WatchUserInfo::findOne(['uid' => $data['uid']]);
                    if (!$user){
                        $user = new WatchUserInfo();
                        $user->uid = $data["uid"];
                        $user->create_at = $data['time'];
                    }
                    $user->weight = $value['weight'];
                    $user->height = $value['height'];
                    $user->gender = $value['gender'];
                    $user->birth = $value['birth'];
                    $user->update_at = $data['time'];
                    $user->save();
                    /* $user = $db->createCommand('
                    INSERT INTO watch_user_info (uid,weight,height,gender,birth,update_at)
                    VALUES (:uid,:weight,:height,:gender,:birth,:update_at)
                    ON DUPLICATE KEY UPDATE weight = :weight,height = :height,gender = :gender,birth = :birth,update_at = :update_at', [
                                    ':uid' => $data['uid'],
                                    ':weight' => $value['weight'],
                                    ':height' => $value['height'],
                                    ':gender' => $value['gender'],
                        ':birth' => $value['birth'],
                        ':update_at' => $data['time']
                    ]);
                    //file_put_contents($logPath, date('Y-m-d H:i:s')."===".$user->getRawSql()."\r\n
", FILE_APPEND|LOCK_EX);
                    $user->execute(); */
                } catch (Exception $e){
                    Yii::error($e->errorInfo,'db');
                }
            }
        }
        try {
            foreach ($data as $k => $val) {
                if (is_numeric($k)) {
                    $value = $val['value'];
                    $value =  is_array($value) ? Json::encode($value) : $value;
                    $db->createCommand()
                        ->insert(WatchUser::tableName(), [
                        'uid' => $val['uid'],
                        'did' => $val['did'],
                        'data_key' => $val['key'],
                        'type' => $val['type'],
                        'value' => empty($value) ? "" : $value, //is_string($value) ? $value : Json::encode($value)
                        'timeAt' => $val['time']
                    ])->execute();
                } else {
                    $value = is_array($value) ? Json::encode($value) : $value;
                    $query = $db->createCommand()
                        ->insert(WatchUser::tableName(), [
                        'uid' => $data['uid'],
                        'did' => $data['did'],
                        'data_key' => $data['key'],
                        'type' => $data['type'],
                        'value' => empty($value) ? "" : $value,
                        'timeAt' => $data['time']
                    ])->execute();
                    break;
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $result['code'] = $e->getCode();
            $result['message'] = array_pop($e->errorInfo);
            Yii::error($e->errorInfo,'db');
            $transaction->rollBack();
        }

        return $dataService->encryptData(Json::encode($result));
    }

    public function writeApiData($jsonstr) {
        $base = Yii::getAlias("@api/log/apidata");
        $filepath =$base . DIRECTORY_SEPARATOR . date('Y-m-d') . '.txt';
        if(!is_dir($base)){
            FileHelper::createDirectory($base);
        }

        file_put_contents($filepath, date('Y-m-d H:i:s')."===".$jsonstr."\n\r
", FILE_APPEND|LOCK_EX);
    }
}


text:
angular.module('app',['ngTouch','textAngular','colorpicker.module']).controller("MainCtrl",
		[ '$scope', function($scope) {

		} ]);

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace App\Handlers\MateyUser;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * Created by PhpStorm.
 * User: marko
 * Date: 30.11.16.
 * Time: 02.00
 */
interface UserHandlerInterface
{
    public function handleGetUser(Application $app, Request $request, $id);
    public function handleFollow(Application $app, Request $request, $id);
    public function handleGetConnections(Application $app, Request $request, $id, $type);
}


text:
-   [Overview](../../overview-summary.html.md)
-   Package

-   [FRAMES](../../index.html.md)
-   [NO FRAMES](package-summary.html.md)

Package examples.options
------------------------

| Class Summary                                     |
|---------------------------------------------------|
| [BookBean](BookBean.html.md)                         |
| [PrepareOptionsAction](PrepareOptionsAction.html.md) |
| [ProcessOptionsAction](ProcessOptionsAction.html.md) |

-   [Overview](../../overview-summary.html.md)
-   Package

-   [FRAMES](../../index.html.md)
-   [NO FRAMES](package-summary.html.md)

------------------------------------------------------------------------

Copyright © 2000-2008 Apache Software Foundation. All Rights Reserved.


text:
from django.conf import settings
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^new/', views.new_score_entry),
    url(r'^list/', views.get_score_list)
]


text:
package org.knowm.xchange.mercadobitcoin.service.marketdata;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.mercadobitcoin.MercadoBitcoinExchange;
import org.knowm.xchange.service.marketdata.MarketDataService;

/** @author timmolter */
public class TickerFetchIntegration {

  @Test
  public void tickerFetchTest() throws Exception {

    Exchange exchange =
        ExchangeFactory.INSTANCE.createExchange(MercadoBitcoinExchange.class.getName());
    MarketDataService marketDataService = exchange.getMarketDataService();
    Ticker ticker = marketDataService.getTicker(new CurrencyPair("BTC", "BRL"));
    System.out.println(ticker.toString());
    assertThat(ticker).isNotNull();
  }
}


text:
package com.leo.cattle.data.entity;

import com.google.gson.annotations.SerializedName;

/**
 * Created by leobui on 3/16/2016.
 */
public class ChatSessionEntity {
    @SerializedName("id")
    private int id;
    @SerializedName("name")
    private String name;
    @SerializedName("ownerId")
    private int ownerId;
    @SerializedName("status")
    private int status;
    @SerializedName("topic")
    private String topic;
    @SerializedName("type")
    private int type;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(int ownerId) {
        this.ownerId = ownerId;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Elasticsearch.Net;

namespace Nest
{
	public partial class ElasticClient
	{
		/// <inheritdoc />
		public IBulkResponse DeleteMany<T>(IEnumerable<T> @objects, string index = null, string type = null) where T : class
		{
			@objects.ThrowIfEmpty("objects");
			return this.Bulk(b => b.FixedPath(index, type).DeleteMany(@objects));
		}

		/// <inheritdoc />
		public Task<IBulkResponse> DeleteManyAsync<T>(IEnumerable<T> objects, string index = null, string type = null)
			where T : class
		{
			@objects.ThrowIfEmpty("objects");
			return this.BulkAsync(b => b.FixedPath(index, type).DeleteMany(@objects));
		}
	}
}


text:
<?php

$chat = erLhcoreClassChat::getSession()->load( 'erLhcoreClassModelChat', $Params['user_parameters']['chat_id']);

$currentUser = erLhcoreClassUser::instance();

if (!$currentUser->validateCSFRToken($Params['user_parameters_unordered']['csfr'])) {
	die('Invalid CSRF Token');
	exit;
}

CSCacheAPC::getMem()->removeFromArray('lhc_open_chats', $chat->id);

if ($currentUser->hasAccessTo('lhchat','deleteglobalchat') || ($currentUser->hasAccessTo('lhchat','deletechat') && $chat->user_id == $currentUser->getUserID()))
{
	erLhcoreClassChatEventDispatcher::getInstance()->dispatch('chat.delete',array('chat' => & $chat,'user' => $currentUser));
	$chat->removeThis();
}

header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;

?>


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('questions', '0005_useranswer'),
    ]

    operations = [
        migrations.AddField(
            model_name='useranswer',
            name='my_points',
            field=models.IntegerField(default=-1),
        ),
        migrations.AddField(
            model_name='useranswer',
            name='their_points',
            field=models.IntegerField(default=-1),
        ),
    ]


text:
'use strict';

var Base = require('../ModouTask');
var logger = require('terminal-task-runner').logger;
var Q = require('terminal-task-runner').Q;

var list_plugins = '/api/plugin/installed_plugins';
var stop_plugin = '/api/plugin/stop_plugin';

var endswith = function(src, str) {
    var reg = new RegExp(str + '$');
    return reg.test(src);
};

var Task = Base.extend({
    operTxt: '',
    api: '',
    status: false,
    run: function(cons) {

        var _this = this;

        var listPromise = this.doModou(this.ajaxGet(list_plugins));

        listPromise.success(function(resp) {
            var plugins = resp.data.plugins;

            var stopped = plugins.filter(function(plugin) {
                return plugin.isRunning === _this.status;
            });

            if (stopped.length === 0) {
                logger.warn('您没有任何插件需要' + _this.operTxt);
                cons();
                return;
            }

            stopped.forEach(function(plugin) {
                plugin.value = plugin.id;
            });
            _this.prompt([{
                type: 'checkbox',
                name: 'ids',
                message: '选择需要' + _this.operTxt + '的插件',
                choices: stopped
            }], function(answer) {
                    if (!answer.ids || !answer.ids.length) {
                        logger.warn('您没有选中任何插件');
                        cons();
                        return;
                    }

                    var promises = answer.ids.map(function(plugin) {
                        return _this.doModou(_this.ajaxPost(_this.api, {
                            id: plugin
                        }));
                    });

                    Q.all(promises).then(function() {
                        cons();
                    }, function(err) {
                            cons(err.msg);
                        });
                });

        });

        listPromise.error(function(err) {
            if (err === 'GEEKDISABLED') {
                cons('极客模式尚未开启,请先启动魔豆路由上的极客模式');
                return;
            }
            if (err === 'PASSWORDERROR') {
                cons('尝试登录失败,请重试...');
                return;
            }
        });

    }
});

module.exports = Task;


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title></title>
			<link rel="stylesheet" href="media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

Root class CodeGenerator

CodeGenerator

Root class DeclaredClass

DeclaredClass

Root class FakeObjectGenerator

FakeObjectGenerator

Root class ReturnValuesManager

ReturnValuesManager

		Documentation generated on Thu, 28 May 2009 17:33:40 +0200 by phpDocumentor 1.4.2


text:
require File.join(File.dirname(__FILE__), 'spec_helper.rb')

describe Attributor::Type do

  subject(:test_type) do
    Class.new do
      include Attributor::Type
      def self.native_type
        ::String
      end

      def self.name
        'Testing'
      end

      def self.family
        'testing'
      end
    end
  end

  let(:attribute_options) { Hash.new }
  let(:attribute_attributes) { Hash.new }

  let(:attribute) do
    double "attribute",
      :options => attribute_options,
      :attributes => attribute_attributes
  end

  its(:native_type) { should be(::String) }
  its(:id) { should eq('Testing')}

  context 'load' do
    let(:value) { nil }
    let(:context) { nil }

    context "when given a nil value" do
      it 'always successfully returns it (i.e., you can always load nil)' do
        test_type.load(value).should be(value)
      end
    end

    context "when given a value that is of native_type" do
      let(:value) { "one" }
      it 'returns the value' do
        test_type.load(value).should be(value)
      end
    end

    context "when given a value that is not of native_type" do
      let(:value) { 1 }
      let(:context) { ['top','sub'] }

      it 'raises an exception' do
        expect { test_type.load(value,context) }.to raise_error( Attributor::IncompatibleTypeError, /cannot load values of type Fixnum.*while loading top.sub/)
      end

    end

  end

  context 'validate' do
    let(:context) { ['some_attribute'] }

    let(:attribute_options) { {} }

      let(:attribute) { double("some_attribute", :options => attribute_options)}
      subject(:errors) { test_type.validate(value, context, attribute) }

    context 'min and max' do
      let(:min) { 10 }
      let(:max) { 100}

      let(:attribute_options) { {:min => min, :max => max} }

      context "with a value <= min" do
        let(:value) { 1 }

        it { should_not be_empty }
        it 'returns the correct error message' do
          errors.first.should =~ /value \(#{value}\) is smaller than the allowed min/
        end
      end

      context "with a value >= max" do
        let(:value) { 1000 }
        it { should_not be_empty }
        it 'returns the correct error message' do
          errors.first.should =~ /value \(#{value}\) is larger than the allowed max/
        end

      end

      context 'with a value within the range' do
        let(:value) { 50 }
        it { should be_empty }
      end

    end

     context 'regexp' do
      let(:regexp) { /dog/ }
      let(:attribute_options) { {:regexp => regexp} }

      context 'with a value that matches' do
        let(:value) { 'bulldog' }

        it { should be_empty }
      end

      context 'with a value that does not match' do
        let(:value) { 'chicken' }
        it { should_not be_empty}
        it 'returns the correct error message' do
          errors.first.should =~ /value \(#{value}\) does not match regexp/
        end
      end

     end

  end

  context 'example' do

  end

  context 'id' do
    it 'works for built-in types' do
      Attributor::String.id.should eq('Attributor-String')
    end

    it 'returns nil for anonymous types' do
      type = Class.new(Attributor::Model)
      type.id.should eq(nil)
    end
  end

  context 'describe' do
    let(:example){ "Foo" }
    subject(:description) { test_type.describe }
    it 'outputs the type name' do
      description[:name].should eq(test_type.name)
    end
    it 'outputs the type id' do
      description[:id].should eq(test_type.name)
    end

    context 'with an example' do
      subject(:description) { test_type.describe(example: example) }
      it 'includes it in the :example key' do
        description.should have_key(:example)
        description[:example].should be(example)
      end
    end

  end

end


text:
package com.intellij.ide.navigationToolbar;

import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import consulo.util.dataholder.Key;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.ScrollingUtil;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import javax.annotation.Nonnull;

import javax.annotation.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;

/**
* @author Konstantin Bulenkov
*/
class NavBarListWrapper extends JBScrollPane implements DataProvider {
  private static final int MAX_SIZE = 20;
  private final JList myList;

  public NavBarListWrapper(final JList list) {
    super(list);
    list.addMouseMotionListener(new MouseMotionAdapter() {
      boolean myIsEngaged = false;
      @Override
      public void mouseMoved(MouseEvent e) {
        if (myIsEngaged && !UIUtil.isSelectionButtonDown(e)) {
          final Point point = e.getPoint();
          final int index = list.locationToIndex(point);
          list.setSelectedIndex(index);
        } else {
          myIsEngaged = true;
        }
      }
    });

    ScrollingUtil.installActions(list);

    final int modelSize = list.getModel().getSize();
    setBorder(BorderFactory.createEmptyBorder());
    if (modelSize > 0 && modelSize <= MAX_SIZE) {
      list.setVisibleRowCount(0);
      getViewport().setPreferredSize(list.getPreferredSize());
    } else {
      list.setVisibleRowCount(MAX_SIZE);
    }
    myList = list;
  }

  @Override
  @Nullable
  public Object getData(@Nonnull @NonNls Key<?> dataId) {
    if (PlatformDataKeys.SELECTED_ITEM == dataId){
      return myList.getSelectedValue();
    }
    if (PlatformDataKeys.SELECTED_ITEMS == dataId){
      return myList.getSelectedValues();
    }
    return null;
  }

  @Override
  public void setBorder(Border border) {
    if (myList != null){
      myList.setBorder(border);
    }
  }

  @Override
  public void requestFocus() {
    IdeFocusManager.getGlobalInstance().doForceFocusWhenFocusSettlesDown(myList);
  }

  @Override
  public synchronized void addMouseListener(MouseListener l) {
    myList.addMouseListener(l);
  }
}


text:
const setup = require("./packages/test-helpers/lib/index");

module.exports = setup;


text:
package ua.romenskyi.webapp.shopping.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import ua.romenskyi.webapp.shopping.config.CurrentUser;
import ua.romenskyi.webapp.shopping.domain.users.User;

/**
 * @author dmytro.romenskyi - Jun 29, 2016
 *
 */
@Controller
@RequestMapping(path="/imports", method=RequestMethod.GET)
public class ImportsController {

	@RequestMapping(path="/{importName}")
	public ModelAndView getImport(@PathVariable String importName,
									@RequestParam(name="pageTitle", required=false) String title,
									@RequestParam(name="root", defaultValue="false") String root,
									ModelAndView mv,
									@CurrentUser User user) {
		mv.addObject("pageTitle", title);
		mv.addObject("root", root);
		mv.addObject("currentUser", user);
		mv.setViewName("imports/" + importName);

		return mv;
	}

	@RequestMapping(path="/modals/{modalName}")
	public ModelAndView getModal(@PathVariable String modalName,
								  ModelAndView mv,
								  @CurrentUser User user) {

		mv.addObject("currentUser", user);
		mv.setViewName("imports/modals/" + modalName);

		return mv;
	}
}


text:
@echo off
echo WARNING: This batch file performs unconfirmable uninstallation of possible existing Tundra 2 installation.
echo Close the window if you wish to abort.
pause
chcp 1252
SET ORIG_PATH=%CD%
SET TUNDRA_PATH=""
IF EXIST "C:\Program Files (x86)\Tundra 2.0\Tundra.exe" GOTO ProgFilesx86
IF EXIST "C:\Program Files\Tundra 2.0\Tundra.exe" GOTO ProgFiles
echo Previous Tundra installation not found from Program Files. Skipping uninstallation phase.
GOTO Install

:ProgFilesx86
set TUNDRA_PATH="C:\Program Files (x86)\Tundra 2.0"
GOTO Uninstall

:ProgFiles
set TUNDRA_PATH="C:\Program Files\Tundra 2.0"
GOTO Uninstall

:Uninstall
echo Unistalling previous Tundra installation...
%TUNDRA_PATH%\uninstaller.exe /S
GOTO Install

:Install
pushd \\ServerAddress\TundraInstallerFolder\
copy realXtend-Tundra-2.0.exe %ORIG_PATH%
popd
realXtend-Tundra-2.0.exe
del realXtend-Tundra-2.0.exe


text:
package eu.qualimaster.families.inf;

import java.io.Serializable;
import eu.qualimaster.base.algorithm.IFamily;
import eu.qualimaster.base.algorithm.IDirectGroupingInfo;

/**
 * Defines the interface for the algorithm family "IFFinancialNetworkExtraction" (GEN).
 */
public interface IFFinancialNetworkExtraction extends IFamily{

    /**
     * Defines the data input interface for the {@link IIFFinancialNetworkExtractionAnalysisInput} algorithm (over all defined input tuples).
     */
    public static interface IIFFinancialNetworkExtractionAnalysisInput extends Serializable {

        /**
         * Returns the input value for tuple field "status".
         * @return the tuple value
         */
        public twitter4j.Status getStatus();

        /**
         * Changes the output value for tuple field "status".
         * @param status the field value
         */
        public void setStatus(twitter4j.Status status);
    }

    /**
     * Defines the data output interface for the {@link IIFFinancialNetworkExtractionAnalysisOutput} algorithm (over all defined output tuples).
     */
    public static interface IIFFinancialNetworkExtractionAnalysisOutput extends Serializable, eu.qualimaster.base.algorithm.IOutputItem<IIFFinancialNetworkExtractionAnalysisOutput>, IDirectGroupingInfo {

        /**
         * Returns the input value for tuple field "edges".
         * @return the tuple value
         */
        public java.util.List<eu.qualimaster.families.datatypes.financialnetwork.IFEdge> getEdges();

        /**
         * Changes the output value for tuple field "edges".
         * @param edges the field value
         */
        public void setEdges(java.util.List<eu.qualimaster.families.datatypes.financialnetwork.IFEdge> edges);
        /**
         * Returns the input value for tuple field "timeInterval".
         * @return the tuple value
         */
        public eu.qualimaster.families.datatypes.common.IFTimeInterval getTimeInterval();

        /**
         * Changes the output value for tuple field "timeInterval".
         * @param timeInterval the field value
         */
        public void setTimeInterval(eu.qualimaster.families.datatypes.common.IFTimeInterval timeInterval);
    }

    /**
     * Calculates the actual result for input.
     *
     * @param input the algorithm input taken from the input stream
     * @param result the result calculated by the algorithm
     */
    public void calculate(IIFFinancialNetworkExtractionAnalysisInput input, IIFFinancialNetworkExtractionAnalysisOutput analysisResult);

    /**
     * Sets the algorithm parameter "timeSeriesGranularity".
     *
     * @param value the new value of the algorithm parameter
     */
    public void setParameterTimeSeriesGranularity(int value);

}


text:
package com.alibaba.csp.sentinel;

import com.alibaba.csp.sentinel.context.ContextTestUtil;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.util.function.Predicate;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Carpenter Lee
 */
public class TracerTest extends Tracer {

    @Before
    public void setUp() {
        ContextTestUtil.cleanUpContext();
        ContextTestUtil.resetContextMap();
        Tracer.exceptionPredicate = null;
    }

    @After
    public void tearDown() {
        ContextTestUtil.cleanUpContext();
        ContextTestUtil.resetContextMap();
        Tracer.exceptionPredicate = null;
    }

    @Test
    public void testTraceWhenContextSizeExceedsThreshold() {
        int i = 0;
        for (; i < Constants.MAX_CONTEXT_NAME_SIZE; i++) {
            ContextUtil.enter("test-context-" + i);
            ContextUtil.exit();
        }

        try {
            ContextUtil.enter("test-context-" + i);
            throw new RuntimeException("test");
        } catch (Exception e) {
            Tracer.trace(e);
        } finally {
            ContextUtil.exit();
        }
    }

    @Test
    public void setExceptionsToTrace() {
        Tracer.ignoreClasses = null;
        Tracer.traceClasses = null;
        Tracer.setExceptionsToTrace(TraceException.class, TraceException2.class);
        Assert.assertTrue(Tracer.shouldTrace(new TraceException2()));
        Assert.assertTrue(Tracer.shouldTrace(new TraceExceptionSub()));
        Assert.assertFalse(Tracer.shouldTrace(new Exception()));
    }

    @Test
    public void setExceptionPredicate() {

        Predicate<Throwable> throwablePredicate = new Predicate<Throwable>() {
            @Override
            public boolean test(Throwable throwable) {
                if (throwable instanceof TraceException) {
                    return true;
                } else if (throwable instanceof IgnoreException) {
                    return false;
                }
                return false;
            }
        };
        Tracer.setExceptionPredicate(throwablePredicate);
        Assert.assertTrue(Tracer.shouldTrace(new TraceException()));
        Assert.assertFalse(Tracer.shouldTrace(new IgnoreException()));
    }

    @Test
    public void setExceptionsToIgnore() {
        Tracer.ignoreClasses = null;
        Tracer.traceClasses = null;
        Tracer.setExceptionsToIgnore(IgnoreException.class, IgnoreException2.class);
        Assert.assertFalse(Tracer.shouldTrace(new IgnoreException()));
        Assert.assertFalse(Tracer.shouldTrace(new IgnoreExceptionSub()));
        Assert.assertTrue(Tracer.shouldTrace(new Exception()));
    }

    @Test
    public void testBoth() {
        Tracer.ignoreClasses = null;
        Tracer.traceClasses = null;
        Tracer.setExceptionsToTrace(TraceException.class, TraceException2.class, BothException.class);
        Tracer.setExceptionsToIgnore(IgnoreException.class, IgnoreException2.class, BothException.class);
        Assert.assertFalse(Tracer.shouldTrace(new IgnoreException()));
        Assert.assertFalse(Tracer.shouldTrace(new BothException()));
        Assert.assertTrue(Tracer.shouldTrace(new TraceException()));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNull() {
        Tracer.setExceptionsToTrace(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNull1() {
        Tracer.setExceptionsToTrace(TraceException.class, null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNull2() {
        Tracer.setExceptionsToIgnore(IgnoreException.class, null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNull3() {
        Tracer.setExceptionPredicate(null);
    }

    private class TraceException extends Exception {}

    private class TraceException2 extends Exception {}

    private class TraceExceptionSub extends TraceException {}

    private class IgnoreException extends Exception {}

    private class IgnoreException2 extends Exception {}

    private class IgnoreExceptionSub extends IgnoreException {}

    private class BothException extends Exception {}
}


text:
package org.apache.karaf.features.extension;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.osgi.framework.Bundle;
import org.osgi.framework.hooks.resolver.ResolverHook;
import org.osgi.framework.namespace.ExecutionEnvironmentNamespace;
import org.osgi.framework.namespace.HostNamespace;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRequirement;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.resource.Capability;
import org.osgi.resource.Resource;

class StoredWiringResolver implements ResolverHook {
    private final Map<Long, BundleWires> wiring = new HashMap<>();
    private Path path;

    StoredWiringResolver(Path path) {
        this.path = path;
        load();
    }

    void load() {
        try {
            Files.createDirectories(path);
            Files.list(path).forEach(p -> {
                String name = p.getFileName().toString();
                if (name.matches("[0-9]+")) {
                    long id = Long.parseLong(name);
                    try (BufferedReader reader = Files.newBufferedReader(p)) {
                        wiring.put(id, new BundleWires(id, reader));
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            });
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public void filterResolvable(Collection<BundleRevision> candidates) {
    }

    @Override
    public void filterSingletonCollisions(BundleCapability singleton,
                                          Collection<BundleCapability> collisionCandidates) {
    }

    @Override
    public void filterMatches(BundleRequirement requirement, Collection<BundleCapability> candidates) {
        long sourceId = getBundleId(requirement);
        wiring.get(sourceId).filterMatches(requirement, candidates);
    }

    @Override
    public void end() {
    }

    private long getBundleId(BundleRequirement requirement) {
        long sourceId = requirement.getRevision().getBundle().getBundleId();
        if (isFragment(requirement.getRevision())
            && !requirement.getNamespace().equals(HostNamespace.HOST_NAMESPACE)
            && !requirement.getNamespace().equals(ExecutionEnvironmentNamespace.EXECUTION_ENVIRONMENT_NAMESPACE)) {
            sourceId = wiring.get(sourceId).getFragmentHost();
        }
        return sourceId;
    }

    private static boolean isFragment(Resource resource) {
        for (Capability cap : resource.getCapabilities(null)) {
            if (IdentityNamespace.IDENTITY_NAMESPACE.equals(cap.getNamespace())) {
                return IdentityNamespace.TYPE_FRAGMENT
                    .equals(cap.getAttributes().get(IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE));
            }
        }
        return false;
    }

    synchronized void update(Bundle bundle) {
        BundleWires bw = new BundleWires(bundle);
        bw.save(path);
        wiring.put(bundle.getBundleId(), bw);
    }

    synchronized void delete(Bundle bundle) {
        if (wiring.get(bundle.getBundleId()) != null) {
            wiring.get(bundle.getBundleId()).delete(path);
        }
    }
}


text:
###Binary Tree Paths
URL: https://leetcode.com/problems/binary-tree-paths/

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

	   1
	 /   \
	2     3
	 \
	  5

All root-to-leaf paths are:

	["1->2->5", "1->3"]

__Code:__

	/**
	 * Definition for a binary tree node.
	 * struct TreeNode {
	 *     int val;
	 *     TreeNode *left;
	 *     TreeNode *right;
	 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
	 * };
	 */
	class Solution {
	public:
	    vector<string> TreePaths;
	    void DFS(TreeNode* node, string answer)
	    {
	        answer += "->" + to_string(node->val);
	        if(node->left == NULL && node->right == NULL)
	            TreePaths.push_back(answer);
	        else
	        {
	            if(node->left != NULL)
	                DFS(node->left, answer);
	            if(node->right != NULL)
	                DFS(node->right, answer);
	        }
	    }
	    vector<string> binaryTreePaths(TreeNode* root) {
	        if(root != NULL)
	        {
	            DFS(root, "");
	            for(int i = 0; i < TreePaths.size(); i++)
	                TreePaths[i].erase(TreePaths[i].begin(), TreePaths[i].begin() + 2);
	        }
	        return TreePaths;
	    }
	};


text:
package chapter1;

import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

/**
 * Created by Daniel on 23/04/2016.
 */
public class P17Trip {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        while (n != 0) {
            LinkedList<Float> money = new LinkedList();
            float sum = 0;

            for (int i = 0; i < n; i++) {
                money.add(scanner.nextFloat());
                sum += money.getLast();
            }

            float media = sum / money.size() + .005f;
            float result = 0;

            for (int j = 0; j < n; j++) {
                if (money.get(j) > media) {
                    result += money.get(j) - media;
                }
            }

            System.out.println(String.format("$%.2f", result));
            n = scanner.nextInt();
        }
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>wtf.opi.worker.single.Worker</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

Visit WTF Online

        Package wtf ::
        Package opi ::
        Package worker ::
        Module single ::
        Class Worker

[hide private]

[frames] | no frames]

Class Worker

source code

object --+
         |
        Worker

Worker "pool" implementation

        Instance Methods
        [hide private]

          __init__(self,
        model,
        sock,
        prerun,
        parent_cleanup,
        child_cleanup)

      Initialization

            source code

          run(self)

      Pool runner

            source code

          shutdown(self)

      Pool shutdown

            source code

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Class Variables
        [hide private]

        __implements__ = [<class 'wtf.opi.worker.WorkerPoolInterface'>]

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        model,
        sock,
        prerun,
        parent_cleanup,
        child_cleanup)

(Constructor)

  	source code

  Initialization

Parameters:

model (SingleWorker) - The worker model implementation

sock (<tt class="rst-docutils literal">socket.socket</tt>) - The main socket

prerun (<tt class="rst-docutils literal">callable</tt>) - Prerunner (maybe <tt class="rst-docutils literal">None</tt>)

parent_cleanup (<tt class="rst-docutils literal">callable</tt>) - Parent cleanup function (ignored)

child_cleanup (<tt class="rst-docutils literal">callable</tt>) - Child cleanup function (ignored)

Overrides:
        object.__init__

run(self)

  	source code

  Pool runner

See Also:
        wtf.opi.worker.WorkerPoolInterface

shutdown(self)

  	source code

  Pool shutdown

See Also:
        wtf.opi.worker.WorkerPoolInterface

         Home

         Trees

         Indices

         Help

Visit WTF Online


text:
module Beam
  module UploadControllerMethods
    attr_accessor :model, :upload_method

    def upload
      @upload_status = file_upload_status(params)
      @upload_status.merge!(additional_params_on_success) if @upload_status[:success_msg]

      respond_to do |format|
        format.json { render json: @upload_status }
        format.html { redirect_to :back }
      end
    end

    def error_file
      send_file "#{Beam.config[:data_upload_path]}/errors_#{self.controller_name.downcase}.csv"
    end

    def self.included(base)
      private

      # hook for post successful upload, in case additional parameters need to be send
      def additional_params_on_success
        {}
      end

      def zip_file?(file)
        ["application/zip", "application/x-zip-compressed", "application/octet-stream"].include?(file.content_type)  && file.original_filename.include?(".zip")
      end

      def file_upload_status(params)
        file_obj = params[:upload] ? params[:upload][:upload_file] : params[:files][0]

        status = file_obj ? file_status(file_obj) : not_file_status
        status[:message] = status[:num_errors] && status[:num_errors].zero? ? status[:success_msg] : status[:error_msg]
        status[:status] = status[:message] == status[:success_msg] ? "success" : "failure"
        status[:status_code] = status[:message] == status[:success_msg] ? 200 : 500
        status
      end

      def file_status(file)
        zip_file?(file) ? csv_file_status(file) : not_csv_file_status
      end

      def not_file_status
        {error_msg: "No file detected, please upload a file"}
      end

      def csv_file_status(file)
        response = upload_file(file)
        upload_status_by_response(response)
      end

      def upload_file(file)
        require 'fileutils'
        @model ||= controller_name.classify.constantize
        tmp = file.tempfile
        file_path = File.join(Beam.config[:data_upload_path], file.original_filename)
        FileUtils.cp_r tmp.path, file_path, remove_destination: true

        @upload_method ?
          @model.upload_file(file.original_filename, Beam.config[:data_upload_path], @upload_method) :
          @model.upload_file(file.original_filename, Beam.config[:data_upload_path])
      end

      def not_csv_file_status
        {error_msg: "Only zipped csv files are allowed"}
      end

      def upload_status_by_response(response)
        if response[:status] == 500
          failure_status
        else
        response[:errors].zero? ?
          upload_without_queue_success_status :
          upload_without_queue_failure_status(response[:errors])
        end
      end

      def failure_status
        {num_errors: 1, controller_name: self.controller_name, error_msg: "Please check the format of zipped file"}
      end

      def upload_through_queue_status(errors)
        {
          num_errors:      nil,
          controller_name: self.controller_name,
          success_msg:     "In Progress"
        }
      end

      def upload_without_queue_success_status
        {
          num_errors:      0,
          controller_name: self.controller_name,
          success_msg:     "File uploaded successfully"
        }
      end

      def upload_without_queue_failure_status(errors)
        {
          num_errors:      errors,
          controller_name: self.controller_name,
          error_msg:       "There are #{errors} row(s) with errors while uploading config file." +
                            " Please check whether you have selected correct module or you have valid data in the file."
        }
      end

    end

  end
end


text:
simple nvd3 Pie Chart - Publikationen nach Wissenschaftsbereich.

http://zsivienna.github.io/pubpie/


text:
package com.sun.java.swing.plaf.gtk.resources;

import java.util.ListResourceBundle;

public final class gtk extends ListResourceBundle {
    protected final Object[][] getContents() {
        return new Object[][] {
            { "FileChooser.acceptAllFileFilter.textAndMnemonic", "All Files" },
            { "FileChooser.cancelButton.textAndMnemonic", "Cancel" },
            { "FileChooser.cancelButtonToolTip.textAndMnemonic", "Abort file chooser dialog." },
            { "FileChooser.deleteFileButton.textAndMnemonic", "De&lete File" },
            { "FileChooser.filesLabel.textAndMnemonic", "&Files" },
            { "FileChooser.filterLabel.textAndMnemonic", "Filter:" },
            { "FileChooser.foldersLabel.textAndMnemonic", "Fol&ders" },
            { "FileChooser.newFolderButton.textAndMnemonic", "&New Folder" },
            { "FileChooser.newFolderDialog.textAndMnemonic", "Folder name:" },
            { "FileChooser.newFolderNoDirectoryError.textAndMnemonic", "Error creating directory \"{0}\": No such file or directory" },
            { "FileChooser.newFolderNoDirectoryErrorTitle.textAndMnemonic", "Error" },
            { "FileChooser.openButton.textAndMnemonic", "OK" },
            { "FileChooser.openButtonToolTip.textAndMnemonic", "Open selected file." },
            { "FileChooser.openDialogTitle.textAndMnemonic", "Open" },
            { "FileChooser.pathLabel.textAndMnemonic", "&Selection:" },
            { "FileChooser.renameFileButton.textAndMnemonic", "&Rename File" },
            { "FileChooser.renameFileDialog.textAndMnemonic", "Rename file \"{0}\" to" },
            { "FileChooser.renameFileError.textAndMnemonic", "Error renaming file \"{0}\" to \"{1}\"" },
            { "FileChooser.renameFileError.titleAndMnemonic", "Error" },
            { "FileChooser.saveButton.textAndMnemonic", "OK" },
            { "FileChooser.saveButtonToolTip.textAndMnemonic", "Save selected file." },
            { "FileChooser.saveDialogTitle.textAndMnemonic", "Save" },
            { "GTKColorChooserPanel.blue.textAndMnemonic", "&Blue:" },
            { "GTKColorChooserPanel.color.textAndMnemonic", "Color &Name:" },
            { "GTKColorChooserPanel.green.textAndMnemonic", "&Green:" },
            { "GTKColorChooserPanel.hue.textAndMnemonic", "&Hue:" },
            { "GTKColorChooserPanel.red.textAndMnemonic", "R&ed:" },
            { "GTKColorChooserPanel.saturation.textAndMnemonic", "&Saturation:" },
            { "GTKColorChooserPanel.textAndMnemonic", "&GTK Color Chooser" },
            { "GTKColorChooserPanel.value.textAndMnemonic", "&Value:" },
        };
    }
}


text:
package com.txey.wxgzh.zyqd.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test(){
        return "/test.jsp";
    }

}


text:
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace dbqf.WPF.UIElements.Controls
{
    /// <summary>
    /// Interaction logic for BetweenControl.xaml
    /// </summary>
    [ImplementPropertyChanged]
    public partial class BetweenControl : UserControl
    {
        public BetweenControl()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        /// <summary>
        /// Gets or sets the label that appears before any other controls.
        /// </summary>
        public string PrefixText { get; set; }
        public Visibility PrefixVisibility
        {
            get { return String.IsNullOrEmpty(PrefixText) ? Visibility.Collapsed : Visibility.Visible; }
        }

        /// <summary>
        /// Gets or sets the label that appears after all other controls.
        /// </summary>
        public string PostfixText { get; set; }
        public Visibility PostfixVisibility
        {
            get { return String.IsNullOrEmpty(PostfixText) ? Visibility.Collapsed : Visibility.Visible; }
        }

        /// <summary>
        /// Sets the first or 'from' control.
        /// </summary>
        public UIElement Control1 { get; set; }

        /// <summary>
        /// Sets the second or 'to' control.
        /// </summary>
        public UIElement Control2 { get; set; }
    }
}


text:
<?php
//
// New translations & fixes are welcome:
// * chatelao(ät)users.sourceforge.net
//
$supported_langs[] = 'ca';

$use_flag['ca'] = 'catalonia';

$messages['DIR']['ca'] = ""; //
$messages['LANGUAGE']['ca'] = "idioma"; // language
$messages['auto']['ca'] = "configuració navegador (automàtic)"; // bowser settings (automatic)
$messages['en']['ca'] = "anglès"; // English
$messages['cs']['ca'] = "txec"; // Czech
$messages['de']['ca'] = "alemany"; // German
$messages['pl']['ca'] = "polonès"; // Polish
$messages['JANUARY']['ca'] = "gener"; // January
$messages['FEBRUARY']['ca'] = "febrer"; // February
$messages['MARCH']['ca'] = "març"; // March
$messages['APRIL']['ca'] = "abril"; // April
$messages['MAY']['ca'] = "maig"; // May
$messages['JUNE']['ca'] = "juny"; // June
$messages['JULY']['ca'] = "juliol"; // July
$messages['AUGUST']['ca'] = "agost"; // August
$messages['SEPTEMBER']['ca'] = "setembre"; // September
$messages['OCTOBER']['ca'] = "octubre"; // October
$messages['NOVEMBER']['ca'] = "novembre"; // November
$messages['DECEMBER']['ca'] = "desembre"; // December
$messages['ADDRESS_BOOK']['ca'] = "llibreta d'adreces"; // address book
$messages['FOR']['ca'] = "per"; // for
$messages['SEARCH']['ca'] = "cerca"; // search
$messages['HOME']['ca'] = "inici"; // home
$messages['NEXT_BIRTHDAYS']['ca'] = "pròxim aniversari"; // next birthdays
$messages['ADD_NEW']['ca'] = "afegir-ne nou"; // add new
$messages['PRINT_ALL']['ca'] = "imprimir-los tots"; // print all
$messages['PRINT_PHONES']['ca'] = "imprimir telèfons"; // print phones
$messages['EXPORT_CSV']['ca'] = "exportar CSV"; // export csv
$messages['GROUPS']['ca'] = "grups"; // groups
$messages['MANAGE_GROUPS']['ca'] = "grups"; // groups
$messages['NEW_GROUP']['ca'] = "grup nou"; // new group
$messages['DELETE_GROUPS']['ca'] = "esborrar grups"; // delete group(s)
$messages['EDIT_GROUP']['ca'] = "editar grup"; // edit group
$messages['GROUP_NAME']['ca'] = "nom del grup"; // group name
$messages['GROUP_HEADER']['ca'] = "Capçalera de grup (Logo)"; // Group header (Logo)
$messages['GROUP_FOOTER']['ca'] = "Peu de grup (Comentari)"; // Group footer (Comment)
$messages['SEARCH_FOR_ANY_TEXT']['ca'] = "cercar qualsevol text"; // search for any text
$messages['NUMBER_OF_RESULTS']['ca'] = "Nombre de resultats"; // Number of results
$messages['ALL']['ca'] = "tots"; // all
$messages['NONE']['ca'] = "cap"; // none
$messages['SELECT_ALL']['ca'] = "seleccionar-los tots"; // select all
$messages['REMOVE_FROM']['ca'] = "eliminar"; // remove from
$messages['MAIL_CLIENT']['ca'] = "client de correu"; // mail client
$messages['SEND_EMAIL']['ca'] = "Enviar correu"; // Send e-Mail
$messages['ADD_TO']['ca'] = "afegir a"; // add to
$messages['DETAILS']['ca'] = "detalls"; // details
$messages['EDIT']['ca'] = "editar"; // edit
$messages['MODIFY']['ca'] = "modificar"; // modify
$messages['PRINT']['ca'] = "imprimir"; // print
$messages['EDIT_ADD_ENTRY']['ca'] = "Editar o afegir entrades a llibreta d'adreces"; // Edit / add address book entry
$messages['GUESSED_HOMEPAGE']['ca'] = "Pàgina principal possible"; // Guessed homepage
$messages['PREFERENCES']['ca'] = "preferències"; // preferences
$messages['FIRSTNAME']['ca'] = "nom"; // first name
$messages['LASTNAME']['ca'] = "cognoms"; // last name
$messages['ADDRESS']['ca'] = "adreça"; // address
$messages['TELEPHONE']['ca'] = "telèfon"; // telephone
$messages['PHONE_HOME']['ca'] = "inici"; // home
$messages['PHONE_MOBILE']['ca'] = "mòbil"; // mobile
$messages['PHONE_WORK']['ca'] = "feina"; // work
$messages['EMAIL']['ca'] = "correu"; // e-mail
$messages['ZIP']['ca'] = "codi postal"; // ZIP
$messages['CITY']['ca'] = "ciutat"; // city
$messages['E_MAIL_HOME']['ca'] = "correu casa"; // e-mail home
$messages['E_MAIL_OFFICE']['ca'] = "correu oficina"; // e-mail office
$messages['2ND_ADDRESS']['ca'] = "segona adreça"; // second address
$messages['2ND_PHONE']['ca'] = "segon telèfon"; // second phone
$messages['BIRTHDAY']['ca'] = "aniversari"; // birthday
$messages['UPDATE']['ca'] = "actualitzar"; // update
$messages['DELETE']['ca'] = "eliminar"; // delete
$messages['INVALID']['ca'] = "no vàlid"; // invalid
$messages['ENTER']['ca'] = "entrar"; // enter
$messages['MEMBER_OF']['ca'] = "membre de"; // member of
$messages['SECONDARY']['ca'] = "Secundària"; // Secondary
$messages['H:']['ca'] = "H:"; // H:
$messages['M:']['ca'] = "M:"; // M:
$messages['W:']['ca'] = "F:"; // W:
$messages['ar']['ca'] = "àrab"; // Arabic
$messages['el']['ca'] = "grec"; // Greek
$messages['es']['ca'] = "castellà"; // Spanish
$messages['fr']['ca'] = "francès"; // French
$messages['zh']['ca'] = "xinès"; // Chinese
$messages['he']['ca'] = "hebreu"; // Hebrew
$messages['hi']['ca'] = "hindi"; // Hindi
$messages['ko']['ca'] = "coreà"; // Korean
$messages['pt']['ca'] = "portuguès"; // Portugese
$messages['ru']['ca'] = "rus"; // Russian
$messages['ja']['ca'] = "japonès"; // Japanese
$messages['th']['ca'] = "tailandès"; // Thai
$messages['vi']['ca'] = "vietnamita"; // Vietnamese
$messages['ca']['ca'] = "català"; // Catalonian
$messages['it']['ca'] = "italià"; // Italian
$messages['nl']['ca'] = "neerlandès"; // Dutch
$messages['sv']['ca'] = "suec"; // Swedish
$messages['bg']['ca'] = "búlgar"; // Bulgarian
$messages['rm']['ca'] = "retoromànic"; // Rhaeto-Romance
$messages['tr']['ca'] = "turc"; // Turkish
$messages['GROUP']['ca'] = "grup"; // group
$messages['COMPANY']['ca'] = "empresa"; // company
$messages['FAX']['ca'] = "fax"; // fax
$messages['HOMEPAGE']['ca'] = "Pàgina principal"; // Homepage
$messages['NOTES']['ca'] = "notes"; // notes
$messages['CREATED']['ca'] = "creat"; // created
$messages['MODIFIED']['ca'] = "modificació"; // modified
$messages['F:']['ca'] = "F:"; // F:
$messages['da']['ca'] = "danès"; // Danish
$messages['fi']['ca'] = "finès"; // Finnish
$messages['USER']['ca'] = "Usuari"; // User
$messages['PASSWORD']['ca'] = "Contrasenya"; // Password
$messages['LOGIN']['ca'] = "Login"; // Login
$messages['LOGOUT']['ca'] = "Desconnectar"; // Logout
$messages['UPDATED']['ca'] = ""; //
$messages['EXPORT']['ca'] = "exportació"; // export
$messages['IMPORT']['ca'] = "importació"; // import
$messages['GROUP_PARENT']['ca'] = "grup de Pares"; // Parent group
$messages['TRANSLATOR']['ca'] = ""; //
$messages['sr']['ca'] = "Serbi"; // Serbian
$messages['sl']['ca'] = "Eslovè"; // Slovenian
$messages['fa']['ca'] = "Persa"; // Farsi
$messages['hu']['ca'] = "Hongarès"; // Hungarian
?>


text:
package com.codeest.geeknews.base.contract.gold;

import com.codeest.geeknews.base.BasePresenter;
import com.codeest.geeknews.base.BaseView;
import com.codeest.geeknews.model.bean.GoldManagerBean;
import com.codeest.geeknews.model.bean.GoldManagerItemBean;

import java.util.List;

/**
 * Created by codeest on 16/11/28.
 */

public interface GoldMainContract {

    interface View extends BaseView {

        void updateTab(List<GoldManagerItemBean> mList);

        void jumpToManager(GoldManagerBean mBean);
    }

    interface Presenter extends BasePresenter<View> {

        void initManagerList();

        void setManagerList();
    }
}


text:
var Hoek = require('hoek');
var Boom = require('boom');
var Joi = require('joi');
var Wreck = require('wreck');

var internals = {};

exports.register = function (plugin, options, next) {
    plugin.auth.scheme('access-token', internals.implementation);
    next();
};

exports.register.attributes = {
    pkg: require('../package.json')
};

internals.schema = Joi.object({
    accessTokenKeyName: Joi.string(),
    profileUrl: Joi.string(),
    validateFunc: Joi.func().required().description('The function which will parse the user profile from the response object'),
    requestOptions: Joi.object().description('The Wreck request options')
});

internals.defaults = {
    accessTokenKeyName: 'access_token',
    profileUrl: 'https://graph.facebook.com/v2.6/me?access_token=',
    requestOptions: {
        timeout: 10000,
        maxBytes: 1048576, // 1 mb - very generous!
    }
};

internals.implementation = function (server, options) {
    Hoek.assert(options, internals.schema);
    internals.options = Hoek.applyToDefaults(internals.defaults, options);

    return { authenticate: internals.authenticate, payload: internals.authenticateWithPayload };
};

internals.authenticate = function (request, reply) {

    var accessToken;
    if (request.query && request.query[internals.options.accessTokenKeyName]) {
        accessToken = request.query[internals.options.accessTokenKeyName];
    }

    if (!accessToken && request.payload && request.payload[internals.options.accessTokenKeyName]) {
        accessToken = request.payload[internals.options.accessTokenKeyName];
    }

    if (!accessToken) {
        // Set this here so it'll try the authenticate with payload method
        return reply.continue({credentials: {}});
    }

    Wreck.get(internals.options.profileUrl + encodeURIComponent(accessToken), internals.options.requestOptions, function(err, res, payload) {

        if (err) {
            return reply(err);
        }

        if (res.statusCode > 299) {
            var error = JSON.parse(payload);
            return reply(Boom.unauthorized(error.error.message));
        }
        internals.options.validateFunc(payload, accessToken, reply, request);
    });
};

internals.authenticateWithPayload = function(request, reply) {

    var accessToken;
    if (request.query && request.query[internals.options.accessTokenKeyName]) {
        accessToken = request.query[internals.options.accessTokenKeyName];
    }

    if (!accessToken && request.payload && request.payload[internals.options.accessTokenKeyName]) {
        accessToken = request.payload[internals.options.accessTokenKeyName];
    }

    if (!accessToken) {
        return reply(Boom.unauthorized('No access token specified', 'access-token'));
    }

    return Wreck.get(internals.options.profileUrl + encodeURIComponent(accessToken), internals.options.requestOptions, function(err, res, payload) {
        if (err) {
            return reply(err);
        }

        if (res.statusCode > 299) {
            var error = JSON.parse(payload);
            return reply(Boom.unauthorized(error.error.message));
        }

        return internals.options.validateFunc(payload, accessToken, reply, request);
    });
};


text:
<?php

namespace Iyzipay\Request;

use Iyzipay\JsonBuilder;
use Iyzipay\Request;
use Iyzipay\RequestStringBuilder;

class RetrievePaymentRequest extends Request
{
    private $paymentId;
    private $paymentConversationId;

    public function getPaymentId()
    {
        return $this->paymentId;
    }

    public function setPaymentId($paymentId)
    {
        $this->paymentId = $paymentId;
    }

    public function getPaymentConversationId()
    {
        return $this->paymentConversationId;
    }

    public function setPaymentConversationId($paymentConversationId)
    {
        $this->paymentConversationId = $paymentConversationId;
    }

    public function getJsonObject()
    {
        return JsonBuilder::fromJsonObject(parent::getJsonObject())
            ->add("paymentId", $this->getPaymentId())
            ->add("paymentConversationId", $this->getPaymentConversationId())
            ->getObject();
    }

    public function toPKIRequestString()
    {
        return RequestStringBuilder::create()
            ->appendSuper(parent::toPKIRequestString())
            ->append("paymentId", $this->getPaymentId())
            ->append("paymentConversationId", $this->getPaymentConversationId())
            ->getRequestString();
    }
}


text:
namespace os {

namespace stat {

namespace internal {

inline Try<struct ::stat> stat(
    const std::string& path,
    const FollowSymlink follow)
{
  struct ::stat s;

  switch (follow) {
    case DO_NOT_FOLLOW_SYMLINK:
      if (::lstat(path.c_str(), &s) < 0) {
        return ErrnoError("Failed to lstat '" + path + "'");
      }
      return s;
    case FOLLOW_SYMLINK:
      if (::stat(path.c_str(), &s) < 0) {
        return ErrnoError("Failed to stat '" + path + "'");
      }
      return s;
  }

  UNREACHABLE();
}

} // namespace internal {

inline bool islink(const std::string& path)
{
  // By definition, you don't followsymlinks when trying
  // to find whether a path is a link. If you followed it,
  // it wouldn't ever be a link.
  Try<struct ::stat> s = internal::stat(path, DO_NOT_FOLLOW_SYMLINK);
  return s.isSome() && S_ISLNK(s->st_mode);
}

inline bool isdir(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  return s.isSome() && S_ISDIR(s->st_mode);
}

inline bool isfile(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  return s.isSome() && S_ISREG(s->st_mode);
}

// Returns the size in Bytes of a given file system entry. When
// applied to a symbolic link with `follow` set to
// `DO_NOT_FOLLOW_SYMLINK`, this will return the length of the entry
// name (strlen).
inline Try<Bytes> size(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  return Bytes(s->st_size);
}

inline Try<long> mtime(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  return s->st_mtime;
}

inline Try<mode_t> mode(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  return s->st_mode;
}

inline Try<dev_t> dev(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  return s->st_dev;
}

inline Try<dev_t> rdev(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  if (!S_ISCHR(s->st_mode) && !S_ISBLK(s->st_mode)) {
    return Error("Not a special file: " + path);
  }

  return s->st_rdev;
}

inline Try<ino_t> inode(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  return s->st_ino;
}

inline Try<uid_t> uid(
    const std::string& path,
    const FollowSymlink follow = FOLLOW_SYMLINK)
{
  Try<struct ::stat> s = internal::stat(path, follow);
  if (s.isError()) {
    return Error(s.error());
  }

  return s->st_uid;
}

} // namespace stat {

} // namespace os {

#endif // __STOUT_OS_POSIX_STAT_HPP__


text:
import os
import posixpath
import sys
import time
from django.conf import settings
from django.contrib.staticfiles import finders

_win = (sys.platform == "win32")

def get_mtime(filename):
    stat = os.stat(filename)
    mtime = stat.st_mtime
    if _win:
        mtime -= stat.st_ctime
    return mtime

def resolve_media_url(url):
    if settings.MEDIA_URL and url.startswith(settings.MEDIA_URL):
        filename = url[len(settings.MEDIA_URL):]
        filename = posixpath.normpath(filename).lstrip('/')
        filename = os.path.join(settings.MEDIA_ROOT, filename)
        return filename
    if settings.STATIC_URL and url.startswith(settings.STATIC_URL):
        filename = url[len(settings.STATIC_URL):]
        filename = posixpath.normpath(filename).lstrip('/')
        filename = finders.find(filename)
        return filename

class FileWatcher(object):
    def __init__(self, resources):
        self._resources = resources

    @property
    def resources(self):
        return self._resources

    def get_updated_files(self):
        modified = []
        for resource in self.resources:
            if resource.modified():
                modified.append(resource)
        return modified

    def has_updates(self):
        for resource in self.resources:
            if resource.modified():
                return True
        return False

class SourceWatcher(FileWatcher):
    def __init__(self):
        self._timestamp = time.time()

    def _module_to_filename(self, module):
        filename = getattr(module, '__file__', None)
        if filename is None:
            return filename
        if filename.endswith(".pyc") or filename.endswith(".pyo"):
            filename = filename[:-1]
        if filename.endswith("$py.class"):
            filename = filename[:-9] + ".py"
        if not os.path.exists(filename):
            return None
        return filename

    def get_source_files(self):
        source_files = []
        for module in sys.modules.values():
            filename = self._module_to_filename(module)
            if filename:
                source_files.append(filename)
        return source_files

    @property
    def resources(self):
        sources = self.get_source_files()
        sources = [Resource(src, self._timestamp) for src in sources]
        return sources

class Resource(object):
    def __init__(self, name, timestamp=None):
        self.name = name
        self.timestamp = timestamp or time.time()
        self._exists = self.exists()

    @property
    def path(self):
        return self.name

    def exists(self):
        if not self.path:
            return False
        return os.path.exists(self.path)

    def modified(self):
        # delete was created or deleted
        exists = self.exists()
        if self._exists != exists:
            return True
        elif not exists:
            return False
        mtime = get_mtime(self.path)
        if mtime > self.timestamp:
            return True
        return False

    @property
    def mtime(self):
        if self.exists():
            return get_mtime(self.path)

    def __unicode__(self):
        return self.name
    __str__ = __unicode__

class MediaResource(Resource):
    def __init__(self, *args, **kwargs):
        super(MediaResource, self).__init__(*args, **kwargs)

    @property
    def path(self):
        name = self.name
        if '?' in name:
            name, query = self.name.split('?', 1)
        return resolve_media_url(name)


text:
using System;
using System.Collections.Generic;
using OctoNet.Models;
using OctoNet.Models.Dto;
using OctoNet.Utility;
using OctoNet.Web;

namespace OctoNet.Services
{
    public class IssueService : IIssueService
    {
        private readonly IGitHubClient _client;

        public IssueService(IGitHubClient gitHubClient)
        {
            Requires.ArgumentNotNull(gitHubClient, "gitHubClient");

            _client = gitHubClient;
        }

        #region IIssueService Members

        public GitHubRequestAsyncHandle CreateIssueAsync(string user,
                                                         string repo,
                                                         string title,
                                                         string body,
                                                         string assignee,
                                                         string mileStone,
                                                         string[] labels,
                                                         Action<Issue> callback,
                                                         Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull("user", user);
            Requires.ArgumentNotNull("repo", repo);
            Requires.ArgumentNotNull("title", title);

            string resource = string.Format("/repos/{0}/{1}/issues", user, repo);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new IssueDto
                                                {
                                                    title = title,
                                                    body = body,
                                                    assignee = assignee,
                                                    milestone = mileStone,
                                                    labels = labels
                                                });
            return _client.CallApiAsync<Issue>(request,
                                               r => callback(r.Data),
                                               onError);
        }

        public GitHubRequestAsyncHandle GetIssueAsync(string user,
                                                      string repo,
                                                      int issueNumber,
                                                      Action<Issue> callback,
                                                      Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            string resource = string.Format("/repos/{0}/{1}/issues/{2}", user, repo, issueNumber);
            var request = new GitHubRequest(resource, API.v3, Method.GET);
            return _client.CallApiAsync<Issue>(request,
                                               r => callback(r.Data),
                                               onError);
        }

        public GitHubRequestAsyncHandle GetIssuesAsync(string user,
                                                       string repo,
                                                       State state,
                                                       int page,
                                                       Action<IEnumerable<Issue>> callback,
                                                       Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            string resource = string.Format("/repos/{0}/{1}/issues", user, repo);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            Parameter.State(state),
                                            Parameter.Page(page));

            return _client.CallApiAsync<List<Issue>>(request,
                                                     r => callback(r.Data),
                                                     onError);
        }

        public GitHubRequestAsyncHandle CreateCommentAsync(string user,
                                                           string repo,
                                                           int issueNumber,
                                                           string comment,
                                                           Action<Comment> callback,
                                                           Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");
            Requires.ArgumentNotNull(comment, "comment");

            string resource = string.Format("/repos/{0}/{1}/issues/{2}/comments",
                                            user,
                                            repo,
                                            issueNumber);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.POST,
                                            new CommentDto {Body = comment});

            return _client.CallApiAsync<Comment>(request,
                                                 r => callback(r.Data),
                                                 onError);
        }

        public GitHubRequestAsyncHandle GetCommentsAsync(string user,
                                                         string repo,
                                                         int issueNumber,
                                                         int page,
                                                         Action<IEnumerable<Comment>> callback,
                                                         Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(user, "user");
            Requires.ArgumentNotNull(repo, "repo");

            string resource = string.Format("/repos/{0}/{1}/issues/{2}/comments",
                                            user,
                                            repo,
                                            issueNumber);
            var request = new GitHubRequest(resource,
                                            API.v3,
                                            Method.GET,
                                            Parameter.Page(page));
            return _client.CallApiAsync<List<Comment>>(request,
                                                       r => callback(r.Data),
                                                       onError);
        }

        #endregion
    }
}


text:
import time
import unittest

from datamountaineer.schemaregistry.tests import data_gen
from datamountaineer.schemaregistry.tests import mock_registry

from datamountaineer.schemaregistry.client import SchemaRegistryClient
from datamountaineer.schemaregistry.serializers import Util

class TestCacheSchemaRegistryClient(unittest.TestCase):

    def setUp(self):
        self.server = mock_registry.ServerThread(9001)
        self.server.start()
        time.sleep(1)
        self.client = SchemaRegistryClient('http://127.0.0.1:9001')

    def tearDown(self):
        self.server.shutdown()
        self.server.join()

    def assertLatest(self, meta_tuple, sid, schema, version):
        self.assertNotEqual(sid, -1)
        self.assertNotEqual(version, -1)
        self.assertEqual(meta_tuple[0], sid)
        self.assertEqual(meta_tuple[1], schema)
        self.assertEqual(meta_tuple[2], version)

    def test_register(self):
        parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA)
        client = self.client
        schema_id = client.register('test', parsed)
        self.assertTrue(schema_id == 1)
        self.assertEqual(len(client.id_to_schema), 1)

    def test_multi_subject_register(self):
        parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA)
        client = self.client
        schema_id = client.register('test', parsed)
        self.assertTrue(schema_id == 1)

        # register again under different subject
        dupe_id = client.register('other', parsed)
        self.assertEqual(schema_id, dupe_id)
        self.assertEqual(len(client.id_to_schema), 1)

    def test_dupe_register(self):
        parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA)
        subject = 'test'
        client = self.client
        schema_id = client.register(subject, parsed)
        self.assertTrue(schema_id == 1)
        latest = client.get_latest_schema(subject)

        # register again under same subject
        dupe_id = client.register(subject, parsed)
        self.assertEqual(schema_id, dupe_id)
        dupe_latest = client.get_latest_schema(subject)
        self.assertEqual(latest, dupe_latest)

    def test_getters(self):
        parsed = Util.parse_schema_from_string(data_gen.BASIC_SCHEMA)
        client = self.client
        subject = 'test'
        version = client.get_version(subject, parsed)
        self.assertEqual(version, 1)
        schema = client.get_by_id(1)
        # self.assertEqual(schema, parsed)
        latest = client.get_latest_schema(subject)
        self.assertEqual(latest, (1, schema, 1))

        # register
        schema_id = client.register(subject, parsed)
        latest = client.get_latest_schema(subject)
        version = client.get_version(subject, parsed)
        self.assertLatest(latest, schema_id, parsed, version)

        fetched = client.get_by_id(schema_id)
        self.assertEqual(fetched, parsed)


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

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: Plugins > gamestick > IAPPurchaseItem</title>
  <meta name="revised" content="06-Sep-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  Plugins > gamestick > IAPPurchaseItem" />

  <link rel="stylesheet" href="../../css/style.css" type="text/css" />

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

plugin.gamestick.IAPPurchaseItem()

Overview

Syntax

options (required)

listener (required)

Format for options

itemID (required)

requestID (required)

Examples

Ξ  ▸  Plugins  ▸  gamestick  ▸  IAPPurchaseItem

plugin.gamestick.IAPPurchaseItem()

Type
function

Library
gamestick.*

Return value
TYPE

Revision
Current Public Release (2013.2076)

Keywords
gamestick, IAP, inapppurchase

Sample code

See also

Overview

gamestick.IAPPurchaseItem() makes a request to process a purchase through the GameStick servers. Note: On confirmation that a purchase has been successful, developers will need to implement their own code to determine what this purchase will do.

Syntax

gamestick.IAPPurchaseItem( {itemID = "string", requestID = 1}, listener)

options (required)

Table. A table of parameters.

listener (required)

TYPE. The listener function which will handle the API response.

Format for options

The options table contains the following properties:

itemID (required)

TYPE. A string representing the ID number for the item you wish to get the URL for. The ID number can be retrieved using gamestick.IAPGetItemsForPurchase() if not already known.

requestID (required)

TYPE. An integer which will be returned with the response data as a property called "id". This is used to simplify matching up requests and responses when multiple requests are made close together

Examples

local function gamestickListener( event )

    --Failed to get a valid response from server
    if event.isError then
        native.showAlert( "Error: "..event.name, event.message, { "OK" } )
    else
        if event.name == "IAPPurchaseItem" then
            --NOTE: BOTH OF THE RETURNED FIELDS ARE EXTREMELY IMPORTANT IN DETERMINING WHETHER
            --A PURCHASE HAS BEEN SUCCESSFUL, AND WHICH ITEM WAS BOUGHT.

            --event.id will match the requestID from the function call. If 2 purchases are made in quick succession
            --this id will allow you to determine which purchase you are receiving a response for.
            local id  = event.id

             --event.response is a boolean stating whether or not the purchase was successful.
             --If this is false, the purchase was not successful so this will need to be conveyed to the user.
            local response = event.response
        end
    end
end

gamestick.IAPPurchaseItem( {itemID = "string", requestID = 1}, gamestickListener)

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 06-Sep-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text:
package com.yammer.metrics.reporting.tests;

import com.yammer.metrics.core.Clock;
import com.yammer.metrics.core.Gauge;
import com.yammer.metrics.core.MetricsRegistry;
import com.yammer.metrics.core.VirtualMachineMetrics;
import com.yammer.metrics.reporting.MetricsServlet;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class MetricsServletTest {
    private final Clock clock = mock(Clock.class);
    private final VirtualMachineMetrics vm = mock(VirtualMachineMetrics.class);
    private final MetricsRegistry registry = new MetricsRegistry("testRegistry", clock);
    private final JsonFactory factory = mock(JsonFactory.class);

    private final HttpServletRequest request = mock(HttpServletRequest.class);
    private final HttpServletResponse response = mock(HttpServletResponse.class);
    private final ServletOutputStream output = mock(ServletOutputStream.class);
    private final MetricsServlet servlet = new MetricsServlet(clock, vm, registry, factory, false);

    private final ByteArrayOutputStream json = new ByteArrayOutputStream();

    @Before
    public void setUp() throws Exception {
        when(clock.time()).thenReturn(12345678L);

        when(request.getMethod()).thenReturn("GET");

        when(response.getOutputStream()).thenReturn(output);

        final JsonGenerator generator = new JsonFactory(new ObjectMapper()).createJsonGenerator(json,
                                                                                JsonEncoding.UTF8);
        when(factory.createJsonGenerator(output, JsonEncoding.UTF8)).thenReturn(generator);
    }

    @Test
    public void generatesVirtualMachineMetrics() throws Exception {
        when(vm.name()).thenReturn("vm");
        when(vm.version()).thenReturn("version");
        when(vm.totalInit()).thenReturn(1.0);
        when(vm.totalUsed()).thenReturn(2.0);
        when(vm.totalMax()).thenReturn(3.0);
        when(vm.totalCommitted()).thenReturn(4.0);
        when(vm.heapInit()).thenReturn(5.0);
        when(vm.heapUsed()).thenReturn(6.0);
        when(vm.heapMax()).thenReturn(7.0);
        when(vm.heapCommitted()).thenReturn(8.0);

        final Map<String, Double> pools = new TreeMap<String, Double>();
        pools.put("one", 100.0);
        pools.put("two", 200.0);
        when(vm.memoryPoolUsage()).thenReturn(pools);

        when(vm.daemonThreadCount()).thenReturn(300);
        when(vm.threadCount()).thenReturn(400);

        when(vm.heapUsage()).thenReturn(34.0);
        when(vm.nonHeapUsage()).thenReturn(37.0);
        when(vm.uptime()).thenReturn(9991L);
        when(vm.fileDescriptorUsage()).thenReturn(0.222);

        final Map<Thread.State, Double> threads = new TreeMap<Thread.State, Double>();
        threads.put(Thread.State.BLOCKED, 0.33);
        when(vm.threadStatePercentages()).thenReturn(threads);

        final Map<String, VirtualMachineMetrics.GarbageCollectorStats> gcs =
                new TreeMap<String, VirtualMachineMetrics.GarbageCollectorStats>();

        final VirtualMachineMetrics.GarbageCollectorStats gc = mock(VirtualMachineMetrics.GarbageCollectorStats.class);
        when(gc.getTime(TimeUnit.MILLISECONDS)).thenReturn(40L);
        when(gc.getRuns()).thenReturn(20L);
        gcs.put("one", gc);
        when(vm.garbageCollectors()).thenReturn(gcs);

        final VirtualMachineMetrics.BufferPoolStats direct = mock(VirtualMachineMetrics.BufferPoolStats.class);
        when(direct.getCount()).thenReturn(1L);
        when(direct.getMemoryUsed()).thenReturn(2L);
        when(direct.getTotalCapacity()).thenReturn(3L);

        final VirtualMachineMetrics.BufferPoolStats mapped = mock(VirtualMachineMetrics.BufferPoolStats.class);
        when(mapped.getCount()).thenReturn(10L);
        when(mapped.getMemoryUsed()).thenReturn(20L);
        when(mapped.getTotalCapacity()).thenReturn(30L);

        final Map<String, VirtualMachineMetrics.BufferPoolStats> bufferPoolStats =
                new TreeMap<String, VirtualMachineMetrics.BufferPoolStats>();

        bufferPoolStats.put("direct", direct);
        bufferPoolStats.put("mapped", mapped);

        when(vm.getBufferPoolStats()).thenReturn(bufferPoolStats);

        final MetricsServlet servlet = new MetricsServlet(clock, vm, registry, factory, true);

        servlet.service(request, response);

        assertThat(json.toString(),
                   is("{\"jvm\":{\"vm\":{\"name\":\"vm\",\"version\":\"version\"},\"memory\":{" +
                              "\"totalInit\":1.0,\"totalUsed\":2.0,\"totalMax\":3.0," +
                              "\"totalCommitted\":4.0,\"heapInit\":5.0,\"heapUsed\":6.0,\"" +
                              "heapMax\":7.0,\"heapCommitted\":8.0,\"heap_usage\":34.0," +
                              "\"non_heap_usage\":37.0,\"memory_pool_usages\":{\"one\":100.0," +
                              "\"two\":200.0}},\"buffers\":{\"direct\":{\"getCount\":1," +
                              "\"memoryUsed\":2,\"totalCapacity\":3},\"mapped\":{\"getCount\":10," +
                              "\"memoryUsed\":20,\"totalCapacity\":30}},\"daemon_thread_count\":300," +
                              "\"thread_count\":400,\"current_time\":12345678,\"uptime\":9991," +
                              "\"fd_usage\":0.222,\"thread-states\":{\"blocked\":0.33}," +
                              "\"garbage-collectors\":{\"one\":{\"runs\":20,\"time\":40}}}}"));
    }

    @Test
    public void generatesGauges() throws Exception {
        registry.newGauge(MetricsServletTest.class, "gauge", new Gauge<Double>() {
            @Override
            public Double value() {
                return 22.2;
            }
        });

        servlet.service(request, response);

        assertThat(json.toString(),
                   is("{\"com.yammer.metrics.reporting.tests.MetricsServletTest\":" +
                              "{\"gauge\":{\"type\":\"gauge\",\"value\":22.2}}}"));
    }

    @Test
    public void generatesCounters() throws Exception {
        registry.newCounter(MetricsServletTest.class, "counter").inc(12);

        servlet.service(request, response);

        assertThat(json.toString(),
                   is("{\"com.yammer.metrics.reporting.tests.MetricsServletTest\":" +
                              "{\"counter\":{\"type\":\"counter\",\"getCount\":12}}}"));
    }

    @Test
    public void generatesHistograms() throws Exception {
        registry.newHistogram(MetricsServletTest.class, "histogram").update(12);

        servlet.service(request, response);

        assertThat(json.toString(),
                   is("{\"com.yammer.metrics.reporting.tests.MetricsServletTest\":" +
                              "{\"histogram\":{\"type\":\"histogram\",\"getCount\":1,\"getMin\":12.0," +
                              "\"getMax\":12.0,\"getMean\":12.0,\"std_dev\":0.0,\"median\":12.0," +
                              "\"p75\":12.0,\"p95\":12.0,\"p98\":12.0,\"p99\":12.0,\"p999\":12.0}}}"));
    }

    @Test
    public void generatesMeters() throws Exception {
        when(clock.tick()).thenReturn(100000L, 110000L);

        registry.newMeter(MetricsServletTest.class, "meter", "things", TimeUnit.SECONDS)
                .mark(12);

        servlet.service(request, response);

        assertThat(json.toString(),
                   is("{\"com.yammer.metrics.reporting.tests.MetricsServletTest\":" +
                              "{\"meter\":{\"type\":\"meter\",\"event_type\":\"things\"," +
                              "\"unit\":\"seconds\",\"getCount\":12,\"getMean\":1200000.0," +
                              "\"m1\":0.0,\"m5\":0.0,\"m15\":0.0}}}"));
    }

    @Test
    public void generatesTimers() throws Exception {
        when(clock.tick()).thenReturn(100000L, 110000L);

        registry.newTimer(MetricsServletTest.class, "timer").update(100, TimeUnit.MILLISECONDS);

        servlet.service(request, response);

        assertThat(json.toString(),
                   is("{\"com.yammer.metrics.reporting.tests.MetricsServletTest\":{\"timer\":" +
                              "{\"type\":\"timer\",\"duration\":{\"unit\":\"milliseconds\"," +
                              "\"getMin\":100.0,\"getMax\":100.0,\"getMean\":100.0,\"std_dev\":0.0," +
                              "\"median\":100.0,\"p75\":100.0,\"p95\":100.0,\"p98\":100.0," +
                              "\"p99\":100.0,\"p999\":100.0},\"rate\":{\"unit\":\"seconds\"," +
                              "\"getCount\":1,\"getMean\":100000.0,\"m1\":0.0,\"m5\":0.0," +
                              "\"m15\":0.0}}}}"));
    }

    // TODO: 1/19/12 <coda> -- test class prefix
    // TODO: 1/19/12 <coda> -- test pretty printing
    // TODO: 1/19/12 <coda> -- test full sample dumping
    // TODO: 1/19/12 <coda> -- test servlet configuring
}


text:
//
//  BDJNewsViewController.m
//  CSBSBDJ
//
//  Created by Apple on 16/4/20.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "BDJNewsViewController.h"

@interface BDJNewsViewController ()

@end

@implementation BDJNewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package com.google.gwt.user.client.ui;

public class NotificationMole_BinderImpl_TemplateImpl implements com.google.gwt.user.client.ui.NotificationMole_BinderImpl.Template {

  public com.google.gwt.safehtml.shared.SafeHtml html1(java.lang.String arg0,java.lang.String arg1,java.lang.String arg2,java.lang.String arg3,java.lang.String arg4) {
    StringBuilder sb = new java.lang.StringBuilder();
    sb.append("

");
return new com.google.gwt.safehtml.shared.OnlyToBeUsedInGeneratedCodeStringBlessedAsSafeHtml(sb.toString());
}
}


text:
class AddLoginToProfile < ActiveRecord::Migration
  def up
    add_column :profiles, :password_digest, :string
    add_column :profiles, :remember_token, :string
  end
  def down
    remove_column :profiles, :password_digest
    remove_column :profiles, :remember_token
  end
end


text:
from setuptools import setup

setup(name = "cloudeebus",
	version = "0.5.99",
	description = "Javascript-DBus bridge",
	author = "Luc Yriarte, Christophe Guiraud, Frederic Paut",
	author_email = "luc.yriarte@intel.com, christophe.guiraud@intel.com, frederic.paut@intel.com",
	url = "https://github.com/01org/cloudeebus/wiki",
	license = "http://www.apache.org/licenses/LICENSE-2.0",
	scripts = ["cloudeebus/cloudeebus.py"],
	packages = ["cloudeebus"],
	data_files = [("cloudeebus" ,["AUTHORS", "README.md", "LICENSE"]),
				 ('/etc/dbus-1/system.d/', ['org.cloudeebus.conf'])],
	platforms = ("Any"),
	install_requires = ["setuptools", "autobahn>=0.5.8"],
	classifiers = ["License :: OSI Approved :: Apache Software License",
		  "Development Status :: 3 - Alpha",
		  "Environment :: Console",
		  "Intended Audience :: Developers",
		  "Operating System :: OS Independent",
		  "Programming Language :: Python",
		  "Topic :: Internet",
		  "Topic :: Software Development :: Libraries"],
	keywords = "cloudeebus autobahn websocket dbus javascript bridge")


text:
Ext.define('Propial.model.Publication', {
  extend: 'Ext.data.Model',
  requires: [
    'Propial.model.Resource',
    'Propial.model.Ambient',
    'Propial.model.Location'
  ],
  fields: ['id', 'title', 'type', 'address', 'age', 'description', 'price',
      'currencyType', 'expenses', 'surface', 'forProfessional', 'operation',
      'status'],
  hasMany: [
    {model: 'Propial.model.Resource', name: 'resources'},
    {model: 'Propial.model.Ambient', name: 'ambients'},
    {model: 'Propial.model.Location', name: 'locations'}
  ],
  proxy: {
    type: 'rest',
    url: '/services/publications/',
    reader: {
      root: 'data'
    }
  }
});


text:
page_type: sample
products:
- office-sp
languages:
- aspx
- csharp
extensions:
  contentType: samples
  technologies:
  - Add-ins
  createdDate: 1/1/2016 12:00:00 AM
---
# OfficeDevPnP.Core.Framework.Authentication
An ASP.NET Core implementation of the TokenHelper and SharePointContext classes for use in SharePoint Add-ins that run on ASP.NET Core 2.x.

This library (and sample) demonstrates how to get ASP.NET Core provider-hosted apps authenticated through SharePoint.

### Summary ###
The PnP solution includes the following projects:
- OfficeDevPnP.Core.Framework.Authentication - The .NET Core assembly port with the necessary ASP.NET Core authentication middleware and authentication handler.
- AspNetCore.Mvc.StarterWeb - A sample ASP.NET Core web application demonstrating how to consume the above library and build a SharePoint provider-hosted app that can get SharePoint data
- AspNetCore.Mvc.SharePointApp - A sample SharePoint app to make deployment and testing easier

### Solution ###
Solution | Author(s)
---------|----------
AspNetCode.Authentication | Radi Atanassov, OneBit Software; Velin Georgiev, OneBit Software;

### Applies to ###
-  Office 365 Multi-Tenant (MT)

### Version history ###
Version  | Date | Comments
---------| -----| --------
1.0  | May 20th 2016 | Initial version
1.0  | September 2016 | Updated to run on RTM bits
2.0  | September 2017 | Updated to run with .net core 2.0 authentication changes

### Disclaimer ###
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**

----------

## Design Decisions ##
This library/solution has the following goals in mind (some still not achieved!)

- We want it to be very easy to "Add" and "Use", based on the plug 'n' play model of ASP.NET Core
- We want it to achieve the least amount of change to the developer experience
- Based on the ASP.NET Core middleware design pattern
- We must compile to .NET Framework rather than Core due to Microsoft.IdentityModel.Extensions.dll. We will review this in future and see what our best options are.
- We've followed ASP.NET Core configuration and logging patterns
- Based on the ASP.NET Authorization & Authentication model
- We cannot add it to the current PnP Core assembly due to the old project format and the DNX format of this library
- Will be released through NuGet

## Further Reading ##
You will find more details on the decisions, challenges and implementations here:

[Developing the ASP.NET Core Authentication/Authorization Middleware for SharePoint Provider-Hosted Apps (Add-ins)](http://www.sharepoint.bg/radi/post/Developing-the-ASPNET-Core-AuthenticationAuthorization-Middleware-for-SharePoint-Provider-Hosted-Apps-(Add-ins))

[Getting Started with ASP.NET Core Add-ins for SharePoint Online](http://www.sharepoint.bg/radi/post/Getting-Started-with-ASPNET-Core-Add-ins-for-SharePoint-Online)

## Getting Started ##
1. Build the OfficeDevPnP.Core.Framework.Authentication project and add a reference to the output NuGet package.

2. The following must be added to the Startup.cs ConfigureServices method in your ASP.NET Core web application. Cookies and Session are also added here:
```C#
            services.AddSession();

            services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = SharePointAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = SharePointAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme = SharePointAuthenticationDefaults.AuthenticationScheme;
            })
            //OPTIONAL
            ////.AddCookie(options =>
            ////{
            ////    options.Cookie.HttpOnly = false; //set to false so we can read it from JavaScript
            ////    options.Cookie.Expiration = TimeSpan.FromDays(14);
            ////})
            .AddSharePoint(options =>
            {
                options.ClientId = Configuration["SharePointAuthentication:ClientId"];
                options.ClientSecret = Configuration["SharePointAuthentication:ClientSecret"];
                //OPTIONAL
                ////options.CookieAuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                //Handle events raised by the auth handler
                options.Events = new SharePointAuthenticationEvents()
                {
                    OnAuthenticationSucceeded = succeededContext => Task.FromResult<object>(null),
                    OnAuthenticationFailed = failedContext => Task.FromResult<object>(null)
                };
            });
```
3. The library needs Session in order to keep track of the client requests during redirects. Add the following to the Configure method:
```C#
	app.UseSession();

	app.UseAuthentication();
```
4. You might need to restore your Bower and Nuget packages if they are not present on your machine.

## Release Notes ##
- Works on RTM
- This only works with ACS, High Trust is still not supported/developed yet :(
- Remote Event Receivers not tested yet

<img src="https://telemetry.sharepointpnp.com/pnp/solutions/AspNetCore.Authentication" />