text:
title: Vtiger
date: 2016-03-4
tags: crm
---

# Vtiger
Vtiger 强大的开源 crm 系统。
## Demo

    vtiger6.0演示地址:http://vtiger6.vtcrm.cn/
    用户名:admin
    密 码:admin

## 源码下载和安装
* [https://www.vtiger.com/open-source-downloads/](https://www.vtiger.com/open-source-downloads/)
* [http://community.vtiger.com/help/vtigercrm/administrators/installation.html](http://community.vtiger.com/help/vtigercrm/administrators/installation.html)

将解压的文件全部复制到/var/www/或根据/etc/apache2/sites-available配置的目录.

## 安装依赖
apache mysql php php-imap php-curl php-xml

```
apt-get install php5-imap
apt-get install php5-curl
apt-get install php5enmod imap

```
重启
```
service apache2 restart
```
/etc/php5/apache2/php.ini 修改apache2的php设置

## 相关链接
* [vtiger中文网|vtigercrm技术|vtiger本土化](http://www.vtcrm.cn/)
* [How to Install LAMP in Ubuntu 14.04 LTS](http://engineerbabu.com/2014/09/13/how-to-install-lamp-in-ubuntu/)
* [How to install VtigerCRM in ubuntu 14.04](http://engineerbabu.com/2014/10/03/install-vtigercrm-ubuntu-14-04/)
* [中文语言包](https://marketplace.vtiger.com/extensions?id=18)

## 错误

### [How can enable imap in php.ini](http://stackoverflow.com/questions/23242402/how-can-enable-imap-in-php-ini)
```
sudo apt-get install php5-imap
sudo php5enmod imap
sudo service apache2 restart
```
### Invalid command 'Header'

    /var/www/.htaccess: Invalid command 'Header'

需要开启模块

    sudo a2enmod headers

### [PHP不能创建目录](http://stackoverflow.com/questions/20563662/mkdir-permission-denied-in-var-www-vtiger-includes-runtime-viewer-php)

```
mkdir(): Permission denied in /var/www/vtiger/includes/runtime/Viewer.php
```
需要修改文件夹拥有者
```
    cd /var/www
    chown -R www-data:www-data .
```
### can't login
Problem can't login {"success":false,"error":{"code":"Illegal request","message":"Illegal request"}}

通过本机地址登陆,密码正确的情况下出现Illegal request
```
vi config.inc.php
$site_URL = 'http://127.0.0.1/';
```

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('taggit', '0003_taggeditem_add_unique_index'),
    ]

    operations = [
        migrations.CreateModel(
            name='Album',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('name', models.CharField(max_length=255)),
                ('slug', models.SlugField()),
                ('date', models.DateField()),
                ('mbid', models.CharField(max_length=255, unique=True)),
                ('popularity', models.FloatField(default=0.0)),
                ('score', models.IntegerField(default=0)),
                ('score_url', models.URLField()),
                ('summary', models.TextField()),
                ('spotify_id', models.CharField(max_length=255)),
                ('spotify_url', models.URLField(blank=True, null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Artist',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('name', models.CharField(max_length=255)),
                ('slug', models.SlugField()),
                ('bio', models.TextField()),
                ('bio_url', models.URLField()),
                ('mbid', models.CharField(max_length=255, unique=True)),
                ('spotify_id', models.CharField(max_length=255)),
                ('spotify_url', models.URLField(blank=True, null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Image',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('large', models.URLField(blank=True, null=True)),
                ('mbid', models.CharField(max_length=255, unique=True)),
                ('medium', models.URLField(blank=True, null=True)),
                ('small', models.URLField(blank=True, null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Publisher',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('name', models.CharField(max_length=255)),
                ('url', models.URLField(unique=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='SonicInfo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('acousticness', models.FloatField(default=0.0)),
                ('danceability', models.FloatField(default=0.0)),
                ('energy', models.FloatField(default=0.0)),
                ('instrumentalness', models.FloatField(default=0.0)),
                ('liveness', models.FloatField(default=0.0)),
                ('loudness', models.FloatField(default=0.0)),
                ('mbid', models.CharField(max_length=255, unique=True)),
                ('speechiness', models.FloatField(default=0.0)),
                ('tempo', models.FloatField(default=0.0)),
                ('valence', models.FloatField(default=0.0)),
                ('mode', models.IntegerField(null=True)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Track',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('duration', models.IntegerField()),
                ('mbid', models.CharField(max_length=255, unique=True)),
                ('name', models.CharField(max_length=255)),
                ('spotify_id', models.CharField(max_length=255)),
                ('spotify_url', models.URLField(blank=True, null=True)),
                ('popularity', models.FloatField(default=0.0)),
                ('track_number', models.IntegerField(null=True)),
                ('album', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.Album')),
                ('sonic_info', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='catalog.SonicInfo')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TaggedArtist',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('content_object', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='catalog.Artist')),
                ('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='catalog_taggedartist_items', to='taggit.Tag')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TaggedAlbum',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('content_object', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='catalog.Album')),
                ('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='catalog_taggedalbum_items', to='taggit.Tag')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Review',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_date', models.DateTimeField(auto_now_add=True)),
                ('updated_date', models.DateTimeField(auto_now=True)),
                ('date', models.DateField(null=True)),
                ('score', models.IntegerField()),
                ('summary', models.TextField()),
                ('url', models.URLField(unique=True)),
                ('album', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.Album')),
                ('publisher', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.Publisher')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AddField(
            model_name='artist',
            name='image',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='catalog.Image'),
        ),
        migrations.AddField(
            model_name='artist',
            name='sonic_info',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='catalog.SonicInfo'),
        ),
        migrations.AddField(
            model_name='artist',
            name='tags',
            field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='catalog.TaggedArtist', to='taggit.Tag', verbose_name='Tags'),
        ),
        migrations.AddField(
            model_name='album',
            name='artist',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='catalog.Artist'),
        ),
        migrations.AddField(
            model_name='album',
            name='image',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='catalog.Image'),
        ),
        migrations.AddField(
            model_name='album',
            name='sonic_info',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='catalog.SonicInfo'),
        ),
        migrations.AddField(
            model_name='album',
            name='tags',
            field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='catalog.TaggedAlbum', to='taggit.Tag', verbose_name='Tags'),
        ),
    ]


text:
Retrieve oAuth Client Id from: https://console.cloud.google.com/apis/credentials

![Cloud Client UI](images/cloud_client_web.png)
[View Cloud Client UI Setup Larger](images/cloud_client_web.png)

### Setup Steps

 1. Google Cloud Project -> APIs & Services -> Credentials -> Create Credentials -> oAuth Client Id.
   1. Select Web.
   1. Name is StarThinker.
   1. Auth Redirect URI is ( you can have several or change them later ):
     - http://localhost:8000/oauth_callback/ ( if you deploy the local UI )
     - http://[your appengine instance ]/oauth_callback/ ( if you deploy on appengine )
     - http://[your custom domain ]/oauth_callback/ ( if you deploy on a custom domain )
 1. Click the download icon next to the new credentials and open the downloaded file.
 1. Copy the contents and paste into the StarThinker deployment script when prompted for Client Web Credentials.

### Change Steps

If you change the Auth Redirect URI you will need to re-download the credentials into StarThinker.

 1. Edit the credentials and add a new Auth Redirect URI.
 1. Click the download icon next to the new credentials and open the downloaded file.
 1. Copy the contents and paste into the StarThinker deployment script when prompted for Client Web Credentials.
   1. ```source install/deploy.sh```
   1. ```7) Change UI Credentials```

### Verify

If all goes well, after deployment, the following file should exist with your credentials inside:

- starthinker_assets/client_web.json

---
© 2019 Google Inc. - Apache License, Version 2.0


text:
  Les Pradeaux est
       un village
       localisé dans le département de Puy-de-Dôme en Auvergne. Elle totalisait 324 habitants en 2008.

À coté de Les Pradeaux sont localisées les villes de
Ceilloux localisée à 7 km, 156 habitants,
Chalus à 4 km, 169 habitants,
Neuville localisée à 3 km, 330 habitants,
Échandelys située à 6 km, 234 habitants,
Saint-Jean-des-Ollières localisée à 6 km, 445 habitants,
Cunlhat située à 7 km, 1 322 habitants,
 entre autres. De plus, Les Pradeaux est située à seulement 27 km de Cournon-d'Auvergne.

Si vous pensez demenager à Les Pradeaux, vous pourrez aisément trouver une maison à acheter.

La commune propose quelques  équipements sportifs, elle propose entre autres un centre d'équitation et un terrain de sport.

Le parc de logements, à Les Pradeaux, se décomposait en 2011 en 30 appartements et 138 maisons soit
 un marché plutôt équilibré.


text:
package org.apache.nifi.web.api.dto.status;

import javax.xml.bind.annotation.XmlType;

/**
 * Detail of a status history metric.
 */
@XmlType(name = "statusHistoryDetail")
public class StatusHistoryDetailDTO {

    private String label;
    private String value;

    /**
     * The label for this status detail.
     *
     * @return
     */
    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    /**
     * The value for this status detail.
     *
     * @return
     */
    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}


text:
/*
 Tests the R error handling in an application
 which embeds R. Here, we generate the error by calling stop().
 We also provide an on.exit() also.
 */

#include "embeddedRCall.h"
#include "R_ext/RStartup.h"

int
main(int argc, char *argv[])
{
    SEXP e;
    int errorOccurred;
    char *localArgs[] = {"R", "--silent"};
    init_R(sizeof(localArgs)/sizeof(localArgs[0]), localArgs);

    /*
      Evaluates the two expressions:
      source("error.R")
      and then calls foo()  twice
      where foo is defined in the file error.R
    */
    PROTECT(e = lang2(install("source"), mkString("error.R")));
    R_tryEval(e, R_GlobalEnv, &errorOccurred);
    UNPROTECT(1);

    PROTECT(e = lang1(install("foo")));
    R_tryEval(e, R_GlobalEnv, &errorOccurred);
    fprintf(stderr, "Trying again (yes it will fail also!)\n");fflush(stderr);
    R_tryEval(e, R_GlobalEnv, &errorOccurred);
    UNPROTECT(1);

    end_R();

    return(0);
}


text:
package com.google.cloud.asset.v1.samples;

// [START asset_v1_generated_assetserviceclient_updatesavedquery_sync]
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.SavedQuery;
import com.google.cloud.asset.v1.UpdateSavedQueryRequest;
import com.google.protobuf.FieldMask;

public class SyncUpdateSavedQuery {

  public static void main(String[] args) throws Exception {
    syncUpdateSavedQuery();
  }

  public static void syncUpdateSavedQuery() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (AssetServiceClient assetServiceClient = AssetServiceClient.create()) {
      UpdateSavedQueryRequest request =
          UpdateSavedQueryRequest.newBuilder()
              .setSavedQuery(SavedQuery.newBuilder().build())
              .setUpdateMask(FieldMask.newBuilder().build())
              .build();
      SavedQuery response = assetServiceClient.updateSavedQuery(request);
    }
  }
}
// [END asset_v1_generated_assetserviceclient_updatesavedquery_sync]


text:
<md-card flex-sm="95" flex-gt-sm="90" flex-gt-md="80">
    <md-card-content>

{{systemSettings.workplace}}

Login to continue.

          <form name="loginForm" ng-submit="login(loginForm.$valid)" novalidate>
            <md-input-container>
              Email Address
              <input type="email" name="email" ng-model="email" required>

This is required!

That's too long!

That's too short!

            </md-input-container>

            <md-input-container>
              Password
              <input name="password" ng-model="password" type="password" required>

This is required!

That's too long!

That's too short!

            </md-input-container>

            <md-button class="md-primary md-raised" type="submit">
              Login
            </md-button>
          </form>
          <md-button ng-click="forgotPwd($event)">Forgot Password?</md-button>
    </md-card-content>
  </md-card>


text:
package com.mcs.mframe.ui.activity;

import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.DecelerateInterpolator;

/**
 * @author mochangsheng
 * @version 1.0
 * @description 该类的主要功能描述
 * @created 2016/12/30
 * @changeRecord [修改记录] <br/>
 */

public abstract class ToolbarActivity extends BaseActivity {

    protected AppBarLayout mAppBar;
    protected Toolbar mToolbar;
    protected boolean mIsHidden = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);//去掉原有的ActionBar
        beforeSetContent();
        setContentView(provideContentViewId());
        mAppBar = (AppBarLayout) findViewById(provideAppBarLayoutId());
        mToolbar = (Toolbar) findViewById(provideToolbarId());
        if (mToolbar == null || mAppBar == null) {
            throw new IllegalStateException(
                    "The subclass of ToolbarActivity must contain a toolbar.");
        }
        mToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onToolbarClick();
            }
        });
        setSupportActionBar(mToolbar);
        if (canBack()) {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) actionBar.setDisplayHomeAsUpEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            mAppBar.setElevation(10.6f);
        }
    }

    public boolean canBack() {
        return false;
    }

    protected void setAppBarAlpha(float alpha) {
        mAppBar.setAlpha(alpha);
    }

    public Toolbar getToolbar() {
        return mToolbar;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    protected void hideOrShowToolbar() {
        mAppBar.animate()
                .translationY(mIsHidden ? 0 : -mAppBar.getHeight())
                .setInterpolator(new DecelerateInterpolator(2))
                .start();
        mIsHidden = !mIsHidden;
    }

    public void onToolbarClick() {

    }

    protected void beforeSetContent() {

    }

    public void setBarTitle(String title) {
        getSupportActionBar().setTitle(title);//mToolbar.setTitle("ninhao")这样设置无效
    }

    /**********抽象方法*************/

    /**
     * 提供layout 资源id
     * @return
     */
    protected abstract int provideContentViewId();

    /**
     * 提供AppBar id
     */
    protected abstract int provideAppBarLayoutId();

    /**
     * 提供Toolbar id
     */
    protected abstract int provideToolbarId();
}


text:
wmi_query                 'Select FreePhysicalMemory from Win32_OperatingSystem'
wmi_query_send_attributes 'FreePhysicalMemory'
collectd_plugin           'memory'
collectd_type             'memory'
collectd_type_instance    'free'
collectd_units_factor     1024


text:
<?php

namespace LaraPayNG\Exceptions;

class UnspecifiedFieldsInTransactionData extends \Exception
{
}


text:
#ifndef BOOST_HANA_DETAIL_NESTED_THAN_FWD_HPP
#define BOOST_HANA_DETAIL_NESTED_THAN_FWD_HPP

#include <boost/hana/config.hpp>

namespace boost { namespace hana { namespace detail {
    template <typename Algorithm>
    struct nested_than_t {
        template <typename X>
        constexpr decltype(auto) operator()(X&& x) const;
    };

    //! @ingroup group-details
    //! Provides a `.than` static constexpr function object.
    //!
    //! When creating a binary function object of type `Algo` whose signature
    //! is `A x B -> Return`, `nested_than<Algo>` can be used as a base class
    //! of `Algo`. Doing so will provide a static constexpr member called
    //! `than`, which has the following signature:
    //! @code
    //!     B -> A -> Return
    //! @endcode
    //!
    //! Note that the function object `Algo` must be default-constructible,
    //! since it will be called as `Algo{}(arguments...)`.
    //!
    //! @note
    //! This function object is especially useful because it takes care of
    //! avoiding ODR violations caused by the nested static constexpr member.
    template <typename Algorithm>
    struct nested_than { static constexpr nested_than_t<Algorithm> than{}; };

    template <typename Algorithm>
    constexpr nested_than_t<Algorithm> nested_than<Algorithm>::than;
} }} // end namespace boost::hana

#endif // !BOOST_HANA_DETAIL_NESTED_THAN_FWD_HPP


text:
classdef (InferiorClasses = {?double}) crdiskmap < scmap

    properties
        crossratio
        affine
        qlgraph
        qdata
        original
        center
        accuracy
    end

    methods
        function map = crdiskmap(poly,varargin)
            %CRDISKMAP Schwarz-Christoffel cross-ratio disk map object.
            %   CRDISKMAP(P) constructs a Schwarz-Christoffel crossratio disk map
            %   object for the polygon P. The parameter problem is solved using
            %   default options for the crossratios of the prevertices.
            %
            %   CRDISKMAP(P,OPTIONS) uses an options structure of the type created
            %   by SCMAPOPT in solving the parameter problem.
            %
            %   CRDISKMAP(P,CR,Q) creates a crdiskmap object having the given
            %   prevertex crossratios CR and quadrilateral graph Q.  An OPTIONS
            %   argument can be added, although only the error tolerance will be
            %   used.
            %
            %   CRDISKMAP(M), where M is a crdiskmap object, just returns M.
            %
            %   CRDISKMAP(M,P) returns a new crdiskmap object for the polygon P
            %   using the options in crdiskmap M. The crossratios in M will be used
            %   as the starting guess for the parameter problem of the new map. Thus
            %   P should properly be a perturbation of the polygon for M. An OPTIONS
            %   structure may be added to override options in M.
            %
            %   Use CRDISKMAP instead of DISKMAP when the polygon has elongations,
            %   or when DISKMAP fails to converge.
            %
            %   See also SCMAPOPT, classes POLYGON, DISKMAP.

            %   Copyright 1998-2001 by Toby Driscoll.

            % Assign empties to optional args
            import sctool.*
            cr = [];
            c = [];
            opt = [];

            % Branch based on class of first argument
            switch class(poly)

                case 'crdiskmap'
                    oldmap = poly;
                    % Continuation of given map to given polygon
                    poly = varargin{1};
                    opt = options(oldmap);
                    cr0 = oldmap.crossratio;
                    if length(cr0) ~= length(poly)-3
                        msg = 'Polygon %s must have the same length as that in %s.';
                        error(msg,inputname(2),inputname(1))
                    end
                    if nargin > 2
                        opt = scmapopt(opt,varargin{2});
                    end
                    opt = scmapopt(opt,'initial',cr0);
                    orig = oldmap.original;

                case 'polygon'
                    % Parse optional arguments
                    for j = 1:length(varargin)
                        arg = varargin{j};
                        % Each arg is an options struct, cr, or quadrilateral graph
                        if isa(arg,'struct')
                            if strmatch('edge',fieldnames(arg))
                                Q = arg;
                            else
                                opt = arg;
                            end
                        elseif length(arg) == length(poly)-3
                            cr = arg;
                            cr = cr(:);
                        else
                            msg = 'Unable to parse argument ''%s''.';
                            error(msg,inputname(j+1))
                        end
                    end

                otherwise
                    msg = 'Expected ''%s'' to be of class polygon or crdiskmap.';
                    error(msg,inputname(1))

            end % switch

            % Retrieve options
            opt = scmapopt(opt);

            % Get data for the low-level functions
            w = vertex(poly);
            beta = angle(poly)-1;

            % Find prevertices if necessary
            if isempty(cr)
                % Apply SCFIX to enforce solver rules
                [w,beta] = scfix('d',w,beta);

                % Solve
                if isempty(opt.InitialGuess)
                    % Standard solution
                    [w,beta,cr,aff,Q,orig,qdata] = ...
                        crparam(w,beta,opt.InitialGuess,opt);
                    % Remake polygon to reflect change in w
                    poly = polygon(w,beta+1);
                else
                    % Continutation syntax
                    [cr,aff,Q] = crparam(w,beta,opt.InitialGuess,opt);
                    nqpts = ceil(-log10(opt.Tolerance));
                    qdata = scqdata(beta,nqpts);
                end

            else
                orig = true(size(w));
                % Base accuracy of quadrature on given options
                nqpts = ceil(-log10(opt.Tolerance));
                qdata = scqdata(beta,nqpts);
            end

            map = map@scmap(poly,opt);

            map.crossratio = cr;
            map.affine = aff;
            map.qlgraph = Q;
            map.qdata = qdata;
            map.original = orig;

            % Set conformal center as center of 1st triangle
            T = Q.qlvert(1:3,1);
            wc = mean(w(T));
            wcfix = crfixwc(w,beta,cr,aff,Q,wc);
            map.center = {wc,wcfix};

            % Now fill in true accuracy
            map.accuracy = accuracy(map);

        end
    end

    methods (Static)
        % Needed by crrectmap
        function varargout = craffine(varargin)
            [varargout{1:nargout}] = craffine(varargin{:});
        end
        function varargout = crembed(varargin)
            [varargout{1:nargout}] = crembed(varargin{:});
        end
        function varargout = imap0(varargin)
            [varargout{1:nargout}] = crimap0(varargin{:});
        end
        function varargout = map0(varargin)
            [varargout{1:nargout}] = crmap0(varargin{:});
        end

    end
end


text:
using namespace cv;
class edgeDetectors
{
public:
    edgeDetectors();
    ~edgeDetectors();

    void detectCar(Mat frame, int index);
};

#endif // EDGEDETECTORS_H


text:
package hcs

import "github.com/sirupsen/logrus"

func logOperationBegin(ctx logrus.Fields, msg string) {
	logrus.WithFields(ctx).Debug(msg)
}

func logOperationEnd(ctx logrus.Fields, msg string, err error) {
	if err == nil {
		logrus.WithFields(ctx).Debug(msg)
	} else {
		logrus.WithFields(ctx).WithError(err).Error(msg)
	}
}


text:
EventPipeBuffer::EventPipeBuffer(unsigned int bufferSize, EventPipeThread* pWriterThread, unsigned int eventSequenceNumber)
{
    CONTRACTL
    {
        THROWS;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;
    m_state = EventPipeBufferState::WRITABLE;
    m_pWriterThread = pWriterThread;
    m_eventSequenceNumber = eventSequenceNumber;
    m_pBuffer = new BYTE[bufferSize];
    memset(m_pBuffer, 0, bufferSize);
    m_pLimit = m_pBuffer + bufferSize;
    m_pCurrent = GetNextAlignedAddress(m_pBuffer);

    QueryPerformanceCounter(&m_creationTimeStamp);
    _ASSERTE(m_creationTimeStamp.QuadPart > 0);
    m_pCurrentReadEvent = NULL;
    m_pPrevBuffer = NULL;
    m_pNextBuffer = NULL;
}

EventPipeBuffer::~EventPipeBuffer()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        // We should never be deleting a buffer that a writer thread might still try to write to
        PRECONDITION(m_state == EventPipeBufferState::READ_ONLY);
    }
    CONTRACTL_END;

    delete[] m_pBuffer;
}

bool EventPipeBuffer::WriteEvent(Thread *pThread, EventPipeSession &session, EventPipeEvent &event, EventPipeEventPayload &payload, LPCGUID pActivityId, LPCGUID pRelatedActivityId, StackContents *pStack)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(((size_t)m_pCurrent % AlignmentSize) == 0);
        // We should never try to write to a buffer that isn't expecting to be written to.
        PRECONDITION(m_state == EventPipeBufferState::WRITABLE);
    }
    CONTRACTL_END;

    // Calculate the size of the event.
    unsigned int eventSize = sizeof(EventPipeEventInstance) + payload.GetSize();

    // Make sure we have enough space to write the event.
    if(m_pCurrent + eventSize > m_pLimit)
        return false;

    bool success = true;
    EX_TRY
    {
        // Calculate the location of the data payload.
        BYTE *pDataDest = payload.GetSize() == 0 ? NULL : m_pCurrent + sizeof(EventPipeEventInstance);

        // Placement-new the EventPipeEventInstance.
        // if pthread is NULL, it's likely we are running in something like a GC thread which is not a Thread object, so it can't have an activity ID set anyway

        StackContents s;
        memset((void *)&s, 0, sizeof(s));
        if (event.NeedStack() && !session.RundownEnabled() && pStack == NULL)
        {
            EventPipe::WalkManagedStackForCurrentThread(s);
            pStack = &s;
        }

        unsigned int procNumber = EventPipe::GetCurrentProcessorNumber();
        EventPipeEventInstance *pInstance = new (m_pCurrent) EventPipeEventInstance(
            event,
            procNumber,
            (pThread == NULL) ?
#ifdef FEATURE_PAL
                ::PAL_GetCurrentOSThreadId()
#else
                ::GetCurrentThreadId()
#endif
                : pThread->GetOSThreadId64(),
            pDataDest,
            payload.GetSize(),
            (pThread == NULL) ? NULL : pActivityId,
            pRelatedActivityId);

        // Copy the stack if a separate stack trace was provided.
        if (pStack != NULL)
        {
            StackContents *pInstanceStack = pInstance->GetStack();
            pStack->CopyTo(pInstanceStack);
        }

        // Write the event payload data to the buffer.
        if (payload.GetSize() > 0)
        {
            payload.CopyData(pDataDest);
        }
    }
    EX_CATCH
    {
        // If a failure occurs, bail out and don't advance the pointer.
        success = false;
    }
    EX_END_CATCH(SwallowAllExceptions);

    if (success)
    {
        // Advance the current pointer past the event.
        m_pCurrent = GetNextAlignedAddress(m_pCurrent + eventSize);
    }

    return success;
}

LARGE_INTEGER EventPipeBuffer::GetCreationTimeStamp() const
{
    LIMITED_METHOD_CONTRACT;

    return m_creationTimeStamp;
}

void EventPipeBuffer::MoveNextReadEvent()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(m_state == EventPipeBufferState::READ_ONLY);
    }
    CONTRACTL_END;

    EventPipeEventInstance *pNextInstance = NULL;

    // If m_pCurrentReadEvent is NULL we've reached the end of the events
    if (m_pCurrentReadEvent != NULL)
    {
        // Confirm that pEvent is within the used range of the buffer.
        if (((BYTE*)m_pCurrentReadEvent < m_pBuffer) || ((BYTE*)m_pCurrentReadEvent >= m_pCurrent))
        {
            _ASSERT(!"Input pointer is out of range.");
            m_pCurrentReadEvent = NULL;
        }
        else
        {
            if (m_pCurrentReadEvent->GetData())
            {
                // We have a pointer within the bounds of the buffer.
                // Find the next event by skipping the current event with it's data payload immediately after the instance.
                m_pCurrentReadEvent = (EventPipeEventInstance *)GetNextAlignedAddress(const_cast<BYTE *>(m_pCurrentReadEvent->GetData() + m_pCurrentReadEvent->GetDataLength()));
            }
            else
            {
                // In case we do not have a payload, the next instance is right after the current instance
                m_pCurrentReadEvent = (EventPipeEventInstance*)GetNextAlignedAddress((BYTE*)(m_pCurrentReadEvent + 1));
            }
            // this may roll over and that is fine
            m_eventSequenceNumber++;

            // Check to see if we've reached the end of the written portion of the buffer.
            if ((BYTE*)m_pCurrentReadEvent >= m_pCurrent)
            {
                m_pCurrentReadEvent = NULL;
            }
        }
    }

    // Ensure that the timestamp is valid.  The buffer is zero'd before use, so a zero timestamp is invalid.
#ifdef DEBUG
    if (m_pCurrentReadEvent != NULL)
    {
        LARGE_INTEGER nextTimeStamp = *m_pCurrentReadEvent->GetTimeStamp();
        _ASSERTE(nextTimeStamp.QuadPart != 0);
    }
#endif
}

EventPipeEventInstance* EventPipeBuffer::GetCurrentReadEvent()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(m_state == READ_ONLY);
    }
    CONTRACTL_END;

    return m_pCurrentReadEvent;
}

unsigned int EventPipeBuffer::GetCurrentSequenceNumber()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
        PRECONDITION(m_state == READ_ONLY);
    }
    CONTRACTL_END;

    return m_eventSequenceNumber;
}

EventPipeThread* EventPipeBuffer::GetWriterThread()
{
    LIMITED_METHOD_CONTRACT;
    return m_pWriterThread;
}

EventPipeBufferState EventPipeBuffer::GetVolatileState()
{
    LIMITED_METHOD_CONTRACT;
    return m_state.Load();
}

void EventPipeBuffer::ConvertToReadOnly()
{
    LIMITED_METHOD_CONTRACT;
    _ASSERTE(m_pWriterThread->GetLock()->OwnedByCurrentThread());
    _ASSERTE(m_pCurrentReadEvent == NULL);
    m_state.Store(EventPipeBufferState::READ_ONLY);

    // If this buffer contains an event, select it.
    BYTE *pFirstAlignedInstance = GetNextAlignedAddress(m_pBuffer);
    if (m_pCurrent > pFirstAlignedInstance)
    {
        m_pCurrentReadEvent = (EventPipeEventInstance*)pFirstAlignedInstance;
    }
    else
    {
        m_pCurrentReadEvent = NULL;
    }
}

#ifdef _DEBUG
bool EventPipeBuffer::EnsureConsistency()
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        MODE_ANY;
    }
    CONTRACTL_END;

    // Check to see if the buffer is empty.
    if (GetNextAlignedAddress(m_pBuffer) == m_pCurrent)
    {
        // Make sure that the buffer size is greater than zero.
        _ASSERTE(m_pBuffer != m_pLimit);
    }

    // Validate the contents of the filled portion of the buffer.
    BYTE *ptr = GetNextAlignedAddress(m_pBuffer);
    while (ptr < m_pCurrent)
    {
        // Validate the event.
        EventPipeEventInstance *pInstance = (EventPipeEventInstance *)ptr;
        _ASSERTE(pInstance->EnsureConsistency());

        // Validate that payload and length match.
        _ASSERTE((pInstance->GetData() != NULL && pInstance->GetDataLength() > 0) || (pInstance->GetData() == NULL && pInstance->GetDataLength() == 0));

        // Skip the event.
        ptr = GetNextAlignedAddress(ptr + sizeof(*pInstance) + pInstance->GetDataLength());
    }

    // When we're done walking the filled portion of the buffer,
    // ptr should be the same as m_pCurrent.
    _ASSERTE(ptr == m_pCurrent);

    // Walk the rest of the buffer, making sure it is properly zeroed.
    while (ptr < m_pLimit)
    {
        _ASSERTE(*ptr++ == 0);
    }

    return true;
}
#endif // _DEBUG

#endif // FEATURE_PERFTRACING


text:
def main(request, response):
  if b"cookie" in request.cookies:
    return (500, [], "Cookie should not be sent to this endpoint")
  return """
{
  "privacy_policy_url": "https://privacypolicy.com"
}
"""


text:
package org.kj6682.frigo;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * Created by luigi on 29/08/16.
 *

 * As its names states clearly, this class is the RestController for the Katering application.
 * In case the Frigo microservice should provide also other interfaces, by mvc and templates for instance,
 * we will provide the appropriated controller.
 *

 * This class wraps the service and exposes it in a defined protocol to clients.
 *

 * No business logic must be implemented in this class.
 *

 * It is not necessary to expose this class as public, so keep it package private.
 */
@ApiV1
@RestController
class FrigoRestController {

    @Autowired
    private FrigoService frigoService;

    @GetMapping(value = "/frigo/{id}")
    Frigo findById(@PathVariable String id) {
        return frigoService.findById(id);

    }

    @GetMapping(value = "/frigo", headers = "frigo.version=v1")
    @ApiImplicitParams({@ApiImplicitParam(name = "frigo.version", required = true, dataType = "string", paramType = "header")})
    List<Frigo> find(@RequestParam(value = "search4me", required = false) String search4me) {

        return frigoService.find(search4me);

    }

    @PostMapping(value = "/frigo")
    void create(@RequestParam(value = "name") String title,
                @RequestParam(value = "since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                @RequestParam(value = "bestBefore") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate bestBefore,
                @RequestParam(value = "quantity", defaultValue = "1") Integer quantity,
                @RequestParam(value = "location") String location) {

        frigoService.insertOne(title, since, bestBefore, quantity, location);

    }

    @PutMapping(value = "/frigo/{id}")
    void update(@PathVariable String id,
                @RequestParam(value = "name", defaultValue = "no name") String name,
                @RequestParam(value = "since") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate since,
                @RequestParam(value = "bestBefore") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate bestBefore,
                @RequestParam(value = "quantity", defaultValue = "1") Integer quantity,
                @RequestParam(value = "location", defaultValue = "nowhere") String location) {

        frigoService.replaceOne(id, name, since, bestBefore, quantity, location);
    }

    @DeleteMapping(value = "/frigo/{id}")
    void delete(@PathVariable String id) {
        frigoService.delete(id);
    }

}


text:
<!DOCTYPE html>

    <title>BMSPushClient Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset='utf-8'>

BMSPush Docs (90% documented)

        BMSPush Reference

        BMSPushClient Class Reference

            Classes

                BMSPushClient

                BMSPushUtils

            Enums

                IMFPushErrorvalues

            Extensions

                Response

BMSPushClient

public class BMSPushClient: NSObject

A singleton that serves as an entry point to Bluemix client- Push service communication.

Properties (Public)

                    sharedInstance

This singleton should be used for all BMSPushClient activity.

Declaration

Swift

public static let sharedInstance = BMSPushClient()

                    clientSecret

Undocumented

Declaration

Swift

public class BMSPushClient: NSObject

                    applicationId

Undocumented

Declaration

Swift

public class BMSPushClient: NSObject

                    overrideServerHost

Undocumented

Declaration

Swift

public class BMSPushClient: NSObject

Initializers

                    initializeWithAppGUID(_:clientSecret:)

The required intializer for the BMSPushClient class.

This method will intialize the BMSPushClient with clientSecret based registration.

Declaration

Swift

public func initializeWithAppGUID (appGUID: String?, clientSecret: String?)

Parameters

                                clientSecret

The clientSecret of the Push Service

                                appGUID

The pushAppGUID of the Push Service

                    initializeWithAppGUID(_:)

The required intializer for the BMSPushClient class.

This method will intialize the BMSPushClient.

Declaration

Swift

public func initializeWithAppGUID (appGUID: String?)

Parameters

                                appGUID

The pushAppGUID of the Push Service

TODO: New method of device registraion with UsrId

                    registerWithDeviceToken(_:WithUserId:completionHandler:)

This Methode used to register the client device to the Bluemix Push service. This is the normal registration, without userId.

Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .

Parameter

    Parameter deviceToken: This is the response we get from the push registartion in APNS.

Parameter

    Parameter WithUserId: This is the userId value.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

Declaration

Swift

public func registerWithDeviceToken(deviceToken:NSData , WithUserId:String?, completionHandler: (response:String?, statusCode:Int?, error:String) -> Void)

Parameters

                                deviceToken

This is the response we get from the push registartion in APNS.

                                WithUserId

This is the userId value.

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

                    registerWithDeviceToken(_:completionHandler:)

This Methode used to register the client device to the Bluemix Push service. This is the normal registration, without userId.

Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .

Parameter

    Parameter deviceToken: This is the response we get from the push registartion in APNS.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

Declaration

Swift

public func registerWithDeviceToken (deviceToken:NSData, completionHandler: (response:String?, statusCode:Int?, error:String) -> Void)

Parameters

                                deviceToken

This is the response we get from the push registartion in APNS.

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

                    registerDeviceToken(_:completionHandler:)

This Methode used to register the client device to the Bluemix Push service.

Call this methode after successfully registering for remote push notification in the Apple Push
Notification Service .

Parameter

    Parameter deviceToken: This is the response we get from the push registartion in APNS.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

Declaration

Swift

public func registerDeviceToken (deviceToken:NSData, completionHandler: (response:String?, statusCode:Int?, error:String) -> Void)

Parameters

                                deviceToken

This is the response we get from the push registartion in APNS.

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

                    retrieveAvailableTagsWithCompletionHandler(_:)

This Method used to Retrieve all the available Tags in the Bluemix Push Service.

This methode will return the list of available Tags in an Array.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).

Declaration

Swift

public func retrieveAvailableTagsWithCompletionHandler (completionHandler: (response:NSMutableArray?, statusCode:Int?, error:String) -> Void)

Parameters

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).

                    subscribeToTags(_:completionHandler:)

This Methode used to Subscribe to the Tags in the Bluemix Push srvice.

This methode will return the list of subscribed tags. If you pass the tags that are not present in the Bluemix App it will be classified under the TAGS NOT FOUND section in the response.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).

Declaration

Swift

public func subscribeToTags (tagsArray:NSArray, completionHandler: (response:NSMutableDictionary?, statusCode:Int?, error:String) -> Void)

Parameters

                                tagsArray

the array that contains name tags.

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).

                    retrieveSubscriptionsWithCompletionHandler(_:)

This Methode used to Retrieve the Subscribed Tags in the Bluemix Push srvice.

This methode will return the list of subscribed tags.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).

Declaration

Swift

public func retrieveSubscriptionsWithCompletionHandler (completionHandler: (response:NSMutableArray?, statusCode:Int?, error:String) -> Void)

Parameters

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (NSMutableArray), StatusCode (Int) and error (string).

                    unsubscribeFromTags(_:completionHandler:)

This Methode used to Unsubscribe from the Subscribed Tags in the Bluemix Push srvice.

This methode will return the details of Unsubscription status.

Parameter

    Parameter tagsArray: The list of tags that need to be unsubscribed.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).

Declaration

Swift

public func unsubscribeFromTags (tagsArray:NSArray, completionHandler: (response:NSMutableDictionary?, statusCode:Int?, error:String) -> Void)

Parameters

                                tagsArray

The list of tags that need to be unsubscribed.

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (NSMutableDictionary), StatusCode (Int) and error (string).

                    unregisterDevice(_:)

This Methode used to UnRegister the client App from the Bluemix Push srvice.

Parameter

    Parameter completionHandler: The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

Declaration

Swift

public func unregisterDevice (completionHandler: (response:String?, statusCode:Int?, error:String) -> Void)

Parameters

                                completionHandler

The closure that will be called when this request finishes. The response will contain response (String), StatusCode (Int) and error (string).

© 2016 IBM Bluemix Services Mobile SDK. All rights reserved. (Last updated: 2016-07-26)

Generated by jazzy ♪♫ v0.7.0, a Realm project.


text:
describe MangoPay::Client do
  include_context 'users'
  include_context 'payins'

  describe 'FETCH' do
    it 'fetches the current client details' do
      clnt = MangoPay::Client.fetch
      expect(clnt['ClientId']).to eq(MangoPay.configuration.client_id)
    end
  end

  describe 'FETCH' do
    it "fetches the client headquarter's phone number" do
      client = MangoPay::Client.fetch
      expect(client['HeadquartersPhoneNumber']).to_not be_nil
    end
  end

  describe 'UPDATE' do
    it 'updates the current client details' do
      clnt = MangoPay::Client.fetch
      before = clnt['PrimaryThemeColour']
      after = before == '#aaaaaa' ? '#bbbbbb' : '#aaaaaa' # change the color
      clnt['PrimaryThemeColour'] = after
      clnt['HeadquartersAddress'] = {
          AddressLine1: 'Rue Dandelion, n. 17',
          City: 'Lyon',
          Country: 'FR',
          PostalCode: '150770'
      }
      clnt['TechEmails'] = ['support@mangopay.com']
      phoneNumber = rand(99999999).to_s
      clnt['HeadquartersPhoneNumber'] = phoneNumber

      updated = MangoPay::Client.update(clnt)
      expect(updated['ClientId']).to eq(MangoPay.configuration.client_id)
      expect(updated['PrimaryThemeColour']).to eq(after)
      expect(updated['HeadquartersPhoneNumber']).to eq(phoneNumber)
    end
  end

  describe 'UPLOAD LOGO' do
    it 'accepts Base64 encoded file content' do
      fnm = __FILE__.sub('.rb', '.png')
      bts = File.open(fnm, 'rb') { |f| f.read }
      b64 = Base64.encode64(bts)
      ret = MangoPay::Client.upload_logo(b64)
      expect(ret).to be_nil
    end

    it 'accepts file path' do
      fnm = __FILE__.sub('.rb', '.png')
      ret = MangoPay::Client.upload_logo(nil, fnm)
      expect(ret).to be_nil
    end

    it 'fails when input string is not base64-encoded' do
      file = 'any file content...'
      expect { MangoPay::Client.upload_logo(file) }.to raise_error { |err|
        expect(err).to be_a MangoPay::ResponseError
        expect(err.code).to eq '400'
        expect(err.type).to eq 'param_error'
      }
    end
  end

  describe 'fetch_wallets' do
    it 'fetches all client wallets' do
      wlts = MangoPay::Client.fetch_wallets
      expect(wlts).to be_kind_of(Array)
      expect(wlts).not_to be_empty
    end

    it 'fetches all client fees wallets' do
      wlts = MangoPay::Client.fetch_wallets('fees')
      expect(wlts).to be_kind_of(Array)
      expect(wlts).not_to be_empty
      expect((wlts.map { |m| m['FundsType'] }).uniq).to eq(['FEES'])
    end

    it 'fetches all client credit wallets' do
      wlts = MangoPay::Client.fetch_wallets('credit')
      expect(wlts).to be_kind_of(Array)
      expect(wlts).not_to be_empty
      expect((wlts.map { |m| m['FundsType'] }).uniq).to eq(['CREDIT'])
    end
  end

  describe 'fetch_wallet' do
    it 'fetches one of client wallets by funds type (fees) and currency' do
      wlt = MangoPay::Client.fetch_wallet('fees', 'EUR')
      expect(wlt).to be_kind_of(Hash)
      expect(wlt['FundsType']).to eq('FEES')
      expect(wlt['Currency']).to eq('EUR')
    end

    it 'fetches one of client wallets by funds type (credit) and currency' do
      wlt = MangoPay::Client.fetch_wallet('credit', 'EUR')
      expect(wlt).to be_kind_of(Hash)
      expect(wlt['FundsType']).to eq('CREDIT')
      expect(wlt['Currency']).to eq('EUR')
    end
  end

  describe 'fetch_wallets_transactions' do
    it 'fetches transactions for all client wallets' do
      trns = MangoPay::Client.fetch_wallets_transactions
      expect(trns).to be_kind_of(Array)
      expect(trns).not_to be_empty
    end
  end

  describe 'fetch_wallets_transactions' do
    it 'fetches transactions of one of client wallets by funds type (fees) and currency' do
      trns = MangoPay::Client.fetch_wallet_transactions('fees', 'EUR')
      expect(trns).to be_kind_of(Array)
      expect(trns).not_to be_empty
      #expect((trns.map {|m| m['DebitedWalletId']}).uniq).to eq(['FEES_EUR'])
    end

    it 'fetches transactions of one of client wallets by funds type (credit) and currency' do
      trns = MangoPay::Client.fetch_wallet_transactions('credit', 'EUR')
      expect(trns).to be_kind_of(Array)
      expect(trns).not_to be_empty
      #expect((trns.map {|m| m['CreditedWalletId']}).uniq).to eq(['CREDIT_EUR'])
    end
  end

  # describe 'validate' do
  #   it 'validates card' do
  #     client = MangoPay::Client.fetch
  #     completed = new_card_registration_completed
  #     card_id = completed['CardId']
  #     client_id = client['ClientId']
  #
  #     card = MangoPay::Client.validate(client_id, card_id)
  #     expect(client).not_to be_nil
  #     expect(card).not_to be_nil
  #   end
  # end

  describe 'create_bank_account' do
    it 'creates a new bank account' do
      bank_account = MangoPay::Client.create_bank_account(Type: 'IBAN',
                                                          OwnerName: 'John',
                                                          OwnerAddress: {
                                                              AddressLine1: 'Le Palais Royal',
                                                              AddressLine2: '8 Rue de Montpensier',
                                                              City: 'Paris',
                                                              Region: '',
                                                              PostalCode: '75001',
                                                              Country: 'FR'
                                                          },
                                                          IBAN: 'FR7630004000031234567890143',
                                                          BIC: 'BNPAFRPP',
                                                          Tag: 'Test bank account')
      expect(bank_account).not_to be_nil
      expect(bank_account['Id']).not_to be_nil
    end
  end

  describe 'create_payout' do
    it 'creates a new payout' do
      wallets = MangoPay::Client.fetch_wallets('FEES')
      bank_account = MangoPay::Client.create_bank_account(Type: 'IBAN',
                                                          OwnerName: 'John',
                                                          OwnerAddress: {
                                                              AddressLine1: 'Le Palais Royal',
                                                              AddressLine2: '8 Rue de Montpensier',
                                                              City: 'Paris',
                                                              Region: '',
                                                              PostalCode: '75001',
                                                              Country: 'FR'
                                                          },
                                                          IBAN: 'FR7630004000031234567890143',
                                                          BIC: 'BNPAFRPP',
                                                          Tag: 'Test bank account')
      pay_out = MangoPay::Client.create_payout(BankAccountId: bank_account['Id'],

                                               DebitedFunds: {
                                                   Currency: 'EUR',
                                                   Amount: 12
                                               },
                                               DebitedWalletId: wallets[0]['Id'],
                                               BankWireRef: 'invoice 7282',
                                               PayoutModeRequested: 'STANDARD',
                                               Tag: 'bla')

      expect(pay_out).not_to be_nil
      expect(pay_out['Id']).not_to be_nil
    end
  end

end