text:
Reyns
=====

Simple yet powerful local (micro) services orchestrator capable of managing entire platforms. Allows to speed up both Dev (every developer can run its own instance of the platform) and Ops (what is put in production is deterministically tested before).

Developed by Stefano Alberto Russo with an important contribution from Gianfranco Gallizia. Thanks also to Enerlife (http://www.enerlife.it) and eXact Lab (http://www.exact-lab.it) for allowing this project to be open source.

# Quick start and demo

**Requirements:** Docker > 1.9.0, Bash, Python 2.7 to 3.6.

To install, run the following commands:

	$ git clone https://github.com/sarusso/Reyns.git
	$ cd Reyns
	$ ./install.sh

To install and run the demo, run the following commands:

	$ reyns install_demo
	Demo installed.
	Quickstart: enter into "reyns-demo", then:
	- to build it, type "reyns build:all"
	- to run it, type "reyns run:all"
	- to see running services, type "reyns ps"
	- to ssh into the "demo", instance "two" service, type "reyns ssh:demo,instance=two"
	 - to ping service "demo", instance "one", type: "ping demo-one"
	 - to exit ssh type "exit"
	- to stop the demo, type "reyns clean:all"

# Documentation

## Introduction and basics

Reyns allow you to manage a set of *services* (defined through Docker images and run as Docker containers) by defining how to build, run and interconnect them in a *project*.

Reyns comes with a base Docker image which you should build all your services, where Supervisor and SSH are installed and configured by default. The default user is named "reyns" and it has the SSH keys for accessing every other service you create on top of the base image. Please note that in production you may want to change the SSH keys and/or the rndc (DNS) key in the "keys" folder.

A project is organised in folders: each service must have its own folder and by default they have to be contained in a top-level folder named "services". Inside the folder of a service, you have to place a Dockerfile which starts with the line:

	FROM reyns/reyns-base-ubuntu14.04

..and with your Dokerfile commands.

The basic usage of Reyns relies on four very simple commands.

- First, you have to build your service using `reyns build:your_service_name`.
- Then, you can run an instance of it by simply typing `reyns run:your_service_name`. In this case a the name chosen for the instance is randomly generated.
-  Once the service is started, you can ssh into is using `reyns ssh:your_service_name`.
-  To turn it off, just use `reyns clean:your_service_name`.

## Building a service

The first thing you probably want to do in your services is to run some applications (or daemons). The suggested way is to use Supervisord. The following Example is taken from Reyns' internal DNS:

    [program:bind]

    ; Process definition
    process_name = bind
    command      = /runbind.sh
    autostart    = true
    autorestart  = true
    startsecs    = 5
    stopwaitsecs = 10
    priority     = 100

    ; Log files
    stdout_logfile          = /var/log/supervisor/%(program_name)s_out.log
    stdout_logfile_maxbytes = 100MB
    stdout_logfile_backups  = 5
    stderr_logfile          = /var/log/supervisor/%(program_name)s_err.log
    stderr_logfile_maxbytes = 100MB
    stderr_logfile_backups  = 5

..and this configuration file (which is named "supervisord_bind.conf") should be placed in supervisor/conf.d/. In your Dockerfile:

    COPY supervisord_bind.conf /etc/supervisor/conf.d/

This approach allows you also to hierarchically extend services. There is also support for executing custom prestartup scripts for each service, hierarchically:

    COPY prestartup_reyns--dns.sh /prestartup/

The Reyns' entrypoint script will execute every script inside the /prestartup/ directory of the service, and it will execute parent's prestartup scripts first. In the service prestartup scripts you also have full access to all environment variables (read the "Environment variables" section for more details about them).

## Running a service

As for the building, place yourself at the level of the apps_services directory, and issue the following command.

    $ reyns run:your_service_name[,instance=your_instance_name, instance_type=standard
                  published/persistent/master/debug, group=your_service_group_name, persistent_data=True/False,
                  persistent_opt=True/False, persistent_log=True/False, publish_ports=True/False,
                  linked=True/False, seed_command=custom_seed_command, safemode=True/False,
                  interactive=True/False, conf=conf_file(default:default.conf), extra_args=None, publish_ssh_on=None]

All the above arguments are explained in detail in the following sections. There are also some env variables

## Services properties

When you run a service using Reyns, there are a few properties already implemented to make the life easier. These are:

* `persistent_data`: if enabled, all the data in /data inside the service is made persistent on the host filesystem (if data is already present, it is preserved).
* `persistent_opt`: if enabled, all the data in /opt inside the services made persistent on the host filesystem (if data is already present, it is preserved).
* `persistent_log`: if enabled, all the data in /var/log inside the service is made persistent on the host filesystem (if data is already present, it is preserved).
* `publish_ports`: if set to true, publish the ports on the host according to Reyns comment-annotations in the Dockerfile (i.e. "# reyns: expose 53/tcp" or "# reyns: expose 53/udp").
* `linked`: linking enabled or not (according to the conf file being used, see later).
* `seed_command`: specify here a custom seed command to execute at the service startup. The default is 'supervisord'.
* `safemode`: if enabled services prestartup scripts will not be executed. See the "Logging and debugging" section for more info.
* `interactive`: provides you an interactive shell. See the "Logging and debugging" section for more info.
* `conf`: the configuration file to use (with or without the ".conf" extension).

## Instances
Reyns introduces the concept of *instances* of the same Docker container (or Reyns service): this is just a naming convention and does not modify in any way how Docker works, but it is an useful logical separation. For example you can have a service running in two instances (i.e. nodeA and nodeB).

A Reyns instance can be of five `instance_type `: **standard**, **published**, **persistent**, **master** and **debug**. The following table summarize the default propertied for the instances types, but no one prevents you from specifying custom settings (command line arguments have the highest possible priority in Reyns)

| Instance name | Intance type| linked | publish ports | persistent data | persisten opt | persistent log | interactive | prestartup executed|
|---------------|-------------|:------:|:-------------:|:---------------:|:-------------:|:--------------:|:-----------:|:------------------:|
|   *      | standard    | YES    | NO            | NO              | NO            | NO             | NO          | YES                |
| published     | published   | YES    | YES           | NO              | NO            | NO             | NO          | YES                |
| persistent    | persistent  | YES    | NO            | YES             | NO            | YES            | NO          | YES                |
| master        | master      | YES*   | YES           | YES             | NO            | YES            | NO          | YES                |
| debug         | debug       | NO     | NO            | NO              | NO            | NO             | YES         | NO                 |

*the linking in an instance of type **master** without using the DNS service (reyns-dns) requires a proper setting of the environment
variables (as explained in the dedicated section "Linking")

*Note:* basically, a master instance is a instance of both types published and persistent.

Examples for running a standard instance:

    $ reyns run:postgres,instance=one
    $ reyns run:postgres,instance=master,instance_type=standard

Examples for running a published instance:

    $ reyns run:postgres,instance=published
    $ reyns run:postgres,instance=one,instance_type=published

Examples for runnign a master instance:

    $ reyns run:postgres,instance=master
    $ reyns run:postgres,instance=one,instance_type=master

There are also two particular ways of running instances of a given type: *interactive* and in *safe mode*.

An instance which run in  **interactive** mode has the particularity that it does not start supervisord, but it start a shell and gives you access to in in the terminal. In an instance which run in **safemode** the the prestartup scripts are not executed, to allow debugging in cases where the instance cannot even start.

You may also want to disable linking by using **linked=False** depending on the use case. You can also have an instance which runs both in safemode and interactively

Example:

    $ reyns run:postgres,instance=one,safemode=True,interactive=True,linked=False

## Taking control of the services

### Environment variables
The resolution of the environment variables follow the priority order reported below:

1. Environment variable vars set at runtime
2. Environment variable specified in the host.conf file
3. Environment variable set int he run conf file being used (i.e. run.cof, or run_published.conf, or...)

The service has full visibility on a fixed set of environment variables, which are:

**SERVICE_IP**: where the service(s) is expected to respond. In particular, the IP used to register the service on the Dynamic DNS, and the IP on which the DNS itself will respond. If not set, docker network IP addresses are used. Mandatory if the instance type is 'master'.

**SERVICE**: service name.

**INSTANCE**: instance name.

**INSTANCE_TYPE**: instance type.

**PERSISTENT_DATA**: if data is set to persisistent or not.

**PERSISTENT_LOG**: if log is set to persisistent or not.

**PERSISTENT_OPT**: if opt is set to persisistent or not.

**SAFEMODE**: if safemode is enabled or not.

**HOST_HOSTNAME**: Host's hostname.

*Note:* If a variable starts with "from_", then Reyns will set the value using the IP of the network interface coming after. In example, "from_eth0" will take the value of the IP address of the host's eth0 network interface.

### Prestartup scripts
Coming soon...

## Project-level management
Concepts..
### Building a project
Coming soon...
### Running a project
Coming soon...

### Linking
**Linking is going to be deprecated in Docker soon**. Reyns supports (and extends) standard style Docker's linking system, but only at project-level thought the run conf settings. Links have to be defined in the run conf file, and can be extended or simple. An extended link works as follows:

    "links": [
               {
                 "name": "MYAPP",
                 "service": "myapp_service",
                 "instance": null
                }
              ]

If this method is used, Reyns set up a link with the linked service by providing an environment  variable named MYAPP_SERVICE_IP in the service linking the MYAPP service.

The above fields should be self-explanatory. The 'null' value in the instance means "Find any running instance of the service 'myapp_service'" and link against it. If more than one instances are found, the link against the first one and issue a warning. You can of course set a name in the instance filed, as 'master', 'one', or 'myinstance1'.

You can also set up quick and simple links by using the following syntax (with wildcards support):

    "links": ["reyns-dns-master:dns"],

which correspond to the following syntax:

    "links": [
               {
                 "name": "dns",
                 "service": "reyns-dns",
                 "instance": "master"
               }
             ]

The suggested way to link services is, anyway, to use Reyns' Dynamic DNS (see section "Reyns Dynamic DNS"). See the relevant sections for more informations about how to use the service. The pro of this approach is that you you can shut down and up any service independently and avoid to end up with a broken linking.

## Reyns' Dynamic DNS

Reyns provides a dynamic DNS service. If enabled, Other services running in the same project
updates their records so that you can interconnect services just by using the hostname. This method
is much more powerful that base Docker linking, as it allows to move a service on another host seamlessly.

To use it in your project, just add it to the conf file following this example:

    [
     {
      "service": "reyns-dns",
      "instance": "master",
      "sleep": 0,
      "links": [],
      "env_vars": {"SERVICE_IP":"from_eth0" }
      },
     {
      "service": "reyns-base",
      "instance": "one",
      "sleep": 0,
      "links": ["reyns-dns-master:dns"],
      },
     {
      "service": "reyns-base",
      "instance": "two",
      "sleep": 0,
      "links": [],
      "env_vars": {"DNS_SERVICE_IP": "from_eth0" }
       },
      {
      "service": "demo",
      "instance": "one",
      "sleep": 0,
      "links": [
                 {
                   "name": "BASE",
                   "service": "reyns-base",
                   "instance": null
                  }
                ]
      }
     ]

You can see this example in action by just typing 'reyns install_demo' and following the quickstart.

After this, you should be able to contact the DNS service and ask it your local zone members (e.g. via `host dns.local.zone.`).

Note that for enabling the DNS service the connection can both be established using the standard linking and just by setting the DNS_SERVICE_IP env var.

Services register themselves on the DNS both as their hostname (i.e. "demo-one") and as their service name (i.e. "demo"). The behaviour on how to handle the service name (i.e. "demo") in case of multiple instances (i.e. "demo-one" and "demo-two") depends on the update policy, which is defined thought the environment variable DNS_UPDATE_POLICY and can follow three different approaches:

- **DNS_UPDATE_POLICY="HIDE"**: The service is not published to the DNS at all, but the DNS service is queryable. Useful for testing purposes as an "observer".

- **DNS_UPDATE_POLICY="REPLACE"** *(default)*: the DNS record corresponding to the service name, if already present, is replaced. In other words, if there are two instances of the same service running and you query the DNS for the service name, only the IP address of the last instance will be provided. Useful for hot-updating servers.

- **DNS_UPDATE_POLICY="APPEND"**: In this case the DNS record corresponding to the service name is appended, so if there are two instances of the same service running and you query the DNS for the service name, both the IPs of the instances will be provided (in Round Robin). Particularly useful for scaling up. Please note that scaling down and re-running services is not supported for now, as removing records from the DNS is not yet supported.

**Notes:**

If running in published mode, be sure that nothing is listening on port 53 both TCP **AND** UDP (E.G.
dnsmasq or bind) on **your** host because DNS queries are sent through
UDP but DNS updates are sent through TCP so both need to be available.

Also, you might want to increase the sleep timer to allow bind to set up in the DNS service.

Thanks to Gianfranco Gallizia and eXact Lab (http://www.exact-lab.it/) for this contribution.

## Multi-node setup
While not one of its core features, Reyns support to deploy project across multiple nodes. This requires publishing all necessary ports for inter-node communications as well as the DNS service. please not that this setup is suited for private networks _only_. Never publish Reyns' dynamic DNS on a public IP.

To configure a multi-node setup, you can start from the demo, using the "default-multinode.conf" file as a guide. To test on a single node before going multi-node, just install the demo somewhere (with "reyns install_demo") but instead of following the quick start run the following commands:

    $ reyns run:group=master,conf=default-multinode
    $ reyns run:group=node1,conf=default-multinode
    $ reyns run:group=node2,conf=default-multinode

You will be asked for the DNS_SERVICE_IP env var: here you need to put the external IP address of the external network interface.

Test with:

    $ reyns ssh:demo,onenode2
    reyns@demo-onenode2:~$ ping demo-onenode1

**Note:** the  "default-multinode.conf" file shipped with the demo assume the network interface "eth0" as the external interface (the "from_eth0" placeholder). You can change (i..e on en0 for macOS) or just replace it with the external IP address instead of the ""

## Logging and debugging

To enable the debug mode, just set the "LOG_LEVEL" env var to "DEBUG". for example:

    $ LOG_LEVEL=DEBUG reyns run:postgres,instance=master

If you instance does not run as expect when starting (and since it does not start you cannot ssh in it) you can try few things:

First of all, you can try to run in in an interactive way:

    $ reyns run:postgres,instance=master,interactive=True

This will run the services prestartup scripts and and give you a shell. You can then type 'supervisord' to start the service as normal (but still interactively).

If you have errors in the execution of the prestartup scripts for some services, you can use the safemode, which just runs  Reyns's prestartup (that should never fail) and not the service prestarup scripts

    $ reyns run:postgres,instance=master,safemode=True

You can also combine the two, which is probably the most useful approach:

    $ reyns run:postgres,instance=master,interactive=True,safemode=True

..and you can execute the prestartup scripts in the interactive mode just by typing /prestartup.sh.

Note: Sometimes you can get an error similar to "mv: inter-device move failed error". In this case, and in partiucular if you are running with persistent data enabled,  you can try to temporary rename the data dir to understand why the error arise.

## Troubleshooting
In case of a failure in the building process: first of all, retry building (maybe temporary network problem). If error persist, try building without cache (i.e. reyns build:all,cache=False), fis till no errors, try to re-init base containers (reyns init). Also check disk space both on local filesystem and in the virtual machine filesystem if on Windows or Mac.

# Licensing
Reyns is licensed under the Apache License, Version 2.0. See
[LICENSE](https://raw.githubusercontent.com/sarusso/Reyns/master/LICENSE) for the full
license text.


text:
layout: page
title: Tough Red Entertainment Trade Fair
date: 2016-05-24
author: Adam Fry
tags: weekly links, java
status: published
summary: Fusce convallis odio ac sollicitudin placerat. Sed vitae feugiat mauris.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 12/02/2018
  endDate: 12/05/2018
  ctyhocn: CGICGHX
  groupCode: TRETF
published: true
---
Vivamus hendrerit vehicula magna nec viverra. Vivamus pellentesque, augue imperdiet convallis sollicitudin, turpis tortor semper massa, in condimentum quam urna at enim. Nam quis gravida nibh. Donec risus nibh, consectetur vel aliquet dapibus, placerat et orci. Curabitur eu tellus quam. Proin egestas, nulla et mollis vestibulum, nisl lacus tincidunt urna, at efficitur dolor metus in dolor. Aenean dignissim convallis felis. Nulla iaculis pellentesque sagittis. Donec mattis laoreet mi, nec aliquam lectus posuere eu. Curabitur pretium ipsum sit amet tincidunt blandit. Etiam ultrices risus id lorem ultrices blandit. Proin sed faucibus tellus, ut vulputate nisi.

* In porttitor leo vel magna vestibulum, a tempus risus tristique
* Mauris id massa nec odio semper ultrices ut ac odio
* Sed dapibus metus vitae elit suscipit semper.

Nunc dapibus nec tortor ac placerat. Sed ultricies rhoncus massa in iaculis. Fusce ullamcorper vulputate ipsum, scelerisque convallis ipsum maximus a. Aenean vel felis bibendum, consectetur dolor sed, tincidunt urna. Vestibulum consectetur pulvinar scelerisque. Nulla a mauris non enim faucibus porta euismod eget turpis. Suspendisse auctor ligula sed malesuada tincidunt. Quisque luctus dolor vitae enim ullamcorper, sed tincidunt mi maximus. Vivamus dictum ipsum quis dui laoreet, et tristique eros tincidunt.

redpajama_set_name: RedPajamaGithub


text:
  Saint-Samson est
       un village
       géographiquement positionné dans le département des Calvados en Basse-Normandie. Elle comptait 348 habitants en 2008.

Si vous pensez emmenager à Saint-Samson, vous pourrez facilement trouver une maison à acheter.

À coté de Saint-Samson sont localisées les villes de
Touffréville localisée à 4 km, 301 habitants,
Saint-Pierre-du-Jonquet située à 2 km, 174 habitants,
Janville à 2 km, 380 habitants,
Banneville-la-Campagne située à 4 km, 99 habitants,
Saint-Pair localisée à 2 km, 237 habitants,
Troarn située à 1 km, 3 645 habitants,
 entre autres. De plus, Saint-Samson est située à seulement quatorze km de Caen.

Le nombre de logements, à Saint-Samson, était réparti en 2011 en trois appartements et 125 maisons soit
 un marché relativement équilibré.


text:
"use strict";

/* MOCKUP */
(function () {
  // VARIABLES
  var mockupCloseButton = document.getElementById('mockupCloseButton'),
      mockupContainer = document.getElementById('mockupContainer'),
      mockupButton = document.getElementById('mockupButton'); // FUNCTION

  function showOverlay(callback) {
    mockupContainer.classList.add('mockup__container--open');
    setTimeout(callback);
  }

  function showCloseButton() {
    mockupCloseButton.classList.add('is-visible');
  } // CLICK EVENTS

  mockupButton.addEventListener('click', function () {
    event.preventDefault();
    showOverlay(showCloseButton);
  });
  mockupCloseButton.addEventListener('click', function () {
    mockupContainer.classList.remove('mockup__container--open');
    mockupCloseButton.classList.remove('is-visible');
  });
})();


text:
import * as vscode from 'vscode';
import { telemetryService } from '../telemetry';
import { OrgAuthInfo, workspaceUtils } from '../util';

export enum OrgType {
  SourceTracked,
  NonSourceTracked
}

export async function getWorkspaceOrgType(
  defaultUsernameOrAlias?: string
): Promise<OrgType> {
  if (!defaultUsernameOrAlias) {
    const e = new Error();
    e.name = 'NoDefaultusernameSet';
    throw e;
  }
  const username = await OrgAuthInfo.getUsername(defaultUsernameOrAlias);
  const isScratchOrg = await OrgAuthInfo.isAScratchOrg(username).catch(err =>
    telemetryService.sendException(
      'get_workspace_org_type_scratch_org',
      err.message
    )
  );
  return isScratchOrg ? OrgType.SourceTracked : OrgType.NonSourceTracked;
}

export function setWorkspaceOrgTypeWithOrgType(orgType: OrgType) {
  setDefaultUsernameHasChangeTracking(orgType === OrgType.SourceTracked);
  setDefaultUsernameHasNoChangeTracking(orgType === OrgType.NonSourceTracked);
}

export async function setupWorkspaceOrgType(defaultUsernameOrAlias?: string) {
  try {
    setHasDefaultUsername(!!defaultUsernameOrAlias);
    const orgType = await getWorkspaceOrgType(defaultUsernameOrAlias);
    setWorkspaceOrgTypeWithOrgType(orgType);
  } catch (e) {
    console.error(e);
    if (e instanceof Error) {
      telemetryService.sendException('send_workspace_org_type', e.message);
      switch (e.name) {
        case 'NamedOrgNotFound':
          // If the info for a default username cannot be found,
          // then assume that the org can be of either type
          setDefaultUsernameHasChangeTracking(true);
          setDefaultUsernameHasNoChangeTracking(true);
          break;
        case 'NoDefaultusernameSet':
          setDefaultUsernameHasChangeTracking(false);
          setDefaultUsernameHasNoChangeTracking(false);
          break;
        default:
          setDefaultUsernameHasChangeTracking(true);
          setDefaultUsernameHasNoChangeTracking(true);
      }
    }
  }
}

function setDefaultUsernameHasChangeTracking(val: boolean) {
  vscode.commands.executeCommand(
    'setContext',
    'sfdx:default_username_has_change_tracking',
    val
  );
}

function setDefaultUsernameHasNoChangeTracking(val: boolean) {
  vscode.commands.executeCommand(
    'setContext',
    'sfdx:default_username_has_no_change_tracking',
    val
  );
}

function setHasDefaultUsername(val: boolean) {
  vscode.commands.executeCommand(
    'setContext',
    'sfdx:has_default_username',
    val
  );
}

export async function getDefaultUsernameOrAlias(): Promise<string | undefined> {
  if (workspaceUtils.hasRootWorkspace()) {
    return await OrgAuthInfo.getDefaultUsernameOrAlias(true);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DayEarn
{
    class DayEarn
    {
        static void Main(string[] args)
        {
            var workDaysInMonth = double.Parse(Console.ReadLine());
            var moneyEarnPerDay = double.Parse(Console.ReadLine());
            var KursUSD = double.Parse(Console.ReadLine());

            var monthPayment = workDaysInMonth * moneyEarnPerDay;
            var yearIncome = (monthPayment * 12) + (monthPayment * 2.5);
            var valueTax = (yearIncome * 25) / 100;
            var nettoYearIncome = (yearIncome - valueTax) * KursUSD;
            var middleEarnPerDay = nettoYearIncome / 365;

            {
                Console.WriteLine("{0:F2}", middleEarnPerDay);
            }
        }
    }
}


text:
require 'test_helper'

class Salesforce::CaseFeedTest < ActiveSupport::TestCase
  def test_should_return_case_feeds
    # see 'test_helper.rb' for USERID, PASSWORD, and SECURITY_TOKEN
    # Salesforce::SfBase.login(USERID, PASSWORD, SECURITY_TOKEN)
    user = Salesforce::User.first

    case_feeds = Array.new
    case_feeds = Salesforce::CaseFeed.find(:all).count
    assert_not_nil case_feeds
  end
end


text:
"""Module for pull and push command."""
import abc
from base64 import b64decode
import six
from six.moves import configparser

from ..core.exceptions import AuthyTokenIssue
from ..core.api import API
from ..core.commands import AbstractCommand
from ..core.models.terminal import clean_order
from .client.controllers import ApiController
from .client.cryptor import RNCryptor
from ..core.storage.strategies import RelatedGetStrategy, SyncSaveStrategy

@six.add_metaclass(abc.ABCMeta)
class CloudSynchronizationCommand(AbstractCommand):
    """Base class for pull and push commands."""

    def extend_parser(self, parser):
        """Add more arguments to parser."""
        parser.add_argument('-p', '--password', metavar='PASSWORD')
        return parser

    @abc.abstractmethod
    def process_sync(self, api_controller):
        """Do sync staff here."""

    # pylint: disable=no-self-use
    def prompt_authy_token(self):
        """Ask authy token prompt."""
        return six.moves.input('Authy token: ')

    def take_action(self, parsed_args):
        """Process CLI call."""
        encryption_salt = b64decode(self.config.get('User', 'salt'))
        hmac_salt = b64decode(self.config.get('User', 'hmac_salt'))
        password = parsed_args.password
        if password is None:
            password = self.prompt_password()
        try:
            self.validate_password(password)
        except AuthyTokenIssue:
            self.log.error('Authy token is invalid.')
            return
        cryptor = RNCryptor()
        cryptor.password = password
        cryptor.encryption_salt = encryption_salt
        cryptor.hmac_salt = hmac_salt
        controller = ApiController(self.storage, self.config, cryptor)
        with self.storage:
            self.process_sync(controller)

    def validate_password(self, password):
        """Raise an error when password invalid."""
        username = self.config.get('User', 'username')
        api = API()
        try:
            api.login(username, password)
        except AuthyTokenIssue:
            authy_token = self.prompt_authy_token()
            api.login(username, password, authy_token=authy_token)

class PushCommand(CloudSynchronizationCommand):
    """push data to the Termius Cloud"""

    get_strategy = RelatedGetStrategy
    save_strategy = SyncSaveStrategy

    def process_sync(self, api_controller):
        """Push outdated local instances."""
        try:
            api_controller.put_setting()
            api_controller.post_bulk()
        except (configparser.NoSectionError, configparser.NoOptionError):
            self.log.error('Call pull at first.')
        else:
            self.log.info('Data delivered successfully')

class PullCommand(CloudSynchronizationCommand):
    """pull data from the Termius Cloud"""

    save_strategy = SyncSaveStrategy

    def process_sync(self, api_controller):
        """Pull updated remote instances."""
        api_controller.get_settings()
        api_controller.get_bulk()
        self.log.info('Data successfully collected')

class FullCleanCommand(CloudSynchronizationCommand):
    """remove user data from the Termius Cloud"""

    get_strategy = RelatedGetStrategy
    save_strategy = SyncSaveStrategy

    supported_models = clean_order

    def process_sync(self, api_controller):
        """Pull updated remote instances."""
        api_controller.get_bulk()
        with self.storage:
            self.full_clean()
        api_controller.post_bulk()
        self.log.info('Full clean data from Termius cloud.')

    def full_clean(self):
        """Remove all local and remote instances."""
        for model in self.supported_models:
            self.log.info('Start cleaning %s...', model)
            instances = self.storage.get_all(model)
            for i in instances:
                self.storage.delete(i)
            self.log.info('Complete cleaning')

class CryptoCommand(CloudSynchronizationCommand):
    """encrypt and decrypt text"""

    def extend_parser(self, parser):
        """Add more arguments to parser."""
        super(CryptoCommand, self).extend_parser(parser)
        parser.add_argument(
            '-d', '--decrypt',
            action='store_const', const='decrypt',
            dest='operation'
        )
        parser.add_argument(
            '-e', '--encrypt',
            action='store_const', const='encrypt',
            dest='operation'
        )
        parser.add_argument(
            'text',
            nargs=1,
            metavar='TEXT',
            action='store',
            help='string data'
        )
        return parser

    def process_sync(self, api_controller):
        """Do sync staff here."""

    def take_action(self, parsed_args):
        """Process decrypt and encrypt text."""
        encryption_salt = b64decode(self.config.get('User', 'salt'))
        hmac_salt = b64decode(self.config.get('User', 'hmac_salt'))
        password = parsed_args.password
        if password is None:
            password = self.prompt_password()
        self.validate_password(password)
        cryptor = RNCryptor()
        cryptor.password = password
        cryptor.encryption_salt = encryption_salt
        cryptor.hmac_salt = hmac_salt

        for i in parsed_args.text:
            result_text = getattr(cryptor, parsed_args.operation)(i)
            self.app.stdout.write('{}\n'.format(result_text))


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php  echo $language;  ?>" lang="<?php  echo $language;  ?>">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<meta http-equiv="Content-Language" content="<?php  echo $language;  ?>" />
	<title><?php  echo $name;  ?> - <?php  echo $title;  ?> - Powered by TQBlog</title>

    <meta name="keywords" content="<?php  echo $keywords;  ?>" />
	<meta name="description" content="<?php  echo $description;  ?>" />
    <meta name="generator" content="<?php  echo $tqblogphp;  ?>" />
	<meta name="author" content="<?php  echo $tqauthor;  ?>" />
	<meta name="copyright" content="2008-2028 tqtqtq.com" />
	<meta name="MSSmartTagsPreventParsing" content="True" />
	<meta http-equiv="MSThemeCompatible" content="Yes" />

	<link rel="shortcut icon" href="<?php  echo $host;  ?>favicon.ico" />
	<link rel="stylesheet" rev="stylesheet" href="<?php  echo $host;  ?>content/theme/<?php  echo $theme;  ?>/style/<?php  echo $style;  ?>.css" type="text/css" media="all"/>
	<script src="<?php  echo $host;  ?>admin/script/common.js" type="text/javascript"></script>
	<script src="<?php  echo $host;  ?>admin/script/html_util.php" type="text/javascript"></script>
<?php  echo $header;  ?>
<?php if ($type=='index' && $page=='1') { ?>
	<link rel="alternate" type="application/rss+xml" href="<?php  echo $feedurl;  ?>" title="<?php  echo $name;  ?>" />
	<link rel="EditURI" type="application/rsd+xml" title="RSD" href="<?php  echo $host;  ?>admin/xmlrpc/?rsd" />
	<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="<?php  echo $host;  ?>admin/xmlrpc/wlwmanifest.xml" />
<?php }else{  ?>
	<link rel="alternate" type="application/rss+xml" href="<?php  echo $feedurl;  ?>" title="<?php  echo $name;  ?>" />
<?php } ?>


text:
namespace wsiToDicomConverter {

inline OFCondition generateFramePositionMetadata(DcmDataset* resultObject,
                                                 uint32_t numberOfFrames,
                                                 uint32_t rowSize, uint32_t row,
                                                 uint32_t column, uint32_t x,
                                                 uint32_t y) {
  std::unique_ptr<DcmSequenceOfItems> PerFrameFunctionalGroupsSequence =
      std::make_unique<DcmSequenceOfItems>(
          DCM_PerFrameFunctionalGroupsSequence);
  for (uint32_t frameNumber = 0; frameNumber < numberOfFrames; frameNumber++) {
    if (column > rowSize) {
      column = 1;
      row++;
    }
    std::string index = std::to_string(column) + "\\" + std::to_string(row);
    std::unique_ptr<DcmItem> dimension = std::make_unique<DcmItem>();
    dimension->putAndInsertString(DCM_DimensionIndexValues, index.c_str());

    std::unique_ptr<DcmSequenceOfItems> sequenceDimension =
        std::make_unique<DcmSequenceOfItems>(DCM_FrameContentSequence);
    sequenceDimension->insert(dimension.release());

    std::unique_ptr<DcmItem> pixelPosition = std::make_unique<DcmItem>();
    pixelPosition->putAndInsertSint32(DCM_ColumnPositionInTotalImagePixelMatrix,
                                      (column - 1) * x + 1);
    pixelPosition->putAndInsertSint32(DCM_RowPositionInTotalImagePixelMatrix,
                                      (row - 1) * y + 1);

    std::unique_ptr<DcmSequenceOfItems> sequencePosition =
        std::make_unique<DcmSequenceOfItems>(DCM_PlanePositionSlideSequence);
    sequencePosition->insert(pixelPosition.release());

    std::unique_ptr<DcmItem> positionItem = std::make_unique<DcmItem>();
    positionItem->insert(sequenceDimension.release());
    positionItem->insert(sequencePosition.release());
    PerFrameFunctionalGroupsSequence->insert(positionItem.release());
    column++;
  }
  return resultObject->insert(PerFrameFunctionalGroupsSequence.release());
}

inline OFCondition generateSharedFunctionalGroupsSequence(
    DcmDataset* resultObject, double pixelSizeWidthMm,
    double pixelSizeHeightMm) {
  if (pixelSizeWidthMm <= 0) {
    pixelSizeWidthMm = 0.1;
  }
  if (pixelSizeHeightMm <= 0) {
    pixelSizeHeightMm = 0.1;
  }
  std::unique_ptr<DcmItem> sharedFunctionalGroupsSequence =
      std::make_unique<DcmItem>();
  std::unique_ptr<DcmItem> pixelMeasuresSequence = std::make_unique<DcmItem>();
  std::string pixelSizeMmStr = std::to_string(pixelSizeHeightMm) + "\\" +
                               std::to_string(pixelSizeWidthMm);

  pixelMeasuresSequence->putAndInsertString(DCM_PixelSpacing,
                                            pixelSizeMmStr.c_str());
  sharedFunctionalGroupsSequence->insertSequenceItem(
      DCM_PixelMeasuresSequence, pixelMeasuresSequence.release());
  return resultObject->insertSequenceItem(
      DCM_SharedFunctionalGroupsSequence,
      sharedFunctionalGroupsSequence.release());
}

inline std::unique_ptr<DcmItem> pointerItem(char* dimensionOrganizationUIDstr) {
  std::unique_ptr<DcmItem> pointerItem = std::make_unique<DcmItem>();
  pointerItem->putAndInsertOFStringArray(DCM_DimensionOrganizationUID,
                                         dimensionOrganizationUIDstr);
  std::unique_ptr<DcmAttributeTag> slideSequence =
      std::make_unique<DcmAttributeTag>(DCM_FunctionalGroupPointer);
  slideSequence->putTagVal(DCM_PlanePositionSlideSequence);
  std::unique_ptr<DcmAttributeTag> columnPosition =
      std::make_unique<DcmAttributeTag>(DCM_DimensionIndexPointer);
  columnPosition->putTagVal(DCM_ColumnPositionInTotalImagePixelMatrix);
  pointerItem->insert(slideSequence.release());
  pointerItem->insert(columnPosition.release());
  return pointerItem;
}

inline OFCondition generateDimensionIndexSequence(DcmDataset* resultObject) {
  std::unique_ptr<DcmItem> dimensionOrganizationUID =
      std::make_unique<DcmItem>();
  char dimensionOrganizationUIDstr[100];
  dimensionOrganizationUID->putAndInsertOFStringArray(
      DCM_DimensionOrganizationUID,
      dcmGenerateUniqueIdentifier(dimensionOrganizationUIDstr,
                                  SITE_STUDY_UID_ROOT));
  std::unique_ptr<DcmSequenceOfItems> dimensionOrganizationSequence =
      std::make_unique<DcmSequenceOfItems>(DCM_DimensionOrganizationSequence);
  dimensionOrganizationSequence->insert(dimensionOrganizationUID.release());
  resultObject->insert(dimensionOrganizationSequence.release());

  std::unique_ptr<DcmSequenceOfItems> sequence =
      std::make_unique<DcmSequenceOfItems>(DCM_DimensionIndexSequence);
  sequence->insert(pointerItem(dimensionOrganizationUIDstr).release());
  sequence->insert(pointerItem(dimensionOrganizationUIDstr).release());
  return resultObject->insert(sequence.release());
}

std::string formatTime(absl::string_view format) {
  std::string format_str = std::move(static_cast<std::string>(format));
  std::stringstream stringStream;
  struct tm utcTime;
  time_t timeNow = time(nullptr);
  gmtime_r(&timeNow, &utcTime);
  stringStream << std::put_time(&utcTime, format_str.c_str());
  return stringStream.str();
}

std::string currentDate() { return formatTime("%Y%m%d"); }
std::string currentTime() { return formatTime("%OH%OM%OS"); }

OFCondition insertPixelMetadata(DcmDataset* dataset,
                                const DcmtkImgDataInfo& imgInfo,
                                uint32_t numberOfFrames) {
  OFCondition cond =
      dataset->putAndInsertUint16(DCM_SamplesPerPixel, imgInfo.samplesPerPixel);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertOFStringArray(DCM_PhotometricInterpretation,
                                            imgInfo.photoMetrInt);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_PlanarConfiguration, imgInfo.planConf);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_Rows, imgInfo.rows);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_Columns, imgInfo.cols);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_BitsAllocated, imgInfo.bitsAlloc);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_BitsStored, imgInfo.bitsStored);
  if (cond.bad()) return cond;

  cond = dataset->putAndInsertUint16(DCM_HighBit, imgInfo.highBit);
  if (cond.bad()) return cond;

  if (numberOfFrames >= 1) {
    char buf[10];
    int err = snprintf(buf, sizeof(buf), "%u", numberOfFrames);
    if (err == -1) return EC_IllegalCall;
    cond = dataset->putAndInsertOFStringArray(DCM_NumberOfFrames, buf);
    if (cond.bad()) return cond;

    std::string lossy = "00";
    if (imgInfo.transSyn == EXS_JPEGProcess1) {
      lossy = "01";
      cond = dataset->putAndInsertOFStringArray(DCM_LossyImageCompressionMethod,
                                                  "ISO_10918_1", true);
      if (cond.bad()) return cond;
      cond = dataset->putAndInsertOFStringArray(DCM_LossyImageCompressionRatio,
                                        imgInfo.compressionRatio.c_str());
      if (cond.bad()) return cond;
    }
    cond = dataset->putAndInsertOFStringArray(DCM_LossyImageCompression,
                                                lossy.c_str(), true);

    // DerivationDescription is text constructed from image source
    // and frame generation text.  See dcmFileDraft.cpp for
    // construction of image source and frame representation components.
    if (cond.bad()) return cond;
    cond = dataset->putAndInsertOFStringArray(DCM_DerivationDescription,
                                         imgInfo.derivationDescription.c_str(),
                                         true);
    if (cond.bad()) return cond;
  }
  return dataset->putAndInsertUint16(DCM_PixelRepresentation,
                                     imgInfo.pixelRepr);
}

OFCondition generateDcmDataset(I2DOutputPlug* outPlug, DcmDataset* resultDset,
                               const DcmtkImgDataInfo& imgInfo,
                               uint32_t numberOfFrames) {
  if (!outPlug) return EC_IllegalParameter;

  OFCondition cond = insertPixelMetadata(resultDset, imgInfo, numberOfFrames);

  if (cond.bad()) {
    return cond;
  }

  cond = outPlug->convert(*resultDset);
  if (cond.bad()) {
    return cond;
  }

  if (cond.bad()) {
    return cond;
  }
  return EC_Normal;
}

OFCondition DcmtkUtils::populateDataSet(
    const int64_t imageHeight, const int64_t imageWidth,
    const uint32_t rowSize, absl::string_view studyId,
    absl::string_view seriesId, absl::string_view imageName,
    std::unique_ptr<DcmPixelData> pixelData,
    const DcmtkImgDataInfo& imgInfo, const uint32_t numberOfFrames,
    const uint32_t row, const uint32_t column, const int32_t instanceNumber,
    const int32_t downsample, const int batchNumber, const uint32_t offset,
    const uint32_t totalNumberOfFrames, const bool tiled,
    DcmTags* additionalTags, const double firstLevelWidthMm,
    const double firstLevelHeightMm, DcmDataset* dataSet) {
  std::unique_ptr<I2DOutputPlug> outPlug;

  OFString pixDataFile, outputFile;

  outPlug = std::make_unique<I2DOutputPlugSC>();
  if (outPlug.get() == nullptr) return EC_MemoryExhausted;

  OFBool insertType2 = OFTrue;
  OFBool inventType1 = OFTrue;
  OFBool doChecks = OFTrue;

  outPlug->setValidityChecking(doChecks, insertType2, inventType1);

  if (!dcmDataDict.isDictionaryLoaded()) {
    dcmDataDict.wrlock().reloadDictionaries(true, false);
    dcmDataDict.wrunlock();
  }

  OFCondition cond =
      generateDcmDataset(outPlug.get(), dataSet, imgInfo, numberOfFrames);

  if (cond.bad()) return cond;

  cond = dataSet->insert(pixelData.release());
  if (cond.bad()) return cond;

  cond = generateDateTags(dataSet);

  if (cond.bad()) return cond;

  cond = insertIds(studyId, seriesId, dataSet);

  if (cond.bad()) return cond;

  cond = insertBaseImageTags(imageName, imageHeight, imageWidth,
                             firstLevelWidthMm, firstLevelHeightMm, dataSet);

  if (cond.bad()) return cond;

  insertMultiFrameTags(imgInfo, numberOfFrames, rowSize, row, column,
                       instanceNumber, batchNumber, offset,
                       totalNumberOfFrames, tiled, seriesId, dataSet);
  if (cond.bad()) return cond;

  cond = insertStaticTags(dataSet, downsample);

  if (cond.bad()) return cond;

  cond = generateSharedFunctionalGroupsSequence(
      dataSet, firstLevelWidthMm / static_cast<double>(imageWidth),
               firstLevelHeightMm / static_cast<double>(imageHeight));
  if (cond.bad()) return cond;

  cond = generateDimensionIndexSequence(dataSet);

  if (cond.bad()) return cond;

  if (additionalTags != nullptr) {
    additionalTags->populateDataset(dataSet);
  }

  return cond;
}

OFCondition DcmtkUtils::generateDateTags(DcmDataset* dataSet) {
  OFCondition cond = dataSet->putAndInsertOFStringArray(DCM_ContentDate,
                                                        currentDate().c_str());
  if (cond.good())
    cond = dataSet->putAndInsertOFStringArray(DCM_ContentTime,
                                              currentTime().c_str());
  return cond;
}

OFCondition DcmtkUtils::insertStaticTags(DcmDataset* dataSet, int downsample) {
  OFCondition cond = dataSet->putAndInsertOFStringArray(
      DCM_SOPClassUID, UID_VLWholeSlideMicroscopyImageStorage);
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(DCM_Modality, "SM");
  if (cond.bad()) return cond;
  if (downsample <= 1) {
    cond = dataSet->putAndInsertOFStringArray(DCM_ImageType,
                                          "ORIGINAL\\PRIMARY\\VOLUME\\NONE");
  } else {
    cond = dataSet->putAndInsertOFStringArray(DCM_ImageType,
                                     "DERIVED\\PRIMARY\\VOLUME\\RESAMPLED");
  }
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(DCM_ImageOrientationSlide,
                                            "0\\-1\\0\\-1\\0\\0");
  if (cond.bad()) return cond;
  dataSet->putAndInsertUint16(DCM_RepresentativeFrameNumber, 1);

  return cond;
}

OFCondition DcmtkUtils::insertIds(absl::string_view studyId,
                                  absl::string_view seriesId,
                                  DcmDataset* dataSet) {
  char instanceUidGenerated[100];
  dcmGenerateUniqueIdentifier(instanceUidGenerated, SITE_INSTANCE_UID_ROOT);
  OFCondition cond = dataSet->putAndInsertOFStringArray(DCM_SOPInstanceUID,
                                                        instanceUidGenerated);
  if (cond.bad()) return cond;
  std::string studyId_str = std::move(static_cast<std::string>(studyId));
  cond =
      dataSet->putAndInsertOFStringArray(DCM_StudyInstanceUID,
                                         studyId_str.c_str());
  if (cond.bad()) return cond;
  std::string seriesId_str = std::move(static_cast<std::string>(seriesId));
  cond = dataSet->putAndInsertOFStringArray(DCM_SeriesInstanceUID,
                                            seriesId_str.c_str());
  return cond;
}

OFCondition DcmtkUtils::insertBaseImageTags(absl::string_view imageName,
                                            const int64_t imageHeight,
                                            const int64_t imageWidth,
                                            const double firstLevelWidthMm,
                                            const double firstLevelHeightMm,
                                            DcmDataset* dataSet) {
  std::string imageName_str = std::move(static_cast<std::string>(imageName));
  OFCondition cond;
  if (imageName_str.length() > 0) {
    cond = dataSet->putAndInsertOFStringArray(DCM_SeriesDescription,
                                              imageName_str.c_str());
    if (cond.bad()) return cond;
  }
  cond = dataSet->putAndInsertUint32(DCM_TotalPixelMatrixColumns, imageWidth);
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertUint32(DCM_TotalPixelMatrixRows, imageHeight);
  if (firstLevelWidthMm > 0 && firstLevelHeightMm > 0 && cond.good()) {
    cond =
        dataSet->putAndInsertFloat32(DCM_ImagedVolumeWidth, firstLevelWidthMm);
    if (cond.bad()) return cond;
    cond = dataSet->putAndInsertFloat32(DCM_ImagedVolumeHeight,
                                        firstLevelHeightMm);
  }
  return cond;
}

OFCondition DcmtkUtils::insertMultiFrameTags(
    const DcmtkImgDataInfo& imgInfo, const uint32_t numberOfFrames,
    const uint32_t rowSize, const uint32_t row, const uint32_t column,
    const int instanceNumber, const int batchNumber, const uint32_t offset,
    const uint32_t totalNumberOfFrames, const bool tiled,
    absl::string_view seriesId, DcmDataset* dataSet) {
  unsigned int concatenationTotalNumber;
  std::string seriesId_str = std::move(static_cast<std::string>(seriesId));

  if (totalNumberOfFrames - offset == numberOfFrames) {
    concatenationTotalNumber = batchNumber + 1;
  } else {
    concatenationTotalNumber =
        std::ceil(static_cast<double>(totalNumberOfFrames) /
                  static_cast<double>(numberOfFrames));
  }

  OFCondition cond = dataSet->putAndInsertOFStringArray(
      DCM_InstanceNumber, std::to_string(instanceNumber).c_str());
  if (concatenationTotalNumber > 1 && cond.good()) {
    cond =
        dataSet->putAndInsertUint32(DCM_ConcatenationFrameOffsetNumber, offset);
    if (cond.bad()) return cond;
    cond =
        dataSet->putAndInsertUint16(DCM_InConcatenationNumber, batchNumber + 1);
    if (cond.bad()) return cond;
    cond = dataSet->putAndInsertUint16(DCM_InConcatenationTotalNumber,
                                       concatenationTotalNumber);
    if (cond.bad()) return cond;
    cond = dataSet->putAndInsertOFStringArray(
        DCM_ConcatenationUID,
        (seriesId_str + "." + std::to_string(instanceNumber)).c_str());
  }
  if (cond.bad()) return cond;
  cond = dataSet->putAndInsertOFStringArray(
      DCM_FrameOfReferenceUID,
      (seriesId_str + "." + std::to_string(instanceNumber)).c_str());
  if (cond.bad()) return cond;
  if (tiled) {
    cond = dataSet->putAndInsertOFStringArray(DCM_DimensionOrganizationType,
                                              "TILED_FULL");
  } else {
    cond = dataSet->putAndInsertOFStringArray(DCM_DimensionOrganizationType,
                                              "TILED_SPARSE");
    if (cond.bad()) return cond;
    cond = generateFramePositionMetadata(dataSet, numberOfFrames, rowSize, row,
                                         column, imgInfo.rows, imgInfo.cols);
  }
  return cond;
}

OFCondition DcmtkUtils::startConversion(
    int64_t imageHeight, int64_t imageWidth, uint32_t rowSize,
    absl::string_view studyId, absl::string_view seriesId,
    absl::string_view imageName, std::unique_ptr<DcmPixelData> pixelData,
    const DcmtkImgDataInfo& imgInfo, uint32_t numberOfFrames, uint32_t row,
    uint32_t column, const int32_t instanceNumber, const int32_t downsample,
    int batchNumber, uint32_t offset, uint32_t totalNumberOfFrames,
    bool tiled, DcmOutputStream* outStream) {
  return startConversion(imageHeight, imageWidth, rowSize, studyId, seriesId,
                         imageName, std::move(pixelData), imgInfo,
                         numberOfFrames, row, column, instanceNumber,
                         downsample, batchNumber, offset, totalNumberOfFrames,
                         tiled, nullptr, 0.0, 0.0, outStream);
}

OFCondition DcmtkUtils::startConversion(
    int64_t imageHeight, int64_t imageWidth, uint32_t rowSize,
    absl::string_view studyId, absl::string_view seriesId,
    absl::string_view imageName, std::unique_ptr<DcmPixelData> pixelData,
    const DcmtkImgDataInfo& imgInfo, uint32_t numberOfFrames, uint32_t row,
    uint32_t column, const int32_t instanceNumber, const int32_t downsample,
    int batchNumber, unsigned int offset, uint32_t totalNumberOfFrames,
    bool tiled, DcmTags* additionalTags, double firstLevelWidthMm,
    double firstLevelHeightMm, DcmOutputStream* outStream) {
  E_GrpLenEncoding grpLenEncoding = EGL_recalcGL;
  E_EncodingType encodingType = EET_ExplicitLength;
  E_PaddingEncoding paddingEncoding = EPD_noChange;
  uint8_t filepad = 0;
  uint8_t itempad = 0;
  E_FileWriteMode writeMode = EWM_fileformat;

  std::unique_ptr<DcmDataset> resultObject = std::make_unique<DcmDataset>();

  OFCondition cond = populateDataSet(
      imageHeight, imageWidth, rowSize, studyId, seriesId, imageName,
      std::move(pixelData), imgInfo, numberOfFrames, row, column,
      instanceNumber, downsample, batchNumber, offset, totalNumberOfFrames,
      tiled, additionalTags, firstLevelWidthMm, firstLevelHeightMm,
      resultObject.get());

  DcmFileFormat dcmFileFormat(resultObject.get());

  DcmWriteCache wcache;
  cond = outStream->status();
  if (cond.good()) {
    dcmFileFormat.transferInit();
    cond = dcmFileFormat.write(*outStream, imgInfo.transSyn, encodingType,
                               &wcache, grpLenEncoding, paddingEncoding,
                               OFstatic_cast(Uint32, filepad),
                               OFstatic_cast(Uint32, itempad), 0, writeMode);
    dcmFileFormat.transferEnd();
  }
  if (cond.bad()) {
    BOOST_LOG_TRIVIAL(error) << "error"
                             << ": " << cond.text();
  }
  return cond;
}

}  // namespace wsiToDicomConverter


text:
namespace blink {

class Document;
class ProcessingInstruction;

class DocumentXSLT final : public GarbageCollected<DocumentXSLT>,
                           public Supplement<Document> {
  USING_GARBAGE_COLLECTED_MIXIN(DocumentXSLT);

 public:
  static const char kSupplementName[];

  Document* TransformSourceDocument() {
    return transform_source_document_.Get();
  }

  void SetTransformSourceDocument(Document* document) {
    DCHECK(document);
    transform_source_document_ = document;
  }

  static DocumentXSLT& From(Document&);

  // The following static methods don't use any instance of DocumentXSLT.
  // They are just using DocumentXSLT namespace.
  static void ApplyXSLTransform(Document&, ProcessingInstruction*);
  static ProcessingInstruction* FindXSLStyleSheet(Document&);
  static bool ProcessingInstructionInsertedIntoDocument(Document&,
                                                        ProcessingInstruction*);
  static bool ProcessingInstructionRemovedFromDocument(Document&,
                                                       ProcessingInstruction*);
  static bool SheetLoaded(Document&, ProcessingInstruction*);
  static bool HasTransformSourceDocument(Document&);

  explicit DocumentXSLT(Document&);
  void Trace(Visitor*) override;

 private:
  Member<Document> transform_source_document_;
  DISALLOW_COPY_AND_ASSIGN(DocumentXSLT);
};

}  // namespace blink

#endif


text:
using System;
using System.Linq;
using Bytes2you.Validation.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Bytes2you.Validation.UnitTests.GuardTests
{
    [TestClass]
    public class Constructors_Should
    {
        [TestMethod]
        public void NotBePublic()
        {
            // Act.
            bool hasPublicConstructors = typeof(Guard).HasPublicConstructors();

            // Assert.
            Assert.IsFalse(hasPublicConstructors);
        }
    }
}


text:
<?php

/**
 * GridField config necessary for managing a SiteTree object.
 *
 * @package silverstripe
 * @subpackage blog
 */
class GridFieldConfig_BlogPost extends GridFieldConfig_Lumberjack {
	/**
	 * @param null|int $itemsPerPage
	 */
	public function __construct($itemsPerPage = null) {
		parent::__construct($itemsPerPage);

		$this->removeComponentsByType('GridFieldSiteTreeState');
		$this->addComponent(new GridFieldBlogPostState());
	}
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Database\Driver\mysql\Install\Tasks.
 */

namespace Drupal\Core\Database\Driver\mysql\Install;

use Drupal\Core\Database\Install\Tasks as InstallTasks;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Driver\mysql\Connection;
use Drupal\Core\Database\DatabaseNotFoundException;

/**
 * Specifies installation tasks for MySQL and equivalent databases.
 */
class Tasks extends InstallTasks {
  /**
   * The PDO driver name for MySQL and equivalent databases.
   *
   * @var string
   */
  protected $pdoDriver = 'mysql';

  /**
   * Constructs a \Drupal\Core\Database\Driver\mysql\Install\Tasks object.
   */
  public function __construct() {
    $this->tasks[] = array(
      'arguments' => array(
        'SET NAMES utf8mb4',
        'The %name database server supports utf8mb4 character encoding.',
        'The %name database server must support utf8mb4 character encoding to work with Drupal. Make sure to use a database server that supports utf8mb4 character encoding, such as MySQL/MariaDB/Percona versions 5.5.3 and up.',
      ),
    );
    $this->tasks[] = array(
      'arguments' => array(),
      'function' => 'ensureInnoDbAvailable',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function name() {
    return t('MySQL, MariaDB, Percona Server, or equivalent');
  }

  /**
   * {@inheritdoc}
   */
  public function minimumVersion() {
    return '5.5.3';
  }

  /**
   * {@inheritdoc}
   */
  protected function connect() {
    try {
      // This doesn't actually test the connection.
      db_set_active();
      // Now actually do a check.
      Database::getConnection();
      $this->pass('Drupal can CONNECT to the database ok.');
    }
    catch (\Exception $e) {
      // Attempt to create the database if it is not found.
      if ($e->getCode() == Connection::DATABASE_NOT_FOUND) {
        // Remove the database string from connection info.
        $connection_info = Database::getConnectionInfo();
        $database = $connection_info['default']['database'];
        unset($connection_info['default']['database']);

        // In order to change the Database::$databaseInfo array, need to remove
        // the active connection, then re-add it with the new info.
        Database::removeConnection('default');
        Database::addConnectionInfo('default', 'default', $connection_info['default']);

        try {
          // Now, attempt the connection again; if it's successful, attempt to
          // create the database.
          Database::getConnection()->createDatabase($database);
        }
        catch (DatabaseNotFoundException $e) {
          // Still no dice; probably a permission issue. Raise the error to the
          // installer.
          $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage())));
        }
      }
      else {
        // Database connection failed for some other reason than the database
        // not existing.
        $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.

Is the database server running?

Does the database exist or does the database user have sufficient privileges to create the database?

Have you entered the correct database name?

Have you entered the correct username and password?

Have you entered the correct database hostname?

', array('%error' => $e->getMessage())));
        return FALSE;
      }
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormOptions(array $database) {
    $form = parent::getFormOptions($database);
    if (empty($form['advanced_options']['port']['#default_value'])) {
      $form['advanced_options']['port']['#default_value'] = '3306';
    }

    return $form;
  }

  /**
   * Ensure that InnoDB is available.
   */
  function ensureInnoDbAvailable() {
    $engines = Database::getConnection()->query('SHOW ENGINES')->fetchAllKeyed();
    if (isset($engines['MyISAM']) && $engines['MyISAM'] == 'DEFAULT' && !isset($engines['InnoDB'])) {
      $this->fail(t('The MyISAM storage engine is not supported.'));
    }
  }

}


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>elasticsearch-integrated</title>
    <link rel="stylesheet" type="text/css" href="css/blue-glass/sidebar.css" />

head

kopf

inquisitor

hq

bigdesk

segmentspy

paramedic

sql


text:
/* $Id$ */

package org.apache.fop.render.pcl;

// FOP
import org.apache.fop.render.AbstractGenericSVGHandler;
import org.apache.fop.render.Renderer;
import org.apache.fop.render.RendererContext;

/**
 * PCL XML handler for SVG. Uses Apache Batik for SVG processing.
 * This handler handles XML for foreign objects when rendering to HP GL/2.
 * It renders SVG to HP GL/2 using the PCLGraphics2D.
 */
public class PCLSVGHandler extends AbstractGenericSVGHandler {

    /** {@inheritDoc} */
    public boolean supportsRenderer(Renderer renderer) {
        return false;
    }

    /** {@inheritDoc} */
    protected void updateRendererContext(RendererContext context) {
        //Work around a problem in Batik: Gradients cannot be done in ColorSpace.CS_GRAY
        context.setProperty(PCLRendererContextConstants.PCL_COLOR_CANVAS,
                Boolean.TRUE);
    }

}


text:
import tl = require("vsts-task-lib/task");

var taskJson = require("./task.json");
const area: string = "CreateCampaign";
var createsend = require("createsend-node");
var sleep = require("thread-sleep");
import * as fs from "fs";

function getDefaultProps() {
    var hostType = (tl.getVariable("SYSTEM.HOSTTYPE") || "").toLowerCase();
    return {
        hostType: hostType,
        definitionName: hostType === "release" ? tl.getVariable("RELEASE.DEFINITIONNAME") : tl.getVariable("BUILD.DEFINITIONNAME"),
        processId: hostType === "release" ? tl.getVariable("RELEASE.RELEASEID") : tl.getVariable("BUILD.BUILDID"),
        processUrl: hostType === "release" ? tl.getVariable("RELEASE.RELEASEWEBURL") : (tl.getVariable("SYSTEM.TEAMFOUNDATIONSERVERURI") + tl.getVariable("SYSTEM.TEAMPROJECT") + "/_build?buildId=" + tl.getVariable("BUILD.BUILDID")),
        taskDisplayName: tl.getVariable("TASK.DISPLAYNAME"),
        jobid: tl.getVariable("SYSTEM.JOBID"),
        agentVersion: tl.getVariable("AGENT.VERSION"),
        version: taskJson.version
    };
}

function publishEvent(feature, properties: any): void {
    try {
        var splitVersion = (process.env.AGENT_VERSION || "").split(".");
        var major = parseInt(splitVersion[0] || "0");
        var minor = parseInt(splitVersion[1] || "0");
        let telemetry = "";
        if (major > 2 || (major === 2 && minor >= 120)) {
            telemetry = `##vso[telemetry.publish area=${area};feature=${feature}]${JSON.stringify(Object.assign(getDefaultProps(), properties))}`;
        }
        else {
            if (feature === "reliability") {
                let reliabilityData = properties;
                telemetry = "##vso[task.logissue type=error;code=" + reliabilityData.issueType + ";agentVersion=" + tl.getVariable("Agent.Version") + ";taskId=" + area + "-" + JSON.stringify(taskJson.version) + ";]" + reliabilityData.errorMessage;
            }
        }
        console.log(telemetry);
    }
    catch (err) {
        tl.warning("Failed to log telemetry, error: " + err);
    }
}

function getErrorMessage(err): string {
    if (err) {
        if (err.Message) {
            return err.Message;
        }
    }

    return err;
}

async function sendPreview(api: any, campaignId: string, recipients: string[]): Promise<any> {
    return new Promise<any>(async (resolve, reject) => {

        var previewDetails = {
            "PreviewRecipients": recipients,
            "Personalize": "Random"
        };

        await api.campaigns.sendPreview(campaignId, previewDetails, (err, res) => {
            if (err) {
                var errorMessage = getErrorMessage(err);
                console.log(err);
                reject(errorMessage);
            } else {
                console.log(`Preview sent`);
                resolve();
            }
        });
    });
}

async function run(): Promise<number>  {
    var promise = new Promise<number>(async (resolve, reject) => {

        try {
            const authenticationType: string = tl.getInput("CampaignMonitorAuthenticationType", true);
            const apiKey: string = tl.getInput("CampaignMonitorApiKey");
            const authToken: string = tl.getInput("CampaignMonitorAuthToken");
            const clientId: string = tl.getInput("CampaignMonitorClientId");
            const listId: string = tl.getInput("CampaignMonitorListId");
            const templateId: string = tl.getInput("CampaignMonitorTemplateId");
            const fromEmailAddress: string = tl.getInput("CampaignMonitorFromEmailAddress");
            const replyToEmailAddress: string = tl.getInput("CampaignMonitorReplyToEmailAddress");
            const campaignName: string = tl.getInput("CampaignMonitorCampaignName");
            const campaignSubject: string = tl.getInput("CampaignMonitorCampaignSubject");
            const previewRecipients: string = tl.getInput("CampaignMonitorPreviewRecipients");
            const fromName: string = tl.getInput("CampaignMonitorFromName");
            const singleLines: string = tl.getInput("CampaignMonitorSingleLines");
            const multipleLinesSourceType: string = tl.getInput("CampaignMonitorMultipleLinesSourceType");
            const multipleLinesInline: string = tl.getInput("CampaignMonitorMultipleLinesInline");
            const multipleLinesFilePath: string = tl.getInput("CampaignMonitorMultipleLinesFilePath");

            // Get the multiple lines text
            let multipleLines: string;

            switch (multipleLinesSourceType.toLowerCase()) {
                case "inline":
                    multipleLines = JSON.parse(multipleLinesInline);
                    break;
                case "file":
                    if (!fs.existsSync(multipleLinesFilePath)) {
                        reject(`Failed to locate the multiple lines file on disk ${multipleLinesFilePath}`);
                        return;
                    }

                    multipleLines = JSON.parse(fs.readFileSync(multipleLinesFilePath, "utf8"));
                    break;
                default:
                    throw "Failed to parse the argument [CampaignMonitorMultipleLinesSourceType], expected 'Inline' or 'File'.";
            }

            var opts = {};

            if (authenticationType.toLowerCase() === "apikey") {
                if (!apiKey) {
                    reject("Api Key was not supplied");
                    return;
                } else {
                    opts = {
                        apiKey: apiKey
                    };
                }
            } else if (authenticationType.toLowerCase() === "authtoken") {
                if (!authToken) {
                    reject("Auth Token was not supplied");
                    return;
                } else {
                    opts = {
                        accessToken: authToken
                    };
                }
            } else {
                reject(`AuthenticationType ${authenticationType} is invalid`);
                return;
            }

            var api = new createsend(opts);

            var details = {
                "Name": campaignName,    // name of the campaign
                "Subject": campaignSubject,       // subject of the campaign
                "FromName": fromName,       // "from" name
                "FromEmail": fromEmailAddress,      // "from" email address
                "ReplyTo": replyToEmailAddress,        // "reply to" email address
                "ListIDs": [listId], // array of lists to send the campaign to
                "TemplateID": templateId,     // id of the template
                "TemplateContent": {        // only an example, follow the instructions at https://www.campaignmonitor.com/api/campaigns/#creating-campaign-template to match your template
                    "Multilines": multipleLines,
                    "Singlelines": JSON.parse(singleLines)
                }
            };

            console.log(`Creating campaign...`);
            await api.campaigns.createFromTemplate(clientId, details, async (err, res) => {
                if (err) {
                    var errorMessage = getErrorMessage(err);
                    console.log(err);
                    reject(errorMessage);
                } else {
                    var campaignId = res.campaignId;
                    console.log(`Campaign created successfully with Id [${campaignId}]`);

                    if (previewRecipients) {
                        console.log(`Sending Preview...`);
                        var parsedRecipients = previewRecipients.split(",");

                        let retries = 3;
                        let success = false;
                        let attempts = 0;
                        let errors = new Array<string>();

                        while (retries-- > 0 && success === false) {
                            attempts++;
                            console.log(`Sending preview: Attempt ${attempts} of ${attempts + retries}`);
                            await sendPreview(api, campaignId, parsedRecipients).then(data => {
                                success = true;
                                resolve(campaignId);
                            }).catch(reason => {
                                tl.warning(`Failed to send preview, retrying in 5 seconds...`);
                                sleep(5000);
                                errors.push(reason);
                            });
                        }

                        if (!success) {
                            // manually set the output variable
                            tl.setVariable("CampaignMonitorCampaignId", campaignId);

                            tl.warning(`The campaign was created successfully, but sending the preview failed.`);
                            reject(errors.join(", "));
                        } else {
                            resolve(campaignId);
                        }

                    } else {
                        resolve(campaignId);
                    }
                }
            });

        } catch (err) {
            reject(err);
        }
    });

    return promise;
}

run()
    .then((result) => {
            tl.setVariable("CampaignMonitorCampaignId", result.toString());
            tl.setResult(tl.TaskResult.Succeeded, "");
        }
    )
    .catch((err) => {
        publishEvent("reliability", { issueType: "error", errorMessage: JSON.stringify(err, Object.getOwnPropertyNames(err)) });
        tl.setResult(tl.TaskResult.Failed, err);
    });


text:
<?xml version="1.0" encoding="UTF-8"?><data jsxid="jsxroot">
  <record group="object" include="master.xml"/>

  <record group="1" jsxid="jsx3list" jsxtext="List">
    <record disallow="[^0-9]" docdefault="jsx3.gui.List.DEFAULTHEADERHEIGHT. See the API documentation for this component." docgetter="getHeaderHeight" docsetter="setHeaderHeight" eval="1" jsxid="jsxheaderheight" jsxmask="jsxtext" jsxtext="Header Height" jsxtip="Sets the height of the header row in implied pixels. Only positive integers are allowed. Set to 0 if the list does not use a header."/>

    <record disallow="[^-0-9a-zA-Z#\(\);:\/\.,]" docdefault="jsx3.gui.List.DEFAULTBACKGROUNDCOLORHEAD. See the API documentation for this component." docgetter="getBackgroundColorHead" docsetter="setBackgroundColorHead" eval="0" jsxid="jsxbgcolorhead" jsxmask="jsxcolor" jsxtext="BG Color Head" jsxtip="Sets the background color of the header row of the list. Accepts valid CSS values, such as predefined color names, RGB, or hexadecimal values. For example, red, rgb(255,0,0), or #ff0000."/>
    <record disallow="'" docdefault="jsx3.gui.List.DEFAULTBACKGROUNDHEAD. See the API documentation for this component." docgetter="getBackgroundHead" docsetter="setBackgroundHead" eval="0" jsxid="jsxbghead" jsxmask="jsxtext" jsxtext="Background Head" jsxtip="Sets the CSS background property for the header row. For example, background-image:url(abc.gif);background-repeat:repeat-x;."/>

    <record group="box_list" include="master.xml"/>

    <record children="1" group="jsxrequired" include="master.xml"/>
    <record docdefault="Multi-Select (jsx3.gui.List.MULTI)" docgetter="getMultiSelect" docsetter="setMultiSelect" eval="1" jsxexecute="objJSX.setMultiSelect(vntValue);" jsxid="jsxmultiselect" jsxmask="jsxselect" jsxtext="Selectable" jsxtip="Sets whether or not the list is multi-select, single-select, or not selectable.">
      <enum jsxid="jsx3.gui.List.MULTI" jsxtext="Multi-Select"/>
      <enum jsxid="jsx3.gui.List.SINGLE" jsxtext="Single-Select"/>
      <enum jsxid="jsx3.gui.List.NOTSELECTABLE" jsxtext="Not Selectable"/>
    </record>

    <record group="column_interactions" include="master.xml"/>
    <record children="1" group="drag" include="master.xml"/>

    <record group="1" jsxid="myspy" jsxtext="Spyglass">
      <record include="master.xml" path="/data/record[@jsxid='move']/record[@jsxid='jsxspy']"/>
    </record>

    <record children="1" group="list" include="master.xml"/>

  </record>

  <record group="blockx" include="master.xml"/>
  <record include="master.xml" path="/data/record[@jsxid='font']/record[@jsxid='jsxfontname' or @jsxid='jsxfontsize']"/>

  <record include="master.xml" path="/data/record[@jsxid='css']/record[@jsxid!='jsxstyleoverride']"/>

  <record include="master.xml" path="/data/record[@jsxid='jsxmenu']/*"/>
  <record include="master.xml" path="//record[@jsxid='jsxindex']"/>
  <record group="metadata" include="master.xml"/>
</data>


text:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.utils import add_postgis_srs

class Command(BaseCommand):
    args = '<srid>'
    help = 'Add Custom SRID'

    def handle(self, *args, **options):
        srid = args[0]
        try:
            add_postgis_srs(srid)
        except:
            raise CommandError('Problem adding SRID: %s' % srid)

        self.stdout.write('Successfully added SRID "%s"' % srid)


text:
package om.sstvencoder.Output;

public interface IOutput {
    double getSampleRate();

    void init(int samples);

    void write(double value);

    void finish(boolean cancel);
}