text:
package org.hisp.dhis.user;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.common.AuditLogUtil;
import org.hisp.dhis.commons.filter.FilterUtils;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.period.PeriodType;
import org.hisp.dhis.security.PasswordManager;
import org.hisp.dhis.setting.SettingKey;
import org.hisp.dhis.setting.SystemSettingManager;
import org.hisp.dhis.system.deletion.DeletionManager;
import org.hisp.dhis.system.filter.UserAuthorityGroupCanIssueFilter;
import org.hisp.dhis.system.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author Chau Thu Tran
 */
@Transactional
public class DefaultUserService
    implements UserService
{
    private static final Log log = LogFactory.getLog( DefaultUserService.class );

    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private UserStore userStore;

    public void setUserStore( UserStore userStore )
    {
        this.userStore = userStore;
    }

    private UserGroupService userGroupService;

    public void setUserGroupService( UserGroupService userGroupService )
    {
        this.userGroupService = userGroupService;
    }

    private UserCredentialsStore userCredentialsStore;

    public void setUserCredentialsStore( UserCredentialsStore userCredentialsStore )
    {
        this.userCredentialsStore = userCredentialsStore;
    }

    private UserAuthorityGroupStore userAuthorityGroupStore;

    public void setUserAuthorityGroupStore( UserAuthorityGroupStore userAuthorityGroupStore )
    {
        this.userAuthorityGroupStore = userAuthorityGroupStore;
    }

    private CurrentUserService currentUserService;

    public void setCurrentUserService( CurrentUserService currentUserService )
    {
        this.currentUserService = currentUserService;
    }

    private SystemSettingManager systemSettingManager;

    public void setSystemSettingManager( SystemSettingManager systemSettingManager )
    {
        this.systemSettingManager = systemSettingManager;
    }

    private PasswordManager passwordManager;

    public void setPasswordManager( PasswordManager passwordManager )
    {
        this.passwordManager = passwordManager;
    }

    @Autowired
    private DeletionManager deletionManager;

    // -------------------------------------------------------------------------
    // UserService implementation
    // -------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // User
    // -------------------------------------------------------------------------

    @Override
    public int addUser( User user )
    {
        AuditLogUtil.infoWrapper( log, currentUserService.getCurrentUsername(), user, AuditLogUtil.ACTION_CREATE );

        return userStore.save( user );
    }

    @Override
    public void updateUser( User user )
    {
        userStore.update( user );

        AuditLogUtil.infoWrapper( log, currentUserService.getCurrentUsername(), user, AuditLogUtil.ACTION_UPDATE );
    }

    @Override
    public void deleteUser( User user )
    {
        AuditLogUtil.infoWrapper( log, currentUserService.getCurrentUsername(), user, AuditLogUtil.ACTION_DELETE );

        // Invoke deletion manager directly for credentials, not intercepted

        deletionManager.execute( user.getUserCredentials() );

        // Credentials deleted through deletion handler

        userStore.delete( user );
    }

    @Override
    public List<User> getAllUsers()
    {
        return userStore.getAll();
    }

    @Override
    public User getUser( int userId )
    {
        return userStore.get( userId );
    }

    @Override
    public User getUser( String uid )
    {
        return userStore.getByUid( uid );
    }

    @Override
    public List<User> getUsersByUid( List<String> uids )
    {
        return userStore.getByUid( uids );
    }

    @Override
    public List<User> getAllUsersBetweenByName( String name, int first, int max )
    {
        UserQueryParams params = new UserQueryParams();
        params.setQuery( name );
        params.setFirst( first );
        params.setMax( max );

        return userStore.getUsers( params );
    }

    @Override
    public List<User> getManagedUsers( User user )
    {
        UserQueryParams params = new UserQueryParams( user );
        params.setCanManage( true );
        params.setAuthSubset( true );

        return userStore.getUsers( params );
    }

    @Override
    public int getManagedUserCount( User user )
    {
        UserQueryParams params = new UserQueryParams( user );
        params.setCanManage( true );
        params.setAuthSubset( true );

        return userStore.getUserCount( params );
    }

    @Override
    public List<User> getUsers( UserQueryParams params )
    {
        handleUserQueryParams( params );

        if ( !validateUserQueryParams( params ) )
        {
            return Lists.newArrayList();
        }

        return userStore.getUsers( params );
    }

    @Override
    public int getUserCount( UserQueryParams params )
    {
        handleUserQueryParams( params );

        if ( !validateUserQueryParams( params ) )
        {
            return 0;
        }

        return userStore.getUserCount( params );
    }

    @Override
    public int getUserCount()
    {
        return userStore.getUserCount();
    }

    private void handleUserQueryParams( UserQueryParams params )
    {
        boolean canGrantOwnRoles = (Boolean) systemSettingManager.getSystemSetting( SettingKey.CAN_GRANT_OWN_USER_AUTHORITY_GROUPS );
        params.setDisjointRoles( !canGrantOwnRoles );

        if ( params.getUser() == null )
        {
            params.setUser( currentUserService.getCurrentUser() );
        }

        if ( params.getUser() != null && params.getUser().isSuper() )
        {
            params.setCanManage( false );
            params.setAuthSubset( false );
            params.setDisjointRoles( false );
        }

        if ( params.getInactiveMonths() != null )
        {
            Calendar cal = PeriodType.createCalendarInstance();
            cal.add( Calendar.MONTH, (params.getInactiveMonths() * -1) );
            params.setInactiveSince( cal.getTime() );
        }
    }

    public boolean validateUserQueryParams( UserQueryParams params )
    {
        if ( params.isCanManage() && (params.getUser() == null || !params.getUser().hasManagedGroups()) )
        {
            log.warn( "Cannot get managed users as user does not have any managed groups" );
            return false;
        }

        if ( params.isAuthSubset() && (params.getUser() == null || !params.getUser().getUserCredentials().hasAuthorities()) )
        {
            log.warn( "Cannot get users with authority subset as user does not have any authorities" );
            return false;
        }

        if ( params.isDisjointRoles() && (params.getUser() == null || !params.getUser().getUserCredentials().hasUserAuthorityGroups()) )
        {
            log.warn( "Cannot get users with disjoint roles as user does not have any user roles" );
            return false;
        }

        return true;
    }

    @Override
    public List<User> getUsersByPhoneNumber( String phoneNumber )
    {
        UserQueryParams params = new UserQueryParams();
        params.setPhoneNumber( phoneNumber );
        return getUsers( params );
    }

    @Override
    public boolean isLastSuperUser( UserCredentials userCredentials )
    {
        if ( !userCredentials.isSuper() )
        {
            return false; // Cannot be last if not super user
        }

        Collection<UserCredentials> users = userCredentialsStore.getAll();

        for ( UserCredentials user : users )
        {
            if ( user.isSuper() && !user.equals( userCredentials ) )
            {
                return false;
            }
        }

        return true;
    }

    @Override
    public boolean isLastSuperRole( UserAuthorityGroup userAuthorityGroup )
    {
        Collection<UserAuthorityGroup> groups = userAuthorityGroupStore.getAll();

        for ( UserAuthorityGroup group : groups )
        {
            if ( group.isSuper() && group.getId() != userAuthorityGroup.getId() )
            {
                return false;
            }
        }

        return true;
    }

    @Override
    public boolean canAddOrUpdateUser( Collection<String> userGroups )
    {
        User currentUser = currentUserService.getCurrentUser();

        if ( currentUser == null )
        {
            return false;
        }

        boolean canAdd = currentUser.getUserCredentials().isAuthorized( UserGroup.AUTH_USER_ADD );

        if ( canAdd )
        {
            return true;
        }

        boolean canAddInGroup = currentUser.getUserCredentials().isAuthorized( UserGroup.AUTH_USER_ADD_IN_GROUP );

        if ( !canAddInGroup )
        {
            return false;
        }

        boolean canManageAnyGroup = false;

        for ( String uid : userGroups )
        {
            UserGroup userGroup = userGroupService.getUserGroup( uid );

            if ( currentUser.canManage( userGroup ) )
            {
                canManageAnyGroup = true;
                break;
            }
        }

        return canManageAnyGroup;
    }

    // -------------------------------------------------------------------------
    // UserAuthorityGroup
    // -------------------------------------------------------------------------

    @Override
    public int addUserAuthorityGroup( UserAuthorityGroup userAuthorityGroup )
    {
        return userAuthorityGroupStore.save( userAuthorityGroup );
    }

    @Override
    public void updateUserAuthorityGroup( UserAuthorityGroup userAuthorityGroup )
    {
        userAuthorityGroupStore.update( userAuthorityGroup );
    }

    @Override
    public void deleteUserAuthorityGroup( UserAuthorityGroup userAuthorityGroup )
    {
        userAuthorityGroupStore.delete( userAuthorityGroup );
    }

    @Override
    public List<UserAuthorityGroup> getAllUserAuthorityGroups()
    {
        return userAuthorityGroupStore.getAll();
    }

    @Override
    public UserAuthorityGroup getUserAuthorityGroup( int id )
    {
        return userAuthorityGroupStore.get( id );
    }

    @Override
    public UserAuthorityGroup getUserAuthorityGroup( String uid )
    {
        return userAuthorityGroupStore.getByUid( uid );
    }

    @Override
    public UserAuthorityGroup getUserAuthorityGroupByName( String name )
    {
        return userAuthorityGroupStore.getByName( name );
    }

    @Override
    public List<UserAuthorityGroup> getUserRolesByUid( Collection<String> uids )
    {
        return userAuthorityGroupStore.getByUid( uids );
    }

    @Override
    public List<UserAuthorityGroup> getUserRolesBetween( int first, int max )
    {
        return userAuthorityGroupStore.getAllOrderedName( first, max );
    }

    @Override
    public List<UserAuthorityGroup> getUserRolesBetweenByName( String name, int first, int max )
    {
        return userAuthorityGroupStore.getAllLikeName( name, first, max );
    }

    @Override
    public int getUserRoleCount()
    {
        return userAuthorityGroupStore.getCount();
    }

    @Override
    public int getUserRoleCountByName( String name )
    {
        return userAuthorityGroupStore.getCountLikeName( name );
    }

    @Override
    public int countDataSetUserAuthorityGroups( DataSet dataSet )
    {
        return userAuthorityGroupStore.countDataSetUserAuthorityGroups( dataSet );
    }

    @Override
    public void canIssueFilter( Collection<UserAuthorityGroup> userRoles )
    {
        User user = currentUserService.getCurrentUser();

        boolean canGrantOwnUserAuthorityGroups = (Boolean) systemSettingManager.getSystemSetting( SettingKey.CAN_GRANT_OWN_USER_AUTHORITY_GROUPS );

        FilterUtils.filter( userRoles, new UserAuthorityGroupCanIssueFilter( user, canGrantOwnUserAuthorityGroups ) );
    }

    // -------------------------------------------------------------------------
    // UserCredentials
    // -------------------------------------------------------------------------

    @Override
    public int addUserCredentials( UserCredentials userCredentials )
    {
        return userCredentialsStore.save( userCredentials );
    }

    @Override
    public void updateUserCredentials( UserCredentials userCredentials )
    {
        userCredentialsStore.update( userCredentials );
    }

    @Override
    public List<UserCredentials> getAllUserCredentials()
    {
        return userCredentialsStore.getAll();
    }

    @Override
    public void encodeAndSetPassword( User user, String rawPassword )
    {
        encodeAndSetPassword( user.getUserCredentials(), rawPassword );
    }

    @Override
    public void encodeAndSetPassword( UserCredentials userCredentials, String rawPassword )
    {
        if ( StringUtils.isEmpty( rawPassword ) && !userCredentials.isExternalAuth() )
        {
            return; // Leave unchanged if internal authentication and no password supplied
        }

        if ( userCredentials.isExternalAuth() )
        {
            userCredentials.setPassword( UserService.PW_NO_INTERNAL_LOGIN );

            return; // Set unusable, not-encoded password if external authentication
        }

        boolean isNewPassword = StringUtils.isBlank( userCredentials.getPassword() ) ||
            !passwordManager.matches( rawPassword, userCredentials.getPassword() );

        if ( isNewPassword )
        {
            userCredentials.setPasswordLastUpdated( new Date() );
        }

        // Encode and set password

        userCredentials.setPassword( passwordManager.encode( rawPassword ) );
    }

    @Override
    public UserCredentials getUserCredentialsByUsername( String username )
    {
        return userCredentialsStore.getUserCredentialsByUsername( username );
    }

    @Override
    public UserCredentials getUserCredentialsByOpenId( String openId )
    {
        return userCredentialsStore.getUserCredentialsByOpenId( openId );
    }

    @Override
    public UserCredentials getUserCredentialsByLdapId( String ldapId )
    {
        return userCredentialsStore.getUserCredentialsByLdapId( ldapId );
    }

    @Override
    public void setLastLogin( String username )
    {
        UserCredentials credentials = getUserCredentialsByUsername( username );

        if ( credentials != null )
        {
            credentials.setLastLogin( new Date() );
            updateUserCredentials( credentials );
        }
    }

    @Override
    public int getActiveUsersCount( int days )
    {
        Calendar cal = PeriodType.createCalendarInstance();
        cal.add( Calendar.DAY_OF_YEAR, (days * -1) );

        return getActiveUsersCount( cal.getTime() );
    }

    @Override
    public int getActiveUsersCount( Date since )
    {
        UserQueryParams params = new UserQueryParams();
        params.setLastLogin( since );

        return getUserCount( params );
    }

    @Override
    public boolean credentialsNonExpired( UserCredentials credentials )
    {
        int credentialsExpires = systemSettingManager.credentialsExpires();

        if ( credentialsExpires == 0 )
        {
            return true;
        }

        int months = DateUtils.monthsBetween( credentials.getPasswordLastUpdated(), new Date() );

        return months < credentialsExpires;
    }
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { ContentGuard } from './content-guard.service';
import { MasterComponent } from './master/master.component';
import { SyncComponent } from './sync/sync.component';

const routes: Routes = [
    {
        path: '',
        redirectTo: '/sync',
        pathMatch: 'full'
    },
    {
        path: 'sync',
        component: SyncComponent
    },
    {
        path: '**',
        component: MasterComponent,
        canActivate: [ContentGuard]
    }
];

/**
 * Defines app routes.
 *
 * @export
 * @class AppRoutingModule
 */
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    providers: [ContentGuard]
})
export class AppRoutingModule {
}

export const routedComponents = [MasterComponent, SyncComponent];

redpajama_set_name: RedPajamaGithub


text:
@interface MOBProjectionEPSG32740 : MOBProjection

@end


text:
import { ClientFunction, Selector, t } from 'testcafe';

const timeoutOptions = { timeoutSeconds: 10 };

const getSource = ClientFunction(() => {
  const value = window.monaco.editor.getModels()[0].getValue();
  return JSON.parse(value);
});

const setSource = ClientFunction(() => {
  window.monaco.editor.getModels()[0].setValue(source);
});

export default class ObjectEditor {
  monaco = Selector('.monaco-editor');

  async getSource() {
    await t.expect(this.monaco.visible).ok(timeoutOptions);
    return await getSource();
  }

  async setSource(source) {
    await t.expect(this.monaco.visible).ok(timeoutOptions);
    return await setSource.with({ dependencies: { source } })();
  }
}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\ApiPlatform\Tests\Mock;

use Rollerworks\Component\Search\ApiPlatform\Tests\Fixtures\BookFieldSet;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\Field\OrderField;
use Rollerworks\Component\Search\FieldSet;

final class FieldSetStub implements FieldSet
{
    public function getSetName(): ?string
    {
        return BookFieldSet::class;
    }

    public function get(string $name): FieldConfig
    {
    }

    public function all(): array
    {
        return [];
    }

    public function has(string $name): bool
    {
        return false;
    }

    public function isOrder(string $name): bool
    {
        return OrderField::isOrder($name);
    }

    public function isPrivate(string $name): bool
    {
        return $name[0] === '_';
    }
}


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
The [Keep a Changelog](http://keepachangelog.com/) format will be
used to track changes in this project.

## [Unreleased]

### Added
- [#53](../../issues/53): Admin user should be able to manage attachments (multiple features)
- CreateCatalogPromotionCommand
- CreateProductQuantityDiscountCommand

### Changed
- [#42](../../issues/42): Change all use case Actions to require a string ID instead of UuidInterface
- [#21](../../issues/21): Cart price rules carried over and linked to an Order (DB migration)
- [#40](../../issues/40): Change ProductRepository::getRelatedProductsByIds to not require $tagIds
- [#47](../../issues/47): Modify OrderItem to require Order in the constructor
- Deprecated CatalogPromotion.code
- Changed CreateCouponCommand from using a DTO to scalar types

### DB Migration
- TBD

## [0.6.0]

### Initial pre-release


text:
function addImageForm(collectionHolder, $newLinkLi) {
    // Get the data-prototype explained earlier
    var prototype = collectionHolder.data('prototype');

    // get the new index
    var index = collectionHolder.data('index');

    // Replace '__name__' in the prototype's HTML to
    // instead be a number based on how many items we have
    var newForm = prototype.replace(/__name__/g, index);

    // increase the index with one for the next item
    collectionHolder.data('index', index + 1);

    // Display the form in the page in an li, before the "Add a tag" link li
    var $newFormLi = $('

').append(newForm);
    $newLinkLi.before($newFormLi);
    addImageFormDeleteLink($newFormLi);
}

function addImageFormDeleteLink($tagFormLi) {
    var $removeFormA = $('Удалить фото');
    $tagFormLi.append($removeFormA);

    $removeFormA.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();
        $tagFormLi.remove();
    });
}

$(document).ready(function(){

  var collectionImageHolder = $('ul.images');
    // setup an "add a tag" link
    var $addImageLink = $('Добавить фото');
    var $newImageLinkLi = $('

').append($addImageLink);

    collectionImageHolder.find('li').each(function() {
        addImageFormDeleteLink($(this));
    });
    // add the "add a tag" anchor and li to the tags ul
    collectionImageHolder.append($newImageLinkLi);

    // count the current form inputs we have (e.g. 2), use that as the new
    // index when inserting a new item (e.g. 2)
    collectionImageHolder.data('index', collectionImageHolder.find(':input').length);

    $addImageLink.on('click', function(e) {
        // prevent the link from creating a "#" on the URL
        e.preventDefault();

        // add a new tag form (see next code block)
        addImageForm(collectionImageHolder, $newImageLinkLi);
    });
});


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

	<title>D.O.H. v2</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8">

Self tests

This will run several tests using this library, don't be scared when some
	of the test fail, this is intentionally, to test the test suite itself.

Your result should look like this:

0 tests ran, 0 failures, 0 errors


text:
/*
 * File: app/view/Events.js
 *
 * This file was generated by Sencha Architect version 3.0.4.
 * http://www.sencha.com/products/architect/
 *
 * This file requires use of the Ext JS 4.2.x library, under independent license.
 * License of Sencha Architect does not include license for Ext JS 4.2.x. For more
 * details see http://www.sencha.com/license or contact license@sencha.com.
 *
 * This file will be auto-generated each and everytime you save your project.
 *
 * Do NOT hand edit this file.
 */

Ext.define('AI.view.Events', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.eventgrid',

    requires: [
        'AI.view.FilterField',
        'Ext.toolbar.Toolbar',
        'Ext.button.Button',
        'Ext.toolbar.Fill',
        'Ext.form.field.Text',
        'Ext.grid.column.Column',
        'Ext.grid.View',
        'Ext.selection.RowModel'
    ],

    itemId: 'EventInspector',
    iconCls: 'icn-events',
    title: 'Events',
    store: 'Events',

    initComponent: function() {
        var me = this;

        Ext.applyIf(me, {
            dockedItems: [
                {
                    xtype: 'toolbar',
                    dock: 'top',
                    items: [
                        {
                            xtype: 'button',
                            itemId: 'ClearEvents',
                            iconCls: 'icn-clear',
                            text: 'Clear'
                        },
                        {
                            xtype: 'button',
                            itemId: 'RecordEvents',
                            iconCls: 'icn-record',
                            text: 'Record'
                        },
                        {
                            xtype: 'button',
                            hidden: true,
                            itemId: 'StopRecording',
                            iconCls: 'icn-stop',
                            text: 'Stop Recording'
                        },
                        {
                            xtype: 'tbfill'
                        },
                        {
                            xtype: 'filterfield',
                            itemId: 'FilterEventsList'
                        }
                    ]
                }
            ],
            columns: [
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'eventName',
                    text: 'Event Name'
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'source',
                    text: 'Event Source',
                    flex: 1
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'xtype',
                    text: 'XType',
                    flex: 1
                },
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'cmpId',
                    text: 'Cmp ID',
                    flex: 1
                }
            ],
            listeners: {
                beforeadd: {
                    fn: me.onEventInspectorBeforeAdd,
                    scope: me
                }
            },
            selModel: Ext.create('Ext.selection.RowModel', {
                mode: 'MULTI'
            })
        });

        me.callParent(arguments);
    },

    onEventInspectorBeforeAdd: function(container, component, index, eOpts) {
        this.setTitle(AI.util.i18n.getMessage(this.title));

    }

});


text:
  <wicket:panel>

      [role details]
      [Status Panel]

            <wicket:message key="inheritAttributes"/>

        [role attributes]

            <wicket:message key="inheritDerivedAttributes"/>

        [role derived attributes]

            <wicket:message key="inheritVirtualAttributes"/>

        [role virtual attributes]

      [resources]

      [entitlements]

      [security]

  </wicket:panel>


text:
#ifndef LIBPSEC_GENERIC_TIGER_H
#define LIBPSEC_GENERIC_TIGER_H

#include <stdio.h>

/* Definitions */
#define TIGER_HASH_DIGEST_SIZE		24
#define TIGER2_HASH_DIGEST_SIZE		24
#define TIGER_HASH_BLOCK_SIZE		64
#define TIGER2_HASH_BLOCK_SIZE		64

/* Prototypes */

/* TIGER Generic Interface */
unsigned char *tiger_buffer(unsigned char *out, const unsigned char *in, size_t in_len);
unsigned char *tiger_file(unsigned char *out, FILE *fp);
/* TIGER2 Generic Interface */
unsigned char *tiger2_buffer(unsigned char *out, const unsigned char *in, size_t in_len);
unsigned char *tiger2_file(unsigned char *out, FILE *fp);

#endif


text:
package com.lody.welike.database;

import com.lody.welike.database.annotation.Ignore;
import com.lody.welike.database.annotation.NotNull;

import java.lang.reflect.Field;

/**
 * @author Lody
 *         解析Java的<b>数据类型</b>,将其转换为对应的SQL类型.
 *
 *         2015/8/17 :支持 boolean 类型.
 *
 * @version 2.2
 */
public class SQLTypeParser {

    /**
     * 根据字段类型匹配它在数据库中的对应类型.
     *
     * @param field
     * @return
     */
    public static DataType getDataType(Field field) {
        Class<?> clazz = field.getType();
        if (clazz == (String.class)) {
            return DataType.TEXT.nullable((field.getAnnotation(NotNull.class) == null));
        } else if (clazz == (int.class) || clazz == (Integer.class)) {
            return DataType.INTEGER.nullable((field.getAnnotation(NotNull.class) == null));
        } else if (clazz == (float.class) || clazz == (Float.class)) {
            return DataType.FLOAT.nullable((field.getAnnotation(NotNull.class) == null));
        } else if (clazz == (long.class) || clazz == (Long.class)) {
            return DataType.BIGINT.nullable((field.getAnnotation(NotNull.class) == null));
        } else if (clazz == (double.class) || clazz == (Double.class)) {
            return DataType.DOUBLE.nullable((field.getAnnotation(NotNull.class) == null));
        } else if (clazz == (boolean.class) || clazz == (Boolean.class)) {
            return DataType.INTEGER.nullable((field.getAnnotation(NotNull.class) == null));
        }
        return null;
    }

    /**
     * 根据字段类型匹配它在数据库中的对应类型.
     *
     * @param clazz
     * @return
     */
    public static DataType getDataType(Class<?> clazz) {
        if (clazz == (String.class)) {
            return DataType.TEXT;
        } else if (clazz == (int.class) || clazz == (Integer.class)) {
            return DataType.INTEGER;
        } else if (clazz == (float.class) || clazz == (Float.class)) {
            return DataType.FLOAT;
        } else if (clazz == (long.class) || clazz == (Long.class)) {
            return DataType.BIGINT;
        } else if (clazz == (double.class) || clazz == (Double.class)) {
            return DataType.DOUBLE;
        } else if (clazz == (boolean.class) || clazz == (Boolean.class)) {
            return DataType.INTEGER;
        }
        return null;
    }

    /**
     * 字段类型与数据类型是否匹配?
     *
     * @param field
     * @param dataType
     * @return
     */
    public static boolean matchType(Field field, DataType dataType) {
        DataType fieldDataType = getDataType(field.getType());

        return dataType != null && fieldDataType == (dataType);
    }

    /**
     * 字段是否可以被数据库忽略?
     *
     * @param field
     * @return
     */
    public static boolean isIgnore(Field field) {
        return field.getAnnotation(Ignore.class) != null;
    }

}


text:
DESC = """EPP script for Quant-iT measurements to calculate concentrations and
load input artifact-udfs and output file-udfs of the process with concentration
values and fluorescence intensity.

Reads from:
    --Lims fields--
    "Assay type"                process udf
    "Standard volume"           process udf
    "Standard dilution"         process udf
    "Linearity of standards"    process udf
    "Sample volume"             process udf

    --files--
    "Standards File (.txt)"     "shared result file" uploaded by user.
    "Quant-iT Result File 1"    "shared result file" uploaded by user.
    "Quant-iT Result File 2"    "shared result file" uploaded by user. (optional)

Writes to:
    --Lims fields--
    "Fluorescence intensity 1"  udf of input analytes to the process
    "Fluorescence intensity 2"  udf of input analytes to the  process
    "Concentration"             udf of process artifacts (result file)
    "Conc. Units"               udf of process artifacts (result file)

Logging:
    The script outputs a regular log file with regular execution information.

Performance:
    1)  Makes a linear regression analysis on the End RFU standards read from
    "Standards File (.txt)" --> slope, intersect and R2 (Pearson correlation
    coefficient)

    2)  If R2 is less than "Linearity of standards", standards are not ok and
    the user is warned "Problem with standards! Redo measurement!".

    3)  If R2 is greater than "Linearity of standards", concentration values are
    calculated based on the linear regression parameters, copied to the
    "Concentration"-udf on the output artifacts (one result file per sample).
    The "Conc. Units"-udf on the same artifacts are set to "ng/ul".

    4)  "End RFU" values from "Quant-iT Result File 1" are copied to the udf
    "Fluorescence intensity 1" of the input analyte to the process, and
    "End RFU" values from "Quant-iT Result File 2" are copied to the udf
    "Fluorescence intensity 2".

Written by Maya Brandi
"""

import os
import sys
import logging
import numpy as np

from argparse import ArgumentParser
from requests import HTTPError
from genologics.lims import Lims
from genologics.config import BASEURI,USERNAME,PASSWORD
from genologics.entities import Process
from genologics.epp import EppLogger
from genologics.epp import set_field
from genologics.epp import ReadResultFiles

class QuantitConc():
    def __init__(self, process, file_handler):
        self.file_handler = file_handler
        self.udfs = dict(process.udf.items())
        self.abstract = []
        self.missing_udfs = []
        self.missing_samps =[]
        self.no_samps = 0
        self.standards = {}
        self.model = []
        self.result_files = {}

    def prepare_result_files_dict(self):
        """"Quant-iT Result File 1" and "Quant-iT Result File 2" (the second is
        optional) uploaded by user, are formated and stored in a dict"""
        result_files_dict = {}
        file_names = {'Quant-iT Result File 1':'Fluorescence intensity 1',
                    'Quant-iT Result File 2':'Fluorescence intensity 2'}
        for f_name, udf_name in file_names.items():
            if self.file_handler.shared_files.has_key(f_name):
                result_file = self.file_handler.shared_files[f_name]
                result_files_dict[udf_name] = self.file_handler.format_file(
                    result_file, name = f_name, root_key_col = 1, header_row = 19)
        self.result_files = result_files_dict

    def _make_standards_dict(self):
        """End RFU standards are read from 'Standards File (.txt)' and stored
        in a dict"""
        standards_file = self.file_handler.shared_files['Standards File (.txt)']
        standards_file_formated = self.file_handler.format_file(standards_file,
                name = 'Standards File (.txt)', root_key_col = 1, header_row = 19)
        standards_dict = {}
        for k,v in standards_file_formated.items():
            cond1 = set(['Sample','End RFU']).issubset(v)
            cond2 = v['Sample'].split()[0]=='Standard'
            if cond1 and cond2:
                standard = int(v['Sample'].split()[1])
                standards_dict[standard] = float(v['End RFU'])
        return standards_dict

    def _nuclear_acid_amount_in_standards(self):
        """Nuclear acid amount in standards is calculated as
        "Supposed concentrations of standards" * "Standard volume" / "Standard
        dilution" Supposed concentrations of standards are different between
        Quant-iT BR assays and Quant-iT HS assays."""
        requiered_udfs = set(['Standard volume','Assay type','Standard dilution'])
        supp_conc_stds = {'RNA BR':[0,5,10,20,40,60,80,100],
                          'DNA BR':[0,5,10,20,40,60,80,100],
                          'RNA':[0,0.5,1,2,4,6,8,10],
                          'DNA HS':[0,0.5,1,2,4,6,8,10]}
        if requiered_udfs.issubset(self.udfs.keys()):
            nuclear_acid_amount = np.ones(8)
            for standard in range(8):
                supp_conc_standard = supp_conc_stds[self.udfs['Assay type']][standard]
                stand_conc = supp_conc_standard * self.udfs['Standard volume']
                stand_dil = self.udfs['Standard dilution']
                nuclear_acid_amount[standard] = np.true_divide(stand_conc, stand_dil)
            return nuclear_acid_amount
        elif not requiered_udfs.issubset(self.missing_udfs):
            self.missing_udfs += requiered_udfs
        return None

    def _linear_regression(self, X,Y):
        """Perform linear regression with intersect forced to origin. And
        calculates Pearson correlation coefficient R2. """
        X = np.array(X)
        X_force_zero = X[:,np.newaxis]
        slope = np.linalg.lstsq(X_force_zero, Y)[0]

        A = np.array([ X, np.ones(len(X))])
        resid = np.linalg.lstsq(A.T,Y)[1]
        R2 = 1 - resid / (Y.size * Y.var())
        return float(R2), float(slope)

    def fit_model(self):
        """Performing linear regression on standards.
        X = Relative fluorescence intensities of 8 standards
        Y = Nuclear acid amount in standards
        Y = slope*X + intersect; R2=Pearson correlation coefficient."""
        self.standards = self._make_standards_dict()
        amount_in_standards = self._nuclear_acid_amount_in_standards()
        if amount_in_standards is not None:
            relative_standards = np.ones(8)
            for k,v in self.standards.items():
                relative_standards[k-1] = v - self.standards[1]
            R2, slope = self._linear_regression(relative_standards,
                            amount_in_standards)
            self.model = [R2, slope]
        else:
            self.model = None

    def get_and_set_fluor_int(self, target_file):
        """Copies "End RFU" values from "Quant-iT Result File 1" and
        "Quant-iT Result File 2" (if provided) to udfs "Fluorescence intensity 1"
        and "Fluorescence intensity 2. Calculates and returns Relative
        fluorescence intensity standards:
        rel_fluor_int = The End RFU of standards - Background fluorescence
        intensity"""
        sample = target_file.samples[0].name
        fluor_int = []
        target_udfs = target_file.udf
        # For the moment we dont know ofa way to delete udfs. Should be solved.
        #if dict(target_udfs.items()).has_key('Fluorescence intensity 1'):
        #    del target_udfs['Fluorescence intensity 1']
        #if dict(target_udfs.items()).has_key('Fluorescence intensity 2'):
        #    del target_udfs['Fluorescence intensity 2']
        target_file.udf = target_udfs
        for udf_name ,formated_file in self.result_files.items():
            if sample in formated_file.keys():
                fluor_int.append(float(formated_file[sample]['End RFU']))
                target_file.udf[udf_name] = float(formated_file[sample]['End RFU'])
            else:
                self.missing_samps.append(sample)
        set_field(target_file)
        rel_fluor_int = np.mean(fluor_int) - self.standards[1]
        return rel_fluor_int

    def calc_and_set_conc(self, target_file, rel_fluor_int):
        """Concentrations are calculated based on the linear regression
        parametersand copied to the "Concentration"-udf of the target_file. The
        "Conc. Units"-udf is set to "ng/ul"""
        requiered_udfs = set(['Sample volume','Standard dilution','WS volume'])
        if requiered_udfs.issubset(self.udfs.keys()) and self.model:
            conc = np.true_divide((self.model[1] * rel_fluor_int * (
                self.udfs['WS volume'] + self.udfs['Sample volume'])),
                self.udfs['Sample volume']*(self.udfs['WS volume'] +
                self.udfs['Standard volume']))
            target_file.udf['Concentration'] = conc
            target_file.udf['Conc. Units'] = 'ng/ul'
            set_field(target_file)
            self.no_samps +=1
        elif not requiered_udfs.issubset(self.missing_udfs):
            self.missing_udfs += requiered_udfs

def main(lims, pid, epp_logger):
    process = Process(lims,id = pid)
    target_files = dict((r.samples[0].name, r) for r in process.result_files())
    file_handler = ReadResultFiles(process)
    QiT = QuantitConc(process, file_handler)
    QiT.fit_model()
    QiT.prepare_result_files_dict()
    if QiT.model and 'Linearity of standards' in QiT.udfs.keys():
        R2 = QiT.model[0]
        if R2 >= QiT.udfs['Linearity of standards']:
            QiT.abstract.insert(0,"R2 = {0}. Standards OK.".format(R2))
            if QiT.result_files:
                for sample, target_file in target_files.items():
                    rel_fluor_int = QiT.get_and_set_fluor_int(target_file)
                    QiT.calc_and_set_conc(target_file, rel_fluor_int)
                QiT.abstract.append("Concentrations uploaded for {0} "
                                                "samples.".format(QiT.no_samps))
            else:
                QiT.abstract.append("Upload input file(s) for samples.")
        else:
            QiT.abstract.insert(0, "R2 = {0}. Problem with standards! Redo "
                                                    "measurement!".format(R2))
    else:
        QiT.missing_udfs.append('Linearity of standards')
    if QiT.missing_samps:
        QiT.abstract.append("The following samples are missing in Quant-iT "
            "result File 1 or 2: {0}.".format(', '.join(QiT.missing_samps)))
    if QiT.missing_udfs:
        QiT.abstract.append("Are all of the following udfs set? : {0}".format(
                                                   ', '.join(QiT.missing_udfs)))
    print >> sys.stderr, ' '.join(QiT.abstract)

if __name__ == "__main__":
    parser = ArgumentParser(description=DESC)
    parser.add_argument('--pid', default = None , dest = 'pid',
                        help='Lims id for current Process')
    parser.add_argument('--log', dest = 'log',
                        help=('File name for standard log file, '
                              'for runtime information and problems.'))

    args = parser.parse_args()
    lims = Lims(BASEURI,USERNAME,PASSWORD)
    lims.check_version()

    with EppLogger(log_file=args.log, lims=lims, prepend=True) as epp_logger:
        main(lims, args.pid, epp_logger)


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : Dec 23, 2013, 11:49:11 PM
    Author     : Vincent
*/

@font-face {
    font-family: 'MonoSocialIconsFont-1.10';
    src: url('../fonts/MonoSocialIconsFont-1.10.eot'); /* IE9 Compat Modes */
    src: url('../fonts/MonoSocialIconsFont-1.10.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
        url('../fonts/MonoSocialIconsFont-1.10.woff') format('woff'), /* Modern Browsers */
        url('../fonts/MonoSocialIconsFont-1.10.ttf')  format('truetype'), /* Safari, Android, iOS */
        url('../fonts/MonoSocialIconsFont-1.10.svg#svgFontName') format('svg'); /* Legacy iOS */
}

@font-face {
    font-family: 'opensans-light';
    src: url('../fonts/opensans-light.eot'); /* IE9 Compat Modes */
    src: url('../fonts/opensans-light0.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
        url('../fonts/opensans-light.woff') format('woff'), /* Modern Browsers */
        url('../fonts/opensans-light.ttf')  format('truetype'), /* Safari, Android, iOS */
        url('../fonts/opensans-light.svg#svgFontName') format('svg'); /* Legacy iOS */
}

@font-face {
    font-family: 'poetsenone-regular';
    src: url('../fonts/poetsenone-regular.eot'); /* IE9 Compat Modes */
    src: url('../fonts/poetsenone-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
        url('../fonts/poetsenone-regular.woff') format('woff'), /* Modern Browsers */
        url('../fonts/poetsenone-regular.ttf')  format('truetype'), /* Safari, Android, iOS */
        url('../fonts/poetsenone-regular.svg#svgFontName') format('svg'); /* Legacy iOS */
}

html {
    -webkit-font-smoothing: antialiased;
}

.jumbotron {

    background-color: rgba(255, 255, 255, .8);
    font-size: 18px;
    height: 350px;
    background-position: 50% 50%;
    background-repeat: no-repeat;
    color: #666666;

}

.img-circle {
    width: 150px;
    height: auto;
}

.social {
    font-family: 'MonoSocialIconsFont-1.10';
    color: rgba(102,102,102,0.8);
    font-weight: normal;
    font-style: normal;
    font-size: 60px;
}

.social a {
    color: rgb(102,102,102);
}

.social a:hover {
    color: rgb(0,0,0);
    text-decoration: none;

}

.twitter {
    color: #C8C8C8 	;
}

.facebook {
    color: #C8C8C8 	;
}

.flickr {
     color: #C8C8C8 	;
}

.linkedin {
    color: #C8C8C8 	;
}

.art {
    float: left;
    margin: 0px;
    padding: 0px;
    border: 0px;
    width: 1px;
    height: 1px;

}


text:
<!DOCTYPE html>

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

Processing.js

Histogram

This code was updated from the Java source to work with Processing.js asynchronous image loading.

Calculates the histogram of an image.
A histogram is the frequency distribution
of the gray levels with the number of pure black values
displayed on the left and number of pure white values on the right.

Original Processing.org Example: Histogram

<canvas width="200" height="200"></canvas>

// All Examples Written by Casey Reas and Ben Fry
// unless otherwise stated.
size(200, 200);
colorMode(RGB, width);

int[] hist = new int[width];

// Load an image from the data directory
// Load a different image by modifying the comments
PImage a;
a = loadImage("data/cdi01_g.jpg", null, function(){

  image(a, 0, 0);

  // Calculate the histogram
  for (int i=0; i<width; i++) {
    for (int j=0; j<height; j++) {
      hist[int(red(get(i, j)))]++;
    }
  }

  // Find the largest value in the histogram
  float maxval = 0;
  for (int i=0; i<width; i++) {
    if(hist[i] > maxval) {
      maxval = hist[i];
    }
  }

  // Normalize the histogram to values between 0 and "height"
  for (int i=0; i<width; i++) {
    hist[i] = int(hist[i]/maxval * height);
  }

  // Draw half of the histogram (skip every second value)
  stroke(width);
  for (int i=0; i<width; i+=2) {
    line(i, height, i, height-hist[i]);
  }

});


text:
<ion-view title="About">
<ion-content class="has-header">

        Impressum

Angaben gemäß § 5 TMG

Marco Schäfer, Vincent Wagner, Martin Przewloka

                Löberstraße 6a

                35390 Gießen

 Vertreten durch:

                Marco Schäfer

Kontakt:

                Telefon: 0170-2362791

                E-Mail: msfr-dev@posteo.de

Haftungsausschluss und Datenschutzerklärung:

Haftung für Inhalte

                Vielen Dank, dass Sie unsere Dienste nutzen. Durch die Verwendung unserer Dienste stimmen Sie diesem Haftungsausschluss
                und der Datenschutzerklärung zu. Bitte lesen Sie diese sorgfältig durch.

                Die Inhalte unserer Seiten wurden mit größter Sorgfalt erstellt. Für die Richtigkeit, Vollständigkeit und Aktualität der Inhalte können wir jedoch keine Gewähr übernehmen. Als Diensteanbieter sind wir gemäß § 7 Abs.1 TMG für eigene Inhalte auf diesen Seiten nach den allgemeinen Gesetzen verantwortlich. Nach §§ 8 bis 10 TMG sind wir als Diensteanbieter jedoch nicht verpflichtet, übermittelte oder gespeicherte fremde Informationen zu überwachen oder nach Umständen zu forschen, die auf eine rechtswidrige Tätigkeit hinweisen. Verpflichtungen zur Entfernung oder Sperrung der Nutzung von Informationen nach den allgemeinen Gesetzen bleiben hiervon unberührt. Eine diesbezügliche Haftung ist jedoch erst ab dem Zeitpunkt der Kenntnis einer konkreten Rechtsverletzung möglich. Bei Bekanntwerden von entsprechenden Rechtsverletzungen werden wir diese Inhalte umgehend entfernen.

                Schadensersatzansprüche des Nutzers aus direkter und indirekter Nutzung unserer Dienste sind ausdrücklich ausgeschlossen. Die Datenerhebung  erfolgt durch uns als Diensteanbieter sehr sorgsam und über verlässliche Quellen. Trotzdem  können die Anbieter keine Gewähr für die Korrektheit der bereitgestellten Daten wie bspw. Wetter- und Gewässerdaten oder Routeninformationen übernehmen. Bitte vergewissern Sie sich im Zweifelsfall über anderweitige Quellen und verlassen sich nicht auf die in der Applikation gemachten Angaben.

Haftung für Links

                Unser Angebot enthält Links zu externen Webseiten Dritter, auf deren Inhalte wir keinen Einfluss haben. Deshalb können wir für diese fremden Inhalte auch keine Gewähr übernehmen. Für die Inhalte der verlinkten Seiten ist stets der jeweilige Anbieter oder Betreiber der Seiten verantwortlich. Die verlinkten Seiten wurden zum Zeitpunkt der Verlinkung auf mögliche Rechtsverstöße überprüft. Rechtswidrige Inhalte waren zum Zeitpunkt der Verlinkung nicht erkennbar. Eine permanente inhaltliche Kontrolle der verlinkten Seiten ist jedoch ohne konkrete Anhaltspunkte einer Rechtsverletzung nicht zumutbar. Bei Bekanntwerden von Rechtsverletzungen werden wir derartige Links umgehend entfernen.

Urheberrecht

                Die durch die Seitenbetreiber erstellten Inhalte und Werke auf diesen Seiten unterliegen dem deutschen Urheberrecht. Die Vervielfältigung, Bearbeitung, Verbreitung und jede Art der Verwertung außerhalb der Grenzen des Urheberrechtes bedürfen der schriftlichen Zustimmung des jeweiligen Autors bzw. Erstellers. Downloads und Kopien dieser Seite sind nur für den privaten, nicht kommerziellen Gebrauch gestattet. Soweit die Inhalte auf dieser Seite nicht vom Betreiber erstellt wurden, werden die Urheberrechte Dritter beachtet. Insbesondere werden Inhalte Dritter als solche gekennzeichnet. Sollten Sie trotzdem auf eine Urheberrechtsverletzung aufmerksam werden, bitten wir um einen entsprechenden Hinweis. Bei Bekanntwerden von Rechtsverletzungen werden wir derartige Inhalte umgehend entfernen.

Datenschutz

                Wir erfassen von Ihnen standortbezogene Daten, um Ihnen unsere Dienste zur Verfügung zu stellen.
                Diese Daten werden weder gespeichert noch anderweitig ausgewertet. Sie dienen lediglich zur gezielten Anreicherung
                der Dienste wie bspw. der Bestimmung der Entfernung zu einem ausgewählten Badesee.
                Die Nutzung unserer Dienste ist ohne Angabe personenbezogener Daten möglich.

                Wir weisen darauf hin, dass die Datenübertragung im Internet (z.B. bei der Kommunikation per E-Mail) Sicherheitslücken aufweisen kann. Ein lückenloser Schutz der Daten vor dem Zugriff durch Dritte ist nicht möglich.

                Der Nutzung von im Rahmen der Impressumspflicht veröffentlichten Kontaktdaten durch Dritte zur Übersendung von nicht ausdrücklich angeforderter Werbung und Informationsmaterialien wird hiermit ausdrücklich widersprochen. Die Betreiber der Seiten behalten sich ausdrücklich rechtliche Schritte im Falle der unverlangten Zusendung von Werbeinformationen, etwa durch Spam-Mails, vor.

                Unsere Datenschutzerklärung kann sich ändern. Diese Änderungen werden im Rahmen der Aktualisierung der Applikation in gleicher Weise wie bisher veröffentlicht, ohne dass wir den Nutzer hierauf direkt aufmerksam machen.
                Verantwortlich für die Einhaltung der hiermit veröffentlichten Datenschutzrichtlinien sind die im Impressum genannten Personen.

        Über diese App

            Diese App wurde von dem OK Lab in Gießen (CodeForGießen) entwickelt. Das Hessische Landesamt
            für Umwelt und Geologie (HLUG) stellt uns freundlicherweise die Daten zur Verfügung.

        Wenn Du Interesse hast, komme doch einfach bei unseren regelmäßigen Treffen vorbei. Weitere Informationen zu dem OK Lab in Gießen findest Du auf unserer Webseite.

        Du kommst nicht aus Mittelhessen bzw. Gießen? Kein Problem! Wahrscheinlich gibt es ein anderes OK Lab in Deiner Nähe. Schau doch einfach mal auf der  Code for Germany Seite  vorbei.

        Mitwirkende

        {{contributor.name}}, {{contributor.task}}

        Lizenz und Quellcode

The MIT License (MIT)

Copyright (c) 2015 Code for Gießen, http://codefor.de/giessen/

Permission is hereby granted, free of charge, to any person obtaining a copy
            of this software and associated documentation files (the "Software"), to deal
            in the Software without restriction, including without limitation the rights
            to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
            copies of the Software, and to permit persons to whom the Software is
            furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
            all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
            IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
            FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
            AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
            LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
            OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
            THE SOFTWARE.

Repositories

            Service: https://github.com/CodeForGiessen/badeseenservice

            App: https://github.com/CodeForGiessen/badeseenapp

</ion-content>
</ion-view>


text:
var spawn = require('child_process').spawn
var minimist = require('minimist')
var request = require('request')
var cookie = require('cookie')
var util = require('util')
var uri = require('./lib/uri')
var fs = require('fs')
var host, user, pass
var argv

argv = minimist(process.argv.slice(2))
host = argv._[0]
user = process.env.IKVMLOL_USER || argv.user
pass = process.env.IKVMLOL_PASS || argv.pass

var getOpts = {
		timeout : 10000
		, strictSSL : false
}

validate(begin)

function validate(cb) {

	if(!user) {

		console.log("* No user specified, trying defaults.")
		user = 'ADMIN'
		def = true
	}
	if(!pass) {

		if(user != 'ADMIN') {

			console.log("* Export IKVMLOL_USER & IKVMLOL_PASS to win.")
			return cb(new Error('No pass specified.'))
		}
		pass = 'ADMIN'
		def = true
	}
	if(!host) { return cb(new Error('No host specified.')) }

	cb(null)
}

function begin(err) {

	if(err) { return exit(err) }

	console.log("* Attempting login...")
	var login = util.format(uri.login, host)
	form(login, function logged(err, res, body) {

		if(err) {

			if(err.code == 'ETIMEDOUT') { return exit(new Error('Login request timed out.')) }
			else { return exit(new Error(util.format('Error attempting to login [%s].', err.code))) }
		}

		if(res.statusCode != '200') {

			return exit(new Error(
				util.format(
					'HTTP error attempting to login: [%s]'
					, res.statusCode
				)
			))
		}

		var sid = cookie.parse(res.headers['set-cookie'][1]).SID
		if(sid != '' && sid != ';') {

			console.log("* Successfully logged in!")
			webStart(sid)
		}
		else {

			exit(new Error("Unexpected session ID."))
		}
	})
}

function webStart(sid) {

	console.log('* Downloading JNLP file...')
	var jnlp = fs.createWriteStream('/tmp/webstart.jnlp', {

		encoding : null
		, mode : 0700
	})
	var download = util.format(uri.webstart, host)
	dl(download, sid).pipe(jnlp)
	jnlp.on('close', function() {

		console.log("* Done! Launching.")
		var ws = spawn(
			'javaws'
			, [ '/tmp/webstart.jnlp' ]
			, { detached : true }
		)
		process.nextTick(process.exit)
	})
	jnlp.on('error', exit)
}

function dl(uri, sid) {

	var opts = {
		url : uri
		, headers : {
			'Accept-Encoding' : 'gzip,deflate,sdch'
			, 'Accept-Language' : 'en-US,en;q=0.8'
			, 'Cookie' : util.format('SID=%s', sid)
			, 'Referer' : uri
		}
	}
	return request(opts)
}

function get(uri, cb) { return req('GET', uri, cb) }
function form(uri, cb) { return req('FORM', uri, cb) }
function req(method, uri, cb) {

	var opts = getOpts
	opts.method = method
	opts.uri = uri

	if(method == 'FORM') {

		opts.method = 'POST'
		opts.form = { name : user, pwd : pass }
	}
	return request(opts, cb ? cb : null)
}

function exit(err) {

	var code = 0
	if (err) {

		console.log('* %s', err)
		code = 1
	}
	console.log("Exiting.")
	process.exit(code)
}


text:
import numpy as np
import scipy.sparse as sp
from scipy.constants import mu_0

from ...fields import Fields
from ..frequency_domain.fields import FieldsFDEM
from ...utils import spzeros, Identity, Zero
from ..utils import omega

# ##############
# #   Fields   #
# ##############

class _1DField:
    def field_deriv_m(self, field, freq, src, v, adjoint=False):
        sim = self.simulation
        nf = sim.survey.frequencies.index(freq)
        u_src = self[src, sim._solutionType]
        # left deriv
        if not adjoint:
            dA_dm_v = sim.getADeriv(freq, u_src, v, adjoint=False)
            dRHS_dm_v = sim.getRHSDeriv(freq, src, v)
            du_dm_v = sim.Ainv[nf] * (-dA_dm_v + dRHS_dm_v)
            if field == "e":
                return self._eDeriv(src, du_dm_v, v, adjoint=False)
            elif field == "h":
                return self._hDeriv(src, du_dm_v, v, adjoint=False)
        else:
            if field == "e":
                df_duT, df_dmT = self._eDeriv(src, None, v, adjoint=True)
            elif field == "h":
                df_duT, df_dmT = self._hDeriv(src, None, v, adjoint=True)
            ATinv_duT = sim.Ainv[nf] * df_duT
            dA_dmT = sim.getADeriv(freq, u_src, ATinv_duT, adjoint=True)
            dRHS_dmT = sim.getRHSDeriv(freq, src, ATinv_duT, adjoint=True)
            du_dmT = -dA_dmT + dRHS_dmT
            df_dmT += du_dmT
            return df_dmT

class _EField(_1DField):
    """
    A simple class containing some common code to the
    1D and 2D E-fields
    """

    def _e(self, eSolution, source_list):
        return eSolution

    def _eDeriv_u(self, src, du_dm_v, adjoint=False):
        return du_dm_v

    def _eDeriv_m(self, src, v, adjoint=False):
        return Zero()

    def _h(self, eSolution, source_list):
        omegas = np.array([omega(src.frequency) for src in source_list])
        e = self._e(eSolution, source_list)
        if self.simulation.muiMap is not None:
            mui = self.simulation.mui[:, None]
        else:
            mui = self.simulation.mui
        v = mui * (self._C * e)
        return v / (1j * omegas)

    def _hDeriv_u(self, src, du_dm_v, adjoint=False):
        if du_dm_v.ndim == 1:
            du_dm_v = du_dm_v[:, None]
        om = omega(src.frequency)
        if self.simulation.muiMap is not None:
            mui = self.simulation.mui[:, None]
        else:
            mui = self.simulation.mui
        if adjoint:
            y = self._eDeriv_u(src, self._C.T * (mui * du_dm_v), adjoint=adjoint)
            return np.squeeze(y) / (1j * om)
        y = mui * (self._C @ self._eDeriv_u(src, du_dm_v, adjoint=False))
        return np.squeeze(y) / (1j * om)

    def _hDeriv_m(self, src, v, adjoint=False):
        if self.simulation.muiMap is None:
            return Zero()
        om = omega(src.frequency)
        dMui = self.simulation.muiDeriv
        e = self[src, "e"]
        if v.ndim == 1:
            v = v[:, None]
        if adjoint:
            y = dMui.T * ((self._C * e) * v)
            return np.squeeze(y) / (1j * om)
        y = (self._C * e) * (dMui * v)
        return np.squeeze(y) / (1j * om)

class _HField(_1DField):
    """
    A simple class containing some common code to the
    1D and 2D H-fields
    """

    def _h(self, hSolution, source_list):
        return hSolution

    def _hDeriv_u(self, src, du_dm_v, adjoint=False):
        return du_dm_v

    def _hDeriv_m(self, src, v, adjoint=False):
        return Zero()

    def _e(self, hSolution, source_list):
        return self.simulation.rho[:, None] * (
            self._C * self._h(hSolution, source_list)
        )

    def _eDeriv_u(self, src, du_dm_v, adjoint=False):
        if du_dm_v.ndim == 1:
            du_dm_v = du_dm_v[:, None]
        if adjoint:
            y = self._hDeriv_u(
                src, self._C.T * (self.simulation.rho[:, None] * du_dm_v), adjoint=True
            )
            return np.squeeze(y)
        y = self.simulation.rho[:, None] * (
            self._C @ (self._hDeriv_u(src, du_dm_v, adjoint=False))
        )
        return np.squeeze(y)

    def _eDeriv_m(self, src, v, adjoint=False):
        if self.simulation.rhoMap is None:
            return Zero()
        dRho = self.simulation.rhoDeriv
        h = self[src, "h"]
        if v.ndim == 1:
            v = v[:, None]
        if adjoint:
            y = dRho.T * ((self._C * h) * v)
            return np.squeeze(y)
        y = (self._C * h) * (dRho * v)
        return np.squeeze(y)

###########
# 1D Fields
###########

class Fields1DElectricField(_EField, FieldsFDEM):
    """
    Fields
    """

    knownFields = {"eSolution": "N"}
    aliasFields = {
        "e": ["eSolution", "N", "_e"],
        "h": ["eSolution", "CC", "_h"],
    }
    field_directions = "yx"

    def startup(self):
        self._C = self.simulation.mesh.nodal_gradient

class Fields1DMagneticField(_HField, Fields1DElectricField):
    """
    Fields
    """

    knownFields = {"hSolution": "N"}
    aliasFields = {
        "e": ["hSolution", "CC", "_e"],
        "h": ["hSolution", "N", "_h"],
    }

    field_directions = "xy"

    def startup(self):
        # boundary conditions
        self._C = -self.simulation.mesh.nodal_gradient

class Fields1DPrimarySecondary(FieldsFDEM):
    """
    Fields storage for the 1D NSEM solution.

    Solving for e fields, using primary/secondary formulation
    """

    knownFields = {"eSolution": "N"}
    aliasFields = {
        "e": ["eSolution", "N", "_e"],
        "ePrimary": ["eSolution", "N", "_ePrimary"],
        "eSecondary": ["eSolution", "N", "_eSecondary"],
        "b": ["eSolution", "CC", "_b"],
        "bPrimary": ["eSolution", "CC", "_bPrimary"],
        "bSecondary": ["eSolution", "CC", "_bSecondary"],
        "h": ["eSolution", "CC", "_h"],
    }

    field_directions = "xy"

    # def __init__(self, mesh, survey, **kwargs):
    #     super(Fields1DPrimarySecondary, self).__init__(mesh, survey, **kwargs)

    def _ePrimary(self, eSolution, source_list):
        """
        Primary electric field from source

        :param numpy.ndarray eSolution: field we solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: primary electric field as defined by the sources
        """
        ePrimary = np.zeros_like(eSolution)
        for i, src in enumerate(source_list):
            ep = src.ePrimary(self.simulation)
            ePrimary[:, i] = ePrimary[:, i] + ep[:, -1]
        return ePrimary

    def _eSecondary(self, eSolution, source_list):
        """
        Secondary electric field is the thing we solved for

        :param numpy.ndarray eSolution: field we solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: secondary electric field
        """
        return eSolution

    def _eDeriv_u(self, src, du_dm_v, adjoint=False):
        """
        Partial derivative of the total electric field with respect to the solution.

        :param SimPEG.EM.NSEM.Src src: source
        :param numpy.ndarray du_dm_v: vector to take product with
            Size (nE,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True
            (nE,) when adjoint=False"""

        return Identity() * du_dm_v

    def _eDeriv_m(self, src, v, adjoint=False):
        """
        Partial derivative of the total electric field with respect to the inversion model. Here, we assume that the primary does not depend on the model. Note that this also includes derivative contributions from the sources.

        :param SimPEG.electromagnetics.frequency_domain.Src src: source
        :param numpy.ndarray v: vector to take product with
        :param bool adjoint: adjoint?
        :rtype: SimPEG.utils.Zero
        :return: product of the electric field derivative with respect to the inversion model with a vector
        """

        # assuming primary does not depend on the model
        return Zero()

    def _bPrimary(self, eSolution, source_list):
        bPrimary = np.zeros(
            [self.simulation.mesh.nE, eSolution.shape[1]], dtype=complex
        )
        for i, src in enumerate(source_list):
            bp = src.bPrimary(self.simulation)
            bPrimary[:, i] = bPrimary[:, i] + bp[:, -1]
        return bPrimary

    def _bSecondary(self, eSolution, source_list):
        """
        Primary magnetic flux density from source

        :param numpy.ndarray eSolution: field we solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: primary magnetic flux density as defined by the sources
        """
        C = self.mesh.nodal_gradient
        b = C * eSolution
        for i, src in enumerate(source_list):
            b[:, i] *= -1.0 / (1j * omega(src.frequency))
        return b

    def _bDeriv_u(self, src, du_dm_v, adjoint=False):
        """
        Derivative of the magnetic flux density with respect to the solution

        :param SimPEG.electromagnetics.frequency_domain.Src src: source
        :param numpy.ndarray du_dm_v: vector to take product with
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector
        """
        # bPrimary: no model depenency
        C = self.mesh.nodal_gradient
        if adjoint:
            bSecondaryDeriv_u = -1.0 / (1j * omega(src.frequency)) * (C.T * du_dm_v)
        else:
            bSecondaryDeriv_u = -1.0 / (1j * omega(src.frequency)) * (C * du_dm_v)
        return bSecondaryDeriv_u

    def _bDeriv_m(self, src, v, adjoint=False):
        """
        Derivative of the magnetic flux density with respect to the inversion model.

        :param SimPEG.electromagnetics.frequency_domain.Src src: source
        :param numpy.ndarray v: vector to take product with
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: product of the magnetic flux density derivative with respect to the inversion model with a vector
        """
        # Neither bPrimary nor bSeconary have model dependency => return Zero
        return Zero()

    def _h(self, eSolution, source_list):
        return 1 / mu_0 * self._b(eSolution, source_list)

    def _hDeriv_u(self, src, du_dm_v, adjoint=False):
        if adjoint:
            v = 1 / mu_0 * du_dm_v  # MfMui, MfI are symmetric
            return self._bDeriv_u(src, v, adjoint=adjoint)
        return 1 / mu_0 * self._bDeriv_u(src, du_dm_v)

    def _hDeriv_m(self, src, v, adjoint=False):
        """
        Derivative of the magnetic flux density with respect to the inversion model.

        :param SimPEG.electromagnetics.frequency_domain.Src src: source
        :param numpy.ndarray v: vector to take product with
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: product of the magnetic flux density derivative with respect to the inversion model with a vector
        """
        # Neither bPrimary nor bSeconary have model dependency => return Zero
        return Zero()

###########
# 2D Fields
###########

class Fields2DElectricField(_EField, FieldsFDEM):
    """
    Fields
    """

    knownFields = {"eSolution": "E"}
    aliasFields = {
        "e": ["eSolution", "E", "_e"],
        "h": ["eSolution", "CC", "_h"],
    }

    def startup(self):
        self._C = self.simulation.mesh.edge_curl

class Fields2DMagneticField(_HField, FieldsFDEM):
    """
    Fields
    """

    knownFields = {"hSolution": "E"}
    aliasFields = {
        "e": ["hSolution", "CC", "_e"],
        "h": ["hSolution", "E", "_h"],
    }

    def startup(self):
        # boundary conditions
        self._C = -self.simulation.mesh.edge_curl

###########
# 3D Fields
###########
class Fields3DPrimarySecondary(Fields):
    """
    Fields storage for the 3D NSEM solution. Labels polarizations by px and py.

        :param SimPEG object mesh: The solution mesh
        :param SimPEG object survey: A survey object
    """

    # Define the known the alias fields
    # Assume that the solution of e on the E.
    # NOTE: Need to make this more general, to allow for other formats.
    dtype = complex
    knownFields = {"e_pxSolution": "E", "e_pySolution": "E"}
    aliasFields = {
        "e_px": ["e_pxSolution", "E", "_e_px"],
        "e_pxPrimary": ["e_pxSolution", "E", "_e_pxPrimary"],
        "e_pxSecondary": ["e_pxSolution", "E", "_e_pxSecondary"],
        "e_py": ["e_pySolution", "E", "_e_py"],
        "e_pyPrimary": ["e_pySolution", "E", "_e_pyPrimary"],
        "e_pySecondary": ["e_pySolution", "E", "_e_pySecondary"],
        "b_px": ["e_pxSolution", "F", "_b_px"],
        "b_pxPrimary": ["e_pxSolution", "F", "_b_pxPrimary"],
        "b_pxSecondary": ["e_pxSolution", "F", "_b_pxSecondary"],
        "b_py": ["e_pySolution", "F", "_b_py"],
        "b_pyPrimary": ["e_pySolution", "F", "_b_pyPrimary"],
        "b_pySecondary": ["e_pySolution", "F", "_b_pySecondary"],
    }

    # def __init__(self, mesh, survey, **kwargs):
    #     BaseNSEMFields.__init__(self, mesh, survey, **kwargs)

    def _e_pxPrimary(self, e_pxSolution, source_list):
        """
        px polarization of primary electric field from source

        :param numpy.ndarray e_pxSolution: px polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: primary electric field as defined by the sources
        """
        e_pxPrimary = np.zeros_like(e_pxSolution)
        for i, src in enumerate(source_list):
            ep = src.ePrimary(self.simulation)
            if ep is not None:
                e_pxPrimary[:, i] = ep[:, 0]
        return e_pxPrimary

    def _e_pyPrimary(self, e_pySolution, source_list):
        """
        py polarization of primary electric field from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: primary electric field as defined by the sources
        """

        e_pyPrimary = np.zeros_like(e_pySolution)
        for i, src in enumerate(source_list):
            ep = src.ePrimary(self.simulation)
            if ep is not None:
                e_pyPrimary[:, i] = ep[:, 1]
        return e_pyPrimary

    def _e_pxSecondary(self, e_pxSolution, source_list):
        """
        px polarization of secondary electric field from source

        :param numpy.ndarray e_pxSolution: px polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: secondary electric field as defined by the sources
        """

        return e_pxSolution

    def _e_pySecondary(self, e_pySolution, source_list):
        """
        py polarization of secondary electric field from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: secondary electric field as defined by the sources
        """
        return e_pySolution

    def _e_px(self, e_pxSolution, source_list):
        """
        px polarization of electric field from source

        :param numpy.ndarray e_pxSolution: px polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: electric field as defined by the sources
        """
        return self._e_pxPrimary(e_pxSolution, source_list) + self._e_pxSecondary(
            e_pxSolution, source_list
        )

    def _e_py(self, e_pySolution, source_list):
        """
        py polarization of electric field from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: electric field as defined by the sources
        """
        return self._e_pyPrimary(e_pySolution, source_list) + self._e_pySecondary(
            e_pySolution, source_list
        )

    def _b_pxPrimary(self, e_pxSolution, source_list):
        """
        px polarization of primary magnetic flux from source

        :param numpy.ndarray e_pxSolution: px polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: primary magnetic flux as defined by the sources
        """
        b_pxPrimary = np.zeros(
            [self.simulation.mesh.nF, e_pxSolution.shape[1]], dtype=complex
        )
        for i, src in enumerate(source_list):
            bp = src.bPrimary(self.simulation)
            if bp is not None:
                b_pxPrimary[:, i] += bp[:, 0]
        return b_pxPrimary

    def _b_pyPrimary(self, e_pySolution, source_list):
        """
        py polarization of primary magnetic flux from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: primary magnetic flux as defined by the sources
        """
        b_pyPrimary = np.zeros(
            [self.simulation.mesh.nF, e_pySolution.shape[1]], dtype=complex
        )
        for i, src in enumerate(source_list):
            bp = src.bPrimary(self.simulation)
            if bp is not None:
                b_pyPrimary[:, i] += bp[:, 1]
        return b_pyPrimary

    def _b_pxSecondary(self, e_pxSolution, source_list):
        """
        px polarization of secondary magnetic flux from source

        :param numpy.ndarray e_pxSolution: px polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: secondary magnetic flux as defined by the sources
        """
        C = self.mesh.edge_curl
        b = C * e_pxSolution
        for i, src in enumerate(source_list):
            b[:, i] *= -1.0 / (1j * omega(src.frequency))
        return b

    def _b_pySecondary(self, e_pySolution, source_list):
        """
        py polarization of secondary magnetic flux from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: secondary magnetic flux as defined by the sources
        """
        C = self.mesh.edge_curl
        b = C * e_pySolution
        for i, src in enumerate(source_list):
            b[:, i] *= -1.0 / (1j * omega(src.frequency))
        return b

    def _b_px(self, eSolution, source_list):
        """
        py polarization of magnetic flux from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: magnetic flux as defined by the sources
        """
        return self._b_pxPrimary(eSolution, source_list) + self._b_pxSecondary(
            eSolution, source_list
        )

    def _b_py(self, eSolution, source_list):
        """
        py polarization of magnetic flux from source

        :param numpy.ndarray e_pySolution: py polarization that was solved for
        :param list source_list: list of sources
        :rtype: numpy.ndarray
        :return: magnetic flux as defined by the sources
        """
        return self._b_pyPrimary(eSolution, source_list) + self._b_pySecondary(
            eSolution, source_list
        )

    # Derivatives
    # NOTE: For e_p?Deriv_u,
    # v has to be u(2*nE) long for the not adjoint and nE long for adjoint.
    # Returns nE long for not adjoint and 2*nE long for adjoint
    def _e_pxDeriv(self, src, du_dm_v, v, adjoint=False):
        """Derivative of e_px with respect to the solution (u) and model (m)"""
        # e_px does not depend on the model
        return np.array(
            self._e_pxDeriv_u(src, du_dm_v, adjoint)
            + self._e_pxDeriv_m(src, v, adjoint),
            complex,
        )

    def _e_pyDeriv(self, src, du_dm_v, v, adjoint=False):
        """Derivative of e_py with respect to the solution (u) and model (m)"""
        return np.array(
            self._e_pyDeriv_u(src, du_dm_v, adjoint)
            + self._e_pyDeriv_m(src, v, adjoint),
            complex,
        )

    def _e_pxDeriv_u(self, src, du_dm_v, adjoint=False):
        """
        Derivative of e_px wrt u

        :param SimPEG.NSEM.src src: The source of the problem
        :param numpy.ndarray du_dm_v: vector to take product with Size (nE,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True (nE,) when adjoint=False
        """
        # e_pxPrimary doesn't depend on u, only e_pxSecondary
        if adjoint:
            # adjoint: returns a 2*nE long vector with zero's for py
            return np.concatenate((du_dm_v, np.zeros_like(du_dm_v)))
        # Not adjoint: return only the px part of the vector
        return du_dm_v[: int(len(du_dm_v) / 2)]

    def _e_pyDeriv_u(self, src, du_dm_v, adjoint=False):
        """
        Derivative of e_py wrt u

        :param SimPEG.NSEM.src src: The source of the problem
        :param numpy.ndarray du_dm_v: vector to take product with Size (nE,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True (nE,) when adjoint=False

        """

        if adjoint:
            # adjoint: returns a 2*nE long vector with zero's for px
            return np.concatenate((np.zeros_like(du_dm_v), du_dm_v))
        # Not adjoint: return only the px part of the vector
        return du_dm_v[int(len(du_dm_v) / 2) : :]

    def _e_pxDeriv_m(self, src, v, adjoint=False):
        """
        Derivative of e_px wrt m

        :param SimPEG.NSEM.src src: The source of the problem
        :param numpy.ndarray v: vector to take product with Size (nE,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True (nE,) when adjoint=False

        """
        # e_px does not depend on the model
        return Zero()

    def _e_pyDeriv_m(self, src, v, adjoint=False):
        """
        Derivative of e_py wrt m

        :param SimPEG.NSEM.src src: The source of the problem
        :param numpy.ndarray v: vector to take product with Size (nE,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True (nE,) when adjoint=False

        """
        # e_py does not depend on the model
        return Zero()

    # Magnetic flux
    def _b_pxDeriv(self, src, du_dm_v, v, adjoint=False):
        """Derivative of b_px with respect to the solution (u) and model (m)"""
        # b_px does not depend on the model

        return np.array(
            self._b_pxDeriv_u(src, du_dm_v, adjoint)
            + self._b_pxDeriv_m(src, v, adjoint),
            complex,
        )

    def _b_pyDeriv(self, src, du_dm_v, adjoint=False):
        """Derivative of b_px with respect to the solution (u) and model (m)"""
        # Primary does not depend on u
        return np.array(
            self._b_pyDeriv_u(src, du_dm_v, adjoint)
            + self._b_pyDeriv_m(src, v, adjoint),
            complex,
        )

    def _b_pxDeriv_u(self, src, du_dm_v, adjoint=False):
        """
        Derivative of b_px with wrt u

        :param SimPEG.NSEM.src src: The source of the problem
        :param numpy.ndarray du_dm_v: vector to take product with. Size (nF,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True. (nF,) when adjoint=False
        """
        # Primary does not depend on u
        C = sp.hstack(
            (self.mesh.edge_curl, spzeros(self.mesh.nF, self.mesh.nE))
        )  # This works for adjoint = None
        if adjoint:
            return -1.0 / (1j * omega(src.frequency)) * (C.T * du_dm_v)
        return -1.0 / (1j * omega(src.frequency)) * (C * du_dm_v)

    def _b_pyDeriv_u(self, src, du_dm_v, adjoint=False):
        """Derivative of b_py with wrt u

        :param SimPEG.NSEM.src src: The source of the problem
        :param numpy.ndarray du_dm_v: vector to take product with. Size (nF,) when adjoint=True, (nU,) when adjoint=False
        :param bool adjoint: adjoint?
        :rtype: numpy.ndarray
        :return: The calculated derivative, size (nU,) when adjoint=True. (nF,) when adjoint=False
        """
        # Primary does not depend on u
        C = sp.hstack(
            (spzeros(self.mesh.nF, self.mesh.nE), self.mesh.edge_curl)
        )  # This works for adjoint = None
        if adjoint:
            return -1.0 / (1j * omega(src.frequency)) * (C.T * du_dm_v)
        return -1.0 / (1j * omega(src.frequency)) * (C * du_dm_v)

    def _b_pxDeriv_m(self, src, v, adjoint=False):
        """Derivative of b_px wrt m"""
        # b_px does not depend on the model
        return Zero()

    def _b_pyDeriv_m(self, src, v, adjoint=False):
        """Derivative of b_py wrt m"""
        # b_py does not depend on the model
        return Zero()


text:
BEGIN_INANITY_GRAPHICS

AttributeLayoutElement::AttributeLayoutElement(ptr<AttributeLayout> layout, int index)
: layout(layout), index(index) {}

int AttributeLayoutElement::GetIndex() const
{
	return index;
}

DataType AttributeLayoutElement::GetDataType() const
{
	return layout->GetElements()[index].dataType;
}

LayoutDataType AttributeLayoutElement::GetLayoutDataType() const
{
	return layout->GetElements()[index].layoutDataType;
}

END_INANITY_GRAPHICS


text:
<resources>

    <!-- Application theme. -->
    <style name="AppTheme" parent="android:Theme.Holo.Light">
        <item name="android:windowNoTitle">true</item>
    </style>

</resources>


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using ww;

namespace FlightSimulator
{
    class Stimulations
    {
        private Graphics g1;
        private Graphics g2;
        private float widthCenter, heightCenter;

        private int width, height;
        private Color bc;
        Bitmap image1, image2;
        private ushort stiNumber;
        public bool isPosition = true;
        public bool isTorque = true;

        private float blockWidth;
        private float blockHeight;

        private ArrayForDraw afd;
        private int[,] painting;
        private int barWidth;
        private int[,] bar;
        public Stimulations(int width, int height, ushort stiNumber)
        {

            image1 = new Bitmap(width, height);
            g1 = Graphics.FromImage(image1);
            //使绘图质量最高,即消除锯齿
            g1.SmoothingMode = SmoothingMode.AntiAlias;
            g1.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g1.CompositingQuality = CompositingQuality.HighQuality;
            g1.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            this.width = width;
            this.height = height;
            this.stiNumber = stiNumber;

            blockWidth = 100f;
            blockHeight = 40f;

            afd = new ArrayForDraw(width, height,1);
            painting = afd.GiveValueForRandow();

            start = (int)DegreeToValue(-100);
            end = (int)DegreeToValue(100);
            positionNow = start;
        }

        public void setWH(int width, int height)
        {
            this.width = width;
            this.height = height;
        }
        public float DegreeToValue(float degree)
        {
            return width / 2f + width / 360f * degree;

        }

        public int ValueToDegree(float value)
        {
            return (int)((value - width / 2f) * 360 / width);
        }

        public void setRightLeft(bool ifRight)
        {
            if (ifRight)
            {
                ifMoveRight = true;
            }
            else
            {
                ifMoveRight = false;
            }
        }
        public void setSpeed(int value)
        {
            SpeedDegree = value;
        }
        public int getDegree()
        {
            return ValueToDegree(positionNow)+barWidth/2;
        }
        public bool getRightOrLeft()
        {
            return ifMoveRight;
        }

        public void setBarWidth(float value)
        {
            barWidth = (int)(value / 360 * width);
            afd = new ArrayForDraw(barWidth, height, 2);
            bar = afd.GiveValueForRandow();
        }
        private int positionNow=0;
        private int SpeedDegree = 0;
        private int start;
        private int end;
        private bool ifMoveRight = true;

        public Bitmap DrawCBar()
        {

            g1.Clear(Color.White);
            for (int i = 0; i != height; i++)
            {
                for (int j = 0; j != width; j++)
                {
                    if (j >= positionNow & j <positionNow + barWidth)
                    {
                        if (bar[i, j-positionNow] == 0)
                        {
                            //j x   i y
                            image1.SetPixel(j, i, Color.Black);  //100ms
                                                                 //g1.DrawEllipse(Pens.Black,j,i,1,1);  //500ms

                        }
                    }

                    else
                    {
                        if (painting[i, j] == 0)
                        {
                            //j x   i y
                            image1.SetPixel(j, i, Color.Black);  //100ms
                                                                 //g1.DrawEllipse(Pens.Black,j,i,1,1);  //500ms

                        }
                    }
                }
            }

            return image1;
        }
        //public Bitmap DrawACBar(float degree)
        //{
        //    ;
        //}

        public Bitmap DrawV_Test(float degree)
        {
            g1.Clear(Color.White);

            float position = DegreeToValue(degree);
            float x1 = position - blockWidth / 2f;
            float y1 = 1 / 3.0f * height- blockHeight / 2f;
            float x2 = x1 + width / 4f;
            float y2 = 2 / 3.0f * height - blockHeight / 2f;
            float x3 = x2 +  width / 4f;
            float y3 = y1;
            float x4 = x3 + width / 4f;
            float y4 = y2;

            Color c = Color.Black;

            if (x1 + blockWidth > width)
            {

                if (x1 > width)
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x1 - width, y1, blockWidth, blockHeight));
                }
                else
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x1, y1, width - x1, blockHeight));
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(0, y1, blockWidth - width + x1, blockHeight));
                }
            }
            else if (0 > x1)
            {
                g1.FillRectangle(new SolidBrush(c), new RectangleF(x1, y1, blockWidth, blockHeight));
                g1.FillRectangle(new SolidBrush(c), new RectangleF(width+x1, y1, - x1, blockHeight));

            }
            else
            {
                g1.FillRectangle(new SolidBrush(c), new RectangleF(x1, y1, blockWidth, blockHeight));
            }

            if (x2 + blockWidth > width)
            {

                if (x2 > width)
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x2 - width, y2, blockWidth, blockHeight));
                }
                else
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x2, y2, width - x2, blockHeight));
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(0, y2, blockWidth - width + x2, blockHeight));
                }
            }
            else
            {
                g1.FillRectangle(new SolidBrush(c), new RectangleF(x2, y2, blockWidth, blockHeight));
            }

            if (x3 + blockWidth > width)
            {

                if (x3 > width)
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x3 - width, y3, blockWidth, blockHeight));
                }
                else
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x3, y3, width - x3, blockHeight));
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(0, y3, blockWidth - width + x3, blockHeight));
                }
            }
            else
            {
                g1.FillRectangle(new SolidBrush(c), new RectangleF(x3, y3, blockWidth, blockHeight));
            }

            if (x4 + blockWidth > width)
            {

                if (x4 > width)
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x4 - width, y4, blockWidth, blockHeight));
                }
                else
                {
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(x4, y4, width - x4, blockHeight));
                    g1.FillRectangle(new SolidBrush(c), new RectangleF(0, y4, blockWidth - width + x4, blockHeight));
                }
            }
            else
            {
                g1.FillRectangle(new SolidBrush(c), new RectangleF(x4, y4, blockWidth, blockHeight));
            }
            //RectangleF rect1 = new RectangleF(x1,y1, blockWidth, blockHeight);
            //g1.FillRectangle(new SolidBrush(Color.DarkCyan), rect1);

            //RectangleF rect2 = new RectangleF(x2, y2, blockWidth, blockHeight);
            //g1.FillRectangle(new SolidBrush(Color.DarkCyan), rect2);

            //RectangleF rect3 = new RectangleF(x3, y3, blockWidth, blockHeight);
            //g1.FillRectangle(new SolidBrush(Color.DarkCyan), rect3);

            //RectangleF rect4 = new RectangleF(x4, y4, blockWidth, blockHeight);
            //g1.FillRectangle(new SolidBrush(Color.DarkCyan), rect4);

            return image1;

        }

        public void MovingStrip()
        {
            Matrix m = new Matrix();
        }

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<entity-engine-xml>
    <!-- Remote Service security -->
    <SecurityPermission description="Permission to invoke any service remotely." permissionId="SERVICE_INVOKE_ANY"/>

    <!-- add admin to SUPER permission group -->
    <SecurityGroupPermission groupId="SUPER" permissionId="SERVICE_INVOKE_ANY"/>

</entity-engine-xml>


text:
set -e

# Undo the changes made in pregeneration.sh
git -C $GOOGLEAPIS checkout google/cloud/accessapproval/v1/

# Fix up the generated client to use the right gRPC types
sed -i s/AccessApprovalService.AccessApprovalServiceClient/AccessApproval.AccessApprovalClient/g Google.Cloud.AccessApproval.V1/AccessApprovalServiceClient.g.cs

# Fix up unit test classes
sed -i s/AccessApprovalService.AccessApprovalServiceClient/AccessApproval.AccessApprovalClient/g Google.Cloud.AccessApproval.V1.Tests/AccessApprovalServiceClientTest.g.cs

# Fix up the metadata
sed -i 's/"AccessApprovalService": {/"AccessApproval": {/g' gapic_metadata.json


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Gloniella pentastemonis Earle

### Remarks
null


text:
package app.bindingModels.dataExportingModels.jsonModels;

import com.google.gson.annotations.Expose;

public class PhotographerAndGear {

    @Expose
    private String firstName;

    @Expose
    private String lastName;

    @Expose
    private String cameraMake;

    @Expose
    private Integer lensesCount;

    public PhotographerAndGear() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getCameraMake() {
        return cameraMake;
    }

    public void setCameraMake(String cameraMake) {
        this.cameraMake = cameraMake;
    }

    public Integer getLensesCount() {
        return lensesCount;
    }

    public void setLensesCount(Integer lensesCount) {
        this.lensesCount = lensesCount;
    }
}


text:
package org.sagebionetworks.repo.model.bootstrap;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbcp2.BasicDataSource;
import org.sagebionetworks.StackConfiguration;
import org.sagebionetworks.StackConfigurationSingleton;

/**
 * Allows the build to prepare the database.
 *
 * @author jmhill
 *
 */
public class DatabasePreparation {

	public static void main(String[] args) throws Exception {
		// This property is not in stack config beacause it is only used by Bamboo/Hudson builds
		String prop = System.getProperties().getProperty("org.sagebionetworks.database.drop.schema");
		if(prop != null && Boolean.parseBoolean(prop)){
			// Drop the current schema
			StackConfiguration config = StackConfigurationSingleton.singleton();
			// This is a safety check to prevent droping prod-database.
			if(isNonProductionStack(config.getStack())){
				// Make the database connection.
				BasicDataSource ds = new BasicDataSource();
				ds.setDriverClassName(config.getRepositoryDatabaseDriver());
				ds.setUsername(config.getRepositoryDatabaseUsername());
				ds.setPassword(config.getRepositoryDatabasePassword());
				// Setup a URL
				String url = config.getRepositoryDatabaseConnectionUrl();
				String dbName = config.getStack()+config.getStackInstance();
				String subURL = url.substring(0, url.length()-dbName.length());
				System.out.println(subURL);
				ds.setUrl(subURL);
				// Now make a connection
				Connection con =  ds.getConnection();
				try{
					Statement statement = con.createStatement();
					try{
						// This will fail if the DB does not exist.
						statement.execute("DROP SCHEMA `"+dbName+"`");
					}catch(SQLException e){
						// This can happen.
					}
					// Create the schema
					statement.execute("CREATE SCHEMA `"+dbName+"`");
				}finally{
					// Close the connection.
					ds.close();
				}
			}
		}

	}

	/**
	 * Is this a non-production stack?
	 * @param stack
	 * @return
	 */
	public static boolean isNonProductionStack(String stack){
		if("bamboo".equals(stack)) return true;
		if("dev".equals(stack)) return true;
		if("hudson".equals(stack)) return true;
		if("hud".equals(stack)) return true;
		return false;
	}

}


text:
cask :v1 => 'psychopy' do
  version '1.81.00'
  sha256 '121a3ee098ea6a978e7888da8de6dc3a096205455518aabf9e31edf21bbe0183'

  # sourceforge.net is the official download host per the vendor homepage
  url "http://downloads.sourceforge.net/sourceforge/psychpy/StandalonePsychoPy-#{version}-OSX.dmg"
  homepage 'http://www.psychopy.org/'
  license :oss

  app 'PsychoPy2.app'
end


text:
 * Meteor 1.x package/bundle support
 * Git-based repository + branch/tag via environment variables (`REPO` and `BRANCH`)
 * Bundle URL via environment variable (`BUNDLE_URL`)
 * Bind-mount, volume, Dockerfile `ADD` via environment variable (`APP_DIR`)
 * Uses docker-linked MongoDB (i.e. `MONGO_PORT`...) or explicit setting via environment variable (`MONGO_URL`)
 * NOTE: This does NOT set `MONGO_OPLOG_URL`.  There were too many potention complications.  As a result, unless you explicitly set `MONGO_OPLOG_URL`, Meteor will fall back to a polling-based approach to database synchronization.  Note that oplog tailing requires a working replica set on your MongoDB server as well as access to the `local` database.
 * Optionally specify the port on which the web server should run (`PORT`); defaults to 80
 * Deploy-key support (set `DEPLOY_KEY` to the location of your SSH key file)
   * old `GITHUB_DEPLOY_KEY` is also supported but deprecated
 * Non-root location of Meteor tree; the script will search for the first .meteor directory
 * _NOTE_: PhantomJS is no longer pre-installed.  This package was swelling the size of the image by 50%, and it is not maintainable with the standard Docker Node images.  Instead, please use one of the docker-friendly (read port-based) spiderable packages on Meteor, such as [ongoworks:spiderable](https://atmospherejs.com/ongoworks/spiderable);  if there is demand, please create an issue on Github, and I'll see about managing a separate branch for it.

## Versions:

Regardless of the version number of the tool included in this package, your application will run
on whatever version of Meteor it is configured to run under.

## Examples:

### git repo with non-default (master) branch
```sh
docker run --rm \
  -e ROOT_URL=http://testsite.com \
  -e REPO=https://github.com/yourName/testsite \
  -e BRANCH=testing \
  -e MONGO_URL=mongodb://mymongoserver.com:27017/mydatabase \
  -e MONGO_OPLOG_URL=mongodb://mymongoserver.com:27017/local \
  ulexus/meteor
```

### local directory on host (/home/user/myapp)
```sh
docker run --rm \
  -e ROOT_URL=http://testsite.com \
  -e APP_DIR=/app \
  -v /home/user/myapp:/app \
  -e MONGO_URL=mongodb://mymongoserver.com:27017/appdb \
  -e MONGO_OPLOG_URL=mongodb://mymongoserver.com:27017/local \
  ulexus/meteor
```

### Unit file

There is also a sample systemd [unit file](meteor.myapp@.service) in the Github repository.