text:
<template name="candidateActionCell">

        Edit
        {{#if process}}
            View
                Process
        {{/if}}
        {{> quickRemoveButton collection="Candidates" _id=candidate._id onError=onError onSuccess=onSuccess beforeRemove=beforeRemove class="btn btn-danger btn-link text-danger"}}

</template>
<template name="teamActionCell">

        {{#afModal class="btn btn-link" collection="Teams" operation="update" doc=_id}}
            Edit
        {{/afModal}}
        {{> quickRemoveButton collection="Teams" _id=team._id onError=onError onSuccess=onSuccess beforeRemove=beforeRemove class="btn btn-danger btn-link text-danger"}}

</template>
<template name="vacancyActionCell">

        {{#afModal class="btn btn-link" collection="Vacancies" operation="update" doc=_id}}
            Edit
        {{/afModal}}
        {{> quickRemoveButton collection="Vacancies" _id=vacancy._id onError=onError onSuccess=onSuccess beforeRemove=beforeRemove class="btn btn-danger btn-link text-danger"}}

</template>
<template name="teamNameCell">
    {{teamName}}
</template>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ibatis.submitted.typehandler;

import org.apache.ibatis.annotations.Arg;
import org.apache.ibatis.annotations.ConstructorArgs;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.submitted.typehandler.Product.ProductId;
import org.apache.ibatis.type.JdbcType;

public interface Mapper {

  @Select("select * from users where id = #{value}")
  @Results({
    @Result(column="id", property="id"),
    @Result(column="name", property="name"),
    @Result(column="city", property="city", jdbcType=JdbcType.CHAR),
    @Result(column="state", property="state", jdbcType=JdbcType.VARCHAR)
  })
  User getUser(Integer id);

  @Insert({
    "insert into product (name) values (#{name})"
  })
  @Options(useGeneratedKeys = true, keyProperty = "id")
  int insertProduct(Product product);

  @Select("select id, name from product where name = #{value}")
  Product getProductByName(String name);

  Product getProductByNameXml(String name);

  @Select("select id, name from product where name = #{value}")
  @ConstructorArgs({
    @Arg(id = true, column="id", javaType = ProductId.class, jdbcType=JdbcType.INTEGER),
    @Arg(column="name")
  })
  Product getProductByNameUsingConstructor(String name);

  @Select("select id from product where name = #{value}")
  ProductId getProductIdByName(String name);
}


text:
/**
 * Number.isInteger() polyfill
 * @function external:Number#isInteger
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger Number.isInteger}
 */
if (!Number.isInteger) {
  Number.isInteger = function isInteger(nVal) {
    return typeof nVal === "number" && isFinite(nVal) && nVal > -
      9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) ===
      nVal;
  };
}

function ChecktypeError(key, type, value) {
  return SyntaxError(key + ' param should be a ' + (type.name || type) +
    ', not ' + value.constructor.name);
}

//
// Basic types
//

function checkArray(type, key, value) {
  if (!(value instanceof Array))
    throw ChecktypeError(key, 'Array of ' + type, value);

  value.forEach(function (item, i) {
    checkType(type, key + '[' + i + ']', item);
  })
};

function checkBoolean(key, value) {
  if (typeof value != 'boolean')
    throw ChecktypeError(key, Boolean, value);
};

function checkNumber(key, value) {
  if (typeof value != 'number')
    throw ChecktypeError(key, Number, value);
};

function checkInteger(key, value) {
  if (!Number.isInteger(value))
    throw ChecktypeError(key, 'Integer', value);
};

function checkObject(key, value) {
  if (typeof value != 'object')
    throw ChecktypeError(key, Object, value);
};

function checkString(key, value) {
  if (typeof value != 'string')
    throw ChecktypeError(key, String, value);
};

// Checker functions

function checkType(type, key, value, options) {
  options = options || {};

  if (value != undefined) {
    if (options.isArray)
      return checkArray(type, key, value);

    var checker = checkType[type];
    if (checker) return checker(key, value);

    console.warn("Could not check " + key + ", unknown type " + type);
    //    throw TypeError("Could not check "+key+", unknown type "+type);
  } else if (options.required)
    throw SyntaxError(key + " param is required");

};

function checkParams(params, scheme, class_name) {
  var result = {};

  // check MediaObject params
  for (var key in scheme) {
    var value = params[key];

    var s = scheme[key];

    checkType(s.type, key, value, s);

    if (value == undefined) continue;

    result[key] = value;
    delete params[key];
  };

  return result;
};

function checkMethodParams(callparams, method_params) {
  var result = {};

  var index = 0,
    param;
  for (; param = method_params[index]; index++) {
    var key = param.name;
    var value = callparams[index];

    checkType(param.type, key, value, param);

    result[key] = value;
  }

  var params = callparams.slice(index);
  if (params.length)
    console.warning('Unused params:', params);

  return result;
};

module.exports = checkType;

checkType.checkArray = checkArray;
checkType.checkParams = checkParams;
checkType.ChecktypeError = ChecktypeError;

// Basic types

checkType.boolean = checkBoolean;
checkType.double = checkNumber;
checkType.float = checkNumber;
checkType.int = checkInteger;
checkType.Object = checkObject;
checkType.String = checkString;


text:
package org.guvnor.ala.pipeline.execution;

import com.fasterxml.jackson.annotation.JsonTypeInfo;

/**
 * Marker interface for tagging elements that might be produced as pipeline output and wants to be registered as the
 * pipeline output in a pipeline executor trace.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.WRAPPER_OBJECT)
public interface RegistrableOutput {

}


text: <manifest package="com.microsoft.office365.msgraphapiservices"/>


text:
@implementation CrossFadeSegue

- (void)perform
{
	UIViewController *source = self.sourceViewController;
	UIViewController *destination = self.destinationViewController;

	// Start the animation
	[UIView animateWithDuration:0.3f
                          delay:0
                        options:UIViewAnimationOptionTransitionCrossDissolve
                     animations:^(void)
                     {
                         source.view.alpha = 0.0;
                     }
                     completion: ^(BOOL done)
                     {
                         // Properly present the new screen
                         [source presentViewController:destination animated:NO completion:nil];
                     }];
}

@end

//    - (void)perform
//    {
//        UIViewController *source = self.sourceViewController;
//        UIViewController *destination = self.destinationViewController;
//
//        // Create a UIImage with the contents of the destination
//        UIGraphicsBeginImageContext(destination.view.bounds.size);
//        [destination.view.layer renderInContext:UIGraphicsGetCurrentContext()];
//        UIImage *destinationImage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//
//        // Add this image as a subview to the tab bar controller
//        UIImageView *destinationImageView = [[UIImageView alloc] initWithImage:destinationImage];
//        [source.parentViewController.view addSubview:destinationImageView];
//
//        // Scale the image down and rotate it 180 degrees (upside down)
//        CGAffineTransform scaleTransform = CGAffineTransformMakeScale(0.1, 0.1);
//        CGAffineTransform rotateTransform = CGAffineTransformMakeRotation(M_PI);
//        destinationImageView.transform = CGAffineTransformConcat(scaleTransform, rotateTransform);
//
//        // Move the image outside the visible area
//        CGPoint oldCenter = destinationImageView.center;
//        CGPoint newCenter = CGPointMake(oldCenter.x - destinationImageView.bounds.size.width, oldCenter.y);
//        destinationImageView.center = newCenter;
//
//        // Start the animation
//        [UIView animateWithDuration:0.5f delay:0 options:UIViewAnimationOptionCurveEaseOut
//                         animations:^(void)
//         {
//             destinationImageView.transform = CGAffineTransformIdentity;
//             destinationImageView.center = oldCenter;
//         }
//                         completion: ^(BOOL done)
//         {
//             // Remove the image as we no longer need it
//             [destinationImageView removeFromSuperview];
//
//             // Properly present the new screen
//             [source presentViewController:destination animated:NO completion:nil];
//         }];
//    }


text:
In this chapter the notions of UML in the context of database relation creation is covered.
Graded assignments include one (1) quiz set.

## Quiz

The quiz is about how UML maps to relations and is graded. The solutions for this quiz
can be found [here][1].

[1]: uml_quiz.pdf


text:
//
//  LQYPickerView.h
//  MOFSPickerManagerDemo
//
//  Created by luoyuan on 2019/10/22.
//  Copyright © 2019 luoyuan. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "MOFSToolView.h"

NS_ASSUME_NONNULL_BEGIN

@interface LQYPickerViewLayout : NSObject

@property (nonatomic, assign) CGFloat marginLeft;
@property (nonatomic, assign) CGFloat marginRight;
@property (nonatomic, assign) CGFloat marginBottom;

//高度,默认216
@property (nonatomic, assign) CGFloat height;
//默认 44
@property (nonatomic, assign) CGFloat toolBarHeight;

@end

@interface LQYPickerView : UIPickerView

@property (nonatomic, readonly) NSString *objectPointer;

@property (nonatomic, strong) LQYPickerViewLayout *layout;
//背景透明度, 默认0.4
@property (nonatomic, assign) CGFloat maskAlpha;
@property (nonatomic, strong) NSDictionary<NSAttributedStringKey, id> *textAttributes;

@property (nonatomic, strong, readonly) MOFSToolView *toolBar;
@property (nonatomic, strong, readonly) UIView *containerView;
@property (nonatomic, strong, readonly) UIView *maskView;

@property (nonatomic, weak) UIView *parentView;

/**
 * 是否为动态,即联动
 */
@property (nonatomic, assign) BOOL isDynamic;

/**
 * 级数
 * isDynamic = true有效
 * 默认值 1
 */
@property (nonatomic, assign) NSInteger numberOfSection;

/**
* 下一层数据源 key值
* isDynamic = true有效
* @{component : key}
*/
@property (nonatomic, strong) NSDictionary<NSNumber *, NSString *> *dataKeys;

/**
 * 数据内容key值
 * 格式 @{component : key}
 * 当数据源类型为NSDictionary或NSObject时调用
 * 例如 [@[@{@"name_0" : @"kamio"}, @{@"name_1" : @"nagisa"}]]时,其值应该为@{@0 : @"name_0", @1 : @"name_1"};如果key值都相同,可以只设置一个,例如@{@0 : @"name"}
 */
@property (nonatomic, strong) NSDictionary<NSNumber *, NSString *> *dataTextKeys;

/**
 * 数据
 * 内容可以是NSString、NSDictionary和NSObject;其中 NSDictionary和NSObject需要提供dataTextKeys来取出内容
 * 静态格式:1. @[@"kamio", @"nagisa", @"misuzu"] (一级)
 *         2. @[@{@"name" : @"kamio"}, @{@"name" : @"nagisa"}] (一级)
 *         3. @[@[@"a", @"b", @"c"], @[@"1", @"2", @"3"]] (多级,取决于最外层数组长度)
 * 动态格式:@[@{@"name" : @"广东", @"list" : @[@"深圳", @"广州"]}, @{@"name" : @"广西", @"list" : @[@"南宁", @"桂林"]}];
 */
@property (nonatomic, strong) NSArray *dataArray;

/**
 * 确认block
 * json格式为 component : component所选中的数据
 */
@property (nonatomic, copy) void (^commitBlock)(NSDictionary<NSNumber *, id> * _Nullable json);

/**
 * 获取某个component下的 数组
 */
- (nullable NSArray *)getDataArrayForComponent:(NSInteger)component;

- (void)show;

- (void)dismiss;

@end

typedef NS_ENUM(NSUInteger, LQYDateComponent) {
    LQYDateComponentYear   = 0,
    LQYDateComponentMonth  = 1,
    LQYDateComponentDay    = 2,
    LQYDateComponentHour   = 3,
    LQYDateComponentMinute = 4,
    LQYDateComponentSecond = 5
};

typedef NS_ENUM(NSInteger, LQYFormatType) {
    LQYFormatTypeBefore = 1, //加在相应字符串前边
    LQYFormatTypeAfter  = 2, //加在相应字符串后边
};

@interface LQYDatePickerView : LQYPickerView

/**注意:minimumComponent不是LQYDateComponentYear时,请保持minimumDate、maximumDate前面略去的值一致
 * 例如 minimumComponent是LQYDateComponentDay,那么请保持最小minimumDate、最大日期maximumDate
 * 的年份、月份一致
 * 如果不一致,则以小的minimumDate为准
 */

/**
 * 最小日期
 * 默认:2000-01-01
 */
@property (nullable, nonatomic, strong) NSDate *minimumDate;

/**
 * 最大日期
 * 默认:当前时间
 */
@property (nullable, nonatomic, strong) NSDate *maximumDate;

/**
 * 显示的最小component
 * 默认LQYDateComponentYear,从年份开始显示
 */
@property (nonatomic, assign) LQYDateComponent minimumComponent;

/**
 * 显示的最大component
 * 默认为LQYDateComponentDay,显示到 天 为止
 */
@property (nonatomic, assign) LQYDateComponent maximumComponent;

@property (nonatomic, copy) void (^cancelBlock)(void);
@property (nonatomic, copy) void (^dateCommitBlock)(NSDateComponents *components);

/**
 * 设置显示时间格式
 */
- (void)setDateFormat:(NSString *)dateFormat formatType:(LQYFormatType)formatType component:(LQYDateComponent)component;

- (void)showWithCommitBlock:(void(^)(NSDateComponents *components))commitBlock cancelBlock:(void(^)(void))cancelBlock;

@end

NS_ASSUME_NONNULL_END


text:
from msrest.paging import Paged

class ADGroupPaged(Paged):
    """
    A paging container for iterating over a list of :class:`ADGroup <azure.graphrbac.models.ADGroup>` object
    """

    _attribute_map = {
        'next_link': {'key': 'odata\\.nextLink', 'type': 'str'},
        'current_page': {'key': 'value', 'type': '[ADGroup]'}
    }

    def __init__(self, *args, **kwargs):

        super(ADGroupPaged, self).__init__(*args, **kwargs)


text:
using System;

namespace MongoRiver
{
    public static class Utils
    {
        /// <summary>
        /// Convert a DateTime to number seconds from epoc (1/1/1970)
        /// </summary>
        /// <param name="dateTime">The date to convert</param>
        /// <returns>Number of seconds from epoc (1/1/1970)</returns>
        public static int ToInt(this DateTime dateTime)
        {
            TimeSpan t = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            return (int)Math.Floor(t.TotalSeconds);
        }

        /// <summary>
        /// Split a oplog namespace string into two parts from the first period in the string.
        /// </summary>
        /// <param name="ns">Oplog namespace</param>
        /// <returns>Two strings that make up the namespace. Usually [0] = database name and [1] = collection name.</returns>
        public static string[] SplitNamespace(string ns)
        {
            return ns.Split(new char[] { '.' }, 2);
        }
    }
}


text:
''' Goal of this script is to resume ThermoFisher Ion Torrent™ Coverage Analysis
    output (*.stats.cov.txt files) in a CSV table. Those files are usually
    stored in:
        /results/analysis/output/Home/<run>/plugin_out/<coverageAnalysis_out>/*
'''

import pandas as pd
import argparse, sys

COL2FLOAT = [
    "Amplicons reading end-to-end",
    "Amplicons with at least 1 read",
    "Amplicons with at least 100 reads",
    "Amplicons with at least 20 reads",
    "Amplicons with at least 500 reads",
    "Amplicons with no strand bias",
    "Average base coverage depth",
    "Average reads per amplicon",
    "Percent assigned amplicon reads",
    "Percent base reads on target",
    "Percent end-to-end reads",
    "Percent reads on target",
    "Target base coverage at 100x",
    "Target base coverage at 1x",
    "Target base coverage at 20x",
    "Target base coverage at 500x",
    "Target bases with no strand bias",
    "Uniformity of amplicon coverage",
    "Uniformity of base coverage"
    ]

COL2INT = [
    "Bases in target regions",
    "Number of amplicons",
    "Number of mapped reads",
    "Total aligned base reads",
    "Total assigned amplicon reads",
    "Total base reads on target"
    ]

def txt2series(f):
    f = open(f)
    rows = f.readlines()[2:]
    rows_as_kv = [r.strip().split(":") for r in rows]
    d = {k_v[0].strip():k_v[1].strip().strip("%") for k_v in rows_as_kv if len(k_v)>1}
    # Separate barcode_run
    d['Barcode'] = d['Alignments'][:13]
    d['Run'] = d['Alignments'][14:]
    del d['Alignments']
    s = pd.Series(d)
    return s

if __name__ == '__main__':
    # Read input
    parser = argparse.ArgumentParser()
    parser.add_argument("files", nargs='+', help="List of stats.cov.txt")
    args = parser.parse_args()
    files = args.files
    out = sys.stdout

    # Assert input only files ending with ".stats.cov.txt"
    txts = sorted([t for t in files if t[-14:] == ".stats.cov.txt"])

    df = pd.DataFrame()
    for t in txts:
        df = df.append(txt2series(t), ignore_index=True)

    # Ordering
    ordered_index = list(df.columns.difference(COL2FLOAT+COL2INT)) \
                        + COL2INT \
                        + COL2FLOAT
    df = df[ordered_index]

    # Fix type
    df[COL2FLOAT] = df[COL2FLOAT].astype(float)
    df[COL2INT] = df[COL2INT].astype(int)

    # Write to output
    df.to_csv(out, index=False)


text:
<?php

/**
 * @namespace
 */
namespace de\codenamephp\prototype\library\platform;

use \Composer\Script\Event;
use \DateTime;
use \de\codenamephp\platform\di\ContainerBuilder;
use \de\codenamephp\platform\di\iContainer;
use \de\codenamephp\prototype\utils\answerCollector\CollectorSwitch;
use \de\codenamephp\prototype\utils\TemplateCopy;
use \SplFileInfo;
use \Symfony\Component\Filesystem\Filesystem;

/**
 *
 * @author Bastian Schwarz <bastian@codename-php.de>
 */
class Installer {

  /**
   *
   * @var iContainer
   */
  static $di = null;

  /**
   *
   * @return iContainer
   */
  public static function getDi(): iContainer {
    if(!static::$di instanceof iContainer) {
      $containerBuilder = new ContainerBuilder();
      $containerBuilder->addDefinitionsByProvider(new DefinitionsProvider());
      static::$di = $containerBuilder->build();
    }
    return static::$di;
  }

  /**
   *
   * @param iContainer $di
   */
  public static function setDi(iContainer $di) {
    static::$di = $di;
  }

  public static function install(Event $event) {
    $homeDir = realpath($event->getComposer()->getConfig()->get('vendor-dir') . '/..');

    $answers = static::getDi()->get(CollectorSwitch::class)->getAnswers($event, [
      'vendor' => ['question' => 'What is the vendor of the project', 'default' => 'codenamephp'],
      'displayName' => ['question' => 'What is the display name of the project', 'default' => ''],
      'componentName' => ['question' => 'What is the name of the project', 'default' => basename($homeDir)],
      'namespace' => ['question' => 'What is the base namespace of the project', 'default' => '\\' . str_replace('.', '\\', basename($homeDir))],
        ], new SplFileInfo($homeDir . '/answers.serialized'));

    $templateFolder = $homeDir . '/src/main/template';
    static::getDi()->get(TemplateCopy::class)->copy($templateFolder, $homeDir, $answers + [
      'namespacedFolder' => str_replace('\\', DIRECTORY_SEPARATOR, $answers['namespace']),
      'year' => static::getDi()->get(DateTime::class)->format('Y')
    ]);

    static::getDi()->get(Filesystem::class)->remove([
      $homeDir . '/.git',
      $homeDir . '/src/main/php/installer',
      $homeDir . '/src/test/php/installer',
      $templateFolder
    ]);
  }
}


text:
from __future__ import unicode_literals

import re

from .common import InfoExtractor
from ..utils import (
    float_or_none,
    parse_iso8601,
    update_url_query,
    int_or_none,
    determine_protocol,
    unescapeHTML,
)

class SendtoNewsIE(InfoExtractor):
    _VALID_URL = r'https?://embed\.sendtonews\.com/player2/embedplayer\.php\?.*\bSC=(?P<id>[0-9A-Za-z-]+)'

    _TEST = {
        # From http://cleveland.cbslocal.com/2016/05/16/indians-score-season-high-15-runs-in-blowout-win-over-reds-rapid-reaction/
        'url': 'http://embed.sendtonews.com/player2/embedplayer.php?SC=GxfCe0Zo7D-175909-5588&type=single&autoplay=on&sound=YES',
        'info_dict': {
            'id': 'GxfCe0Zo7D-175909-5588'
        },
        'playlist_count': 8,
        # test the first video only to prevent lengthy tests
        'playlist': [{
            'info_dict': {
                'id': '240385',
                'ext': 'mp4',
                'title': 'Indians introduce Encarnacion',
                'description': 'Indians president of baseball operations Chris Antonetti and Edwin Encarnacion discuss the slugger\'s three-year contract with Cleveland',
                'duration': 137.898,
                'thumbnail': r're:https?://.*\.jpg$',
                'upload_date': '20170105',
                'timestamp': 1483649762,
            },
        }],
        'params': {
            # m3u8 download
            'skip_download': True,
        },
    }

    _URL_TEMPLATE = '//embed.sendtonews.com/player2/embedplayer.php?SC=%s'

    @classmethod
    def _extract_url(cls, webpage):
        mobj = re.search(r'''(?x)<script[^>]+src=([\'"])
            (?:https?:)?//embed\.sendtonews\.com/player/responsiveembed\.php\?
                .*\bSC=(?P<SC>[0-9a-zA-Z-]+).*
            \1>''', webpage)
        if mobj:
            sc = mobj.group('SC')
            return cls._URL_TEMPLATE % sc

    def _real_extract(self, url):
        playlist_id = self._match_id(url)

        data_url = update_url_query(
            url.replace('embedplayer.php', 'data_read.php'),
            {'cmd': 'loadInitial'})
        playlist_data = self._download_json(data_url, playlist_id)

        entries = []
        for video in playlist_data['playlistData'][0]:
            info_dict = self._parse_jwplayer_data(
                video['jwconfiguration'],
                require_title=False, m3u8_id='hls', rtmp_params={'no_resume': True})

            for f in info_dict['formats']:
                if f.get('tbr'):
                    continue
                tbr = int_or_none(self._search_regex(
                    r'/(\d+)k/', f['url'], 'bitrate', default=None))
                if not tbr:
                    continue
                f.update({
                    'format_id': '%s-%d' % (determine_protocol(f), tbr),
                    'tbr': tbr,
                })
            self._sort_formats(info_dict['formats'], ('tbr', 'height', 'width', 'format_id'))

            thumbnails = []
            if video.get('thumbnailUrl'):
                thumbnails.append({
                    'id': 'normal',
                    'url': video['thumbnailUrl'],
                })
            if video.get('smThumbnailUrl'):
                thumbnails.append({
                    'id': 'small',
                    'url': video['smThumbnailUrl'],
                })
            info_dict.update({
                'title': video['S_headLine'].strip(),
                'description': unescapeHTML(video.get('S_fullStory')),
                'thumbnails': thumbnails,
                'duration': float_or_none(video.get('SM_length')),
                'timestamp': parse_iso8601(video.get('S_sysDate'), delimiter=' '),
            })
            entries.append(info_dict)

        return self.playlist_result(entries, playlist_id)


text:
package com.npaduch.reminder;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.squareup.otto.Subscribe;

import java.util.ArrayList;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.internal.CardHeader;
import it.gmariotti.cardslib.library.internal.base.BaseCard;
import it.gmariotti.cardslib.library.view.CardListView;

/**
 * Created by nolanpaduch on 5/3/14.
 *
 */

public class CardListFragment extends Fragment {

    private final static String TAG = "CardListFragment";

    // Card adapter and listview
    private CardArrayAdapter mCardArrayAdapter;
    private CardListView mCardListView;

    // Arguments
    public static final String LIST_TYPE = "list_type";
    public static final int LIST_PENDING = 0;
    public static final int LIST_COMPLETED = 1;

    // list type
    private int fragmentType = LIST_PENDING;

    private static Context context;

    public CardListFragment() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        Log.d(TAG, "onActivityCreated");

        // get fragment type
        fragmentType = getArguments().getInt(LIST_TYPE, LIST_PENDING);

        // save off context
        context = getActivity();

        ArrayList<Card> cardList = new ArrayList<Card>();

        // Set the adapter
        mCardArrayAdapter = new CardArrayAdapter(context, cardList);
        // Make swipes undo-able!
        mCardArrayAdapter.setEnableUndo(true);

        // Set ListView
        mCardListView = (CardListView) getView().findViewById(R.id.reminderCardListView);

        if (mCardListView != null) {
            mCardListView.setAdapter(mCardArrayAdapter);
        }

        // load in reminders in the background
        startLoad();

        /** Initialize floating action button **/
        Fab mFab = (Fab)getView().findViewById(R.id.FloatingAddButton);
        mFab.setFabColor(getActivity().getResources().getColor(R.color.app_color_theme));
        mFab.setFabDrawable(getActivity().getResources().getDrawable(R.drawable.ic_action_new));
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BusEvent event = new BusEvent(BusEvent.TYPE_CHANGE_FRAG, BusEvent.TARGET_MAIN);
                event.setToFragment(BusEvent.FRAGMENT_NEW_REMINDER);
                event.setFromFragment(BusEvent.FRAGMENT_PENDING);   // this doesn't matter
                BusProvider.getInstance().post(event);
            }
        });

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_cardlist, container, false);
    }

    @Override
    public void onResume() {
        Log.d(TAG, "OnResume");
        super.onResume();
        BusProvider.getInstance().register(this);

        // set title
        if(fragmentType == LIST_PENDING) {
            getActivity().getActionBar().setTitle(R.string.pending_title);
        } else {
            getActivity().getActionBar().setTitle(R.string.completed_title);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        BusProvider.getInstance().unregister(this);
    }

    @Override
    public void onCreateOptionsMenu(
            Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_fragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            // no items.. placeholder
        }
        return super.onOptionsItemSelected(item);
    }

    private void startLoad(){
        getActivity().setProgressBarIndeterminateVisibility(true);
        //noinspection unchecked
        new LoadReminders(getActivity(), fragmentType).execute();
    }

    private void endLoad(ArrayList<Card> cards){

        mCardArrayAdapter.clear();
        for(Card c : cards){
            int i = 0;
            // for pending list, we want earliest at the top
            // for completed, we want latest at the top
            if(fragmentType == LIST_PENDING) {
                while (i < mCardArrayAdapter.getCount() &&
                        ((ReminderCard) c).getReminder().getMsTime() > ((ReminderCard) mCardArrayAdapter.getItem(i)).getReminder().getMsTime())
                    i++;
            } else {
                while (i < mCardArrayAdapter.getCount() &&
                        ((ReminderCard) c).getReminder().getMsTime() < ((ReminderCard) mCardArrayAdapter.getItem(i)).getReminder().getMsTime())
                    i++;
            }
            mCardArrayAdapter.insert(c, i);
        }

        // update listview
        mCardArrayAdapter.notifyDataSetChanged();

        // set empty view if no reminders
        TextView tv = (TextView) getView().findViewById(R.id.cardListEmptyView);
        mCardListView.setEmptyView(tv);

        // set undoable
        mCardArrayAdapter.setEnableUndo(true);

        // stop progress circle
        getActivity().setProgressBarIndeterminateVisibility(false);
    }

    void addReminderCard(Reminder r){

        // Check if reminder already exists
        boolean found = false;
        for(int i = 0; i < mCardArrayAdapter.getCount(); i++){
            // find the view with Id that matches reminder
            ReminderCard rc = (ReminderCard) mCardArrayAdapter.getItem(i);
            Reminder cardReminder = rc.getReminder();
            if(cardReminder.getReminderID() == r.getReminderID()){
                // found a match, update it with new card
                found = true;
                rc.setReminder(r);
                break;
            }
        }

        // if we didn't find it, it must be new! Add it.
        if(!found) {
            boolean inserted = false;
            if(fragmentType == LIST_PENDING) {
                for (int i = 0; i < mCardArrayAdapter.getCount(); i++) {
                    if (r.getMsTime() < ((ReminderCard) mCardArrayAdapter.getItem(i)).getReminder().getMsTime()) {
                        mCardArrayAdapter.insert(new ReminderCard(getActivity(), r, fragmentType), i);
                        inserted = true;
                        break;
                    }
                }
            } else {
                for (int i = 0; i < mCardArrayAdapter.getCount(); i++) {
                    if (r.getMsTime() > ((ReminderCard) mCardArrayAdapter.getItem(i)).getReminder().getMsTime()) {
                        mCardArrayAdapter.insert(new ReminderCard(getActivity(), r, fragmentType), i);
                        inserted = true;
                        break;
                    }
                }
            }
            // check if it was inserted anywhere. If not, just add it to the end
            if(!inserted){
                mCardArrayAdapter.insert(new ReminderCard(getActivity(), r, fragmentType), mCardArrayAdapter.getCount());
            }
        }

        // update view
        mCardArrayAdapter.notifyDataSetChanged();
    }

    void removeReminderCard(Reminder r){

        // search for reminder and remove it
        for(int i = 0; i < mCardArrayAdapter.getCount(); i++){
            // find the view with Id that matches reminder
            ReminderCard rc = (ReminderCard) mCardArrayAdapter.getItem(i);
            Reminder cardReminder = rc.getReminder();
            if(cardReminder.getReminderID() == r.getReminderID()){
                // found a match, remove it
                mCardArrayAdapter.remove(rc);
                break;
            }
        }

        // update view
        mCardArrayAdapter.notifyDataSetChanged();
    }

    // to do, replace this with bus
    private static void switchToEditFragment(Reminder r){
        BusEvent event = new BusEvent(BusEvent.TYPE_EDIT_REMINDER, BusEvent.TARGET_MAIN);
        event.setReminder(r);
        BusProvider.getInstance().post(event);
    }

    /** Event bus listener **/
    @Subscribe
    public void BusEvent(BusEvent event){
        // check if it's for us
        if(event.getTargets().contains(BusEvent.TARGET_PENDING)) {
            Log.d(TAG, "Message received: " + event.getType());
            switch (event.getType()) {
                case BusEvent.TYPE_ADD:
                    addReminderCard(event.getReminder());
                    break;
                case BusEvent.TYPE_REMOVE:
                    removeReminderCard(event.getReminder());
                    break;
                case BusEvent.TYPE_LOAD_REMINDERS:
                    endLoad(event.getCardList());
                    break;
                case BusEvent.TYPE_EDIT_REMINDER:
                    switchToEditFragment(event.getReminder());
                    break;
                case BusEvent.TYPE_REFRESH_REMINDERS:
                    startLoad();
                    break;
            }
        } else if (event.getTargets().contains(BusEvent.TARGET_COMPLETED)) {
            Log.d(TAG, "Message received: " + event.getType());
            switch (event.getType()) {
                case BusEvent.TYPE_ADD:
                    addReminderCard(event.getReminder());
                    break;
                case BusEvent.TYPE_REMOVE:
                    removeReminderCard(event.getReminder());
                    break;
                case BusEvent.TYPE_LOAD_REMINDERS:
                    endLoad(event.getCardList());
                    break;
                case BusEvent.TYPE_EDIT_REMINDER:
                    switchToEditFragment(event.getReminder());
                    break;
                case BusEvent.TYPE_REFRESH_REMINDERS:
                    startLoad();
                    break;
            }
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
~  Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
~
~  WSO2 Inc. licenses this file to you under the Apache License,
~  Version 2.0 (the "License"); you may not use this file except
~  in compliance with the License.
~  You may obtain a copy of the License at
~
~   http://www.apache.org/licenses/LICENSE-2.0
~
~  Unless required by applicable law or agreed to in writing,
~  software distributed under the License is distributed on an
~  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~  KIND, either express or implied.  See the License for the
~  specific language governing permissions and limitations
~  under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.wso2.carbon.extension.identity.authenticator</groupId>
        <artifactId>org.wso2.carbon.extension.identity.authenticator.emailotp</artifactId>
        <version>1.0.3-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>
    <groupId>org.wso2.carbon.extension.identity.authenticator</groupId>
    <artifactId>org.wso2.carbon.extension.identity.authenticator.emailotp.endpoint</artifactId>
    <packaging>war</packaging>
    <name>WSO2 Carbon - Identity Application Authentication EmailOTP Endpoint</name>
    <description>Identity Application Authentication EmailOTP Endpoint</description>
    <url>http://wso2.org</url>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
                <version>2.3.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <webResources>
                        <resource>
                            <!-- this is relative to the pom.xml directory -->
                            <directory>src/main/webapp</directory>
                        </resource>
                    </webResources>
                    <warName>emailotpauthenticationendpoint</warName>
                    <packagingExcludes>WEB-INF/lib/commons-logging*.jar</packagingExcludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Usnea florida var. leioclada Zahlbr.

### Remarks
null


text:
package DAO;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import VO.LivroVO;

public class ProdutoDAO extends ConexaoMySQL{

	public static ArrayList<LivroVO> getDadosDosLivro(int tipo) throws SQLException {

        String sql = "";
        LivroVO livroVO = null;

        sql = "SELECT * FROM LIVRO WHERE TIPO = '"+tipo+"'";

        ResultSet rs = executaQueryConsulta(sql);
        ArrayList <LivroVO> livrosVO = new ArrayList<LivroVO>();

        while (rs.next()) {
            livroVO = new LivroVO();

            livroVO.setAutor(rs.getString("AUTOR"));
            livroVO.setEditora(rs.getString("EDITORA"));
            livroVO.setAnoDeEdicao(rs.getInt("ANODEEDICAO"));
            livrosVO.add(livroVO);
        }

        sql = "SELECT * FROM PRODUTO WHERE TIPO = '"+tipo+"'";

        //ArrayList <LivroVO> livrosVO = new ArrayList<LivroVO>();
        /*
        while (rs.next()) {
            livroVO = new LivroVO();

            livroVO.setTitulo(rs.getString("TITULO"));
            livroVO.seCodigoDoProduto(rs.getInt("CODIGODOPRODUTO"));
            livroVO.setQtdNaEstante(rs.getInt("QTDNAESTANTE"));

            livrosVO.add(livroVO);
        }*/

        return livrosVO;
    }

	public static ResultSet executaQueryConsulta(String consulta) throws SQLException {

        PreparedStatement stmt = conexao.prepareStatement(consulta);
        ResultSet rs = stmt.executeQuery();

        return rs;
    }

}


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

namespace Tesla.Model
{
    public class IsPinValid : IModelExecute<bool>
    {

        private readonly string _pin = "";

        public IsPinValid(string pin)
        {
            _pin = pin;
        }

        public IOperation<bool> Operation
        {
            get
            {
                return new Operation<bool>()
                {
                    Function = (token) =>
                    {
                        if (_pin == null)
                            return Task.FromResult(false);

                        var result = 0;
                        if (!Int32.TryParse(_pin, out result))
                            return Task.FromResult(false);

                        if (_pin.Length == 4)
                            return Task.FromResult(true);
                        else
                            return Task.FromResult(false);
                    }
                };
            }
        }

        public int TimeoutMilliseconds { get; set; } = 10000;
    }
}


text:
layout: redirect
redirect: docs/skylark/build-style.html
---


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>D.I.T. ( Do It Tizen! ): Globals</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

D.I.T. ( Do It Tizen! )
    1.0.0

Samsung Software Membership

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Globals

All

Functions

Macros

a

b

c

d

g

h

i

l

m

n

o

p

r

s

t

u

v

 All Data Structures Files Functions Macros Pages

Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation:

- p -

pauseAudio()
: File.h
, File.c

pauseVideo()
: File.c
, File.h

playAudio()
: File.h
, File.c

PlayerErrorCheck()
: File.c
, File.h

playVideo()
: File.h
, File.c

PreferenceClear()
: Preference.h
, Preference.c

PreferenceErrorCheck()
: Preference.h
, Preference.c

PreferenceRemove()
: Preference.h
, Preference.c

PressureOff()
: Sensor.h
, Sensor.c

PressureOn()
: Sensor.h
, Sensor.c

ProximityOff()
: Sensor.h
, Sensor.c

ProximityOn()
: Sensor.c
, Sensor.h

<address class="footer">
Generated by

 1.8.6
</address>


text:
var express = require('express'),
    router  = express.Router(),
    app     = express(),
    bodyParser = require('body-parser'),
    mongoose = require('mongoose');

var port = process.env.PORT || 3000; //port set to 3000

var uristring = process.env.MONGODB_URI || 'mongodb://localhost/step';

mongoose.connect(uristring, function (err, res) {
  if (err) {
    console.log('Error connecting to db');
  } else {
    console.log('Succeeded in connecting to db');
  }
});

var donorSchema = new mongoose.Schema({
  name: { type: String },
  age: { type: Number },
  email: { type: String },
  phone: { type: String },
  address: { type: String },
  group: { type: String },
  modifiedOn: { type: Date },
  id: { type: Number },
  done: { type: Boolean }
});
var Donor = mongoose.model('donors', donorSchema);

var statusSchema = new mongoose.Schema({
  name: { type: String },
  count: { type: Number }
});
var Status = mongoose.model('status', statusSchema);

//app specific configurations
//==================================================

app.use('/', express.static(__dirname + '/app/'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

//router configurations
//============================================

router.get('/', function (req, res) {
	res.render('/index.html');
});

router.post('/submit', function (req, res) {
  var data = req.body.data;
  var aDonor = new Donor({
    name: data.name || '',
    age: data.age || '',
    email: data.email || '',
    phone: data.phone || '',
    address: data.address || '',
    group: data.group || '',
    modifiedOn: new Date,
    done: false
  });

  Status.findOne({name: 'bloodDonors'}, function (err, stat) {
    aDonor.id = stat.count + 1;
    stat.count = aDonor.id;
    stat.save(function (err) {
      if (err) {
        console.log('error in updating');
      } else {
        aDonor.save(function (err, obj) {
          if (err) {
            console.log('Error on save!');
          } else {
            console.log('Saving', obj);
            res.json(obj);
          }
        });
      }
    });
  });
});

app.use('/', router);

//run the server========================
var server = app.listen(port, function(){
	console.log('server has started running at localhost:' + port);
});


text:
            arrow_back

        <form ng-submit="$ctrl.save()" flex layout="row" layout-align="start center">
            <input type="password" placeholder="{{$ctrl.attrs.mobileEditPlaceholder}}"
                   flex class="console-form-password"
                   ng-change="$ctrl.check()"
                   ng-model="$ctrl.value">
        </form>

            check

            Between 8-100 characters

            Contains an UPPERCASE letter

            Contains a lowercase letter

            Contains a number


text:
package dispatch

import (
	"math"
	"time"

	"github.com/uber/kraken/lib/torrent/scheduler/dispatch/piecerequest"
	"github.com/uber/kraken/utils/memsize"
	"github.com/uber/kraken/utils/timeutil"
)

// Config defines the configuration for piece dispatch.
type Config struct {

	// PieceRequestMinTimeout is the minimum timeout for all piece requests, regardless of
	// size.
	PieceRequestMinTimeout time.Duration `yaml:"piece_request_min_timeout"`

	// PieceRequestTimeoutPerMb is the duration that will be added to piece request
	// timeouts based on the piece size (in megabytes).
	PieceRequestTimeoutPerMb time.Duration `yaml:"piece_request_timeout_per_mb"`

	// PieceRequestPolicy is the policy that is used to decide which pieces to request
	// from a peer.
	PieceRequestPolicy string `yaml:"piece_request_policy"`

	// PipelineLimit limits the total number of requests can be sent to a peer
	// at the same time.
	PipelineLimit int `yaml:"pipeline_limit"`

	// EndgameThreshold is the number pieces required to complete the torrent
	// before the torrent enters "endgame", where we start overloading piece
	// requests to multiple peers.
	EndgameThreshold int `yaml:"endgame_threshold"`

	DisableEndgame bool `yaml:"disable_endgame"`
}

func (c Config) applyDefaults() Config {
	if c.PieceRequestPolicy == "" {
		c.PieceRequestPolicy = piecerequest.DefaultPolicy
	}
	if c.PieceRequestMinTimeout == 0 {
		c.PieceRequestMinTimeout = 4 * time.Second
	}
	if c.PieceRequestTimeoutPerMb == 0 {
		c.PieceRequestTimeoutPerMb = 4 * time.Second
	}
	if c.PipelineLimit == 0 {
		c.PipelineLimit = 3
	}
	if c.EndgameThreshold == 0 {
		c.EndgameThreshold = c.PipelineLimit
	}
	return c
}

func (c Config) calcPieceRequestTimeout(maxPieceLength int64) time.Duration {
	n := float64(c.PieceRequestTimeoutPerMb) * float64(maxPieceLength) / float64(memsize.MB)
	d := time.Duration(math.Ceil(n))
	return timeutil.MaxDuration(d, c.PieceRequestMinTimeout)
}


text:
'use strict';

var _ = require('lodash');
var Card = require('./card.model');

// Get list of cards
exports.index = function(req, res) {
  Card.find(function (err, cards) {
    if(err) { return handleError(res, err); }
    return res.json(200, cards);
  });
};

// Get a single card
exports.show = function(req, res) {
  Card.findById(req.params.id, function (err, card) {
    if(err) { return handleError(res, err); }
    if(!card) { return res.send(404); }
    return res.json(card);
  });
};

// Creates a new card in the DB.
exports.create = function(req, res) {
  Card.create(req.body, function(err, card) {
    if(err) { return handleError(res, err); }
    return res.json(201, card);
  });
};

// Updates an existing card in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  Card.findById(req.params.id, function (err, card) {
    if (err) { return handleError(res, err); }
    if(!card) { return res.send(404); }
    var updated = _.merge(card, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, card);
    });
  });
};

// Deletes a card from the DB.
exports.destroy = function(req, res) {
  Card.findById(req.params.id, function (err, card) {
    if(err) { return handleError(res, err); }
    if(!card) { return res.send(404); }
    card.remove(function(err) {
      if(err) { return handleError(res, err); }
      return res.send(204);
    });
  });
};

function handleError(res, err) {
  return res.send(500, err);
}


text:
  <button type="button"
          class="btn btn-default"
          ng-click="vm.cancelAction()"
          translate>Cancel
  </button>
  <button ng-if="vm.resetModal"
          type="button"
          class="btn btn-default"
          ng-click="vm.emitOriginal()"
          ng-disabled="vm.isPristine()"
          translate>Reset
  </button>
  <button ng-if="!vm.confirmationModal"
          type="button"
          class="btn btn-primary"
          ng-click="vm.saveResource()"
          ng-disabled="vm.isPristine()"
          translate>Save
  </button>
  <button ng-if="vm.confirmationModal"
          type="button"
          class="btn btn-primary"
          ng-click="vm.affirmConfirmation()"
          translate>OK
  </button>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.digitaltwins.core;

import com.azure.core.http.policy.HttpLogOptions;
import com.azure.digitaltwins.core.helpers.ConsoleLogger;
import com.azure.digitaltwins.core.helpers.FileHelper;
import com.azure.digitaltwins.core.helpers.SamplesArguments;
import com.azure.digitaltwins.core.implementation.models.ErrorResponseException;
import com.azure.digitaltwins.core.models.BasicDigitalTwin;
import com.azure.digitaltwins.core.models.BasicRelationship;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import static com.azure.digitaltwins.core.models.QueryChargeHelper.*;
import static com.azure.digitaltwins.core.helpers.SamplesConstants.*;
import static com.azure.digitaltwins.core.helpers.SamplesUtil.IgnoreConflictError;
import static com.azure.digitaltwins.core.helpers.SamplesUtil.IgnoreNotFoundError;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.util.Arrays.asList;

/**
 * This sample creates all the models in \DTDL\Models folder in the ADT service instance and creates the corresponding twins in \DTDL\DigitalTwins folder.
 * The Diagram for the Hospital model looks like this:
 *
 *          +------------+
 *          |  Building  +-----isEquippedWith-----+
 *          +------------+                        |
 *                |                               v
 *               has                           +-----+
 *                |                            | HVAC|
 *                v                            +-----+
 *          +------------+                        |
 *          |   Floor    +<--controlsTemperature--+
 *          +------------+
 *                |
 *             contains
 *                |
 *                v
 *          +------------+                 +-----------------+
 *          |   Room     |-with component->| WifiAccessPoint |
 *          +------------+                 +-----------------+
 *
 */
public class DigitalTwinsLifecycleAsyncSample {

    private static final int MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS = 10;
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private static final URL DTDL_DIRECTORY_URL = DigitalTwinsLifecycleAsyncSample.class.getClassLoader().getResource("DTDL");
    private static final Path DTDL_DIRECTORY_PATH;
    private static final Path TWINS_PATH;
    private static final Path MODELS_PATH;
    private static final Path RELATIONSHIPS_PATH;

    private static DigitalTwinsAsyncClient client;

    static {
        try {
            assert DTDL_DIRECTORY_URL != null;
            DTDL_DIRECTORY_PATH = Paths.get(DTDL_DIRECTORY_URL.toURI());
        } catch (URISyntaxException e) {
            throw new RuntimeException("Unable to convert the DTDL directory URL to URI", e);
        }
        TWINS_PATH = Paths.get(DTDL_DIRECTORY_PATH.toString(), "DigitalTwins");
        MODELS_PATH = Paths.get(DTDL_DIRECTORY_PATH.toString(), "Models");
        RELATIONSHIPS_PATH = Paths.get(DTDL_DIRECTORY_PATH.toString(), "Relationships");
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        SamplesArguments parsedArguments = new SamplesArguments(args);

        client = new DigitalTwinsClientBuilder()
            .credential(
                new ClientSecretCredentialBuilder()
                    .tenantId(parsedArguments.getTenantId())
                    .clientId(parsedArguments.getClientId())
                    .clientSecret(parsedArguments.getClientSecret())
                    .build()
            )
            .endpoint(parsedArguments.getDigitalTwinEndpoint())
            .httpLogOptions(
                new HttpLogOptions()
                    .setLogLevel(parsedArguments.getHttpLogDetailLevel()))
            .buildAsyncClient();

        // Ensure existing twins with the same name are deleted first
        deleteTwins();

        // Delete existing models
        deleteAllModels();

        // Create all the models
        createAllModels();

        // Get all models
        listAllModels();

        // Create twin counterparts for all the models
        createAllTwins();

        // Get all twins
        queryTwins();

        // Create all the relationships
        connectTwinsTogether();
    }

    /**
     * Delete a twin, and any relationships it might have.
     * @throws IOException If an I/O error is thrown when accessing the starting file.
     * @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
     */
    public static void deleteTwins() throws IOException, InterruptedException {
        ConsoleLogger.printHeader("Delete digital twins");
        Map<String, String> twins = FileHelper.loadAllFilesInPath(TWINS_PATH);

        // Call APIs to clean up any pre-existing resources that might be referenced by this sample. If digital twin does not exist, ignore.
        // Once the async API terminates (either successfully, or with an error), the latch count is decremented, or the semaphore is released.
        for (Map.Entry<String, String> twin : twins.entrySet()) {
            String twinId = twin.getKey();

            // This list contains all the relationships that existing between the twins referenced by this sample.
            List<BasicRelationship> relationshipList = Collections.synchronizedList(new ArrayList<>());

            // This latch is to maintain a thread-safe count to ensure that we wait for both the list relationships and list incoming relationships operations to complete,
            // before proceeding to the delete operation.
            CountDownLatch listRelationshipSemaphore = new CountDownLatch(2);
            // This latch is to maintain a thread-safe count to ensure that we wait for the delete twin operation to complete, before proceeding.
            CountDownLatch deleteTwinsLatch = new CountDownLatch(1);

            // This semaphores indicates when the relationship delete operation has has completed.
            // We cannot use a latch here since we do not know the no. of relationships that will be deleted (so we do cannot set the latch initial count).
            Semaphore deleteRelationshipsSemaphore = new Semaphore(0);

            // Call APIs to retrieve all relationships.
            client.listRelationships(twinId, BasicRelationship.class)
                .doOnNext(relationshipList::add)
                .doOnError(IgnoreNotFoundError)
                .doOnTerminate(listRelationshipSemaphore::countDown)
                .subscribe();

            // Call APIs to retrieve all incoming relationships.
            client.listIncomingRelationships(twinId, null)
                .doOnNext(e -> relationshipList.add(MAPPER.convertValue(e, BasicRelationship.class)))
                .doOnError(IgnoreNotFoundError)
                .doOnTerminate(listRelationshipSemaphore::countDown)
                .subscribe();

            // Call APIs to delete all relationships.
            if (listRelationshipSemaphore.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS)) {
                relationshipList
                    .forEach(relationship -> client.deleteRelationship(relationship.getSourceId(), relationship.getId())
                        .doOnSuccess(aVoid -> {
                            if (twinId.equals(relationship.getSourceId())) {
                                ConsoleLogger.printSuccess("Found and deleted relationship: " + relationship.getId());
                            } else {
                                ConsoleLogger.printSuccess("Found and deleted incoming relationship: " + relationship.getId());
                            }
                        })
                        .doOnError(IgnoreNotFoundError)
                        .doOnTerminate(deleteRelationshipsSemaphore::release)
                        .subscribe());
            }

            // Verify that the relationships have been deleted.
            if (deleteRelationshipsSemaphore.tryAcquire(relationshipList.size(), MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS)) {
                // Now the digital twin should be safe to delete

                // Call APIs to delete the twins.
                client.deleteDigitalTwin(twinId)
                    .doOnSuccess(aVoid -> ConsoleLogger.printSuccess("Deleted digital twin: " + twinId))
                    .doOnError(IgnoreNotFoundError)
                    .doOnTerminate(deleteTwinsLatch::countDown)
                    .subscribe();

                // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
                deleteTwinsLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
            }
        }
    }

    /**
     * Delete models created by FullLifecycleSample for the ADT service instance.
     */
    public static void deleteAllModels() {

        ConsoleLogger.printHeader("Deleting models");

        // This is to ensure models are deleted in an order such that no other models are referencing it.
        List<String> models = asList(ROOM_MODEL_ID, WIFI_MODEL_ID, BUILDING_MODEL_ID, FLOOR_MODEL_ID, HVAC_MODEL_ID);

        // Call APIs to delete the models.
        // Note that we are blocking the async API call. This is to ensure models are deleted in an order such that no other models are referencing it.
        models
            .forEach(modelId -> {
                try {
                    client.deleteModel(modelId).block();
                    ConsoleLogger.printSuccess("Deleted model: " + modelId);
                } catch (ErrorResponseException ex) {
                    if (ex.getResponse().getStatusCode() != HTTP_NOT_FOUND) {
                        ConsoleLogger.printFatal("Could not delete model " + modelId + " due to " + ex);
                    }
                }
            });
    }

    /**
     * Loads all the models found in the Models directory into memory and uses CreateModelsAsync API to create all the models in the ADT service instance.
     * @throws IOException If an I/O error is thrown when accessing the starting file.
     * @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
     */
    public static void createAllModels() throws IOException, InterruptedException {
        ConsoleLogger.printHeader("Creating models");
        List<String> modelsToCreate = new ArrayList<>(FileHelper.loadAllFilesInPath(MODELS_PATH).values());
        final CountDownLatch createModelsLatch = new CountDownLatch(1);

        // Call API to create the models. For each async operation, once the operation is completed successfully, a latch is counted down.
        client.createModels(modelsToCreate)
            .doOnNext(listOfModelData -> listOfModelData.forEach(
                modelData -> ConsoleLogger.printSuccess("Created model: " + modelData.getId())
            ))
            .doOnError(IgnoreConflictError)
            .doOnTerminate(createModelsLatch::countDown)
            .subscribe();

        // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
        createModelsLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    }

    /**
     * Gets all the models within the ADT service instance.
     * @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
     */
    public static void listAllModels() throws InterruptedException {
        ConsoleLogger.printHeader("Listing models");
        final CountDownLatch listModelsLatch = new CountDownLatch(1);

        // Call API to list the models. For each async operation, once the operation is completed successfully, a latch is counted down.
        client.listModels()
            .doOnNext(modelData -> ConsoleLogger.printSuccess("Retrieved model: " + modelData.getId() + ", display name '" + modelData.getDisplayName().get("en") + "'," +
                    " upload time '" + modelData.getUploadTime() + "' and decommissioned '" + modelData.isDecommissioned() + "'"))
            .doOnError(throwable -> ConsoleLogger.printFatal("List models error: " + throwable))
            .doOnTerminate(listModelsLatch::countDown)
            .subscribe();

        // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
        listModelsLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    }

    /**
     * Creates all twins specified in the DTDL->DigitalTwins directory.
     * @throws IOException If an I/O error is thrown when accessing the starting file.
     * @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
     */
    public static void createAllTwins() throws IOException, InterruptedException {
        ConsoleLogger.printHeader("Create digital twins");
        Map<String, String> twins = FileHelper.loadAllFilesInPath(TWINS_PATH);
        final CountDownLatch createTwinsLatch = new CountDownLatch(twins.size());

        // Call APIs to create the twins. For each async operation, once the operation is completed successfully, a latch is counted down.
        twins
            .forEach((twinId, twinContent) -> client.createDigitalTwin(twinId, twinContent, String.class)
                .subscribe(
                    twin -> ConsoleLogger.printSuccess("Created digital twin: " + twinId + "\n\t Body: " + twin),
                    throwable -> ConsoleLogger.printFatal("Could not create digital twin " + twinId + " due to " + throwable),
                    createTwinsLatch::countDown));

        // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
        createTwinsLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    }

    /**
     * Creates all the relationships defined in the DTDL->Relationships directory
     * @throws IOException If an I/O error is thrown when accessing the starting file.
     * @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
     */
    public static void connectTwinsTogether() throws IOException, InterruptedException {
        ConsoleLogger.printHeader("Connect digital twins");
        Map<String, String> allRelationships = FileHelper.loadAllFilesInPath(RELATIONSHIPS_PATH);
        final CountDownLatch connectTwinsLatch = new CountDownLatch(4);

        // For each relationship array we deserialize it first.
        // We deserialize as BasicRelationship to get the entire custom relationship (custom relationship properties).
        allRelationships.values().forEach(
            relationshipContent -> {
                try {
                    List<BasicRelationship> relationships = MAPPER.readValue(relationshipContent, new TypeReference<List<BasicRelationship>>() { });

                    // From loaded relationships, get the source Id and Id from each one, and create it with full relationship payload.
                    relationships
                        .forEach(relationship -> {
                            try {
                                client.createRelationship(relationship.getSourceId(), relationship.getId(), MAPPER.writeValueAsString(relationship), String.class)
                                    .doOnSuccess(s -> ConsoleLogger.printSuccess("Linked twin " + relationship.getSourceId() + " to twin " + relationship.getTargetId() + " as " + relationship.getName()))
                                    .doOnError(IgnoreConflictError)
                                    .doOnTerminate(connectTwinsLatch::countDown)
                                    .subscribe();
                            } catch (JsonProcessingException e) {
                                throw new RuntimeException("JsonProcessingException while serializing relationship string from BasicRelationship: ", e);
                            }
                        });
                } catch (JsonProcessingException e) {
                    throw new RuntimeException("JsonProcessingException while deserializing relationship string to BasicRelationship: ", e);
                }
            }
        );

        // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
        connectTwinsLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    }

    /**
     *
     * Queries for all the digital twins.
     * @throws InterruptedException If the current thread is interrupted while waiting to acquire latch.
     */
    public static void queryTwins() throws InterruptedException {
        ConsoleLogger.printHeader("QUERY DIGITAL TWINS");

        final CountDownLatch queryLatch = new CountDownLatch(1);

        ConsoleLogger.printHeader("Making a twin query and iterating over the results.");

        // Call API to query digital twins. For each async operation, once the operation is completed successfully, a latch is counted down.
        client.query("SELECT * FROM digitaltwins", String.class, null)
            .doOnNext(queryResult -> ConsoleLogger.printHeader("Query result: " + queryResult))
            .doOnError(throwable -> ConsoleLogger.printFatal("Query error: " + throwable))
            .doOnTerminate(queryLatch::countDown)
            .subscribe();

        // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
        queryLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);

        ConsoleLogger.printHeader("Making a twin query, with query-charge header extraction.");

        final CountDownLatch queryWithChargeLatch = new CountDownLatch(1);

        // Call API to query digital twins. For each async operation, once the operation is completed successfully, a latch is counted down.
        client.query("SELECT * FROM digitaltwins", BasicDigitalTwin.class, null)
            .byPage()
            .doOnNext(page ->
            {
                ConsoleLogger.printHeader("Query charge: " + getQueryCharge(page));
                page.getValue()
                    .forEach(item -> ConsoleLogger.printHeader("Found digital twin: " + item.getId()));
            })
            .doOnError(throwable -> ConsoleLogger.printFatal("Query error: " + throwable))
            .doOnTerminate(queryLatch::countDown)
            .subscribe();

        // Wait until the latch count reaches zero, signifying that the async calls have completed successfully.
        queryWithChargeLatch.await(MAX_WAIT_TIME_ASYNC_OPERATIONS_IN_SECONDS, TimeUnit.SECONDS);
    }
}


text:
<form{{ form.attributes|raw }}>
{% if form.hidden %}
    {% for element in form.hidden %}{{ element|raw }}
    {% endfor %}
{% endif %}
{{ _self.meerkat_container(form.elements) }}
{% if form.required_note %}
{{ form.required_note }}
{% endif %}
</form>

{# =============================================================================
ПРОХОД ПРО ГРУППЕ ПОЛЕЙ
============================================================================= #}
{% macro meerkat_container(elements, ingroup) %}
    {% for element in elements %}
        {% if 'fieldset' == element.type %}
            {{ _self.meerkat_fieldset(element) }}
        {% elseif 'checkbox' == element.type %}
            {% if ingroup %}
                {{ _self.meerkat_checkbox_ingroup(element, loop.first, loop.last) }}
            {% else %}
                {{ _self.meerkat_checkbox(element) }}
            {% endif %}
        {% elseif 'radio' == element.type %}
                {{ _self.meerkat_radio_ingroup(element, loop.first, loop.last) }}
        {% elseif 'group' == element.type %}
            {{ _self.meerkat_group(element) }}
        {% elseif 'group_actions' == element.type %}
            {{ _self.meerkat_group_actions(element) }}
        {% else %}
            {% if ingroup %}
                {{ _self.meerkat_element_ingroup(element) }}
            {% else %}
                {{ _self.meerkat_element(element) }}
            {% endif %}
        {% endif %}
    {% endfor %}
{% endmacro %}

{# =============================================================================
    FIELDSET
============================================================================= #}
{% macro meerkat_fieldset(element) %}
<fieldset>
    <legend>{{ element.label }}</legend>
    {{ _self.meerkat_container(element.elements) }}
</fieldset>
{% endmacro %}

{# =============================================================================
    HTML ЭЛЕМЕНТА С ПРЕПЕНДАМИ И АППЕНДАМИ
============================================================================= #}
{% macro meerkat_element_html_addon(element) %}

    {% if element.prepend %}
        {{ element.prepend|raw }}
    {% endif %}
    {{ element.html|raw }}
    {% if element.append %}
        {{ element.append|raw }}
    {% endif %}

{% endmacro %}

{# =============================================================================
    МЕТКА, ОПИСАНИЕ, ПРИМЕР ЗАПОЛНЕНИЯ
============================================================================= #}
{% macro meerkat_element_label(element, class) %}
    {% if element.label %}
        {% if element.required %}*{% endif %} {{ element.label }}
    {% endif %}
{% endmacro %}

{% macro meerkat_element_desc(element) %}
    {% if element.desc %}

{{ element.desc|raw }}

    {% endif %}
{% endmacro %}

{% macro meerkat_element_example(element) %}
    {% if element.example %}

            Например:
            {% for example in element.example %}
            {{ example[1] }}
            {% endfor %}

    {% endif %}
{% endmacro %}

{% macro meerkat_element_error(element) %}

{{ element.error }}

{% endmacro %}

{# =============================================================================
    ЭЛЕМЕНТ В ГРУППЕ
============================================================================= #}
{% macro meerkat_element_ingroup(element, offset) %}
    {% set wrap_class = 'frm-group-element' %}
    {% if element.wrap_class %}
        {% set wrap_class = wrap_class~ ' '~element.wrap_class %}
    {% endif %}
    {% if element.error %}
        {% set wrap_class = wrap_class~ ' has-error' %}
    {% endif %}

    {% if element.prepend or element.append  %}
        {{ _self.meerkat_element_html_addon(element) }}
    {% else %}
        {{ element.html|raw }}
    {% endif %}
    {{ _self.meerkat_element_error(element) }}
    {{ _self.meerkat_element_desc(element) }}
    {{ _self.meerkat_element_example(element) }}

{% endmacro %}

{# =============================================================================
    ЭЛЕМЕНТ
============================================================================= #}
{% macro meerkat_element(element) %}

        {{ _self.meerkat_element_label(element, 'frm-group-label') }}

            {% if element.prepend or element.append  %}
                {{ _self.meerkat_element_html_addon(element) }}
            {% else %}
                {{ element.html|raw }}
            {% endif %}
            {{ _self.meerkat_element_error(element) }}
            {{ _self.meerkat_element_desc(element) }}
            {{ _self.meerkat_element_example(element) }}

{% endmacro %}

{# =============================================================================
    ГРУППА
============================================================================= #}
{% macro meerkat_group(element) %}
{% if element.label %}

    {% if element.required %}*{% endif %} {{ element.label }}
{% else %}

{% endif %}

        {{ _self.meerkat_container(element.elements, true) }}

    {{ _self.meerkat_element_error(element) }}

{% endmacro %}

{% macro meerkat_group_actions(element) %}

    {% for element in element.elements %}
    {{ element.html|raw}}
    {% endfor %}

{% endmacro %}

{# =============================================================================
    CHECKBOX
============================================================================= #}
{% macro meerkat_checkbox(element) %}

                        {{ element.html|raw }}
                        {% if element.required %}*{% endif %} {{ element.label|raw }}

                    {{ _self.meerkat_element_error(element) }}

{% endmacro %}

{% macro meerkat_checkbox_ingroup(element, first, last) %}
    {% if element.is_inline %}

        {{ element.html|raw }}
        {% if element.required %}*{% endif %} {{ element.label|raw }}
        {{ _self.meerkat_element_error(element) }}

        {% else %}

            {{ element.html|raw }}
            {% if element.required %}*{% endif %} {{ element.label|raw }}
            {{ _self.meerkat_element_error(element) }}

    {% endif %}
{% endmacro %}

{# =============================================================================
    RADIO
============================================================================= #}
{% macro meerkat_radio_ingroup(element, first, last) %}
    {% if element.is_inline %}

            {{ element.html|raw }}
            {% if element.required %}*{% endif %} {{ element.label|raw }}
            {{ _self.meerkat_element_error(element) }}

    {% else %}

                {{ element.html|raw }}
                {% if element.required %}*{% endif %} {{ element.label|raw }}

    {% endif %}
{% endmacro %}


text:
package modules.database.tables;

import modules.database.FieldBase;
import modules.database.TableBase;

import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.List;

public class NonCapitalization implements TableBase {
    private static final NonCapitalization self = new NonCapitalization();

    public enum Fields implements FieldBase {
        WORD {
            @Override
            public String fieldName() {
                return "word";
            }

            @Override
            public String type() {
                return "VARCHAR(255)";
            }
        }
    }

    private NonCapitalization() {

    }

    public static NonCapitalization instance() {
        return self;
    }

    @Override
    public String tableName() {
        return "NonCapitalization";
    }

    @Override
    public List<FieldBase> primaryKeys() {
        return Arrays.asList(Fields.WORD);
    }

    @Override
    public List<FieldBase> uniqueKeys() {
        return null;
    }

    @Override
    public List<SimpleEntry<FieldBase, SimpleEntry<TableBase, FieldBase>>> foreignKeys() {
        return null;
    }

    @Override
    public NonCapitalization.Fields[] fields() {
        return NonCapitalization.Fields.values();
    }

    @Override
    public FieldBase id() {
        return null;
    }
}