text:
using CertificateManager.Entities;
using CertificateManager.Entities.Exceptions;
using CertificateManager.Entities.Interfaces;
using CertificateManager.Logic;
using CertificateManager.Logic.Interfaces;
using CertificateManager.Repository;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Linq.Expressions;
using System.Security.Claims;

namespace CertificateManager.UnitTests
{
    [TestClass]
    public class UserManagementLogicTests
    {
        private ImportUsersActiveDirectoryMetadataModel GetImportUsersActiveDirectoryMetadataModelValid()
        {
            return new ImportUsersActiveDirectoryMetadataModel()
            {
                MergeWith = Guid.NewGuid(),
                Merge = true,
                Users = new System.Collections.Generic.List<ActiveDirectoryMetadataAuthPrincipalQueryResultModel>()
                {
                    new ActiveDirectoryMetadataAuthPrincipalQueryResultModel()
                    {
                        SamAccountName = "TestAccountName",
                        UserPrincipalName = "TestUpn"
                    }
                }
            };
        }

        private AuthenticablePrincipal GetAuthenticablePrincipalValid()
        {
            return new AuthenticablePrincipal()
            {
                Enabled = true,
                Name = "TestUser",
                Id = Guid.NewGuid(),
                LocalLogonEnabled = true
            };

        }

        private UpdateUserModel GetUpdateUserModelValid()
        {
            return new UpdateUserModel()
            {
                Enabled = true,
                Id = Guid.NewGuid(),
                Name = "TestUser"
            };
        }

        private AddAuthenticablePrincipalEntity GetAddAuthenticablePrincipalEntityValid()
        {
            return new AddAuthenticablePrincipalEntity()
            {
                Name = "TestUser",
                Id = Guid.NewGuid()
            };
        }

        [TestMethod]
        [ExpectedException(typeof(ReferencedObjectDoesNotExistException))]
        public void UserManagementLogic_SetUser_InvalidUser_ThrowsReferencedObjectDoesNotExistException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            UpdateUserModel updateUserModel = new UpdateUserModel(){ Id = Guid.NewGuid() };

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns((AuthenticablePrincipal)null);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.SetUser(updateUserModel, user);
        }

        [TestMethod]
        [ExpectedException(typeof(InsufficientDataException))]
        public void UserManagementLogic_SetUser_UpdateModelHasNullUpn_ThrowsInsufficientDataException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            UpdateUserModel updateUserModel = new UpdateUserModel() { Id = Guid.NewGuid(), Name = null };
            AuthenticablePrincipal validUser = new AuthenticablePrincipal();

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns(validUser);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.SetUser(updateUserModel, user);
        }

        [TestMethod]
        public void UserManagementLogic_UserExists_RepositoryThrowsException_ReturnsFalse()
        {
            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Throws(new Exception());

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            bool result = userManagementLogic.UserExists(Guid.NewGuid());

            Assert.IsFalse(result);
        }

        [TestMethod]
        public void UserManagementLogic_UserExists_RepositoryReturnsNull_ReturnsFalse()
        {
            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns((AuthenticablePrincipal)null);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            bool result = userManagementLogic.UserExists(Guid.NewGuid());

            Assert.IsFalse(result);
        }

        [TestMethod]
        [ExpectedException(typeof(MergeRequiresMergeTargetException))]
        public void UserManagementLogic_ImportMerge_EntityWithNullMergeWith_ThrowsMergeRequiresMergeTargetException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            ImportUsersActiveDirectoryMetadataModel entity = new ImportUsersActiveDirectoryMetadataModel()
            {
                MergeWith = (Guid?)null,
                Merge = true,
                Users = new System.Collections.Generic.List<ActiveDirectoryMetadataAuthPrincipalQueryResultModel>()
                {
                    new ActiveDirectoryMetadataAuthPrincipalQueryResultModel()
                    {
                        SamAccountName = "TestAccountName",
                        UserPrincipalName = "TestUpn"
                    }

                }
            };

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Exists<AuthenticablePrincipal>(It.IsAny<Expression<Func<AuthenticablePrincipal, bool>>>())).Returns(false);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.ImportUser(entity, user);
        }

        [TestMethod]
        [ExpectedException(typeof(MergeRequiresMergeTargetException))]
        public void UserManagementLogic_ImportMerge_EntityWithExistingSamAccountName_ThrowsMergeRequiresMergeTargetException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            ImportUsersActiveDirectoryMetadataModel entity = new ImportUsersActiveDirectoryMetadataModel()
            {
                MergeWith = Guid.NewGuid(),
                Merge = true,
                Users = new System.Collections.Generic.List<ActiveDirectoryMetadataAuthPrincipalQueryResultModel>()
                {
                    new ActiveDirectoryMetadataAuthPrincipalQueryResultModel()
                    {
                        SamAccountName = "TestAccountName",
                        UserPrincipalName = "TestUpn"
                    }
                }
            };

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Exists<AuthenticablePrincipal>(It.IsAny<Expression<Func<AuthenticablePrincipal, bool>>>())).Returns(false);
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns((AuthenticablePrincipal)null);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.ImportUser(entity, user);
        }

        [TestMethod]
        [ExpectedException(typeof(ReferencedObjectDoesNotExistException))]
        public void UserManagementLogic_ImportMerge_EntityWithInvalidAuthenticationRealm_ThrowsReferencedObjectDoesNotExistException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            ImportUsersActiveDirectoryMetadataModel entity = new ImportUsersActiveDirectoryMetadataModel()
            {
                MergeWith = Guid.NewGuid(),
                Merge = true,
                Users = new System.Collections.Generic.List<ActiveDirectoryMetadataAuthPrincipalQueryResultModel>()
                {
                    new ActiveDirectoryMetadataAuthPrincipalQueryResultModel()
                    {
                        SamAccountName = "TestAccountName",
                        UserPrincipalName = "TestUpn"
                    }
                }
            };

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Exists<AuthenticablePrincipal>(It.IsAny<Expression<Func<AuthenticablePrincipal, bool>>>())).Returns(false);
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns(new AuthenticablePrincipal());

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.ImportUser(entity, user);
        }

        [TestMethod]
        [ExpectedException(typeof(InsufficientDataException))]
        public void UserManagementLogic_ImportMerge_EntityWithEmptyUserPrincipalName_ThrowsInsufficientDataException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            ImportUsersActiveDirectoryMetadataModel entity = new ImportUsersActiveDirectoryMetadataModel()
            {
                MergeWith = Guid.NewGuid(),
                Merge = true,
                Users = new System.Collections.Generic.List<ActiveDirectoryMetadataAuthPrincipalQueryResultModel>()
                {
                    new ActiveDirectoryMetadataAuthPrincipalQueryResultModel()
                    {
                        SamAccountName = "TestAccountName",
                        UserPrincipalName = string.Empty
                    }
                }
            };

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Exists<AuthenticablePrincipal>(It.IsAny<Expression<Func<AuthenticablePrincipal, bool>>>())).Returns(false);
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns(new AuthenticablePrincipal());
            configurationRepository.Setup(x => x.Exists<ActiveDirectoryMetadata>(It.IsAny<Guid>())).Returns(true);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.ImportUser(entity, user);
        }

        [TestMethod]
        [ExpectedException(typeof(InsufficientDataException))]
        public void UserManagementLogic_ImportMerge_EntityWithEmptySamAccountName_ThrowsInsufficientDataException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            ImportUsersActiveDirectoryMetadataModel entity = new ImportUsersActiveDirectoryMetadataModel()
            {
                MergeWith = Guid.NewGuid(),
                Merge = true,
                Users = new System.Collections.Generic.List<ActiveDirectoryMetadataAuthPrincipalQueryResultModel>()
                {
                    new ActiveDirectoryMetadataAuthPrincipalQueryResultModel()
                    {
                        SamAccountName = string.Empty,
                        UserPrincipalName = "TestUpn"
                    }
                }
            };

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();
            configurationRepository.Setup(x => x.Exists<AuthenticablePrincipal>(It.IsAny<Expression<Func<AuthenticablePrincipal, bool>>>())).Returns(false);
            configurationRepository.Setup(x => x.Get<AuthenticablePrincipal>(It.IsAny<Guid>())).Returns(new AuthenticablePrincipal());
            configurationRepository.Setup(x => x.Exists<ActiveDirectoryMetadata>(It.IsAny<Guid>())).Returns(true);

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, new AuthorizeInitialSetup(configurationRepository.Object));

            userManagementLogic.ImportUser(entity, user);
        }

        [TestMethod]
        [ExpectedException(typeof(UnauthorizedAccessException))]
        public void UserManagementLogic_ImportUser_Unauthorized_ThrowsUnauthorizedAccessException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            ImportUsersActiveDirectoryMetadataModel entity = GetImportUsersActiveDirectoryMetadataModelValid();

            Mock<IAuthorizationLogic> authorizationLogic = new Mock<IAuthorizationLogic>();
            authorizationLogic.Setup(x => x.IsAuthorizedThrowsException(AuthorizationScopes.ManageUsers, user, It.IsAny<ILoggableEntity>(), It.IsAny<EventCategory>())).Throws(new UnauthorizedAccessException());

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, authorizationLogic.Object);

            userManagementLogic.ImportUser(entity, user);
        }

        [TestMethod]
        [ExpectedException(typeof(UnauthorizedAccessException))]
        public void UserManagementLogic_DeleteUser_Unauthorized_ThrowsUnauthorizedAccessException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            AuthenticablePrincipal authenticablePrincipal = GetAuthenticablePrincipalValid();

            Mock<IAuthorizationLogic> authorizationLogic = new Mock<IAuthorizationLogic>();
            authorizationLogic.Setup(x => x.IsAuthorizedThrowsException(AuthorizationScopes.ManageUsers, user, It.IsAny<ILoggableEntity>(), It.IsAny<EventCategory>())).Throws(new UnauthorizedAccessException());

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, authorizationLogic.Object);

            userManagementLogic.DeleteUser(authenticablePrincipal, user);
        }

        [TestMethod]
        [ExpectedException(typeof(UnauthorizedAccessException))]
        public void UserManagementLogic_SetUser_Unauthorized_ThrowsUnauthorizedAccessException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            UpdateUserModel authenticablePrincipal = GetUpdateUserModelValid();

            Mock<IAuthorizationLogic> authorizationLogic = new Mock<IAuthorizationLogic>();
            authorizationLogic.Setup(x => x.IsAuthorizedThrowsException(AuthorizationScopes.ManageUsers, user, It.IsAny<ILoggableEntity>(), It.IsAny<EventCategory>())).Throws(new UnauthorizedAccessException());

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, authorizationLogic.Object);

            userManagementLogic.SetUser(authenticablePrincipal, user);
        }

        [TestMethod]
        [ExpectedException(typeof(UnauthorizedAccessException))]
        public void UserManagementLogic_NewUser_Unauthorized_ThrowsUnauthorizedAccessException()
        {
            ClaimsPrincipal user = new ClaimsPrincipal();
            AuthenticablePrincipal newUser = GetAuthenticablePrincipalValid();

            Mock<IAuthorizationLogic> authorizationLogic = new Mock<IAuthorizationLogic>();
            authorizationLogic.Setup(x => x.IsAuthorizedThrowsException(AuthorizationScopes.ManageUsers, user, It.IsAny<ILoggableEntity>(), It.IsAny<EventCategory>())).Throws(new UnauthorizedAccessException());

            Mock<IConfigurationRepository> configurationRepository = new Mock<IConfigurationRepository>();

            UserManagementLogic userManagementLogic = new UserManagementLogic(configurationRepository.Object, authorizationLogic.Object);

            userManagementLogic.NewUser(newUser, user);
        }
    }
}


text:
pymatgen.apps.borg package
==========================

Subpackages
-----------

.. toctree::

Submodules
----------

.. toctree::

   pymatgen.apps.borg.hive
   pymatgen.apps.borg.queen

Module contents
---------------

.. automodule:: pymatgen.apps.borg
    :members:
    :undoc-members:
    :show-inheritance:

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

		<title>DOM - STAGE Unit Tests </title>
		<link rel="stylesheet" type="text/css" href="/src/library/console/themes/basic/css/console.css" />

 VISIBLE

builder5 A

builder5 B

		Standard message.

	<button id="put_message">Firefox4 inner</button>


text:
package com.github.database.rider.core.api.exporter;

import com.github.database.rider.core.api.dataset.DataSetFormat;

import java.lang.annotation.*;

/**
 * Created by rafael-pestano on 30/08/2016.
 *
 * This annotation configures DBUnit properties
 * (http://dbunit.sourceforge.net/properties.html) for a given dataset executor.
 *
 * It can be used at class or method level.
 */
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ExportDataSet {

    /**
     *
     * @return Output format of generated dataset.
     */
    DataSetFormat format() default DataSetFormat.YML;

    /**
     * @return tables to inlude in exported dataset. If empty all tables will be exported
     */
    String[] includeTables() default {};

    /**
     * @return list of select statements which the result will be present in exported dataset.
     */
    String[] queryList() default {};

    /**
     *
     * @return if true will bring dependent tables of declared includeTables.
     */
    boolean dependentTables() default false;

    /**
     *
     * @return file path, relative to the directory where project is executed, to generate the dataset. Ex: target/generated/my-dataset.yml.
     * Default is current directory where the project runs.
     */
    String outputName() default "";

    /**
     *
     * @return type of dataset builder, 'default' or 'column...values' syntax.
     * By default the type is 'NONE' meaning that dataset builder will not be generated.
     *
     * Note that the builder (java) file will be generated on the same path as outputName but the file suffix will be changed to .java.
     */
    BuilderType builderType() default BuilderType.NONE;
}


text:
function Y = propGraph(input,options)
% propGraph(input,res,ths)
% plot distribution of input(:,t) < [res]
% -- input: 2D matrix, sum across first dimention
% -- options.res: resolution of the plot
% -- options.ths: plot specific line thresholds
% -- options.skip: don't calculate proportion
% -- outputs matrix Y

if nargin == 1
    options.tmp = [];
end
res = getoption(options,'res',100);
ths = getoption(options,'ths',[]);
skip = getoption(options,'skip',0);
c = getoption(options,'colormap', colormap);
if not(skip)
    Y(1,:) =  squeeze(sum((input < 1/res)))./size(input,1);
    lineCol{1} = c(round(1/res*size(colormap,1)),:);
    for r = 2:res
        Y(r,:) = squeeze(sum((input <= r/res) .* (input > (r-1)/res)))./size(input,1);

    end
else
    Y = input;
end
h = area(Y');
hold on;
for r = 1:res
    if ismember(r/res,ths)
        plot(sum(Y(1:r,:),1),'color',[0 0 0],'linewidth', 3);
    else
        plot(sum(Y(1:r,:),1),'color',c(round(r/res*size(colormap,1)),:));
    end
end
axis([xlim 0 1]);
hold off;


text:
Infinity OS
===========
Copyright (C) 2013 Designture — see LICENSE.TXT

O Infinity OS é um sistema operativo desenvolvido por portugueses, para diversas arquiteturas, mas com principal foco em computadores baseados em x86-64 e ARM. O OS é escrito em Assembly, C e C++. O desenvolvimento do Sistema Operativo está apoiado em três grandes pontos:
* Computação de Elevada Performance - O objectivo é fornecer um sistema operativo com elevada performance, através da utilização de novas técnicas de programação, e o suporte as ultimas tecnologia tais como o processamento paralelo e multi núcleo.
* Design e Facilidade de Leitura - Este é um ponto muito importante. Devemos sempre desenhar o código da forma mais fácil possível para facilitar a manutenção do mesmo.
* Educação - Proporcionar um ambiente de aprendizagem e experiências com programação Assembly, C e C++ de baixo nível, bem como os fundamentos dos sistemas operativos.

Ve a LICENSE.TXT para redistribuição/modificações, e o ficheiro CREDITS.TXT para a lista de pessoas envolvidas.

Gil Mendes (gil0mendes@designture.net)


text:
package org.dc.riot.lol.rx.model.match;

/**
 * This object contains match list information.
 *
 * @author Dc
 * @since 1.0.0
 */
public class MatchListDto {
	private static long COUNT = 0;
	public static long getInstanceCount() {
		return COUNT;
	}

    private int endIndex;
    private MatchReference[] matches;
    private int startIndex;
    private int totalGames;

    public MatchListDto() {
    	COUNT++;
    }

    /**
     * @return The end index
     */
    public int getEndIndex() {
        return endIndex;
    }

    /**
     * @return The matches
     */
    public MatchReference[] getMatches() {
    	if (matches == null) {
    		return new MatchReference[0];
    	}

        return matches;
    }

    /**
     * @return The start index
     */
    public int getStartIndex() {
        return startIndex;
    }

    /**
     * @return Total games
     */
    public int getTotalGames() {
        return totalGames;
    }
}


text:
ACCEPTED

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

#### Published in
in Rossman, Samuels, Rogerson & Lowen, Stud. Mycol. 42: 167 (1999)

#### Original name
Pseudonectria diparietispora J.H. Mill., Giddens & A.A. Foster, 1958

### Remarks
null


text:
define({
  "showLegend": "Gösterimi göster",
  "controlPopupMenuTitle": "Katman içerik menüsünde gösterilecek eylemleri seçin.",
  "zoomto": "Yakınlaştır",
  "transparency": "Şeffaflık",
  "controlPopup": "Açılır Pencereyi Etkinleştir / Devre Dışı Bırak",
  "moveUpAndDown": "Yukarı taşı / Aşağı taşı",
  "attributeTable": "Öznitelik Tablosunu Aç",
  "url": "Açıklama / Öğe Ayrıntılarını Göster / İndir",
  "layerSelectorTitle": "Listede gösterilecek katmanları seçin."
});


text:
<?php
class Kwc_Basic_Image_Cache_Root_EnlargeTagComponent extends Kwc_Basic_ImageEnlarge_EnlargeTag_Component
{
    public static function getSettings()
    {
        $ret = parent::getSettings();
        $ret['ownModel'] = 'Kwc_Basic_Image_TestModel';
        return $ret;
    }

}


text:
This is a single resource CRUD client app using the React framework and backed by Mongo for data persistence. Tests for all routes are included.

## Running

### Install packages

```bash
> npm install
```

### Install gulp

```bash
> npm install --save-dev gulp
```

### Build assets

```bash
> ./node_modules/.bin/gulp
```

### Start mongodb

```bash
> mongod --dbpath=./db
```

### Run server

```bash
> node ./server.js
```

### CHECK IT OUT

```
open http://localhost:5000
```

####Technologies:

  - React: Client-side framework (including React-router and React-dom) https://github.com/reactjs/react-tutorial
  - Gulp: Task runner
  - Webpack: Module bundler (plus Webpack-stream to run Webpack as a stream to conveniently integrate with Gulp)
  - Express: Server package
  - Babel: Javascript compiler (including Babel-loader to transpile JS files using Babel and Webpack, and Babel-preset-react to transform JSX into createElement calls)
  - Mongoose: MongoDB object modeling tool designed to work in an asynchronous environment

####Dev Team:

    Kris Skelton
    Gene Troy


text:
package linchom.com.linchomspace.mine;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import linchom.com.linchomspace.R;
import linchom.com.linchomspace.mine.pojo.UserInfoBean;
import linchom.com.linchomspace.photoutil.UploadBean;

public class HeadImage_activity extends AppCompatActivity {

    public static final String TAG =" Details_Activity" ;
    private ImageView iv_back1;
    private EditText tv_name;
    private TextView tv_sex;
    private TextView tv_birthday;
    private EditText tv_email;
    private EditText tv_office_phone;
    private EditText tv_home_phone;
    private EditText tv_mobile_phone;
    private TextView tv_ok;
    private RelativeLayout tv_add;
    UserInfoBean.DataBean dataBean;
    private RelativeLayout rl_birthday;
    private  ImageView iv_user_photo;
    private int m_year, m_month, m_day;
    private Calendar c;

    private String photoAddress="";
    String photo="";

    private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file
    Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);//The Uri to store the big bitmap
    private File file;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_head_image_activity);

        //判断sd卡是否存在,存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //目录,文件名Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
            file = new File(Environment.getExternalStorageDirectory(), getPhotoFileName());
            imageUri = Uri.fromFile(file);
        }

         iv_user_photo=((ImageView) findViewById(R.id.iv_user_photo));
        tv_name= ((EditText)findViewById(R.id.tv_name));
        tv_sex = ((TextView) findViewById(R.id.tv_add));
        tv_birthday = ((TextView) findViewById(R.id.tv_birthday1));
        tv_email = ((EditText) findViewById(R.id.tv_email));
        tv_office_phone = ((EditText) findViewById(R.id.tv_office_phone));
        tv_home_phone = ((EditText) findViewById(R.id.tv_home_phone));
        tv_mobile_phone = ((EditText) findViewById(R.id.tv_mobile_phone));
        showDialog();
        rl_birthday = ((RelativeLayout) findViewById(R.id.rl_birthday));
        rl_birthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                System.out.println("rl_birthday");
                showDialog(0);
            }
        });

        tv_add = ((RelativeLayout) findViewById(R.id.rl_add));
        iv_user_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择封面
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setType("image/*");
                /*intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                        "image*//*");*/
                startActivityForResult(intent,1);

            }
        });
        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showView();
            }
        });

//        System.out.println("onCreate");

        iv_back1 = ((ImageView) findViewById(R.id.iv_back1));
        iv_back1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });

        tv_ok = ((TextView) findViewById(R.id.tv_ok));
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getApplicationContext(),Details_Activity.class);
                Bundle bundle=new Bundle();
                upData();
//                uploadImage();
//                System.out.println("dataBean"+dataBean);
                bundle.putSerializable("user",dataBean);
                intent.putExtras(bundle);
                //startActivityForResult(intent,2);
                setResult(2,intent);
                finish();//标识
            }
        });

        initEvent();

        getData();
    }
    public void showDialog(){
        c = Calendar.getInstance();// 获取日历的实例
        m_year = c.get(Calendar.YEAR);// 年
        m_month = c.get(Calendar.MONTH);// 月
        m_day = c.get(Calendar.DAY_OF_MONTH);// 日
        System.out.println("-"+m_year+"-"+m_month+"-"+m_day);
    }

    protected Dialog onCreateDialog(int id) {
        if (id == 0) {
            return new DatePickerDialog(this, datePickerButtonListener, m_year,
                    m_month, m_day);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener datePickerButtonListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // 将当前的设置的时间赋值到文本框中
            c.set(Calendar.YEAR, year);
            c.set(Calendar.MONTH, monthOfYear);
            c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

            tv_birthday.setText(df.format(c.getTime()));

        }
    };

    public void getData(){
        Intent intent=getIntent();
        dataBean= (UserInfoBean.DataBean) intent.getSerializableExtra("user");
        System.out.println("dataBean"+dataBean);
        if (dataBean!=null) {
            tv_name.setText(dataBean.getName());
            tv_sex.setText(dataBean.getSex().equals("1") ? "男" : "女");
            tv_birthday.setText(dataBean.getBirthday());
            tv_email.setText(dataBean.getEmail());
            tv_home_phone.setText(dataBean.getHome_phone());
            tv_office_phone.setText(dataBean.getOffice_phone());
            tv_mobile_phone.setText(dataBean.getMobile_phone());
        }
    }

    private void initEvent() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case 1:

                if (data != null) {
                    crop(data.getData());

                }
                break;
            case 2:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    System.out.println("extras"+extras);
                    if (extras != null) {
                        Bitmap bitmap = extras.getParcelable("data");
                        System.out.println("data"+data);
                        System.out.println("bitmap"+bitmap);
                        showImage(bitmap);
                    }
                }
                break;

        }
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }

    String s=null;
    //显示图片,上传服务器
    public void showImage(Bitmap bitmap) {
        iv_user_photo.setImageBitmap(bitmap);//iv显示图片
        saveImage(bitmap);//保存文件
        System.out.println("file"+file);
        System.out.println("begin");
       /* FileInputStream inputStream= null;
        try {
            FileInputStream is = new FileInputStream(file+"");
            byte[] b = new byte[9024];
            int len;
            while((len=is.read(b))!=-1){
                s=new String(b,0,len);
                System.out.println(s);
            }
            is.close();
            System.out.println("end");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //uploadImage();//上传服务器
    }

    public void uploadImage(){

        RequestParams requestParams=new RequestParams("http://app.linchom.com/appapi.php");
        requestParams.addBodyParameter("act", "uploadimage");
        requestParams.addBodyParameter("photo",new File(file+""));
        requestParams.addBodyParameter("image",s);

        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println(result);
                Gson gson = new Gson();
                UploadBean bean = gson.fromJson(result, UploadBean.class);
                photo=bean.getData();
                photoAddress=photoAddress+photo+"";
                System.out.println(photo);
//                upData(photo);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    public void crop(Uri uri){
        //  intent.setType("image/*");
        //裁剪
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    public void saveImage(Bitmap bitmap) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
    }

    public void upData(){

        String name=tv_name.getText().toString();
        String sex=tv_sex.getText().toString();
        String birthday= tv_birthday.getText().toString();
        String[] birthdaies = birthday.split("-");
        final String email=tv_email.getText().toString();
        String homePhone=tv_home_phone.getText().toString();
        String officePhone=tv_office_phone.getText().toString();
        String mobilePhone=tv_mobile_phone.getText().toString();
        dataBean=new UserInfoBean.DataBean(name,email,sex,birthday,officePhone,homePhone,mobilePhone);
//        Gson gson=new Gson();
//        String userJson=gson.toJson(dataBean);
        RequestParams requestParams=new RequestParams("http://app.linchom.com/appapi.php?act=edituserinfo");
            requestParams.addBodyParameter("user_id","135");
//            requestParams.addQueryStringParameter("user",userJson);
        requestParams.addQueryStringParameter("email",email);
        requestParams.addQueryStringParameter("name",name);
        requestParams.addQueryStringParameter("sex",sex.equals("男")?"1":"0");
        requestParams.addQueryStringParameter("birthdayYear",birthdaies[0]);
        requestParams.addQueryStringParameter("birthdayMonth",birthdaies[1]);
        requestParams.addQueryStringParameter("birthdayDay",birthdaies[2]);
        requestParams.addQueryStringParameter("birthday",birthday);
        requestParams.addQueryStringParameter("photo",photo);
        requestParams.addBodyParameter("office_phone",officePhone);
        requestParams.addBodyParameter("mobile_phone",mobilePhone);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

//               System.out.println("6666666666666666"+result);

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("error=="+ex+"");

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public void showView() {
        final CharSequence[] items = {"男", "女"};
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setSingleChoiceItems(items,-1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which){
                    case 0:
                        tv_sex.setText("男");
                        break;
                    case 1:
                        tv_sex.setText("女");
                        break;
                }
                dialog.dismiss();
            }
        });
        builder.show();

    }

}


text:
@interface RiseUpViewCell : UITableViewCell
@property (nonatomic,copy)NSString * contentText;
+ (instancetype)riseUpViewCellWith:(UITableView*)tableView;
@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />

  <title>
      Weekly Reading: Silk Roads, Dragons, and GIFs—The Appendix
    </title>
  <meta name="description" content="The second installment of our new Weekly Reading series roams from underground dragons to the odd death of Tennessee Williams.">

  <link rel="stylesheet" href="/scripts/fancybox/jquery.fancybox.css">

  <link rel="stylesheet" href="/css/main.css">

  <link rel="canonical" href="http://theappendix.net/posts/2013/11/weekly-reading-the-silk-road-and-a-3d-tour-of-early-london">
  <link rel="alternate" type="application/rss+xml" title="The Appendix" href="http://theappendix.net/feed.xml">

Issues

Blog

Contributors

About

    "To acquire the habit of reading is to construct for yourself a refuge from almost all the miseries of life." - W. Somerset Maugham

Weekly Reading: Silk Roads, Dragons, and GIFs

    Published November 15, 2013

At the end of a long day of work, Machiavelli liked to change into "regal and courtly garments" and spend hours reading his favorite authors. For Machiavelli, this reading was the highlight of his day, and it was not a passive activity but a form of conversation, even communion: "I no longer fear poverty, nor do I tremble at the thought of death," he wrote to his friend Francesco. "I become completely part of them."

We at *The Appendix also believe in the power of the written word to bridge gaps, not only between people living today, but between the past and the present. This is the second installment of a new Appendix feature, Weekly Reading, that combines links to contemporary writing we enjoyed from the past week alongside extracts from authors who might be long dead.*

The good people at Open Culture brought us a rare 1925 film about the making of the Oxford English Dictionary. Its a glimpse at a past world of books that feels decidedly foreign today ("Books were bound by gender-divided teams: A room of women labored in the 'girls' bindery section while men bound books in their own separate room.")

Via Princeton historian Matt Karp, a great quote from a letter by the late C. Vann Woodward about his loathing for Duke's faux-tudor pretensions. ("Professors applauded & Woodward muttered & finally puked on the floor. Goddam, how I loathe that place.")

The Points blog about the history of alcohol and drugs offered up an in-depth analysis of the ideology that motivated the founder of the infamous Silk Road drug market.

The always-delightful (even when its dark) Lapham's Quarterly capped its recent "Death" issue with a miscellany of historical fatalities. Tenessee Williams choked to death on an eye-dropper cap, it turns out, and the painter Turner passed on after he was taken to a window so he could see the play of sunlight on a river.

John Glassie, the author of a recent book about the Jesuit polymath (and Appendix inspiration) Athanasius Kircher, shared this dragon from Kircher's 1664 Mundus Subterraneus.

    "I am aware that two kinds of this animal have been distinguished by authors, the one with, the other without wings," Kircher wrote.

      John Glassie

Public Domain Review got a well deserved shout-out from The Guardian.

The first animated GIF designed for a doctoral dissertation?

New Inquiry launched their self-help issue.

We found lots of photographic proof that meerkats wrestle (with handy chart.)

For more links to good writing and interesting discoveries, follow us on Twitter, Tumblr, and Facebook.

      Home

      Issues

      Blog

      Contributors

      Index

      About

      The Appendix was published between 2012 and 2015, released under the CC-BY license, and hosted on GitHub.

      Publication details are available on the colophon.


text:
void ProfilerTimer::SetTimerFinishHandler(TimerEndHandler timerEndHandler)
{
    m_timerHandler = timerEndHandler;
}

ProfilerTimerType ProfilerTimer::GetTimerType() const
{
    return m_timerType;
}

void ProfilerTimer::SetTimerType(ProfilerTimerType timerType)
{
    m_timerType = timerType;
}

ProfilerTimer::ProfilerTimer(long timerInterval) :
    osTimer(timerInterval),
    m_timerHandler(nullptr),
    m_timerType(NONE)
{

}

void ProfilerTimer::onTimerNotification()
{
    m_timerHandler(m_timerType);
}


text:
using System;
using System.Linq;
using System.Web.Mvc;
using Articulate.Models;
using Umbraco.Core;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;

namespace Articulate.Controllers
{
    /// <summary>
    /// Renders the Articulate root node as the main blog post list by date
    /// </summary>
    public class ArticulateController : RenderMvcController
    {
        /// <summary>
        /// Declare new Index action with optional page number
        /// </summary>
        /// <param name="model"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public ActionResult Index(RenderModel model, int? p)
        {
            return RenderView(model, p);
        }

        /// <summary>
        /// Override and declare a NonAction so that we get routed to the Index action with the optional page route
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [NonAction]
        public override ActionResult Index(RenderModel model)
        {
            return RenderView(model);
        }

        private ActionResult RenderView(IRenderModel model, int? p = null)
        {
            var listNode = model.Content.Children
               .FirstOrDefault(x => x.DocumentTypeAlias.InvariantEquals("ArticulateArchive"));
            if (listNode == null)
            {
                throw new InvalidOperationException("An ArticulateArchive document must exist under the root Articulate document");
            }

            if (p != null && p.Value == 1)
            {
                return new RedirectToUmbracoPageResult(model.Content, UmbracoContext);
            }

            if (p == null || p.Value <= 0)
            {
                p = 1;
            }

            var rootPageModel = new ListModel(model.Content);

            //TODO: I wonder about the performance of this - when we end up with thousands of blog posts,
            // this will probably not be so efficient. I wonder if using an XPath lookup for batches of children
            // would work? The children count could be cached. I'd rather not put blog posts under 'month' nodes
            // just for the sake of performance. Hrm.... Examine possibly too.

            var totalPosts = listNode.Children.Count();
            var pageSize = rootPageModel.PageSize;
            var totalPages = Convert.ToInt32(Math.Ceiling((double)totalPosts/pageSize));

            //Invalid page, redirect without pages
            if (totalPages > 0 && totalPages < p)
            {
                return new RedirectToUmbracoPageResult(model.Content, UmbracoContext);
            }

            var pager = new PagerModel(
                pageSize,
                p.Value - 1,
                totalPages,
                totalPages > p ? model.Content.Url.EnsureEndsWith('?') + "p=" + (p + 1) : null,
                p > 2 ? model.Content.Url.EnsureEndsWith('?') + "p=" + (p - 1) : p > 1 ? model.Content.Url : null);

            var listModel = new ListModel(listNode, pager);
            return View(PathHelper.GetThemeViewPath(listModel, "List"), listModel);
        }
    }
}


text:
package org.apache.causeway.viewer.wicket.viewer.integration;

import java.util.List;

import org.apache.wicket.Application;
import org.apache.wicket.Localizer;
import org.apache.wicket.resource.loader.ClassStringResourceLoader;
import org.apache.wicket.resource.loader.ComponentStringResourceLoader;
import org.apache.wicket.resource.loader.IStringResourceLoader;
import org.apache.wicket.resource.loader.InitializerStringResourceLoader;
import org.apache.wicket.resource.loader.PackageStringResourceLoader;
import org.apache.wicket.resource.loader.ValidatorStringResourceLoader;
import org.apache.wicket.settings.ResourceSettings;
import org.apache.wicket.util.lang.Generics;

import lombok.Getter;

public class CausewayResourceSettings extends ResourceSettings {

    /** Chain of string resource loaders to use */
    private final List<IStringResourceLoader> stringResourceLoaders = Generics.newArrayList(4);

    @Getter(onMethod=@__({@Override}), lazy=true)
    private final Localizer localizer = new Localizer();

    /**
     * Configures Wicket's default ResourceLoaders.
     *
     *

     * In contrast to the default lookup strategy, Causeway' searches for application-specific properties first.
     *
     *

     * For an example in {@code FooApplication} let {@code bar.Foo} extend {@link org.apache.wicket.Component}, this
     * results in the following ordering:
     *

     *
application specific

     *

     *

     *
FooApplication.properties

     *
Application.properties

     *

     *

     *
component specific

     *

     *

     *
bar/Foo.properties

     *
org/apache/wicket/Component.properties

     *

     *

     *
package specific

     *

     *

     *
bar/package.properties

     *
package.properties (on Foo's class loader)

     *
org/apache/wicket/package.properties

     *
org/apache/package.properties

     *
org/package.properties

     *
package.properties (on Component's class loader)

     *

     *

     *
validator specific

     *
Initializer specific

     *

     *

     *
bar.Foo.properties (Foo implementing IInitializer)

     *

     *

     *

     *
     * @param application
     */
    public CausewayResourceSettings(Application application) {
        super(application);

        // consult first (the default implementation checks this only third)
        stringResourceLoaders.add(new ClassStringResourceLoader(application.getClass()));

        stringResourceLoaders.add(new ComponentStringResourceLoader());
        stringResourceLoaders.add(new PackageStringResourceLoader());
        // this is where the default implementation registered the search.
        //stringResourceLoaders.add(new ClassStringResourceLoader(application.getClass()));
        stringResourceLoaders.add(new ValidatorStringResourceLoader());
        stringResourceLoaders.add(new InitializerStringResourceLoader(application.getInitializers()));
    }

    /**
     * @see org.apache.wicket.settings.ResourceSettings#getStringResourceLoaders()
     */
    @Override
    public List<IStringResourceLoader> getStringResourceLoaders() {
        return stringResourceLoaders;
    }

}


text:
package com.bhrobotics.morcontrol;

import com.bhrobotics.morcontrol.devices.AnalogState;
import com.bhrobotics.morcontrol.devices.DeviceRegistry;
import com.bhrobotics.morcontrol.devices.emitter.AxisEmitter;
import com.bhrobotics.morcontrol.devices.output.MotorDevice;
import com.bhrobotics.morcontrol.event.Event;
import com.bhrobotics.morcontrol.event.Handler;
import com.bhrobotics.morcontrol.event.Reactor;

public class MorBot extends Robot {
	private ControlMode mode;
	DeviceRegistry registry;

	public void startOperatorControl() {
		Ticker.getInstance().registerTickable(Reactor.getInstance());
		Ticker.getInstance().start();
		registry = new DeviceRegistry();

		Config config = new Config();
		config.configure(registry);

		Handler[] handlers = {new DriveHandler()};
		Condition[] conditions = {new Condition("Event drive joystick called", handlers)};

		mode = new ControlMode(conditions);
		mode.setUp();
	}

	public void stopOperatorControl() {
		mode.tearDown();
	}

	public class DriveHandler implements Handler {
		private MotorDevice tl = registry.getMotor("top-left");
		private MotorDevice tr = registry.getMotor("top-right");
		private MotorDevice bl = registry.getMotor("bottom-left");
		private MotorDevice br = registry.getMotor("bottom-right");

		private double xValue = 0.0;
		private double yValue = 0.0;
		private double tValue = 1.0;

		public void execute(Event event) {
			switch(event.fetchAsInt(AxisEmitter.AXIS_INDEX)) {
				case 1:
					xValue = event.getAsDouble(AxisEmitter.NEW_AXIS_VALUE);
					update();
					break;
				case 2:
					yValue = event.getAsDouble(AxisEmitter.NEW_AXIS_VALUE);
					update();
					break;
				case 3:
					tValue = (event.fetchAsDouble(AxisEmitter.NEW_AXIS_VALUE) + 1)*.4 + .2;
					update();
					break;
			}
		}

		public void update() {
			tl.update(new AnalogState((yValue - xValue)*tValue));
			tr.update(new AnalogState((-yValue - xValue)*tValue));
			bl.update(new AnalogState((yValue - xValue)*tValue));
			br.update(new AnalogState((-yValue - xValue)*tValue));
		}
	}
}


text:
<? Loader::load('view', 'waterfalls/part/introduction/ListingIntroduction', $introduction) ?>

<? if(count($items) > 0) : ?>
<? Loader::load('view', 'waterfalls/part/Navigation', $navigation) ?>

<? foreach($items as $item) : ?>
<? Loader::load('view', 'waterfalls/part/LogPreview', $item) ?>
<? endforeach ?>

<? Loader::load('view', 'waterfalls/part/Navigation', $navigation) ?>
<? else : ?>

Sorry, there are no logs that fit your request. Please go back to the main page or try a different search.

<? endif ?>

<? Loader::load('view', 'waterfalls/part/sidebar/LogListingSidebar', $sidebar) ?>


text:
"use strict";

/*
If you need to do any global setup or tweaking of Javascript, such as polyfills, then add it here.
*/

/*================================================================================================*/

// Load the application code.
if(module === undefined)require('./server.js');
else module.exports = require('./server.js');

/*################################################################################################*/


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

module ActsAsAuthenticTest
  class LoginTest < ActiveSupport::TestCase
    def test_login_field_config
      assert_equal :login, User.login_field
      assert_nil Employee.login_field

      User.login_field = :nope
      assert_equal :nope, User.login_field
      User.login_field :login
      assert_equal :login, User.login_field
    end

    def test_validate_login_field_config
      assert User.validate_login_field
      assert Employee.validate_login_field

      User.validate_login_field = false
      assert !User.validate_login_field
      User.validate_login_field true
      assert User.validate_login_field
    end

    def test_validates_length_of_login_field_options_config
      assert_equal({:within => 3..100}, User.validates_length_of_login_field_options)
      assert_equal({:within => 3..100}, Employee.validates_length_of_login_field_options)

      User.validates_length_of_login_field_options = {:yes => "no"}
      assert_equal({:yes => "no"}, User.validates_length_of_login_field_options)
      User.validates_length_of_login_field_options({:within => 3..100})
      assert_equal({:within => 3..100}, User.validates_length_of_login_field_options)
    end

    def test_validates_format_of_login_field_options_config
      default = {:with => /\A\w[\w\.\-_@ ]+\z/, :message => I18n.t('error_messages.login_invalid', :default => "should use only letters, numbers, spaces, and .-_@ please.")}
      assert_equal default, User.validates_format_of_login_field_options
      assert_equal default, Employee.validates_format_of_login_field_options

      User.validates_format_of_login_field_options = {:yes => "no"}
      assert_equal({:yes => "no"}, User.validates_format_of_login_field_options)
      User.validates_format_of_login_field_options default
      assert_equal default, User.validates_format_of_login_field_options
    end

    def test_validates_uniqueness_of_login_field_options_config
      default = {:scope => User.validations_scope, :if => "#{User.login_field}_changed?".to_sym}
      assert_equal default, User.validates_uniqueness_of_login_field_options

      User.validates_uniqueness_of_login_field_options = {:yes => "no"}
      assert_equal({:yes => "no"}, User.validates_uniqueness_of_login_field_options)
      User.validates_uniqueness_of_login_field_options default
      assert_equal default, User.validates_uniqueness_of_login_field_options
    end

    def test_validates_length_of_login_field
      u = User.new
      u.login = "a"
      assert !u.valid?
      assert u.errors.on(:login)

      u.login = "aaaaaaaaaa"
      assert !u.valid?
      assert !u.errors.on(:login)
    end

    def test_validates_format_of_login_field
      u = User.new
      u.login = "fdsf@^&*"
      assert !u.valid?
      assert u.errors.on(:login)

      u.login = "fdsfdsfdsfdsfs"
      assert !u.valid?
      assert !u.errors.on(:login)
    end

    def test_validates_uniqueness_of_login_field
      u = User.new
      u.login = "bjohnson"
      assert !u.valid?
      assert u.errors.on(:login)

      u.login = "fdsfdsf"
      assert !u.valid?
      assert !u.errors.on(:login)
    end
  end
end


text:
using org.xmlvm;
namespace java.util.regex {
public class RelCompositeGroupQuantifierSet: global::java.util.regex.CompositeGroupQuantifierSet {
new public void @this(global::java.util.regex.Quantifier n1, global::java.util.regex.AbstractSet n2, global::java.util.regex.AbstractSet n3, int n4, int n5){
//XMLVM_BEGIN_WRAPPER[java.util.regex.RelCompositeGroupQuantifierSet: void <init>(java.util.regex.Quantifier, java.util.regex.AbstractSet, java.util.regex.AbstractSet, int, int)]
    global::System.Object _r0_o = null;
    global::System.Object _r1_o = null;
    global::System.Object _r2_o = null;
    global::System.Object _r3_o = null;
    global::org.xmlvm._nElement _r4;
    global::org.xmlvm._nElement _r5;
    _r0_o = this;
    _r1_o = n1;
    _r2_o = n2;
    _r3_o = n3;
    _r4.i = n4;
    _r5.i = n5;
    ((global::java.util.regex.CompositeGroupQuantifierSet) _r0_o).@this((global::java.util.regex.Quantifier) _r1_o, (global::java.util.regex.AbstractSet) _r2_o, (global::java.util.regex.AbstractSet) _r3_o, (int) _r4.i, (int) _r5.i);
    return;
//XMLVM_END_WRAPPER[java.util.regex.RelCompositeGroupQuantifierSet: void <init>(java.util.regex.Quantifier, java.util.regex.AbstractSet, java.util.regex.AbstractSet, int, int)]
}

public override int matches(int n1, global::java.lang.CharSequence n2, global::java.util.regex.MatchResultImpl n3){
//XMLVM_BEGIN_WRAPPER[java.util.regex.RelCompositeGroupQuantifierSet: int matches(int, java.lang.CharSequence, java.util.regex.MatchResultImpl)]
    global::org.xmlvm._nElement _r0;
    global::System.Object _r0_o = null;
    global::org.xmlvm._nElement _r1;
    global::System.Object _r1_o = null;
    global::org.xmlvm._nElement _r2;
    global::System.Object _r3_o = null;
    global::org.xmlvm._nElement _r4;
    global::System.Object _r5_o = null;
    global::System.Object _r6_o = null;
    _r3_o = this;
    _r4.i = n1;
    _r5_o = n2;
    _r6_o = n3;
    _r2.i = 0;
    _r0.i = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fsetCounter;
    _r0.i = ((global::java.util.regex.MatchResultImpl) _r6_o).getEnterCounter((int) _r0.i);
    _r1_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._finnerSet;
    _r1.i = ((global::java.util.regex.AbstractSet) _r1_o).hasConsumed((global::java.util.regex.MatchResultImpl) _r6_o) ? 1 : 0;
    if (_r1.i != 0) goto label22;
    _r0_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fnext;
    _r0.i = ((global::java.util.regex.AbstractSet) _r0_o).matches((int) _r4.i, (global::java.lang.CharSequence) _r5_o, (global::java.util.regex.MatchResultImpl) _r6_o);
    label21:;
    return _r0.i;
    label22:;
    _r1_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fquantifier;
    _r1.i = ((global::java.util.regex.Quantifier) _r1_o).max();
    if (_r0.i < _r1.i) goto label42;
    _r0.i = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fsetCounter;
    ((global::java.util.regex.MatchResultImpl) _r6_o).setEnterCounter((int) _r0.i, (int) _r2.i);
    _r0_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fnext;
    _r0.i = ((global::java.util.regex.AbstractSet) _r0_o).matches((int) _r4.i, (global::java.lang.CharSequence) _r5_o, (global::java.util.regex.MatchResultImpl) _r6_o);
    goto label21;
    label42:;
    _r1_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fquantifier;
    _r1.i = ((global::java.util.regex.Quantifier) _r1_o).min();
    if (_r0.i < _r1.i) goto label79;
    _r1_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fnext;
    _r1.i = ((global::java.util.regex.AbstractSet) _r1_o).matches((int) _r4.i, (global::java.lang.CharSequence) _r5_o, (global::java.util.regex.MatchResultImpl) _r6_o);
    if (_r1.i >= 0) goto label72;
    _r1.i = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fsetCounter;
    _r0.i = _r0.i + 1;
    ((global::java.util.regex.MatchResultImpl) _r6_o).setEnterCounter((int) _r1.i, (int) _r0.i);
    _r0_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._finnerSet;
    _r0.i = ((global::java.util.regex.AbstractSet) _r0_o).matches((int) _r4.i, (global::java.lang.CharSequence) _r5_o, (global::java.util.regex.MatchResultImpl) _r6_o);
    goto label21;
    label72:;
    _r0.i = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fsetCounter;
    ((global::java.util.regex.MatchResultImpl) _r6_o).setEnterCounter((int) _r0.i, (int) _r2.i);
    _r0.i = _r1.i;
    goto label21;
    label79:;
    _r1.i = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._fsetCounter;
    _r0.i = _r0.i + 1;
    ((global::java.util.regex.MatchResultImpl) _r6_o).setEnterCounter((int) _r1.i, (int) _r0.i);
    _r0_o = ((global::java.util.regex.RelCompositeGroupQuantifierSet) _r3_o)._finnerSet;
    _r0.i = ((global::java.util.regex.AbstractSet) _r0_o).matches((int) _r4.i, (global::java.lang.CharSequence) _r5_o, (global::java.util.regex.MatchResultImpl) _r6_o);
    goto label21;
//XMLVM_END_WRAPPER[java.util.regex.RelCompositeGroupQuantifierSet: int matches(int, java.lang.CharSequence, java.util.regex.MatchResultImpl)]
}

//XMLVM_BEGIN_WRAPPER[java.util.regex.RelCompositeGroupQuantifierSet]
//XMLVM_END_WRAPPER[java.util.regex.RelCompositeGroupQuantifierSet]

} // end of class: RelCompositeGroupQuantifierSet

} // end of namespace: java.util.regex


text:
import React from 'react';
import { shallow } from 'enzyme';

import CodesLists from './codes-lists';
import CodesListsCodes from './codes-lists-codes';

import { WIDGET_CODES_LISTS } from 'constants/dom-constants';
import { CODES_LIST_INPUT_ENUM } from 'constants/pogues-constants';

const { PANEL_CLASS } = WIDGET_CODES_LISTS;
const { NEW, REF, QUEST } = CODES_LIST_INPUT_ENUM;

describe('<CodesList />', () => {
  const customPath = 'this.is.a.fake.path';

  test.skip('Should exists hidden fields with the codes list id and label', () => {
    const wrapper = shallow(<CodesLists path={customPath} />);
    expect(wrapper.find(`Field[name="${customPath}id"]`)).toHaveLength(1);
    expect(wrapper.find(`Field[name="${customPath}label"]`)).toHaveLength(1);
  });

  test.skip('Should render a CodesListsCodes component', () => {
    const wrapper = shallow(<CodesLists path={customPath} />);
    expect(wrapper.find('FieldArray').props()).toMatchObject({
      name: `${customPath}codes`,
      component: CodesListsCodes
    });
  });

  test.skip('Should render a CodesListsPanelSelector component', () => {
    const wrapper = shallow(<CodesLists path={customPath} />);
    expect(wrapper.find('CodesListsPanelSelector')).toHaveLength(1);
  });

  test.skip(
    'Should render a panel to create a new codes list, to search in the codes lists referential and to select a ' +
      'codes list from the existing in the questionnaire',
    () => {
      const wrapper = shallow(<CodesLists path={customPath} />);
      expect(
        wrapper.find(`.${PANEL_CLASS}.${PANEL_CLASS}-${NEW}`)
      ).toHaveLength(1);
      expect(
        wrapper.find(`.${PANEL_CLASS}.${PANEL_CLASS}-${REF}`)
      ).toHaveLength(1);
      expect(
        wrapper.find(`.${PANEL_CLASS}.${PANEL_CLASS}-${QUEST}`)
      ).toHaveLength(1);
    }
  );
});


text:
@implementation UIView (BCBlurView)

- (void)drawBluredBackground:(CGFloat)blurRadius inRect:(CGRect)rect
{
	if (blurRadius == 0.0f || self.hidden) { // not visible anyway! We don't need to make the expensive drawing
		return;
	}

#ifdef DEBUG
	clock_t time = clock();
#endif

	// render the background we want to blur
	self.hidden = YES; // make the button itself invisible as it should not be rendered!

	// walk up the view hierarchy to find the first view that is opaque
	UIView* viewToRender = self.superview;
	while (!viewToRender.opaque) {
		if (viewToRender.superview) {
			viewToRender = viewToRender.superview;
		} else {
			break; // maybe the window isn't set opaque!
		}
	}

	CGRect renderRect = [viewToRender convertRect:rect fromView:self];

	UIGraphicsBeginImageContext(rect.size);

	CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -CGRectGetMinX(renderRect), CGRectGetMaxY(renderRect));
	CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0f, -1.0f);

	[viewToRender.layer renderInContext:UIGraphicsGetCurrentContext()];

	CGImageRef blurInputReference = [UIGraphicsGetImageFromCurrentImageContext() CGImage];

	UIGraphicsEndImageContext();

	self.hidden = NO; // make the button itself visible again for display!

	// blur the rendered background
	CIImage* inputImage = [CIImage imageWithCGImage:blurInputReference];
	CIFilter* blur = [CIFilter filterWithName:@"CIGaussianBlur"];
	[blur setDefaults];
	[blur setValue:@(blurRadius) forKey:@"inputRadius"];
	[blur setValue:inputImage forKey:@"inputImage"];

	CIImage* outputImage = [blur outputImage];
	CIContext* context = [CIContext contextWithOptions:nil];
	CGImageRef blurOutput = [context createCGImage:outputImage fromRect:outputImage.extent];

	// render the blured background - note we need to use the extent of the output image, as it is larger as the original rect!
	CGContextDrawImage(UIGraphicsGetCurrentContext(), outputImage.extent, blurOutput);

	CGImageRelease(blurOutput);

#ifdef DEBUG
	clock_t duration = clock() - time;
	NSLog(@"Glossy drawing took %lu ticks (%f seconds)", duration, ((float)duration)/CLOCKS_PER_SEC);
#endif
}

@end


text:
$( window ).load(function(){
	console.log("Document is loaded");
	var testCaseRowHTML = "

";

	for (i=0 ; i<testCases.length ; i++) {
		document.getElementById('data-table').innerHTML += testCaseRowHTML;
	}
	var allTitleRow = document.getElementsByName('titleRow');
	var allTestCaseRow = document.getElementsByName('testCaseRow');
	for(i=0;i<testCases.length;i++){
		// Title and index
		$("td[name*='title']")[i].textContent = testCases[i].category;
		$("td[name*='index']")[i].textContent = i;

		// Input Images
		$("tr[name*='testCaseRow'] img[name*='noFlashImage']")[i].src = './ProjectPage/img/'+testCases[i].noFlashImage;
		$("tr[name*='testCaseRow'] img[name*='flashImage']")[i].src = './ProjectPage/img/'+testCases[i].flashImage;

		// Output Images
		$("tr[name*='testCaseRow'] img[name*='flash_lshiif']")[i].src = './ProjectPage/img/'+testCases[i].flash_lshiif;
		$("tr[name*='testCaseRow'] img[name*='noFlash_lshiif']")[i].src = './ProjectPage/img/'+testCases[i].noFlash_lshiif;
		$("tr[name*='testCaseRow'] img[name*='opticalFlow']")[i].src = './ProjectPage/img/'+testCases[i].opticalFlow;
		$("tr[name*='testCaseRow'] img[name*='differenceImage']")[i].src = './ProjectPage/img/'+testCases[i].differenceImage;
		$("tr[name*='testCaseRow'] img[name*='saliencyWithoutMD']")[i].src = './ProjectPage/img/'+testCases[i].saliencyWithoutMD;
		$("tr[name*='testCaseRow'] img[name*='saliencyWithMD']")[i].src = './ProjectPage/img/'+testCases[i].saliencyWithMD;

		console.log("Test case " + i + " is loaded");
	}

	$(".lightImage").fadeTo(0,0.5);
		console.log("Test cases are loaded");

		$(".imagePair").mouseenter(function(){
		$(".lightImage").fadeTo(0,1);
		$(".inputImagesHeader").text("Flash Images");
		$(".lshiifImagesHeader").text("Flash LSHIIF");
		showLightImage = true;
	});

	$(".imagePair").mouseleave(function(){
		$(".lightImage").fadeTo(0,0.5);
		$(".inputImagesHeader").text("Image Pairs");
		$(".lshiifImagesHeader").text("LSHIIF");
	});

	$(".imagePair").click(function() {
		if(showLightImage){
			$(".lightImage").fadeTo(0,0);
			$(".inputImagesHeader").text("No flash Images");
			$(".lshiifImagesHeader").text("No flash LSHIIF");
			showLightImage = false;
		}
		else{
			$(".lightImage").fadeTo(0,1);
			$(".inputImagesHeader").text("Flash Images");
			$(".lshiifImagesHeader").text("Flash LSHIIF");
			showLightImage = true;
		}
	});
});

// $( document ).ready(function(){

// });


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE version SYSTEM "../../../lib/pkp/dtd/pluginVersion.dtd">

<!--
  * plugins/generic/customBlockManager/version.xml
  *
  * Copyright (c) 2003-2013 John Willinsky
  * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  *
  * Plugin version information.
  -->
<version>
	<application>customBlockManager</application>
	<type>plugins.generic</type>
	<release>1.1.0.0</release>
	<date>2009-07-13</date>
	<lazy-load>1</lazy-load>
	<class>CustomBlockManagerPlugin</class>
</version>


text:
#include <aws/quicksight/model/GenerateEmbedUrlForRegisteredUserRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::QuickSight::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GenerateEmbedUrlForRegisteredUserRequest::GenerateEmbedUrlForRegisteredUserRequest() :
    m_awsAccountIdHasBeenSet(false),
    m_sessionLifetimeInMinutes(0),
    m_sessionLifetimeInMinutesHasBeenSet(false),
    m_userArnHasBeenSet(false),
    m_experienceConfigurationHasBeenSet(false),
    m_allowedDomainsHasBeenSet(false)
{
}

Aws::String GenerateEmbedUrlForRegisteredUserRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_sessionLifetimeInMinutesHasBeenSet)
  {
   payload.WithInt64("SessionLifetimeInMinutes", m_sessionLifetimeInMinutes);

  }

  if(m_userArnHasBeenSet)
  {
   payload.WithString("UserArn", m_userArn);

  }

  if(m_experienceConfigurationHasBeenSet)
  {
   payload.WithObject("ExperienceConfiguration", m_experienceConfiguration.Jsonize());

  }

  if(m_allowedDomainsHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> allowedDomainsJsonList(m_allowedDomains.size());
   for(unsigned allowedDomainsIndex = 0; allowedDomainsIndex < allowedDomainsJsonList.GetLength(); ++allowedDomainsIndex)
   {
     allowedDomainsJsonList[allowedDomainsIndex].AsString(m_allowedDomains[allowedDomainsIndex]);
   }
   payload.WithArray("AllowedDomains", std::move(allowedDomainsJsonList));

  }

  return payload.View().WriteReadable();
}


text:
/**
 * @file fullscreen-api.js
 * @module fullscreen-api
 * @private
 */
import document from 'global/document';

/**
 * Store the browser-specific methods for the fullscreen API.
 *
 * @type {Object}
 * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
 * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
 */
const FullscreenApi = {};

// browser API methods
const apiMap = [
  [
    'requestFullscreen',
    'exitFullscreen',
    'fullscreenElement',
    'fullscreenEnabled',
    'fullscreenchange',
    'fullscreenerror'
  ],
  // WebKit
  [
    'webkitRequestFullscreen',
    'webkitExitFullscreen',
    'webkitFullscreenElement',
    'webkitFullscreenEnabled',
    'webkitfullscreenchange',
    'webkitfullscreenerror'
  ],
  // Old WebKit (Safari 5.1)
  [
    'webkitRequestFullScreen',
    'webkitCancelFullScreen',
    'webkitCurrentFullScreenElement',
    'webkitCancelFullScreen',
    'webkitfullscreenchange',
    'webkitfullscreenerror'
  ],
  // Mozilla
  [
    'mozRequestFullScreen',
    'mozCancelFullScreen',
    'mozFullScreenElement',
    'mozFullScreenEnabled',
    'mozfullscreenchange',
    'mozfullscreenerror'
  ],
  // Microsoft
  [
    'msRequestFullscreen',
    'msExitFullscreen',
    'msFullscreenElement',
    'msFullscreenEnabled',
    'MSFullscreenChange',
    'MSFullscreenError'
  ]
];

const specApi = apiMap[0];
let browserApi;

// determine the supported set of functions
for (let i = 0; i < apiMap.length; i++) {
  // check for exitFullscreen function
  if (apiMap[i][1] in document) {
    browserApi = apiMap[i];
    break;
  }
}

// map the browser API names to the spec API names
if (browserApi) {
  for (let i = 0; i < browserApi.length; i++) {
    FullscreenApi[specApi[i]] = browserApi[i];
  }
}

export default FullscreenApi;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Bidaud, Moënne-Loccoz, Reumaux & Henry, Atlas des Cortinaires (Meyzieu) 9: 399 (1999)

#### Original name
Cortinarius impennoides Bidaud, Moënne-Locc. & Reumaux

### Remarks
null


text:
<?php

namespace phpDocumentor\Renderer\Template;

use phpDocumentor\Path;
use phpDocumentor\Renderer\Template;

final class PathsRepository implements PathsRepositoryInterface
{
    /** @var string[] */
    private $templateFolders = [];

    /**
     * Initializes this repository with its dependencies.
     * @param string[] $templateFolders
     */
    public function __construct(array $templateFolders = [])
    {
        $this->templateFolders = $templateFolders;
    }

    /**
     * Lists the folders where templates can be found
     *
     * @param Template|null $template
     * @return string[]
     */
    public function listLocations(Template $template = null)
    {
        $templatesFolders = $this->templateFolders;

        // Determine the path of the current template and prepend it to the list so that it will always be queried
        // first.
        // http://twig.sensiolabs.org/doc/recipes.html#overriding-a-template-that-also-extends-itself
        if ($template) {
            $parameters = $template->getParameters();
            if (isset($parameters['directory'])
                && file_exists($parameters['directory']->getValue())
                && is_dir($parameters['directory']->getValue())
            ) {
                array_unshift($templatesFolders, $parameters['directory']->getValue());
            } elseif ($template->getName()) {
                foreach ($templatesFolders as $folder) {
                    $currentTemplatePath = $folder . '/' . $template->getName();
                    if (file_exists($currentTemplatePath)) {
                        array_unshift($templatesFolders, $currentTemplatePath);
                        break;
                    }
                }
            }
        }

        return $templatesFolders;
    }

    /**
     * Finds a template and returns the full name and path of the view
     *
     * @param Template $template
     * @param Path $view
     * @return null|Path
     */
    public function findByTemplateAndPath(Template $template, Path $view)
    {
        foreach ($this->listLocations($template) as $location) {
            $filename = (string)$location . '/' . (string)$view;
            if (file_exists($filename)) {
                if (!is_readable($filename)) {
                    $message = sprintf(
                        'File "%" for template "%s" was found but could not be read',
                        $filename,
                        $template->getName()
                    );

                    throw new \RuntimeException($message);
                }

                return new Path($filename);
            }
        }

        return null;
    }

    /**
     * Lists all available templates
     *
     * @return string[]
     */
    public function listTemplates()
    {
        $templates = [];

        foreach ($this->templateFolders as $templateFolder) {
            $subfolders = new \RecursiveDirectoryIterator($templateFolder);
            foreach ($subfolders as $subfolder) {
                if (file_exists($subfolder . '/template.xml')) {
                    $templates[] = basename($subfolder);
                }
            }
        }

        return $templates;
    }
}


text:
//[-------------------------------------------------------]
//[ Shader start                                          ]
//[-------------------------------------------------------]
#ifdef RHI_DIRECT3D9
if (mRhi->getNameId() == Rhi::NameId::DIRECT3D9)
{

//[-------------------------------------------------------]
//[ Vertex shader source code                             ]
//[-------------------------------------------------------]
// One vertex shader invocation per vertex
vertexShaderSourceCode = R"(
// Attribute input/output
struct VS_OUTPUT
{
	float4 Position : SV_POSITION;	// Clip space vertex position as output, left/bottom is (-1,-1) and right/top is (1,1)
	float2 TexCoord : TEXCOORD0;	// Normalized texture coordinate as output
};

// Programs
VS_OUTPUT main(float2 Position : POSITION)	// Clip space vertex position as input, left/bottom is (-1,-1) and right/top is (1,1)
{
	VS_OUTPUT output;

	// Pass through the clip space vertex position, left/bottom is (-1,-1) and right/top is (1,1)
	output.Position = float4(Position, 0.5f, 1.0f);

	// Calculate the texture coordinate by mapping the clip space coordinate to a texture space coordinate
	// -> Unlike OpenGL or OpenGL ES 3, in Direct3D 9 & 10 & 11 the texture origin is left/top which does not map well to clip space coordinates
	// -> We have to flip the y-axis to map the coordinate system to the Direct3D 9 & 10 & 11 texture coordinate system
	// -> In this example we do this within the fragment shader so have identical wobble across the different graphics APIs
	// -> (-1,-1) -> (0,0)
	// -> (1,1) -> (1,1)
	output.TexCoord = Position.xy * 0.5f + 0.5f;

	// Done
	return output;
}
)";

//[-------------------------------------------------------]
//[ Fragment shader source code - Content generation      ]
//[-------------------------------------------------------]
// One fragment shader invocation per fragment
// "pixel shader" in Direct3D terminology
fragmentShaderSourceCode_ContentGeneration = R"(
// Programs
float4 main(float4 Position : SV_POSITION, float2 TexCoord : TEXCOORD0) : SV_TARGET
{
	// Return the color green
	return float4(0.0f, 1.0f, 0.0f, 1.0f);
}
)";

//[-------------------------------------------------------]
//[ Fragment shader source code - Content processing      ]
//[-------------------------------------------------------]
// One fragment shader invocation per fragment
// "pixel shader" in Direct3D terminology
fragmentShaderSourceCode_ContentProcessing = R"(
// Uniforms
uniform sampler2D ContentMap : register(s0);

// Programs
float4 main(float4 Position : SV_POSITION, float2 TexCoord : TEXCOORD0) : SV_TARGET
{
	// Fetch the texel at the given texture coordinate and return its color
	// -> Apply a simple wobble to the texture coordinate so we can see that content processing is up and running
	// -> Unlike OpenGL or OpenGL ES 3, in Direct3D 9 & 10 & 11 the texture origin is left/top which does not map well to clip space coordinates
	// -> We have to flip the y-axis to map the coordinate system to the Direct3D 9 & 10 & 11 texture coordinate system
	// -> (-1,-1) -> (0,1)
	// -> (1,1) -> (1,0)
	return tex2D(ContentMap, float2(TexCoord.x + sin(TexCoord.x * 100.0f) * 0.01f, 1.0f - TexCoord.y - cos(TexCoord.y * 100.0f) * 0.01f));
}
)";

//[-------------------------------------------------------]
//[ Shader end                                            ]
//[-------------------------------------------------------]
}
else
#endif


text:
package com.vangent.hieos.services.xds.registry.backend;

import com.vangent.hieos.xutil.metadata.structure.Metadata;
import com.vangent.hieos.xutil.metadata.structure.MetadataSupport;
import com.vangent.hieos.xutil.metadata.structure.MetadataParser;
import com.vangent.hieos.xutil.exception.MetadataException;
import com.vangent.hieos.xutil.exception.MetadataValidationException;
import com.vangent.hieos.xutil.exception.XdsException;
import com.vangent.hieos.xutil.exception.XdsInternalException;
import com.vangent.hieos.xutil.xlog.client.XLogMessage;

import com.vangent.hieos.xutil.xml.XMLParser;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.registry.RegistryException;

import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMFactory;
import org.apache.log4j.Logger;

import org.freebxml.omar.server.persistence.PersistenceManager;
import org.freebxml.omar.server.persistence.PersistenceManagerFactory;

/**
 *
 * @author Bernie Thuman
 */
public class BackendRegistry {

    private final static Logger log = Logger.getLogger(BackendRegistry.class);
    private final static String REGISTRY_COMMIT_FAILURE = "ebXML EXCEPTION: Failed to commit transaction";
    private final static String REGISTRY_ROLLBACK_FAILURE = "ebXML EXCEPTION: Failed to rollback transaction";
    private static PersistenceManager pm = PersistenceManagerFactory.getInstance().getPersistenceManager();
    private final static QName idQName = new QName("id");
    private final static String adhocQueryRequestHeader =
            "<query:AdhocQueryRequest\n"
            + "xmlns=\"urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0\"\n"
            + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "xmlns:lcm=\"urn:oasis:names:tc:ebxml-regrep:xsd:lcm:3.0\"\n"
            + "xmlns:rs=\"urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0\"\n"
            + "xmlns:rim=\"urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0\"\n"
            + "xmlns:query=\"urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0\"\n"
            + "xsi:schemaLocation=\"urn:oasis:names:tc:ebxml-regrep:xsd:query:3.0 http://oasis-open.org/committees/regrep/documents/3.0/schema/query.xsd\">\n";
    private XLogMessage logMessage;
    private Connection connection = null;
    private String reason = "";

    /**
     *
     * @param logMessage
     */
    public BackendRegistry(XLogMessage logMessage) {
        this.logMessage = logMessage;
    }

    /**
     *
     * @param reason
     */
    public void setReason(String reason) {
        this.reason = reason;
    }

    /**
     *
     * @param m
     * @return
     * @throws XdsInternalException
     */
    public OMElement submit(Metadata m) throws XdsInternalException {
        OMElement request = m.getV3SubmitObjectsRequest();
        return this.submit(request);
    }

    /**
     *
     * @param registryObjects
     * @return
     * @throws XdsInternalException
     */
    public OMElement submit(List<OMElement> registryObjects) throws XdsInternalException {
        Metadata m = new Metadata();
        OMElement request = m.getV3SubmitObjectsRequest(registryObjects);
        return this.submit(request);
    }

    /**
     *
     * @param objectIds
     * @return
     * @throws XdsInternalException
     */
    public OMElement submitApproveObjectsRequest(List<String> objectIds) throws XdsInternalException {
        OMElement approveObjectsRequest = this.getApproveObjectsRequest(objectIds);
        this.setReason("Approve");
        return this.submit(approveObjectsRequest);
    }

    /**
     *
     * @param objectIds
     * @return
     * @throws XdsInternalException
     */
    public OMElement submitDeprecateObjectsRequest(List<String> objectIds) throws XdsInternalException {
        OMElement deprecateObjectsRequest = this.getDeprecateObjectsRequest(objectIds);
        this.setReason("Deprecate");
        return this.submit(deprecateObjectsRequest);
    }

    /**
     *
     * @param objectIds
     * @return
     * @throws XdsInternalException
     */
    public OMElement submitRemoveObjectsRequest(List<String> objectIds) throws XdsInternalException {
        OMElement removeObjectsRequest = this.getRemoveObjectsRequest(objectIds);
        this.setReason("Remove Objects");
        return this.submit(removeObjectsRequest);
    }

    /**
     *
     * @param objectId
     * @param status
     * @return
     * @throws XdsException
     */
    public OMElement submitSetStatusOnObjectsRequest(String objectId, String status) throws XdsException {
        List<String> objectIds = new ArrayList<String>();
        objectIds.add(objectId);
        return this.submitSetStatusOnObjectsRequest(objectIds, status);
    }

    /**
     *
     * @param objectIds
     * @param status
     * @return
     * @throws XdsInternalException
     */
    public OMElement submitSetStatusOnObjectsRequest(List<String> objectIds, String status) throws XdsInternalException {
        OMElement setStatusOnObjectsRequest = this.getSetStatusOnObjectsRequest(objectIds, status);
        this.setReason("Set Status");
        return this.submit(setStatusOnObjectsRequest);
    }

    /**
     *
     * @param request
     * @return
     * @throws XdsInternalException
     */
    public OMElement submit(OMElement request) throws XdsInternalException {
        if (logMessage != null) {
            logMessage.addOtherParam("ebXML Request (" + reason + ")", request);
        }
        OMElement result = null;
        try {
            Connection conn = this.getConnection();
            OmarRegistry or = new OmarRegistry(request, conn);
            result = or.process();
            if (logMessage != null) {
                logMessage.addOtherParam("ebXML Response", (result != null) ? result : "null");
            }
            return result;
        } catch (Exception ex) {
            try {
                this.rollback();
            } catch (Exception regEx) {
                log.fatal(REGISTRY_ROLLBACK_FAILURE, regEx);
            }
            throw new XdsInternalException("ebXML EXCEPTION: " + ex.getMessage());
        }
    }

    /**
     *
     * @throws XdsInternalException
     */
    public void commit() throws XdsInternalException {
        if (connection != null) {
            try {
                connection.commit();
                pm.releaseConnection(connection);
                connection = null;
            } catch (Exception ex) {
                log.fatal(REGISTRY_COMMIT_FAILURE, ex);
                this.rollback();
                throw new XdsInternalException(REGISTRY_COMMIT_FAILURE + ": " + ex.getMessage());
            }
        }
    }

    /**
     *
     * @throws XdsInternalException
     */
    public void rollback() throws XdsInternalException {
        try {
            if (connection != null) {
                connection.rollback();
                pm.releaseConnection(connection);
                connection = null;
            }
        } catch (Exception ex) {
            log.fatal(REGISTRY_ROLLBACK_FAILURE, ex);
            throw new XdsInternalException(REGISTRY_ROLLBACK_FAILURE + ": " + ex.getMessage());
        }
    }

    /**
     *
     * @param sql
     * @param leafClass
     * @return
     * @throws MetadataException
     * @throws MetadataValidationException
     * @throws XdsInternalException
     */
    public OMElement runQuery(String sql, boolean leafClass) throws MetadataException, MetadataValidationException, XdsInternalException {
        OMElement result = this.basicQuery(sql, leafClass);
        Metadata m = MetadataParser.parseNonSubmission(result);
        m.fixClassifications();
        return result;
    }

    /**
     *
     * @param sql
     * @return
     * @throws XdsException
     */
    public ArrayList<String> runQueryForObjectRefs(String sql) throws XdsException {

        // Perform the query (only for references):
        OMElement result = this.runQuery(sql, false /* leafClass */);

        // Now create the array of object references:
        ArrayList<String> ors = new ArrayList<String>();
        if (result == null) // error occured
        {
            return ors;
        }

        // Parse result and gather all object reference ids:
        OMElement sqlQueryResult = MetadataSupport.firstChildWithLocalName(result, "RegistryObjectList");
        if (sqlQueryResult != null) {
            for (OMElement or : MetadataSupport.childrenWithLocalName(sqlQueryResult, "ObjectRef")) {
                String id = or.getAttributeValue(idQName);
                if (id != null && !id.equals("")) {
                    ors.add(id);
                }
            }
        }
        return ors;
    }

    /**
     *
     * @param sql
     * @return
     * @throws MetadataValidationException
     * @throws XMLParserException
     * @throws XdsException
     */
    //public ArrayList<String> objectRefQuery(String sql)
    //        throws MetadataValidationException, XMLParserException, XdsException {
    //    OMElement response = this.basicQuery(sql, true /* leafClass */);
    //    Metadata m = MetadataParser.parseNonSubmission(response);
    //    return m.getObjectIds(m.getObjectRefs());
    //}
    /**
     *
     * @param sql
     * @param leafClass
     * @return
     * @throws XdsInternalException
     */
    public OMElement basicQuery(String sql, boolean leafClass)
            throws XdsInternalException {
        String queryString = BackendRegistry.adhocQueryRequestHeader
                + "<query:ResponseOption returnType=\""
                + ((leafClass) ? "LeafClass" : "ObjectRef")
                + "\" returnComposedObjects=\"true\">\n"
                + "</query:ResponseOption>\n "
                + "<rim:AdhocQuery id=\"tempId\">\n"
                + "<rim:QueryExpression queryLanguage=\"urn:oasis:names:tc:ebxml-regrep:QueryLanguage:SQL-92\">\n"
                + //		sql +
                "</rim:QueryExpression>\n"
                + "</rim:AdhocQuery>\n"
                + "</query:AdhocQueryRequest>\n";

        OMElement query = XMLParser.stringToOM(queryString);
        //AMS 04/26/2009 - FIXME - Handle the condition that there might be no children with name AdhocQuery.
        // Or does validation already account for that?? ---- RESEARCH
        OMElement adhocQueryRequest = MetadataSupport.firstChildWithLocalName(query, "AdhocQuery");
        OMElement queryExpression = MetadataSupport.firstChildWithLocalName(adhocQueryRequest, "QueryExpression");
        queryExpression.setText(sql);

        OMElement result = this.submit(query);
        return result;
    }

    /**
     *
     * @param uuids
     * @return
     */
    private OMElement getApproveObjectsRequest(List<String> uuids) {
        OMNamespace lcm = MetadataSupport.ebLcm3;
        OMElement req = MetadataSupport.om_factory.createOMElement("ApproveObjectsRequest", lcm);
        req.addChild(this.getObjectRefList(uuids));
        return req;
    }

    /**
     *
     * @param uuids
     * @return
     */
    private OMElement getDeprecateObjectsRequest(List<String> uuids) {
        OMNamespace lcm = MetadataSupport.ebLcm3;
        OMElement req = MetadataSupport.om_factory.createOMElement("DeprecateObjectsRequest", lcm);
        req.addChild(this.getObjectRefList(uuids));
        return req;

    }

     /**
     *
     * @param uuids
     * @return
     */
    private OMElement getRemoveObjectsRequest(List<String> uuids) {
        OMNamespace lcm = MetadataSupport.ebLcm3;
        OMElement req = MetadataSupport.om_factory.createOMElement("RemoveObjectsRequest", lcm);
        req.addChild(this.getObjectRefList(uuids));
        return req;

    }

    /**
     *
     * @param uuids
     * @param status
     * @return
     */
    private OMElement getSetStatusOnObjectsRequest(List<String> uuids, String status) {
        OMNamespace rsExt = MetadataSupport.om_factory.createOMNamespace("urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0:ext", "rsext");
        OMElement req = MetadataSupport.om_factory.createOMElement("SetStatusOnObjectsRequest", rsExt);
        req.addAttribute("status", status, null);
        req.addChild(this.getObjectRefList(uuids));
        return req;

    }

    /**
     * Creates ebXML v3 <ObjectRefList> structure given a set of uuids.
     *
     * @param uuids Arraylist of uuids.
     * @return <ObjectRefList> OMElement node.
     */
    private OMElement getObjectRefList(List<String> uuids) {
        OMNamespace rimNs = MetadataSupport.ebRIMns3;
        OMFactory fact = MetadataSupport.om_factory;
        OMElement objectRefList = fact.createOMElement("ObjectRefList", rimNs);
        for (Iterator it = uuids.iterator(); it.hasNext();) {
            String uuid = (String) it.next();
            OMAttribute attribute = fact.createOMAttribute("id", null, uuid);
            OMElement objectReference = fact.createOMElement("ObjectRef", rimNs);
            objectReference.addAttribute(attribute);
            objectRefList.addChild(objectReference);
        }
        return objectRefList;
    }

    /**
     *
     * @return
     * @throws RegistryException
     */
    private Connection getConnection() throws RegistryException {
        if (connection == null) {
            connection = pm.getConnection();
        }
        return connection;
    }
}