text:
/// <reference path='fourslash.ts'/>

////function C(x: number) { }
////
////module C {
////    export var x = 1;
////}
////module C {
////    export function foo() { }
////}
////
////var /*2*/r = C(/*1*/
////var /*4*/r2 = new C(/*3*/ // using void returning function as constructor
////var r3 = C./*5*/

goTo.marker('1');
verify.completionListContains('C');
edit.insert('C.x);');

verify.quickInfoAt("2", "var r: void");

goTo.marker('3');
verify.completionListContains('C');
edit.insert('C.x);');

verify.quickInfoAt("4", "var r2: any");

goTo.marker('5');
verify.completionListContains('x');
verify.completionListContains('foo');
edit.insert('x;');

verify.numberOfErrorsInCurrentFile(0);

redpajama_set_name: RedPajamaGithub


text:
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { SarkariResults } from '../pages/sarkari-results/sarkari-results';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { ServiceProviders } from '../providers/service-providers';
import { Util } from '../utils/util';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ListPage,
    SarkariResults
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ListPage,
    SarkariResults
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    ServiceProviders,
    Util
  ]
})
export class AppModule {}


text:
<?php
$TRANSLATIONS = array(
"Recovery key successfully enabled" => "恢复密钥成功启用",
"Could not enable recovery key. Please check your recovery key password!" => "不能启用恢复密钥。请检查恢复密钥密码!",
"Recovery key successfully disabled" => "恢复密钥成功禁用",
"Could not disable recovery key. Please check your recovery key password!" => "不能禁用恢复密钥。请检查恢复密钥密码!",
"Password successfully changed." => "密码修改成功。",
"Could not change the password. Maybe the old password was not correct." => "不能修改密码。旧密码可能不正确。",
"Private key password successfully updated." => "私钥密码成功更新。",
"Could not update the private key password. Maybe the old password was not correct." => "无法更新私钥密码。可能旧密码不正确。",
"Encryption app not initialized! Maybe the encryption app was re-enabled during your session. Please try to log out and log back in to initialize the encryption app." => "加密应用还没有初始化!可能加密应用在你会话期间已被重新启用。请注销并重新登录,以初始化加密应用。",
"Missing requirements." => "必填项未填写。",
"Please make sure that PHP 5.3.3 or newer is installed and that OpenSSL together with the PHP extension is enabled and configured properly. For now, the encryption app has been disabled." => "请确认安装了 PHP 5.3.3 或更新版本,且 OpenSSL 及其 PHP 扩展已经启用并正确配置。加密应用现在已被禁用。",
"Following users are not set up for encryption:" => "以下用户还没有设置加密:",
"Encryption" => "加密",
"Enable recovery key (allow to recover users files in case of password loss):" => "启用恢复密钥(允许你在密码丢失后恢复文件):",
"Recovery key password" => "恢复密钥密码",
"Repeat Recovery key password" => "重复恢复密钥密码",
"Enabled" => "开启",
"Disabled" => "禁用",
"Change recovery key password:" => "更改恢复密钥密码",
"Old Recovery key password" => "旧的恢复密钥密码",
"New Recovery key password" => "新的恢复密钥密码",
"Repeat New Recovery key password" => "重复新的密钥恢复密码",
"Change Password" => "修改密码",
"Your private key password no longer match your log-in password:" => "您的私钥密码不再匹配您的登录密码:",
"Set your old private key password to your current log-in password." => "讲您旧的私钥密码改为当前登录密码。",
" If you don't remember your old password you can ask your administrator to recover your files." => "如果您记不住旧的密码,您可以请求管理员恢复您的文件。",
"Old log-in password" => "旧登录密码",
"Current log-in password" => "当前登录密码",
"Update Private Key Password" => "更新私钥密码",
"Enable password recovery:" => "启用密码恢复:",
"Enabling this option will allow you to reobtain access to your encrypted files in case of password loss" => "启用该项将允许你在密码丢失后取回您的加密文件",
"File recovery settings updated" => "文件恢复设置已更新",
"Could not update file recovery" => "不能更新文件恢复"
);
$PLURAL_FORMS = "nplurals=1; plural=0;";


text:
@implementation TestAnimations

@synthesize animationManager;

- (void) didLoadFromCCB
{
    self.animationManager = self.userObject;
}

- (void) pressedIdle:(id)sender
{
    [animationManager runAnimationsForSequenceNamed:@"Idle" tweenDuration:0.3f];
}

- (void) pressedWave:(id)sender
{
    [animationManager runAnimationsForSequenceNamed:@"Wave" tweenDuration:0.3f];
}

- (void) pressedJump:(id)sender
{
    [animationManager runAnimationsForSequenceNamed:@"Jump" tweenDuration:0.3f];
}

- (void) pressedFunky:(id)sender
{
    [animationManager runAnimationsForSequenceNamed:@"Funky" tweenDuration:0.3f];
}

- (void) dealloc
{
    self.animationManager = NULL;
    [super dealloc];
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ProcErrorCallback (Apache Tomcat 9.0.0.M11 API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.tomcat.jni

Interface ProcErrorCallback

public interface ProcErrorCallback

ProcErrorCallback Interface

Author:

Mladen Turk

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
callback(long pool,
        int err,
        String description)

Called in the child process if APR encounters an error
 in the child prior to running the specified program.

Method Detail

callback

void callback(long pool,
              int err,
              String description)

Called in the child process if APR encounters an error
 in the child prior to running the specified program.

Parameters:

pool - Pool associated with the apr_proc_t.  If your child
             error function needs user data, associate it with this
             pool.

err - APR error code describing the error

description - Text description of type of processing which failed

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

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


text:
using namespace Rcpp;

// hypermap
DataFrame hypermap(DataFrame net, double gma, double T, int k_speedup, double m_in, double L_in, double window, DataFrame theta);
RcppExport SEXP NetHypGeom_hypermap(SEXP netSEXP, SEXP gmaSEXP, SEXP TSEXP, SEXP k_speedupSEXP, SEXP m_inSEXP, SEXP L_inSEXP, SEXP windowSEXP, SEXP thetaSEXP) {
BEGIN_RCPP
    Rcpp::RObject rcpp_result_gen;
    Rcpp::RNGScope rcpp_rngScope_gen;
    Rcpp::traits::input_parameter< DataFrame >::type net(netSEXP);
    Rcpp::traits::input_parameter< double >::type gma(gmaSEXP);
    Rcpp::traits::input_parameter< double >::type T(TSEXP);
    Rcpp::traits::input_parameter< int >::type k_speedup(k_speedupSEXP);
    Rcpp::traits::input_parameter< double >::type m_in(m_inSEXP);
    Rcpp::traits::input_parameter< double >::type L_in(L_inSEXP);
    Rcpp::traits::input_parameter< double >::type window(windowSEXP);
    Rcpp::traits::input_parameter< DataFrame >::type theta(thetaSEXP);
    rcpp_result_gen = Rcpp::wrap(hypermap(net, gma, T, k_speedup, m_in, L_in, window, theta));
    return rcpp_result_gen;
END_RCPP
}

static const R_CallMethodDef CallEntries[] = {
    {"NetHypGeom_hypermap", (DL_FUNC) &NetHypGeom_hypermap, 8},
    {NULL, NULL, 0}
};

RcppExport void R_init_NetHypGeom(DllInfo *dll) {
    R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
}


text:
namespace ppapi {
namespace thunk {

namespace {

PP_Resource Create(PP_Instance instance) {
  VLOG(4) << "PPB_URLLoader::Create()";
  EnterResourceCreation enter(instance);
  if (enter.failed())
    return 0;
  return enter.functions()->CreateURLLoader(instance);
}

PP_Bool IsURLLoader(PP_Resource resource) {
  VLOG(4) << "PPB_URLLoader::IsURLLoader()";
  EnterResource<PPB_URLLoader_API> enter(resource, false);
  return PP_FromBool(enter.succeeded());
}

int32_t Open(PP_Resource loader,
             PP_Resource request_info,
             struct PP_CompletionCallback callback) {
  VLOG(4) << "PPB_URLLoader::Open()";
  EnterResource<PPB_URLLoader_API> enter(loader, callback, true);
  if (enter.failed())
    return enter.retval();
  return enter.SetResult(enter.object()->Open(request_info, enter.callback()));
}

int32_t FollowRedirect(PP_Resource loader,
                       struct PP_CompletionCallback callback) {
  VLOG(4) << "PPB_URLLoader::FollowRedirect()";
  EnterResource<PPB_URLLoader_API> enter(loader, callback, true);
  if (enter.failed())
    return enter.retval();
  return enter.SetResult(enter.object()->FollowRedirect(enter.callback()));
}

PP_Bool GetUploadProgress(PP_Resource loader,
                          int64_t* bytes_sent,
                          int64_t* total_bytes_to_be_sent) {
  VLOG(4) << "PPB_URLLoader::GetUploadProgress()";
  EnterResource<PPB_URLLoader_API> enter(loader, true);
  if (enter.failed()) {
    memset(bytes_sent, 0, sizeof(*bytes_sent));
    memset(total_bytes_to_be_sent, 0, sizeof(*total_bytes_to_be_sent));
    return PP_FALSE;
  }
  return enter.object()->GetUploadProgress(bytes_sent, total_bytes_to_be_sent);
}

PP_Bool GetDownloadProgress(PP_Resource loader,
                            int64_t* bytes_received,
                            int64_t* total_bytes_to_be_received) {
  VLOG(4) << "PPB_URLLoader::GetDownloadProgress()";
  EnterResource<PPB_URLLoader_API> enter(loader, true);
  if (enter.failed()) {
    memset(bytes_received, 0, sizeof(*bytes_received));
    memset(total_bytes_to_be_received, 0, sizeof(*total_bytes_to_be_received));
    return PP_FALSE;
  }
  return enter.object()->GetDownloadProgress(bytes_received,
                                             total_bytes_to_be_received);
}

PP_Resource GetResponseInfo(PP_Resource loader) {
  VLOG(4) << "PPB_URLLoader::GetResponseInfo()";
  EnterResource<PPB_URLLoader_API> enter(loader, true);
  if (enter.failed())
    return 0;
  return enter.object()->GetResponseInfo();
}

int32_t ReadResponseBody(PP_Resource loader,
                         void* buffer,
                         int32_t bytes_to_read,
                         struct PP_CompletionCallback callback) {
  VLOG(4) << "PPB_URLLoader::ReadResponseBody()";
  EnterResource<PPB_URLLoader_API> enter(loader, callback, true);
  if (enter.failed())
    return enter.retval();
  return enter.SetResult(enter.object()->ReadResponseBody(buffer,
                                                          bytes_to_read,
                                                          enter.callback()));
}

int32_t FinishStreamingToFile(PP_Resource loader,
                              struct PP_CompletionCallback callback) {
  VLOG(4) << "PPB_URLLoader::FinishStreamingToFile()";
  EnterResource<PPB_URLLoader_API> enter(loader, callback, true);
  if (enter.failed())
    return enter.retval();
  return enter.SetResult(enter.object()->FinishStreamingToFile(
      enter.callback()));
}

void Close(PP_Resource loader) {
  VLOG(4) << "PPB_URLLoader::Close()";
  EnterResource<PPB_URLLoader_API> enter(loader, true);
  if (enter.failed())
    return;
  enter.object()->Close();
}

const PPB_URLLoader_1_0 g_ppb_urlloader_thunk_1_0 = {
  &Create,
  &IsURLLoader,
  &Open,
  &FollowRedirect,
  &GetUploadProgress,
  &GetDownloadProgress,
  &GetResponseInfo,
  &ReadResponseBody,
  &FinishStreamingToFile,
  &Close
};

}  // namespace

const PPB_URLLoader_1_0* GetPPB_URLLoader_1_0_Thunk() {
  return &g_ppb_urlloader_thunk_1_0;
}

}  // namespace thunk
}  // namespace ppapi


text:
<?php

namespace app\modules\approval\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\approval\models\ApprovalProcessStep;

/**
 * SearchApprovalProcessStep represents the model behind the search form about `app\modules\approval\models\ApprovalProcessStep`.
 */
class SearchApprovalProcessStep extends ApprovalProcessStep
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'process_id', 'step', 'created_at'], 'integer'],
            [['step_name', 'approval_user'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ApprovalProcessStep::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'process_id' => $this->process_id,
            'step' => $this->step,
            'created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['like', 'step_name', $this->step_name])
            ->andFilterWhere(['like', 'approval_user', $this->approval_user]);

        return $dataProvider;
    }
}


text:
package org.apache.ambari.logsearch.config.api.model.inputconfig;

public interface MapDateDescriptor extends MapFieldDescriptor {
  String getSourceDatePattern();

  String getTargetDatePattern();
}


text:
<?php

namespace IPS\core\ProfileSync;

/* To prevent PHP errors (extending class does not exist) revealing path */
if ( !defined( '\IPS\SUITE_UNIQUE_KEY' ) )
{
	header( ( isset( $_SERVER['SERVER_PROTOCOL'] ) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0' ) . ' 403 Forbidden' );
	exit;
}

/**
 * Twitter Profile Sync
 */
class _Twitter extends ProfileSyncAbstract
{
	/**
	 * @brief    Login handler key
	 */
	public static $loginKey = 'Twitter';

	/**
	 * @brief    Icon
	 */
	public static $icon = 'twitter';

	/**
	 * @brief    User data
	 */
	protected $user = NULL;

	/**
	 * Get user data
	 *
	 * @return    array
	 */
	protected function user()
	{
		if ( ( $this->user === NULL ) and $this->member->twitter_token )
		{
			try
			{
				$loginHandler = \IPS\Login\LoginAbstract::load( 'twitter' );

				$this->user = $loginHandler->sendRequest(
					'get', "https://api.twitter.com/1.1/account/verify_credentials.json", array(),
					$this->member->twitter_token, $this->member->twitter_secret
				)->decodeJson();

				if ( isset( $this->user['errors'] ) )
				{
					throw new \Exception;
				}
			}
			catch ( \Exception $e )
			{
				$this->member->twitter_token  = '';
				$this->member->twitter_secret = '';
				$this->member->save();

				\IPS\Log::log( isset( $this->user['errors'] ) ? var_export( $this->user['errors'], true ) : $e, 'twitter' );
			}
		}

		return $this->user;
	}

	/**
	 * Is connected?
	 *
	 * @return    bool
	 */
	public function connected()
	{
		return ( $this->member->twitter_id and $this->member->twitter_token and $this->member->twitter_secret );
	}

	/**
	 * Get photo
	 *
	 * @return    \IPS\Http\Url
	 */
	public function photo()
	{
		return $this->resourceUrl( $this->user(), 'profile_image_url' );
	}

	/**
	 * Get cover photo
	 *
	 * @return    \IPS\File|NULL
	 */
	public function cover()
	{
		if ( $coverUrl = $this->resourceUrl( $this->user(), 'profile_background_image_url' ) )
		{
			try
			{
				return $coverUrl->import( 'core_Profile' );
			}
			catch ( \IPS\Http\Request\Exception $e )
			{
				\IPS\Log::log( $e, 'twitter' );
			}
		}

		return NULL;
	}

	/**
	 * Get name
	 *
	 * @return    string
	 */
	public function name()
	{
		$user = $this->user();
		if ( isset( $user['screen_name'] ) )
		{
			return $user['screen_name'];
		}
	}

	/**
	 * Get status
	 *
	 * @return    \IPS\core\Statuses\Status|null
	 */
	public function status()
	{
		$user = $this->user();

		if ( !empty( $user['status'] ) )
		{
			$status = \IPS\core\Statuses\Status::createItem(
				$this->member, $this->member->ip_address, new \IPS\DateTime( $user['status']['created_at'] )
			);

			$status->content = $this->_parseStatusText( $user['status']['text'] );

			return $status;
		}

		return NULL;
	}

	/**
	 * Disassociate
	 *
	 * @return    void
	 */
	protected function _disassociate()
	{
		$this->member->twitter_id     = 0;
		$this->member->twitter_token  = '';
		$this->member->twitter_secret = '';
		$this->member->save();
	}

	/**
	 * Get an HTTPS or HTTP resource URL (HTTPS if available and we are using it locally, otherwise HTTP)
	 *
	 * @param   array       $user
	 * @param   string      $fieldName
	 * @return  \IPS\Http\Url|NULL
	 */
	protected function resourceUrl( $user, $fieldName )
	{
		$scheme = \IPS\Http\Url::internal( '' )->data['scheme'];

		if ( ( $scheme === 'https' ) or \IPS\Settings::i()->logins_over_https )
		{
			if ( !empty( $user[ $fieldName . '_https' ] ) )
			{
				return \IPS\Http\Url::external( $user[ $fieldName . '_https' ] );
			}
		}

		if ( !empty( $user[ $fieldName ] ) )
		{
			return \IPS\Http\Url::external( $user[ $fieldName ] );
		}

		return NULL;
	}
}


text:
package dyconf

import (
	"fmt"
	"io/ioutil"
	"os"
	"regexp"
	"testing"

	"github.com/facebookgo/ensure"
)

func TestDyconfSetGetClose(t *testing.T) {
	cases := []struct {
		data map[string][]byte
	}{
		{
			data: map[string][]byte{
				"Key1": []byte("Value1"),
				"Key2": []byte("Value2"),
				"Key3": []byte("Value3"),
			},
		},
	}

	for i, tc := range cases {
		// Setup
		tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfSetGetClose-Case%d-", i))
		defer os.Remove(tmpFileName)

		// Set the keys.
		wc, err := NewManager(tmpFileName)
		ensure.Nil(t, err, fmt.Sprintf("Case: [%d]", i))
		for key, val := range tc.data {
			err = wc.Set(key, val)
			ensure.Nil(t, err, fmt.Sprintf("Case: [%d]", i))
		}

		// Get the keys.
		conf, err := New(tmpFileName)
		ensure.Nil(t, err, fmt.Sprintf("Case: [%d]", i))
		for key, expectedVal := range tc.data {
			val, err := conf.Get(key)
			ensure.Nil(t, err, fmt.Sprintf("Case: [%d]", i))
			ensure.DeepEqual(t, val, expectedVal, fmt.Sprintf("Case: [%d]", i))
		}

		// Close the writer.
		err = wc.Close()
		ensure.Nil(t, err, fmt.Sprintf("Case-%d", i))

		// Close the reader.
		err = conf.Close()
		ensure.Nil(t, err, fmt.Sprintf("Case-%d", i))
	}
}

func TestDyconfOverwrite(t *testing.T) {
	setSequence := []struct {
		key string
		val []byte
	}{
		{key: "overwrite key", val: []byte("big value 1")},
		{key: "overwrite key", val: []byte("Bigger Value 1")},
		{key: "overwrite key", val: []byte("Bigger Value 2")},
		{key: "some other key", val: []byte("some other value")},
		{key: "overwrite key", val: []byte("very big value 1")},
		{key: "overwrite key", val: []byte("smallval")},
	}
	expected := map[string][]byte{
		"overwrite key":  []byte("smallval"),
		"some other key": []byte("some other value"),
	}

	// Setup
	tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfOverwrite-"))
	defer os.Remove(tmpFileName)

	// Set the keys in the given sequence.
	wc, err := NewManager(tmpFileName)
	ensure.Nil(t, err)
	for _, kvPair := range setSequence {
		err = wc.Set(kvPair.key, kvPair.val)
		ensure.Nil(t, err)
	}

	// Check if the results are as expected.
	conf, err := New(tmpFileName)
	ensure.Nil(t, err)
	for key, expectedVal := range expected {
		val, err := conf.Get(key)
		ensure.Nil(t, err)
		ensure.DeepEqual(t, val, expectedVal)
	}

	err = conf.Close()
	ensure.Nil(t, err)
	err = wc.Close()
	ensure.Nil(t, err)
}

func TestDyconfCollisions(t *testing.T) {
	setSequence := []struct {
		key string
		val []byte
	}{
		{key: "key-1", val: []byte("big value 1")},
		{key: "key-1", val: []byte("Bigger Value 1")},
		{key: "key-1", val: []byte("Bigger Value 2")},
		{key: "some other key", val: []byte("some other value")},
		{key: "key-1", val: []byte("very big value 1")},
		{key: "key-2", val: []byte("Value-222")},
		{key: "key-1", val: []byte("smallval")},
		{key: "key-2", val: []byte("Value-2")},
	}
	expected := map[string][]byte{
		"key-1":          []byte("smallval"),
		"key-2":          []byte("Value-2"),
		"some other key": []byte("some other value"),
	}

	// Setup
	tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfCollisions-"))
	defer os.Remove(tmpFileName)

	// replace hashing function.
	savedHashfunc := defaultHashFunc
	defaultHashFunc = func(key string) (uint32, error) {
		return 32, nil // Everything falls into bucket-32
	}
	defer func() {
		defaultHashFunc = savedHashfunc // restore
	}()

	// Set the keys in the given sequence.
	wc, err := NewManager(tmpFileName)
	ensure.Nil(t, err)
	for _, kvPair := range setSequence {
		err = wc.Set(kvPair.key, kvPair.val)
		ensure.Nil(t, err)
	}

	// Check if the results are as expected.
	conf, err := New(tmpFileName)
	ensure.Nil(t, err)
	for key, expectedVal := range expected {
		val, err := conf.Get(key)
		ensure.Nil(t, err)
		ensure.DeepEqual(t, val, expectedVal)
	}

	err = conf.Close()
	ensure.Nil(t, err)
	err = wc.Close()
	ensure.Nil(t, err)
}

func TestDyconfDelete(t *testing.T) {
	setSequence := []struct {
		key string
		val []byte
	}{
		{key: "key-1", val: []byte("big value 1")},
		{key: "key-1", val: []byte("Bigger Value 1")},
		{key: "key-1", val: []byte("Bigger Value 2")},
		{key: "Non deleted key", val: []byte("Non deleted value")},
		{key: "key-1", val: []byte("very big value 1")},
		{key: "key-2", val: []byte("Value-222")},
		{key: "key-3", val: []byte("Value-3")},
		{key: "key-1", val: []byte("smallval")},
		{key: "key-2", val: []byte("Value-2")},
		{key: "One More Non deleted key", val: []byte("One more Non deleted value")},
	}
	deleteKeys := []string{"key-1", "key-2", "key-3", "NonExistingKey"}
	expected := map[string][]byte{
		"Non deleted key":          []byte("Non deleted value"),
		"One More Non deleted key": []byte("One more Non deleted value"),
	}

	// Setup
	tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfDelete-"))
	defer os.Remove(tmpFileName)

	// Set the keys in the given sequence.
	wc, err := NewManager(tmpFileName)
	ensure.Nil(t, err)
	for _, kvPair := range setSequence {
		err = wc.Set(kvPair.key, kvPair.val)
		ensure.Nil(t, err)
	}
	// delete the keys.
	for _, delKey := range deleteKeys {
		err = wc.Delete(delKey)
		ensure.Nil(t, err)
	}

	// deleted keys must be gone.
	conf, err := New(tmpFileName)
	ensure.Nil(t, err)
	for _, delKey := range deleteKeys {
		val, err := conf.Get(delKey)
		ensure.Err(t, err, regexp.MustCompile(`^dyconf: key .* was not found.*`))
		ensure.True(t, (val == nil))
	}

	// expected key-value pairs must be present.
	for key, expectedVal := range expected {
		val, err := conf.Get(key)
		ensure.Nil(t, err)
		ensure.DeepEqual(t, val, expectedVal)
	}

	// Close.
	err = conf.Close()
	ensure.Nil(t, err)
	err = wc.Close()
	ensure.Nil(t, err)
}

func TestDyconfDeleteWithCollisions(t *testing.T) {
	setSequence := []struct {
		key string
		val []byte
	}{
		{key: "key-1", val: []byte("big value 1")},
		{key: "key-1", val: []byte("Bigger Value 1")},
		{key: "key-1", val: []byte("Bigger Value 2")},
		{key: "Non deleted key", val: []byte("Non deleted value")},
		{key: "key-1", val: []byte("very big value 1")},
		{key: "key-2", val: []byte("Value-222")},
		{key: "key-3", val: []byte("Value-3")},
		{key: "key-1", val: []byte("smallval")},
		{key: "key-2", val: []byte("Value-2")},
		{key: "One More Non deleted key", val: []byte("One more Non deleted value")},
	}
	deleteKeys := []string{"key-1", "key-2", "key-3", "NonExistingKey"}
	expected := map[string][]byte{
		"Non deleted key":          []byte("Non deleted value"),
		"One More Non deleted key": []byte("One more Non deleted value"),
	}

	// Setup
	tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfDeleteWithCollisions-"))
	defer os.Remove(tmpFileName)

	// replace hashing function.
	savedHashfunc := defaultHashFunc
	defaultHashFunc = func(key string) (uint32, error) {
		i, err := savedHashfunc(key)
		return i % 2, err // Everything falls into either bucket 0 or 1
	}
	defer func() {
		defaultHashFunc = savedHashfunc // restore
	}()

	// Set the keys in the given sequence.
	wc, err := NewManager(tmpFileName)
	ensure.Nil(t, err)
	for _, kvPair := range setSequence {
		err = wc.Set(kvPair.key, kvPair.val)
		ensure.Nil(t, err)
	}
	// delete the keys.
	for _, delKey := range deleteKeys {
		err = wc.Delete(delKey)
		ensure.Nil(t, err)
	}

	// deleted keys must be gone.
	conf, err := New(tmpFileName)
	ensure.Nil(t, err)
	for _, delKey := range deleteKeys {
		val, err := conf.Get(delKey)
		ensure.Err(t, err, regexp.MustCompile(`^dyconf: key .* was not found.*`))
		ensure.True(t, (val == nil))
	}

	// expected key-value pairs must be present.
	for key, expectedVal := range expected {
		val, err := conf.Get(key)
		ensure.Nil(t, err)
		ensure.DeepEqual(t, val, expectedVal)
	}

	// Close.
	err = conf.Close()
	ensure.Nil(t, err)
	err = wc.Close()
	ensure.Nil(t, err)
}

func TestDyconfInitErrors(t *testing.T) {
	// try opening a non existing file.
	conf, err := New("/tmp/dyconf-nonexisting-rkkbnbrejhhfellgkrhleuhutncdejvr")
	ensure.Err(t, err, regexp.MustCompile(`^dyconf: failed to open the file.*`))
	ensure.Nil(t, conf)
}

func TestDyconfWriteInitNewFile(t *testing.T) {
	// Create the file first.
	tmpFileName := setupTempFile(t, "TestDyconfWriteInitNewFile-")
	os.Remove(tmpFileName)

	// Initialize the writer.
	wc, err := NewManager(tmpFileName)
	ensure.Nil(t, err)
	ensure.Nil(t, wc.Close())

	// Make sure the file is created and then delete it.
	_, err = os.Stat(tmpFileName)
	ensure.Nil(t, err)
	ensure.Nil(t, os.Remove(tmpFileName))
}

// TestDyconfWriteInitExistingFile tests the initialization of existing config file for writing.
func TestDyconfWriteInitExistingFile(t *testing.T) {
	// Create the file first.
	tmpFileName := setupTempFile(t, "TestDyconfWriteInitExistingFile-")
	os.Remove(tmpFileName)

	// Initialize the writer and create a new config file.
	m, err := NewManager(tmpFileName)
	ensure.Nil(t, err)
	ensure.Nil(t, m.Close())
	// Make sure the file is created.
	_, err = os.Stat(tmpFileName)
	ensure.Nil(t, err)

	// Initialize the writer with the existing config file.
	m, err = NewManager(tmpFileName)
	ensure.Nil(t, err)
	ensure.Nil(t, m.Close())
}

func setupTempFile(t *testing.T, prefix string) string {
	tmpFile, err := ioutil.TempFile("", prefix)
	ensure.Nil(t, err)
	defer tmpFile.Close()
	os.Remove(tmpFile.Name())

	return tmpFile.Name()
}

func TestDyconfMap(t *testing.T) {
	cases := []struct {
		kv []struct {
			key string
			val []byte
		}
	}{
		{ // Case-0: key1 is overwritten.
			kv: []struct {
				key string
				val []byte
			}{
				{key: "key1", val: []byte("val1")},
				{key: "key2", val: []byte("val2")},
				{key: "key1", val: []byte("val1_1")},
				{key: "key3", val: []byte("val3")},
			},
		},
	}

	// Test with normal hashing.
	for i, tc := range cases {
		tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfMap-case-%d-", i))
		// Initialize the writer.
		wc, err := NewManager(tmpFileName)
		defer os.Remove(tmpFileName)
		ensure.Nil(t, err)

		expected := make(map[string][]byte)
		for _, kv := range tc.kv {
			ensure.Nil(t, wc.Set(kv.key, kv.val))
			expected[kv.key] = kv.val
		}
		retMap, err := wc.Map()
		ensure.Nil(t, err, fmt.Sprintf("Case-%d", i))
		ensure.DeepEqual(t, retMap, expected, fmt.Sprintf("Case-%d", i))
		ensure.Nil(t, wc.Close())
	}

	// Test with collisions.
	savedHashfunc := defaultHashFunc
	defaultHashFunc = func(key string) (uint32, error) {
		return 20, nil // Everything falls into bucket-20
	}
	defer func() {
		defaultHashFunc = savedHashfunc // restore
	}()
	for i, tc := range cases {
		tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfMap-case-%d-", i))
		// Initialize the writer.
		wc, err := NewManager(tmpFileName)
		defer os.Remove(tmpFileName)
		ensure.Nil(t, err)

		expected := make(map[string][]byte)
		for _, kv := range tc.kv {
			ensure.Nil(t, wc.Set(kv.key, kv.val))
			expected[kv.key] = kv.val
		}
		retMap, err := wc.Map()
		ensure.Nil(t, err, fmt.Sprintf("Case-%d", i))
		ensure.DeepEqual(t, retMap, expected, fmt.Sprintf("Case-%d", i))
		ensure.Nil(t, wc.Close())
	}
}

func TestDyconfDefrag(t *testing.T) {
	kvPairs := []struct {
		key string
		val []byte
	}{
		// overwrite the same key with different data size causing fragmentation.
		{key: "key", val: []byte("val1")},
		{key: "key", val: []byte("val22")},
		{key: "key", val: []byte("val333")},
		{key: "key", val: []byte("val4444")},
	}
	expectedUsedByteCount := (&dataRecord{key: []byte("key"), data: []byte("val4444")}).size()

	// Initialize the writer.
	tmpFileName := setupTempFile(t, fmt.Sprintf("TestDyconfDefrag-"))
	m, err := NewManager(tmpFileName)
	defer os.Remove(tmpFileName)
	ensure.Nil(t, err)

	for _, kv := range kvPairs {
		ensure.Nil(t, m.Set(kv.key, kv.val))
	}
	// save previous free byte count
	prevFreeBytes, err := m.freeDataByteCount()
	ensure.Nil(t, err)

	// defrag
	ensure.Nil(t, m.Defrag())

	// new free byte count
	newFreeBytes, err := m.freeDataByteCount()
	ensure.Nil(t, err)

	// new free byte count must be greater than previous one.
	ensure.True(t, newFreeBytes > prevFreeBytes)

	// Also verify the size of the data block.
	usedByteCount, err := m.dataBlockSize()
	ensure.Nil(t, err)
	ensure.DeepEqual(t, usedByteCount, expectedUsedByteCount)

	ensure.Nil(t, m.Close())
}


text:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace AlbumReviewerFrontend.Utils
{
    /// <summary>
    /// Generic ImageHelper
    /// </summary>
    public static class ImageHelper
    {
        public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText)
        {
            return Image(helper, id, url, alternateText, null);
        }

        public static HtmlString Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
        {
            // Instantiate a UrlHelper
            var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);

            // Create tag builder
            var builder = new TagBuilder("img");

            // Create valid id
            builder.GenerateId(id);

            // Add attributes
            builder.MergeAttribute("src", urlHelper.Content(url));
            builder.MergeAttribute("alt", alternateText);
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            // Render tag
            var ret = new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));

            return ret;
        }
    }
}


text:
package de.gw.auto.service.implementation;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import de.gw.auto.dao.AutoDAO;
import de.gw.auto.domain.Auto;
import de.gw.auto.domain.Benutzer;
import de.gw.auto.service.RegisteredUser;

@Service
public class AutoService {

	@Autowired
	AutoDAO autoDao;

	public RegisteredUser addAuto(RegisteredUser user, Auto auto){
		user = new RegisteredUser(autoDao.save(user, auto));
		return user;
	}

	public Auto find(String kennzeichen) {
		return autoDao.find(kennzeichen);
	}

	public Auto findByID(int id) {
		return autoDao.findById(id);

	}

	public List<Auto> findByBenutzer(List<Benutzer> users){
		return autoDao.findByBenutzer(users);
	}

	public Auto updateAuto(Auto a){
		return autoDao.updateAuto(a.getId(), a.getKraftstoff(), a.getErstZulassung(), a.getKauf(), a.getKmKauf(), a.getKmAktuell());
	}
}


text:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');

/*
 * API_NAME: Update User's Password
 * API_DESCRIPTION: Method for update user avatar
 * API_ACCESS: admin only
 * API_INPUT: userid - integer, userid
 * API_INPUT: email - string, user email
 * API_INPUT: password - string, new password
 * API_OKRESPONSE: { "result":"ok" }
 */

$curdir = dirname(__FILE__);
include_once ($curdir."/../api.lib/api.base.php");
include_once ($curdir."/../api.lib/api.security.php");
include_once ($curdir."/../../config/config.php");

APIHelpers::checkAuth();

if (!APISecurity::isAdmin())
	APIHelpers::showerror(1120, 'only for admin');

if (!APIHelpers::issetParam('userid'))
  APIHelpers::showerror(1121, 'Not found parameter "userid"');

$userid = APIHelpers::getParam('userid', '');

if (!is_numeric($userid))
	APIHelpers::showerror(1122, 'userid must be numeric');

if ($userid == APISecurity::userid())
	APIHelpers::showerror(1123, 'Please use another function for change your password');

$result = array(
	'result' => 'fail',
	'data' => array(),
);

$conn = APIHelpers::createConnection($config);

if (!APIHelpers::issetParam('password'))
  APIHelpers::showerror(1124, 'Not found parameter "password"');

// TODO must be get email by iduser!!!!
if (!APIHelpers::issetParam('email'))
  APIHelpers::showerror(1125, 'Not found parameter "email"');

$password = APIHelpers::getParam('password', '');
$email = APIHelpers::getParam('email', '');

$password = APISecurity::generatePassword2($email, $password);

$result['data']['password'] = $password;
$result['data']['email'] = $email;
$result['data']['userid'] = $userid;

if (strlen($password) <= 3)
  APIHelpers::showerror(1126, '"password" must be more then 3 characters');

try {
	$query = 'UPDATE users SET pass = ? WHERE id = ? AND email = ?';
	$stmt = $conn->prepare($query);
	if ($stmt->execute(array($password, $userid, $email)))
		$result['result'] = 'ok';
	else
		$result['result'] = 'fail';
} catch(PDOException $e) {
	APIHelpers::showerror(1127, $e->getMessage());
}

echo json_encode($result);


text:
#include "stdafx.h"

#include <d2d1.h>
#include <d2d1helper.h>

#include "QuadraticBezierSegment.h"

using namespace System;

namespace SlimDX
{
namespace Direct2D
{
}
}


text:
var git = require('../git')

module.exports = {
  detect: function() {
    return !!process.env.JENKINS_URL
  },

  configuration: function() {
    console.log('    Jenkins CI Detected')
    return {
      service: 'jenkins',
      commit:
        process.env.ghprbActualCommit || process.env.GIT_COMMIT || git.head(),
      branch:
        process.env.ghprbSourceBranch ||
        process.env.GIT_BRANCH ||
        process.env.BRANCH_NAME,
      build: process.env.BUILD_NUMBER,
      build_url: process.env.BUILD_URL,
      root: process.env.WORKSPACE,
      pr: process.env.ghprbPullId || process.env.CHANGE_ID,
    }
  },
}


text:
<?php

if ( ! defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Manage account participant.
 *
 * @package CarbonCopy
 * @subpackage account
 * @author porquero
 */
class participant extends MX_Controller {

    /**
     * Get all participants from account
     *
     * @return array
     */
    function list_for_resume()
    {
        $this->load->module('file/read');

        $context = '_accounts/' . Modules::run('file/misc/final_slash', $this->session->userdata('current_account')) . '_participants/';
        $participants = $this->read->files($context);
        $result = array();

        foreach ($participants as $participant) {
            $participant_info = (object) $this->read->json_content($participant);
            if ($participant_info->active === TRUE) {
                $result[] = $participant_info;
            }
        }

        return $result;
    }

    /**
     * Get participants for context.
     *
     * @param string $context
     * @return array
     */
    public function list_for_context($context, $kind = 'context')
    {
        if (empty($context)) {
            die('Empty context!');
        }

        $context_info = Modules::run('file/read/json_content', Modules::run('file/misc/final_slash', $context) . 'info_' . $kind . '.json');
        $result = array();

        // TODO: add type validation to avoid server lock!
        if ( ! is_array($context_info)) {
            Plogger::var_dump($context_info);
            die("Fix this!. [{$context}]" . __FILE__ . __LINE__);
        }

        if (preg_match('/\,/', $context_info['participants']) === 1) {
            $participants = explode(',', $context_info['participants']);

            foreach ($participants as $participant) {
                if (empty($participant)) {
                    continue;
                }
                $result[] = $this->info($participant);
            }
        }
        elseif ($context_info['participants'] === '') {
            $context = preg_replace('/\/_topics/', '', $context);
            $context = preg_replace('/\/[a-z0-9-]*$/', '', $context);

            if (preg_match('/\/contexts$/', $context) === 1) {
                return $this->list_for_resume();
            }

            return $this->list_for_context($context);
        }
        else {
            $result[] = $this->info($context_info['participants']);
        }

        return $result;
    }

    /**
     * Get participants for account
     *
     * @param boolean $include_disabled Decides if include disabled participants.
     *
     * @return type
     */
    public function list_for_account($include_disabled = FALSE)
    {
        if ($include_disabled === TRUE) {
            $this->load->module('file/read');
            $result = $this->read->files_basename(_INC_ROOT . '_accounts/' . $this->session->userdata('current_account') . '/_participants');
        }
        else {
            $participants = $this->list_for_resume();
            foreach ($participants as $participant) {
                $result[] = $participant->info['id'] . '.json';
            }
        }

        return $result;
    }

    /**
     * Get account participants and generate select html form
     *
     * @param string $id_name
     * @return string html output
     */
    public function html_select_for_account($id_name, $select = NULL)
    {
        $participants = $this->list_for_account();
        $output = '<select name="' . $id_name . '" id="' . $id_name . '">';
        $select = $select === NULL ? connected_user() : $select;

        foreach ($participants as $participant) {
            $participant = preg_replace('/\.json/', '', $participant);
            $selected = $participant == $select ? 'selected' : '';
            $output .= '<option value="' . $participant . '" ' . $selected . '>' . $participant . '</option>';
        }
        $output .= '</select>';

        return $output;
    }

    /**
     * Get context participants and generate select html form
     *
     * @param string $id_name
     *
     * @return string html output
     */
    public function html_select_for_context($context, $id_name, $select = NULL, $is_topic = FALSE)
    {
        if (empty($context)) {
            die('Contexto vacío!');
        }

        $this->load->module('file/misc');
        $select = $select === NULL ? connected_user() : $select;

        $context = "_accounts/{$this->session->userdata('current_account')}/contexts/{$this->misc->unslug($context)}";
        $participants = $this->list_for_context($is_topic ? topic_real_path($context) : $context, $is_topic ? 'topic' : 'context');
        $output = '<select name="' . $id_name . '" id="' . $id_name . '">';

        foreach ($participants as $participant) {
            $participant = trim($participant->info['id']);
            $selected = $participant == $select ? 'selected' : '';
            $output .= '<option value="' . $participant . '" ' . $selected . '>' . $participant . '</option>';
        }
        $output .= '</select>';

        return $output;
    }

    /**
     * Get account participants and generate checkboxs html form
     *
     * @param type $id_name
     * @return type
     */
    public function html_checkbox_for_account($id_name, $check = array())
    {
        $participants = $this->list_for_account();
        $checked_all = count($check) > 0 ? '' : 'checked="checked"';
        $inherit = lang('inherit');
        $output = <<<PQR

        <input type="checkbox" value="all" {$checked_all} name="{$id_name}" id="{$id_name}" /> {$inherit}
PQR;

        foreach ($participants as $participant) {
            $participant = preg_replace('/\.json/', '', $participant);

            if (connected_user() === $participant) {
                continue;
            }

            $checked = in_array($participant, $check) ? 'checked' : '';
            $output .= '<input type="checkbox" value="' . $participant . '" name="' . $id_name . '[]" '
              . $checked . '/> ' . $participant . '';
        }
        $me = lang('me');
        $output .=<<<PQR
		<input type="checkbox" checked disabled /> {$me}

PQR;

        return $output;
    }

    /**
     * Get context participants and generate checkboxs html form
     *
     * @param string $context
     * @param string $id_name
     *
     * @return string
     */
    public function html_checkbox_for_context($context, $id_name, $for_check = array(), $is_topic = FALSE)
    {
        if (empty($context)) {
            die(lang('empty_context'));
        }

        $this->load->module('file/misc');

        $context = "_accounts/{$this->session->userdata('current_account')}/contexts/{$this->misc->unslug($context)}";
        $participants = $this->list_for_context($is_topic ? topic_real_path($context) : $context, $is_topic ? 'topic' : 'context');
        $checked_all = count($for_check) > 0 ? '' : 'checked="checked"';
        $inherit = lang('inherit');
        $output = <<<PQR

        <input type="checkbox" id="pa" value="all" {$checked_all} name="{$id_name}" id="{$id_name}" /> {$inherit}
PQR;

        foreach ($participants as $participant) {
            $participant = trim($participant->info['id']);

            if (connected_user() === $participant) {
                continue;
            }
            $checked = in_array($participant, $for_check) ? 'checked' : '';
            $output .= '<input type="checkbox" class="pp" value="' . $participant . '" name="' . $id_name . '[]" ' . $checked
              . ' /> ' . $participant . '';
        }
        $me = lang('me');
        $output .=<<<PQR
		<input type="checkbox" checked disabled /> {$me}

PQR;

        return $output;
    }

    /**
     * User profile
     *
     * @param string $username
     */
    public function profile($username, $menu_act = 'all', $ts_date = NULL)
    {
        is_connected();

        $this->load->module('cc/timeline');

        $file = _INC_ROOT . '_accounts/' . $this->session->userdata('current_account') . '/_participants/' . $username . '.json';
        $info = $this->info($username);

        $this->timeline->menu_act[$menu_act] = 'act';
        $participant_id = $menu_act === 'to_me' ? connected_user() : NULL;

        if (is_file($file)) {
            $data = json_decode(file_get_contents($file));
            $lang_username = lang('username');
            $lang_email = lang('email');
            $detail = <<<PQR

{$lang_username} {$data->info->id}

{$lang_email} {$info->email}

PQR;
            $tl_date = is_null($ts_date) ? '' : ': ' . account_date_format($ts_date);

            $this->tpl->variables(
              array(
                  'title' => $info->name,
                  'tl_title' => lang('user_timeline') . $tl_date,
                  'url_all' => '',
                  'url_to_me' => '',
                  'description' => $detail,
                  'participants' => Modules::run('account/participant/list_for_resume'),
                  'timeline' => $this->timeline->get_for_participant($username, TRUE, $participant_id, $ts_date),
                  'menu_act' => $this->timeline->menu_act,
                  'url_all' => site_url('/account/participant/profile/' . $username),
                  'url_to_me' => site_url('/account/participant/profile/' . $username . '/to_me'),
                  'url_ts' => site_url('/account/participant/profile/' . $username . '/' . $menu_act),
            ));
            $this->tpl->section('_view', 'profile.phtml');
            $this->tpl->section('_sidebar', '_sidebar_profile.phtml');
            $this->tpl->load_view(_TEMPLATE);
        }
        else {
            echo lang('participant_not_found');
        }
    }

    /**
     * LIst all people for account
     */
    public function all_people()
    {
        is_connected();
        $this->load->helper('form');
        $this->load->model('cc/m_user');

        $where_in = array();

        foreach ($this->list_for_account(TRUE) as $participant) {
            $where_in[] = preg_replace('/\.json/', '', $participant);
        }

        $this->tpl->variables(
          array(
              'title' => lang('people'),
              'footer' => js_tag('pub/' . _TEMPLATE . '/js/people.js'),
              'description' => lang('all_we_are'),
              'info_participants' => $this->m_user->where_in($where_in),
        ));
        $this->tpl->section('_view', 'all_people.phtml');
        $this->tpl->section('_sidebar', '_sidebar_people.phtml');
        $this->tpl->load_view(_TEMPLATE);
    }

    /**
     * Try to Invite user by email
     */
    public function invite()
    {
        $this->load->library('form_validation');
        $this->load->helper(array('form', 'language'));
        $this->load->language('cc_form_validation');
        $this->form_validation->set_error_delimiters('', '');

        $field = 'email';
        $rules = 'trim|required|min_length[5]|max_length[254]|valid_email';
        $this->form_validation->set_rules($field, 'lang:' . $field, $rules);

        if ($this->form_validation->run() === FALSE) {
            echo json_encode(array(
                'result' => 'fail',
                'message' => validation_errors()
            ));

            return;
        }

        // Send invitation.
        $this->load->model('cc/m_user');
        $this->load->library('email');
        $this->load->module('file/write');

        // Check if user belongs to account.
        if ($this->m_user->email_exists($this->input->post('email'))
          AND $this->m_user->has_account($this->m_user->username($this->input->post('email')), $this->session->userdata('current_account'))) {
            echo json_encode(array(
                'result' => 'fail',
                'message' => lang('already_belongs')
            ));

            return;
        }

        $user_data = $this->m_user->data(connected_user());
        $name = explode(' ', $user_data->name);

        // Avoid add unwanted user.
        $hash = uniqid();
        $this->write->archive(_INC_ROOT . '_accounts/' . $this->session->userdata('current_account') . '/_invitations/' . $hash, $this->input->post('email'));

        $mail_body = nl2br(sprintf(lang('invitation_mail'), $name[0], site_url(), $this->session->userdata('current_account'), $hash, site_url_ws()));

        // TODO Load email from configuration
        $this->email->from('noreply@carboncopycc.com', 'CarbonCopy');
        $this->email->to($this->input->post('email'));

        $this->email->subject(sprintf(lang('invitation_subject'), $name[0]));
        $this->email->message($mail_body);
        $this->email->set_mailtype('html');

        $this->email->send();

        echo json_encode(array(
            'result' => 'ok',
            'message' => ''
        ));
    }

    /**
     * Return user info
     *
     * @param string $username
     *
     * @return object
     */
    public function info($username)
    {
        $this->load->model('cc/m_user');

        return $this->m_user->data($username);
    }

    /**
     * Validate if participant belongs to account
     *
     * @param string $context
     * @param string $user
     *
     * @return type
     */
    public function belongs_to_account($user)
    {
        $participants = Modules::run('account/participant/list_for_resume');

        $plist = '';
        foreach ($participants as $participant) {
            $plist .= $participant->info['id'] . '|';
        }

        return strstr($plist, $user) !== FALSE;
    }

    /**
     * Participant config for current account.
     */
    public function config_form()
    {
        is_connected();

        $this->load->helper('form');
        $this->load->model('cc/m_user');

        $user_config = Modules::run('file/read/json_content', "_accounts/{$this->session->userdata('current_account')}/_participants/" . connected_user() . ".json");
        $user_data = $this->m_user->data(connected_user());

        $this->tpl->variables(
          array(
              'title' => 'Account config',
              'description' => '',
              'user_language' => $user_config['info']['language'],
              'footer' => js_tag('pub/js/jquery.form.js') . js_tag('pub/' . _TEMPLATE . '/js/participant_config.js'),
              'language' => array(
                  'english' => 'english',
                  'spanish' => 'spanish',
              ),
              'user_data' => $user_data,
              'msg_type' => isset($msg_type) ? $msg_type : '',
              'msg' => isset($msg) ? $msg : '',
        ));

        $this->tpl->section('_view', 'config_form.phtml');
        $this->tpl->load_view(_TEMPLATE);
    }

    /**
     * Save user config data.
     *
     * @return string
     */
    public function config()
    {
        is_connected();

        $this->load->module('file/misc');

        if ($this->input->post('submit') === 'cancel') {
            $result = array(
                'result' => 'ok',
                'message' => lang('canceled')
            );
            if ($this->input->is_ajax_request()) {
                echo json_encode($result);
                return;
            }
            else {
                return $result;
            }
        }

        $result = $this->validate_form();

        if ($result['result'] === 'ok') {

            // Save user data.
            $this->load->model('cc/m_user');
            $user_data = $this->m_user->data(connected_user());
            $update_data['name'] = $this->input->post('name');

            // Validating if email already exists in database.
            if ($this->input->post('email') !== $user_data->email) {
                if ($this->m_user->email_exists($this->input->post('email'))) {
                    $result = array(
                        'result' => 'fail',
                        'message' => lang('email_exists')
                    );

                    if ($this->input->is_ajax_request()) {
                        echo json_encode($result);
                    }
                    else {
                        return $result;
                    }

                    // Only for break!
                    return;
                }
                else {
                    $update_data['email'] = $this->input->post('email');
                }
            }

            // Save password if not empty.
            if ($this->input->post('password') !== '') {
                $update_data['password'] = md5($this->input->post('password'));
            }

            $this->m_user->update(connected_user(), $update_data);

            // Save participant data.
            $this->load->module('file/write');

            // Save info data.
            $res = $this->_update(connected_user(), array('language' => $this->input->post('language')));
            $participant_config_path = "_accounts/{$this->session->userdata('current_account')}/_participants/" . connected_user() . ".json";
            $this->session->set_userdata('user_info', Modules::run('file/read/json_content', $participant_config_path));

            $message = '';
            if ($res == 'fail') {
                //@todo Error number is manual now. Create secuencial system error codes next.
                $message = 'Sytem error number #7732143. Please contact us and send the error number.';
            }
            else {
                $this->session->set_flashdata('msg', lang('config_saved'));
                $this->session->set_flashdata('msg_type', 'msg_ok');
            }

            $result = array(
                'result' => $res,
                'message' => $message,
            );
        }
        else {
            $message = validation_errors();
            $result = array(
                'result' => 'fail',
                'message' => $message
            );
        }

        if ($this->input->is_ajax_request()) {
            echo json_encode($result);
        }
        else {
            return $result;
        }
    }

    /**
     * Validate config form.
     *
     * @return array
     */
    public function validate_form()
    {
        $this->load->library('form_validation');
        $this->load->helper(array('form'));
        $this->load->language('cc_form_validation');
        $this->form_validation->set_error_delimiters('', '');
        $result['result'] = 'ok';

        $field = 'name';
        $rules = 'trim|required|min_length[7]|max_length[75]';
        $this->form_validation->set_rules($field, 'lang:' . $field, $rules);

        $field = 'email';
        $rules = 'trim|required|min_length[5]|max_length[254]|valid_email';
        $this->form_validation->set_rules($field, 'lang:' . $field, $rules);

        $field = 'language';
        $rules = 'trim|required';
        $this->form_validation->set_rules($field, 'lang:' . $field, $rules);

        if ($this->form_validation->run() === FALSE) {
            $message = validation_errors();
            $result = array(
                'result' => 'fail',
                'message' => $message
            );
        }

        return $result;
    }

    /**
     * Set participant as administrator.
     *
     * @param string $user
     */
    public function as_administrator($user)
    {
        is_connected('administrator');

        $this->load->module('file/write');

        $res = $this->_update($user, array('type' => 'administrator'));

        if ($this->input->is_ajax_request()) {
            echo $res;
        }
        else {
            return $res;
        }
    }

    /**
     * Set participant as participant.
     *
     * @param string $user
     */
    public function as_participant($user)
    {
        is_connected('administrator');

        $this->load->module('file/write');

        $res = $this->_update($user, array('type' => 'participant'));

        if ($this->input->is_ajax_request()) {
            echo $res;
        }
        else {
            return $res;
        }
    }

    /**
     * Set participant as administrator.
     *
     * @param string $user
     */
    public function activation($user)
    {
        is_connected('administrator');

        $this->load->module('file/write');

        $participant_config_path = "_accounts/{$this->session->userdata('current_account')}/_participants/{$user}.json";
        $participant_info = Modules::run('file/read/json_content', $participant_config_path);

        $res = $this->_update($user, array('active' => ! $participant_info['active']));

        if ($this->input->is_ajax_request()) {
            echo $res;
        }
        else {
            return $res;
        }
    }

    /**
     * Update user config with sent data.
     *
     * @param array $data
     *
     * @return string 1|fail
     */
    private function _update($user, $data)
    {
        $participant_config_path = "_accounts/{$this->session->userdata('current_account')}/_participants/{$user}.json";
        $participant_info = array_replace_recursive(Modules::run('file/read/json_content', $participant_config_path), $data);

        $res = $this->write->archive($participant_config_path, json_encode($participant_info)) === TRUE ? 'ok' : 'fail';

        return $res;
    }

}


text:
/**
 * Created by maxjerin on 11/30/14.
 */
define([
    'jquery',
    'underscore',
    'backbone',
    'views/FooterView',
    'views/HeaderView',
    'text!partials/speakerTemplate.html'
], function($, _, Backbone, FooterView, HeaderView, speakerTemplate){

    var SpeakerView = Backbone.View.extend({
        el: $(".page-container"),

        render: function(){

            this.$el.html('').html(speakerTemplate);

            var headerView = new HeaderView();
            headerView.render();

            var footerView = new FooterView();
            footerView.render();

        }

    });

    return SpeakerView;

});


text:
import json
import subprocess
import sys
from pathlib import Path
from typing import Any, Dict, Generator, List

import pytest
from pytest import TempPathFactory
from python_on_whales import DockerException, docker

@pytest.fixture(scope="session")
def report_dir(tmp_path_factory: TempPathFactory) -> Path:
    return tmp_path_factory.mktemp("reports")

@pytest.fixture(scope="session", autouse=True)
def build_autobahn_testsuite() -> Generator[None, None, None]:

    try:
        docker.build(
            file="tests/autobahn/Dockerfile.autobahn",
            tags=["autobahn-testsuite"],
            context_path=".",
        )
    except DockerException:
        pytest.skip(msg="The docker daemon is not running.")

    try:
        yield
    finally:
        docker.image.remove(x="autobahn-testsuite")

def get_failed_tests(report_path: str, name: str) -> List[Dict[str, Any]]:
    path = Path(report_path)
    result_summary = json.loads((path / "index.json").read_text())[name]
    failed_messages = []
    PASS = {"OK", "INFORMATIONAL"}
    entry_fields = {"case", "description", "expectation", "expected", "received"}
    for results in result_summary.values():
        if results["behavior"] in PASS and results["behaviorClose"] in PASS:
            continue
        report = json.loads((path / results["reportfile"]).read_text())
        failed_messages.append({field: report[field] for field in entry_fields})
    return failed_messages

@pytest.mark.skipif(sys.platform == "darwin", reason="Don't run on macOS")
@pytest.mark.xfail
def test_client(report_dir: Path, request: Any) -> None:
    try:
        print("Starting autobahn-testsuite server")
        autobahn_container = docker.run(
            detach=True,
            image="autobahn-testsuite",
            name="autobahn",
            publish=[(9001, 9001)],
            remove=True,
            volumes=[
                (f"{request.fspath.dirname}/client", "/config"),
                (f"{report_dir}", "/reports"),
            ],
        )
        print("Running aiohttp test client")
        client = subprocess.Popen(
            ["wait-for-it", "-s", "localhost:9001", "--"]
            + [sys.executable]
            + ["tests/autobahn/client/client.py"]
        )
        client.wait()
    finally:
        print("Stopping client and server")
        client.terminate()
        client.wait()
        autobahn_container.stop()

    failed_messages = get_failed_tests(f"{report_dir}/clients", "aiohttp")

    assert not failed_messages, "\n".join(
        "\n\t".join(
            f"{field}: {msg[field]}"
            for field in ("case", "description", "expectation", "expected", "received")
        )
        for msg in failed_messages
    )

@pytest.mark.skipif(sys.platform == "darwin", reason="Don't run on macOS")
@pytest.mark.xfail
def test_server(report_dir: Path, request: Any) -> None:
    try:
        print("Starting aiohttp test server")
        server = subprocess.Popen(
            [sys.executable] + ["tests/autobahn/server/server.py"]
        )
        print("Starting autobahn-testsuite client")
        docker.run(
            image="autobahn-testsuite",
            name="autobahn",
            remove=True,
            volumes=[
                (f"{request.fspath.dirname}/server", "/config"),
                (f"{report_dir}", "/reports"),
            ],
            networks=["host"],
            command=[
                "wait-for-it",
                "-s",
                "localhost:9001",
                "--",
                "wstest",
                "--mode",
                "fuzzingclient",
                "--spec",
                "/config/fuzzingclient.json",
            ],
        )
    finally:
        print("Stopping client and server")
        server.terminate()
        server.wait()

    failed_messages = get_failed_tests(f"{report_dir}/servers", "AutobahnServer")

    assert not failed_messages, "\n".join(
        "\n\t".join(
            f"{field}: {msg[field]}"
            for field in ("case", "description", "expectation", "expected", "received")
        )
        for msg in failed_messages
    )


text:
.. _administrator_guide:

===================
Administrator Guide
===================

This chapter describes how to install, deploy, and administrate a c2cgeoportal
application.

The application administrator configures and administrates the application
through the database. The administrator does not deal with the files of the
application (the integrator is the one responsible for these files). Except for
one file (or set of files) actually: the MapServer mapfile. Adding layers to
the application indeed requires inserting information in the database, as well
as adding ``LAYER`` sections to the application's MapServer mapfile. So the
mapfile is a place where the administrator and the integrator collaborate.

Content:

.. toctree::
   :maxdepth: 1

   mapfile
   administrate
   editing


text:
package watermark

import (
	"flag"
	"path/filepath"
	"time"

	"go-common/app/interface/main/creative/conf"
	"go-common/app/interface/main/creative/service"

	. "github.com/smartystreets/goconvey/convey"
)

var (
	s *Service
	p *service.Public
)

func init() {
	dir, _ := filepath.Abs("../../cmd/creative.toml")
	flag.Set("conf", dir)
	conf.Init()
	rpcdaos := service.NewRPCDaos(conf.Conf)
	p = service.New(conf.Conf, rpcdaos)
	s = New(conf.Conf, rpcdaos, p)
	time.Sleep(time.Second)
}

func WithService(f func(s *Service)) func() {
	return func() {
		Reset(func() {})
		f(s)
	}
}


text:
namespace operations_research::math_opt {

// Removes the model, variables and constraints names of the provided model.
void RemoveNames(ModelProto& model);

// Removes the variables and constraints names of the provided update.
void RemoveNames(ModelUpdateProto& update);

}  // namespace operations_research::math_opt

#endif  // OR_TOOLS_MATH_OPT_IO_NAMES_REMOVAL_H_


text:
class EventNotRegisteredException(Exception):
    pass

class EventMalformedException(Exception):
    pass

class EventHandler(object):
    def __init__(self):
        pass

    def handle_event(self, event, kwargs):
        raise NotImplementedError("Please implement")

class EventManager(object):
    def __init__(self, *handlers):
        self._registered_events = dict()
        self._handlers = handlers or []

    def add_handler(self, event_handler):
        self._handlers.append(event_handler)

    def register_event(self, name, parameters=None):
        self._registered_events[name] = parameters

    def emit(self, event, sender=None, level='info', data={}):
        if not sender:
            raise ArgumentError('Event needs a sender!')

        levels = ['info', 'warning', 'error', 'critical', 'debug']
        if not level in levels:
            raise ArgumentError('Event level needs to be in: {}'.format(levels))

        if event not in self._registered_events:
            raise EventNotRegisteredException("Event %s not registered..." % event)

        # verify params match event
        parameters = self._registered_events[event]
        for k, v in data.iteritems():
            if k not in parameters:
                raise EventMalformedException("Event %s does not require parameter %s" % (event, k))

        # send off to the handlers
        for handler in self._handlers:
            handler.handle_event(event, sender, level, data)


text:
package com.amazonaws.services.sagemaker.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Specifies configuration details for a Git repository in your Amazon Web Services account.
 *

 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GitConfig implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The URL where the Git repository is located.
     *

     */
    private String repositoryUrl;
    /**
     *

     * The default branch for the Git repository.
     *

     */
    private String branch;
    /**
     *

     * The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the credentials
     * used to access the git repository. The secret must have a staging label of AWSCURRENT and must be in
     * the following format:
     *

     *

     * {"username": UserName, "password": Password}
     *

     */
    private String secretArn;

    /**
     *

     * The URL where the Git repository is located.
     *

     *
     * @param repositoryUrl
     *        The URL where the Git repository is located.
     */

    public void setRepositoryUrl(String repositoryUrl) {
        this.repositoryUrl = repositoryUrl;
    }

    /**
     *

     * The URL where the Git repository is located.
     *

     *
     * @return The URL where the Git repository is located.
     */

    public String getRepositoryUrl() {
        return this.repositoryUrl;
    }

    /**
     *

     * The URL where the Git repository is located.
     *

     *
     * @param repositoryUrl
     *        The URL where the Git repository is located.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GitConfig withRepositoryUrl(String repositoryUrl) {
        setRepositoryUrl(repositoryUrl);
        return this;
    }

    /**
     *

     * The default branch for the Git repository.
     *

     *
     * @param branch
     *        The default branch for the Git repository.
     */

    public void setBranch(String branch) {
        this.branch = branch;
    }

    /**
     *

     * The default branch for the Git repository.
     *

     *
     * @return The default branch for the Git repository.
     */

    public String getBranch() {
        return this.branch;
    }

    /**
     *

     * The default branch for the Git repository.
     *

     *
     * @param branch
     *        The default branch for the Git repository.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GitConfig withBranch(String branch) {
        setBranch(branch);
        return this;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the credentials
     * used to access the git repository. The secret must have a staging label of AWSCURRENT and must be in
     * the following format:
     *

     *

     * {"username": UserName, "password": Password}
     *

     *
     * @param secretArn
     *        The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the
     *        credentials used to access the git repository. The secret must have a staging label of
     *        AWSCURRENT and must be in the following format:

     *

     *        {"username": UserName, "password": Password}
     */

    public void setSecretArn(String secretArn) {
        this.secretArn = secretArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the credentials
     * used to access the git repository. The secret must have a staging label of AWSCURRENT and must be in
     * the following format:
     *

     *

     * {"username": UserName, "password": Password}
     *

     *
     * @return The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the
     *         credentials used to access the git repository. The secret must have a staging label of
     *         AWSCURRENT and must be in the following format:

     *

     *         {"username": UserName, "password": Password}
     */

    public String getSecretArn() {
        return this.secretArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the credentials
     * used to access the git repository. The secret must have a staging label of AWSCURRENT and must be in
     * the following format:
     *

     *

     * {"username": UserName, "password": Password}
     *

     *
     * @param secretArn
     *        The Amazon Resource Name (ARN) of the Amazon Web Services Secrets Manager secret that contains the
     *        credentials used to access the git repository. The secret must have a staging label of
     *        AWSCURRENT and must be in the following format:

     *

     *        {"username": UserName, "password": Password}
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GitConfig withSecretArn(String secretArn) {
        setSecretArn(secretArn);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getRepositoryUrl() != null)
            sb.append("RepositoryUrl: ").append(getRepositoryUrl()).append(",");
        if (getBranch() != null)
            sb.append("Branch: ").append(getBranch()).append(",");
        if (getSecretArn() != null)
            sb.append("SecretArn: ").append(getSecretArn());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GitConfig == false)
            return false;
        GitConfig other = (GitConfig) obj;
        if (other.getRepositoryUrl() == null ^ this.getRepositoryUrl() == null)
            return false;
        if (other.getRepositoryUrl() != null && other.getRepositoryUrl().equals(this.getRepositoryUrl()) == false)
            return false;
        if (other.getBranch() == null ^ this.getBranch() == null)
            return false;
        if (other.getBranch() != null && other.getBranch().equals(this.getBranch()) == false)
            return false;
        if (other.getSecretArn() == null ^ this.getSecretArn() == null)
            return false;
        if (other.getSecretArn() != null && other.getSecretArn().equals(this.getSecretArn()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getRepositoryUrl() == null) ? 0 : getRepositoryUrl().hashCode());
        hashCode = prime * hashCode + ((getBranch() == null) ? 0 : getBranch().hashCode());
        hashCode = prime * hashCode + ((getSecretArn() == null) ? 0 : getSecretArn().hashCode());
        return hashCode;
    }

    @Override
    public GitConfig clone() {
        try {
            return (GitConfig) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.sagemaker.model.transform.GitConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
(* ::Package:: *)

<<"C:/users/julian/documents/github/Machine-Vision/NeuralNetworks/NeuralNetwork.m"

(* Examples *)

(*Learning the square function*)
sqNetwork={
   FullyConnected1DTo1D[{.2,.3},{{2},{3}}],Tanh,
   FullyConnected1DTo1D[{.6},{{1,7}}],Tanh
};
sqInputs=Transpose[{Table[x,{x,-1,1,0.1}]}];sqInputs//MatrixForm;
sqOutputs=sqInputs^2;sqOutputs//MatrixForm;
sqTrain:=NNGradientDescent[sqNetwork,sqInputs,sqOutputs,NNGrad,RegressionLoss2D,{MaxEpoch->500000}];

(*See Parallel Distributed Processing Volume 1: Foundations, PDP Research Group, page 332 Figure 4*)
(*Achieves excellent solution quickly*)
XORNetwork={
   FullyConnected1DTo1D[{.2,.3},{{2,.3},{1,Random[]-.5}}],Tanh,
   FullyConnected1DTo1D[{.6},{{1,Random[]-.5}}],Tanh
};
XORInputs={{0,0},{0,1},{1,0},{1,1}};XORInputs//MatrixForm;
XOROutputs=Transpose[{{0,1,1,0}}];XOROutputs//MatrixForm;
XORTrain:=AdaptiveGradientDescent[XORNetwork,XORInputs,XOROutputs,NNGrad,RegressionLoss2D,{MaxEpoch->500000}];

(*Learning to multiply two inputs*)
MultInputs=Flatten[Table[{a,b},{a,0,1,.1},{b,0,1,.1}],1];MultInputs//MatrixForm;
MultOutputs=Map[{#[[1]]*#[[2]]}&,MultInputs];MultOutputs//MatrixForm;
MultTrain:=AdaptiveGradientDescent[XORNetwork,MultInputs,MultOutputs,NNGrad,RegressionLoss2D,{MaxEoch->500000}];

(*Learning circle function*)
circleNetwork={
   FullyConnected1DTo1DInit[2,4],Tanh,
   FullyConnected1DTo1DInit[4,1],Logistic
};
circleInputs=Flatten[Transpose[{Table[{x,y},{x,-1,1,0.1},{y,-1,+1,0.1}]}],2];circleInputs//MatrixForm;
circleOutputs=1.*Map[{Boole[#[[1]]+#[[2]]>1]}&,circleInputs^2];circleOutputs//MatrixForm;
circleTrain:=GradientDescent[circleNetwork,circleInputs,circleOutputs,NNGrad,CrossEntropyLoss,{MaxEpoch->500000}];

(*
   We fail to learn any useful solution using either of these two networks.
*)
parityInputs=Tuples[{0,1},8];
parityOutputs=Map[{Boole[EvenQ[Total[#]]]}&,parityInputs];
parityNetwork={
   FullyConnected1DTo1DInit[8,256],
   Logistic,
   FullyConnected1DTo1DInit[256,1],
   Logistic
};
parityNetwork={
   FullyConnected1DTo1DInit[8,8],Tanh,
   FullyConnected1DTo1DInit[8,4],Tanh,
   FullyConnected1DTo1DInit[4,4],Tanh,
   FullyConnected1DTo1DInit[4,2],Tanh,
   FullyConnected1DTo1DInit[2,2],Tanh,
   FullyConnected1DTo1DInit[2,1],Logistic
};
parityNetwork={
   FullyConnected1DTo1DInit[8,8],
   Logistic,
   FullyConnected1DTo1DInit[8,1],
   Logistic
};
solvedParityNet={
(* Idea comes form Parallel Distributed Processing p .334
   by Rumelhard, Hinton and Williams
   Can manually encode, but can't train
*)
   FullyConnected1DTo1D[Table[5+-i*10,{i,1,8}],Table[10,{i,1,8},{j,1,8}]],
   Logistic,
   FullyConnected1DTo1D[{5},
      {Table[If[EvenQ[i],+10,-10],{i,1,8}]}],
   Logistic
};
parityTrain:=
   NNGradientDescent[parityNetwork,parityInputs,parityOutputs,NNGrad,CrossEntropyLoss,{MaxEpoch->50000000,LearningRate->.5,Momentum->0.9,MomentumType->"Nesterov"}];

(*
   Another PDP example, page 340
   Note, we train using just 200 examples. It sucessfully generalises to the other 56 (of which 3 were symmetric)
*)
symInputs=Tuples[{0,1},8];
symOutputs=Map[
   {Boole[#[[1;;4]]==Reverse[#[[5;;8]]]]}&
   ,symInputs];
symNetwork={
   FullyConnected1DTo1DInit[8,2],
   Logistic,
   FullyConnected1DTo1DInit[2,1],
   Logistic};
SeedRandom[1234];
samp=RandomSample[Transpose[{symInputs,symOutputs}]];
symTrain:=NNGradientDescent[symNetwork,samp[[1;;200,1]],samp[[1;;200,2]],NNGrad,CrossEntropyLoss,{MaxEpoch->50000000,LearningRate->.5,Momentum->0.9,MomentumType->"Nesterov"}];

(*
   Attempt at density modelling
   In 70,000 iterations moderate good approximation to prob density, albeit with some noisy features
*)
circInputs=Join[
   Table[th=Random[];
      {Sin[th*2*\[Pi]],Cos[th*2*\[Pi]]},{100}],
   Table[{Random[]-.5,Random[]-.5}*3,{100}]];
circOutputs=Join[Table[{1},{100}],Table[{0},{100}]];
circNetwork={
   FullyConnected1DTo1DInit[2,20],
   Logistic,
   FullyConnected1DTo1DInit[20,1],
   Logistic};
SeedRandom[1234];
samp=RandomSample[Transpose[{circInputs,circOutputs}]];
circTrain:=NNGradientDescent[circNetwork,samp[[1;;200,1]],samp[[1;;200,2]],NNGrad,CrossEntropyLoss,{MaxEpoch->50000000,LearningRate->.5,Momentum->0.9,MomentumType->"Nesterov"}];
circPlot:=ListPlot3D[
   Table[ForwardPropogate[{{x,y}},wl][[1,1]],{x,-2,+2,.1},{y,-2,+2,.1}]]


text:
layout: post
title: Push Technologies
categories: [Reading]
tags: [Push, Framework]
fullview: false
comments: true
---

这周跟朋友讨论起了server push,之前零星知道一些push technologies,于是想看看是不是有更多的新老技术。[Wikipedia](https://en.wikipedia.org/wiki/Push_technology)永远是个宝!简单整理个列表备忘用吧:

* Webpush:HTTP 2.0特有,主流浏览器都支持
* HTTP server push:基于WebSocket的全双工TCP connection
* Pushlet:基于HTTP persistent connection(也叫[HTTP keep-alive](https://en.wikipedia.org/wiki/HTTP_persistent_connection)或者HTTP connection reuse),client依赖server的timeout setting,通常5-15 seconds。而如果client忘记关闭连接,server不能释放资源
* Long Polling:假装的Push,比pushlet轻量,但需要server hold connection和client的重连逻辑
* Flash XMLSocket relays:读写分离,建立一个Unidirectional network,放一个relay,relay push id,client用id来fetch content。对读写不对称的情况尤其高效。scale的瓶颈在于http stack能容纳多少个concurrent连接。
* Reliable Group Data Delivery (RGDD):主要用来进行数据备份,比如HDFS的replication
* Push Notification:Apple, Google and Microsoft support it.
  * Local: scheduled event / timer event
  * Remote: app注册,server用http发notification

当然,这里没有包括我心爱的[WAP Push](https://en.wikipedia.org/wiki/Wireless_Application_Protocol#WAP_Push),一个只对手机移动网络有效的Push。知道这个的人估计会越来越少啦。


text:
using System.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Persistence.SqlSyntax;

namespace Umbraco.Core.Persistence.Migrations.Upgrades.TargetVersionSevenFiveZero
{
    [Migration("7.5.0", 100, GlobalSettings.UmbracoMigrationName)]
    public class AddRedirectUrlTable : MigrationBase
    {
        public AddRedirectUrlTable(ISqlSyntaxProvider sqlSyntax, ILogger logger)
            : base(sqlSyntax, logger)
        { }

        public override void Up()
        {
            // defer, because we are making decisions based upon what's in the database
            Execute.Code(MigrationCode);
        }

        private string MigrationCode(Database database)
        {
            var umbracoRedirectUrlTableName = "umbracoRedirectUrl";

            var localContext = new LocalMigrationContext(Context.CurrentDatabaseProvider, database, SqlSyntax, Logger);

            var tables = SqlSyntax.GetTablesInSchema(database).ToArray();

            if (tables.InvariantContains(umbracoRedirectUrlTableName))
            {
                var columns = SqlSyntax.GetColumnsInSchema(database).ToArray();
                if (columns.Any(x => x.TableName.InvariantEquals(umbracoRedirectUrlTableName) && x.ColumnName.InvariantEquals("id") && x.DataType == "uniqueidentifier"))
                    return null;
                localContext.Delete.Table(umbracoRedirectUrlTableName);
            }

            localContext.Create.Table(umbracoRedirectUrlTableName)
                .WithColumn("id").AsGuid().NotNullable().PrimaryKey("PK_" + umbracoRedirectUrlTableName)
                .WithColumn("createDateUtc").AsDateTime().NotNullable()
                .WithColumn("url").AsString(2048).NotNullable()
                .WithColumn("contentKey").AsGuid().NotNullable()
                .WithColumn("urlHash").AsString(40).NotNullable();

            localContext.Create.Index("IX_" + umbracoRedirectUrlTableName).OnTable(umbracoRedirectUrlTableName)
                .OnColumn("urlHash")
                .Ascending()
                .OnColumn("contentKey")
                .Ascending()
                .OnColumn("createDateUtc")
                .Descending()
                .WithOptions().NonClustered();

            localContext.Create.ForeignKey("FK_" + umbracoRedirectUrlTableName)
                .FromTable(umbracoRedirectUrlTableName).ForeignColumn("contentKey")
                .ToTable("umbracoNode").PrimaryColumn("uniqueID");

            return localContext.GetSql();
        }

        public override void Down()
        { }
    }
}


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" />

  <title>CXX_EXTENSIONS — CMake 3.3.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="top" title="CMake 3.3.2 Documentation" href="../index.html" />
    <link rel="up" title="cmake-properties(7)" href="../manual/cmake-properties.7.html" />
    <link rel="next" title="CXX_STANDARD" href="CXX_STANDARD.html" />
    <link rel="prev" title="CROSSCOMPILING_EMULATOR" href="CROSSCOMPILING_EMULATOR.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.3.2 Documentation »

cmake-properties(7) »

CXX_EXTENSIONS¶

Boolean specifying whether compiler specific extensions are requested.

This property specifies whether compiler specific extensions should be
used.  For some compilers, this results in adding a flag such
as -std=gnu++11 instead of -std=c++11 to the compile line.  This
property is ON by default.

See the cmake-compile-features(7) manual for information on
compile features and a list of supported compilers.

This property is initialized by the value of
the CMAKE_CXX_EXTENSIONS variable if it is set when a target
is created.

Previous topic

CROSSCOMPILING_EMULATOR

Next topic

CXX_STANDARD

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

    CMake »

    3.3.2 Documentation »

cmake-properties(7) »

        © Copyright 2000-2015 Kitware, Inc..
      Created using Sphinx 1.4a0+.


text:
/* See license.txt for terms of usage */

var EXPORTED_SYMBOLS = ["FunctionTree","FunctionLeaf","cloneFunctionTree","cloneFunctionLeaf"]

// ********************************************************************************************* //
// Function Leaf representation

/*
    A leaf represents a function.
    Each leaf can have children as leaf, they represent the nested functions.
    As of object functions:
        Consider this kind of code

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

            function test(){                    -> Level n
                var obj = {
                    test2: function(){          -> Level n + 1
                        // do Something
                    }
                }

                function nestedFunction (){     -> Level n + 1
                    // do something
                }
            }

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

        test2 and nested function are considered at the same depth.

*/

function FunctionLeaf(path) {

    /*
        The root element of the path represents the script name, then the next depths
        represent functions.
            ex: /script1/functionA/nestedFunctionB
        There can be multiple path for a function because a function can be declared
        multiple times like the extend function in jQuery
            var jQuery.extend = jQuery.fn.extend =  ...
        By default the path exposed is the first one, the other ones are used for function
        use recognition.
    */
    this.path = [""+path];
    this.children = [];

    /*
        We want to be able to fuzz different arguments so that we have to store the
        number of arguments and how they are called (to hint what kind of input they
        require)
     */
    this.args = [];

    /*
        This list represents all the functions that are used inside the body of this
        function. It is a list of references made as URLs.

        For example: pageName/scriptName/test/test2
        ('/' is not a valid character for variable naming, so it can be used as a path
        separator)
    */
    this.usedFunctions = [];

    /*
        This property is specific for functions declared in objects. During the
        fuzzing, as we want to trigger the function, we need the object reference,
        this property is here to provide it. The Object reference only needs to be an
        object containing the object ref and the index of its declaration end.
    */
    this.fromObject = null;

    /*
        This property is used when we are fuzzing a function, it serves as a landmark
        to where we shall insert our fuzzing code.
    */
    this.range = {start: -1, end: -1};

    /**
     * Contains the source code of the function. Can be usefull for user info and for
     * annonymous function execution. This is an array for conditional declarations so
     * that it contains all the alternatives.
     *
     * @type {Array}
     */
    this.functionSource = [];
}

FunctionLeaf.prototype =
{

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Accessors

    appendChild: function(child)
    {
        this.children.push(child);
    },

    hasChildren: function()
    {
        return this.children.length > 0;
    },

    getChildren: function()
    {
        return this.children;
    },

    appendUsedFunction: function(usedFunction)
    {
        this.usedFunctions.push(usedFunction);
    },

    hasUsedFunctions: function()
    {
        return this.usedFunctions.length > 0;
    },

    appendArg: function(arg)
    {
        this.args.push(arg);
    },

    hasArgs: function()
    {
        return this.args.length > 0;
    },

    isMethod: function()
    {
        return this.fromObject != null;
    },

    getObject: function()
    {
        if(this.isMethod())
            return this.fromObject;
    },

    setParentObject: function(strRef)
    {
        this.fromObject = strRef;
    },

    getPath: function()
    {
        return this.path[0];
    },

    getName: function(i)
    {
        if (i)
            return this.path[i].substring(this.path[i].lastIndexOf('/')+1,this.path[i].length);
        else
            return this.path[0].substring(this.path[0].lastIndexOf('/')+1,this.path[0].length);
    },

    setRange(i,j)
    {
        this.range.start = i;
        this.range.end = j;
    },

    getCharEnd: function()
    {
        return this.range.end;
    },

    getCharStart: function()
    {
        return this.range.start;
    },

    getSource: function()
    {
        return this.functionSource;
    },

    appendSource: function(source)
    {
        this.functionSource.push(source);
    },

    findLeafFromPath: function(path)
    {
        var totalDepth = path[0].split('/').length + 1,
            depth = this.path[0].split('/').length + 1;

        if (totalDepth - depth == 1){
            return this.children.find(function(element, index, array){
                return element.path[0] ===path[0] ;
            });
        } else {
            return this.children.find(function(element, index, array){
                return element.path[0] === path[0].split('/',depth).join('/');
            }).findLeafFromPath(path);
        }

    },

    getDependencies: function(functionTree){
        var pathArray = this.path[0].split('/'),
            dependencies = [];

        if (pathArray.length > 2)
            for (var i = 3 ; i<pathArray.length; i++){
                dependencies.push(functionTree.findLeafFromPath(pathArray.slice(0,i).join('/')));
            }

        return dependencies;

    }
}

/**
 * Method to clone a function leaf from its serialized version
 *
 * @param  {Object}         functionLeafStruct Function leaf extracted from a message
 * @return {FunctionLeaf}                      Cloned function leaf
 */
function cloneFunctionLeaf(functionLeafStruct)
{
    var clonedFunctionLeaf = new FunctionLeaf(functionLeafStruct.path);
    clonedFunctionLeaf.path = functionLeafStruct.path.slice(',');

    clonedFunctionLeaf.args = functionLeafStruct.args;
    clonedFunctionLeaf.usedFunctions = functionLeafStruct.usedFunctions;
    clonedFunctionLeaf.fromObject = functionLeafStruct.fromObject;
    clonedFunctionLeaf.range = functionLeafStruct.range;
    clonedFunctionLeaf.functionSource = functionLeafStruct.functionSource;

    if (functionLeafStruct.children.length > 0)
        clonedFunctionLeaf.children = functionLeafStruct.children.map(cloneFunctionLeaf);

    return clonedFunctionLeaf;
}

// ********************************************************************************************* //
// Function Tree representation

/*
    This tree contains access to all the functions contained in a Web page.
    Each of its leaf represents a script file that contains other functions
    This is the root of the tree

    The tree's leaf are ordered so that it represents the declaration order of the script file
*/
function FunctionTree(pageName) {

    this.pageReference = pageName;
    // the children of a function tree for a page are the different scripts.
    this.children = [];
}

FunctionTree.prototype =
{
    appendChild: function(child)
    {
        this.children.push(child);
    },

    hasChildren: function()
    {
        return this.children.length > 0;
    },

    getChildren:function()
    {
        return this.children;
    },

    getPath: function()
    {
        return '/';
    },

    getName: function()
    {
        return this.pageReference;
    },

    findLeafFromPath: function(path)
    {
        var totalDepth = path.split('/').length + 1,
            depth = 1;

        if (totalDepth - depth == 1){
            return this.children.find(function(element, index, array){
                return element.path === path ;
            });
        } else {
            return this.children.find(function(element, index, array){
                return element.path[0] === path.split('/',depth+1).join('/');
            }).findLeafFromPath([path]);
        }

    },
}

/**
 * Method to clone a function Tree from its serialized version
 *
 * @param  {Object}         functionTreeStruct Function leaf extracted from a message
 * @return {FunctionTree}                      Cloned function Tree
 */
function cloneFunctionTree(functionTreeStruct)
{
    var clonedFunctionTree = new FunctionTree(functionTreeStruct.pageName);

    if (functionTreeStruct.children.length > 0)
        clonedFunctionTree.children = functionTreeStruct.children.map(cloneFunctionLeaf);

    return clonedFunctionTree;
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function template swap</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Log 2.0">
<link rel="up" href="../../../logging_sources.html#header.boost.log.sources.basic_logger_hpp" title="Header <boost/log/sources/basic_logger.hpp>">
<link rel="prev" href="basic_composit_idp18959408.html" title="Class template basic_composite_logger<CharT, FinalT, single_thread_model, FeaturesT>">
<link rel="next" href="../../../BOOST_LOG_FORWARD_LOGGER_CONSTRUCTORS.html" title="Macro BOOST_LOG_FORWARD_LOGGER_CONSTRUCTORS">

Function template swap

boost::log::sources::swap

Synopsis

// In header: <boost/log/sources/basic_logger.hpp>

template<typename CharT, typename FinalT, typename ThreadingModelT>
  void swap(basic_logger< CharT, FinalT, ThreadingModelT > & left,
            basic_logger< CharT, FinalT, ThreadingModelT > & right);

Description

Free-standing swap for all loggers

Copyright © 2007-2013 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


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" />

        <title>

    examples.dogpile_caching.environment
 —
    SQLAlchemy 0.9 Documentation

        </title>

                <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
                <link rel="stylesheet" href="../../../_static/changelog.css" type="text/css" />
                <link rel="stylesheet" href="../../../_static/sphinx_paramlinks.css" type="text/css" />
                <link rel="stylesheet" href="../../../_static/docs.css" type="text/css" />

    <link rel="index" title="Index" href="../../../genindex.html" />
    <link rel="search" title="Search" href="../../../search.html" />
        <link rel="copyright" title="Copyright" href="../../../copyright.html" />
    <link rel="top" title="SQLAlchemy 0.9 Documentation" href="../../../index.html" />
        <link rel="up" title="Module code" href="../../index.html" />

        Release: 0.9.9 | Release Date: March 10, 2015

SQLAlchemy 0.9 Documentation

            <form class="search" action="../../../search.html" method="get">
              <input type="text" name="q" size="12" /> <input type="submit" value="Search" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>

            Contents |
            Index

Source code for examples.dogpile_caching.environment

"""environment.py

Establish data / cache file paths, and configurations,
bootstrap fixture data if necessary.

"""
from . import caching_query
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from dogpile.cache.region import make_region
import os
from hashlib import md5
import sys
py2k = sys.version_info < (3, 0)

if py2k:
    input = raw_input

# dogpile cache regions.  A home base for cache configurations.
regions = {}

# scoped_session.  Apply our custom CachingQuery class to it,
# using a callable that will associate the dictionary
# of regions with the Query.
Session = scoped_session(
                sessionmaker(
                    query_cls=caching_query.query_callable(regions)
                )
            )

# global declarative base class.
Base = declarative_base()

root = "./dogpile_data/"

if not os.path.exists(root):
    input("Will create datafiles in %r.\n"
                "To reset the cache + database, delete this directory.\n"
                "Press enter to continue.\n" % root
                )
    os.makedirs(root)

dbfile = os.path.join(root, "dogpile_demo.db")
engine = create_engine('sqlite:///%s' % dbfile, echo=True)
Session.configure(bind=engine)

def md5_key_mangler(key):
    """Receive cache keys as long concatenated strings;
    distill them into an md5 hash.

    """
    return md5(key.encode('ascii')).hexdigest()

# configure the "default" cache region.
regions['default'] = make_region(
            # the "dbm" backend needs
            # string-encoded keys
            key_mangler=md5_key_mangler
        ).configure(
        # using type 'file' to illustrate
        # serialized persistence.  Normally
        # memcached or similar is a better choice
        # for caching.
        'dogpile.cache.dbm',
        expiration_time=3600,
        arguments={
            "filename": os.path.join(root, "cache.dbm")
        }
    )

# optional; call invalidate() on the region
# once created so that all data is fresh when
# the app is restarted.  Good for development,
# on a production system needs to be used carefully
# regions['default'].invalidate()

installed = False

def bootstrap():
    global installed
    from . import fixture_data
    if not os.path.exists(dbfile):
        fixture_data.install()
        installed = True

        © Copyright 2007-2015, the SQLAlchemy authors and contributors.
        Created using Sphinx 1.2.3.


text:
package cn.tanziquan.produce.cole.appinfo.dto;

/**
 * AppDto
 *
 * @author zhigang.tan
 * @version 0.0.1
 */
public class AppDto {

    private Integer id;

    private String appNo;

    private String appName;

    public AppDto() {
        super();
    }

    public AppDto(String appName, String appNo, Integer id) {
        super();
        this.appName = appName;
        this.appNo = appNo;
        this.id = id;
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public Integer getId() {
        return id;
    }

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

    public String getAppNo() {
        return appNo;
    }

    public void setAppNo(String appNo) {
        this.appNo = appNo;
    }
}


text:
stormpath-sdk-go
================

Completely unofficial test project to play around with the Go language


text:
Meteor.startup(function() {
    if (!Meteor.users.findOne()){
        for (var i=1;i<9;i++){
            var email = "user"+i+"@test.com";
            var username = "user"+i;
            var avatar = "ava"+i+".png";
            console.log("creating a user with password 'test123' and username/ email: "+email);
            Meteor.users.insert({profile:{username:username, avatar:avatar}, emails:[{address:email}],services:{ password:{"bcrypt" : "$2a$10$I3erQ084OiyILTv8ybtQ4ON6wusgPbMZ6.P33zzSDei.BbDL.Q4EO"}}});
        }
    }
});

Meteor.publish("chats", function(){
    return Chats.find({
        $or: [
            {user1Id: this.userId},
            {user2Id: this.userId}
        ]
    });
    //return Chats.find();
});

Meteor.publish("users", function() {
    return Meteor.users.find();
});


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>It works!</title>

Woah dude!

It works!
 This file is served locally by a built-in HTTP server.

Video

<video width="320" height="240" autoplay controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.webm" type="video/webm">
</video>

Links

Regular links are opened in the application window.

target='_blank' links are opened in an external browser.