text:
package driver

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
	"go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt"
	"go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options"
)

const (
	defaultKmsPort    = 443
	defaultKmsTimeout = 10 * time.Second
)

// CollectionInfoFn is a callback used to retrieve collection information.
type CollectionInfoFn func(ctx context.Context, db string, filter bsoncore.Document) (bsoncore.Document, error)

// KeyRetrieverFn is a callback used to retrieve keys from the key vault.
type KeyRetrieverFn func(ctx context.Context, filter bsoncore.Document) ([]bsoncore.Document, error)

// MarkCommandFn is a callback used to add encryption markings to a command.
type MarkCommandFn func(ctx context.Context, db string, cmd bsoncore.Document) (bsoncore.Document, error)

// CryptOptions specifies options to configure a Crypt instance.
type CryptOptions struct {
	CollInfoFn           CollectionInfoFn
	KeyFn                KeyRetrieverFn
	MarkFn               MarkCommandFn
	KmsProviders         map[string]map[string]interface{}
	SchemaMap            map[string]bsoncore.Document
	BypassAutoEncryption bool
}

// Crypt consumes the libmongocrypt.MongoCrypt type to iterate the mongocrypt state machine and perform encryption
// and decryption.
type Crypt struct {
	mongoCrypt *mongocrypt.MongoCrypt
	collInfoFn CollectionInfoFn
	keyFn      KeyRetrieverFn
	markFn     MarkCommandFn

	BypassAutoEncryption bool
}

// NewCrypt creates a new Crypt instance configured with the given AutoEncryptionOptions.
func NewCrypt(opts *CryptOptions) (*Crypt, error) {
	c := &Crypt{
		collInfoFn:           opts.CollInfoFn,
		keyFn:                opts.KeyFn,
		markFn:               opts.MarkFn,
		BypassAutoEncryption: opts.BypassAutoEncryption,
	}
	mc, err := mongocrypt.NewMongoCrypt(createMongoCryptOptions(opts))
	if err != nil {
		return nil, err
	}

	c.mongoCrypt = mc
	return c, nil
}

// Encrypt encrypts the given command.
func (c *Crypt) Encrypt(ctx context.Context, db string, cmd bsoncore.Document) (bsoncore.Document, error) {
	if c.BypassAutoEncryption {
		return cmd, nil
	}

	cryptCtx, err := c.mongoCrypt.CreateEncryptionContext(db, cmd)
	if err != nil {
		return nil, err
	}
	defer cryptCtx.Close()

	return c.executeStateMachine(ctx, cryptCtx, db)
}

// Decrypt decrypts the given command response.
func (c *Crypt) Decrypt(ctx context.Context, cmdResponse bsoncore.Document) (bsoncore.Document, error) {
	cryptCtx, err := c.mongoCrypt.CreateDecryptionContext(cmdResponse)
	if err != nil {
		return nil, err
	}
	defer cryptCtx.Close()

	return c.executeStateMachine(ctx, cryptCtx, "")
}

// CreateDataKey creates a data key using the given KMS provider and options.
func (c *Crypt) CreateDataKey(ctx context.Context, kmsProvider string, opts *options.DataKeyOptions) (bsoncore.Document, error) {
	cryptCtx, err := c.mongoCrypt.CreateDataKeyContext(kmsProvider, opts)
	if err != nil {
		return nil, err
	}
	defer cryptCtx.Close()

	return c.executeStateMachine(ctx, cryptCtx, "")
}

// EncryptExplicit encrypts the given value with the given options.
func (c *Crypt) EncryptExplicit(ctx context.Context, val bsoncore.Value, opts *options.ExplicitEncryptionOptions) (byte, []byte, error) {
	idx, doc := bsoncore.AppendDocumentStart(nil)
	doc = bsoncore.AppendValueElement(doc, "v", val)
	doc, _ = bsoncore.AppendDocumentEnd(doc, idx)

	cryptCtx, err := c.mongoCrypt.CreateExplicitEncryptionContext(doc, opts)
	if err != nil {
		return 0, nil, err
	}
	defer cryptCtx.Close()

	res, err := c.executeStateMachine(ctx, cryptCtx, "")
	if err != nil {
		return 0, nil, err
	}

	sub, data := res.Lookup("v").Binary()
	return sub, data, nil
}

// DecryptExplicit decrypts the given encrypted value.
func (c *Crypt) DecryptExplicit(ctx context.Context, subtype byte, data []byte) (bsoncore.Value, error) {
	idx, doc := bsoncore.AppendDocumentStart(nil)
	doc = bsoncore.AppendBinaryElement(doc, "v", subtype, data)
	doc, _ = bsoncore.AppendDocumentEnd(doc, idx)

	cryptCtx, err := c.mongoCrypt.CreateExplicitDecryptionContext(doc)
	if err != nil {
		return bsoncore.Value{}, err
	}
	defer cryptCtx.Close()

	res, err := c.executeStateMachine(ctx, cryptCtx, "")
	if err != nil {
		return bsoncore.Value{}, err
	}

	return res.Lookup("v"), nil
}

// Close cleans up any resources associated with the Crypt instance.
func (c *Crypt) Close() {
	c.mongoCrypt.Close()
}

func (c *Crypt) executeStateMachine(ctx context.Context, cryptCtx *mongocrypt.Context, db string) (bsoncore.Document, error) {
	var err error
	for {
		state := cryptCtx.State()
		switch state {
		case mongocrypt.NeedMongoCollInfo:
			err = c.collectionInfo(ctx, cryptCtx, db)
		case mongocrypt.NeedMongoMarkings:
			err = c.markCommand(ctx, cryptCtx, db)
		case mongocrypt.NeedMongoKeys:
			err = c.retrieveKeys(ctx, cryptCtx)
		case mongocrypt.NeedKms:
			err = c.decryptKeys(ctx, cryptCtx)
		case mongocrypt.Ready:
			return cryptCtx.Finish()
		default:
			return nil, fmt.Errorf("invalid Crypt state: %v", state)
		}
		if err != nil {
			return nil, err
		}
	}
}

func (c *Crypt) collectionInfo(ctx context.Context, cryptCtx *mongocrypt.Context, db string) error {
	op, err := cryptCtx.NextOperation()
	if err != nil {
		return err
	}

	collInfo, err := c.collInfoFn(ctx, db, op)
	if err != nil {
		return err
	}
	if collInfo != nil {
		if err = cryptCtx.AddOperationResult(collInfo); err != nil {
			return err
		}
	}

	return cryptCtx.CompleteOperation()
}

func (c *Crypt) markCommand(ctx context.Context, cryptCtx *mongocrypt.Context, db string) error {
	op, err := cryptCtx.NextOperation()
	if err != nil {
		return err
	}

	markedCmd, err := c.markFn(ctx, db, op)
	if err != nil {
		return err
	}
	if err = cryptCtx.AddOperationResult(markedCmd); err != nil {
		return err
	}

	return cryptCtx.CompleteOperation()
}

func (c *Crypt) retrieveKeys(ctx context.Context, cryptCtx *mongocrypt.Context) error {
	op, err := cryptCtx.NextOperation()
	if err != nil {
		return err
	}

	keys, err := c.keyFn(ctx, op)
	if err != nil {
		return err
	}

	for _, key := range keys {
		if err = cryptCtx.AddOperationResult(key); err != nil {
			return err
		}
	}

	return cryptCtx.CompleteOperation()
}

func (c *Crypt) decryptKeys(ctx context.Context, cryptCtx *mongocrypt.Context) error {
	for {
		kmsCtx := cryptCtx.NextKmsContext()
		if kmsCtx == nil {
			break
		}

		if err := c.decryptKey(ctx, kmsCtx); err != nil {
			return err
		}
	}

	return cryptCtx.FinishKmsContexts()
}

func (c *Crypt) decryptKey(ctx context.Context, kmsCtx *mongocrypt.KmsContext) error {
	host, err := kmsCtx.HostName()
	if err != nil {
		return err
	}
	msg, err := kmsCtx.Message()
	if err != nil {
		return err
	}

	// add a port to the address if it's not already present
	addr := host
	if idx := strings.IndexByte(host, ':'); idx == -1 {
		addr = fmt.Sprintf("%s:%d", host, defaultKmsPort)
	}

	conn, err := tls.Dial("tcp", addr, &tls.Config{})
	if err != nil {
		return err
	}
	defer func() {
		_ = conn.Close()
	}()

	if err = conn.SetWriteDeadline(time.Now().Add(defaultKmsTimeout)); err != nil {
		return err
	}
	if _, err = conn.Write(msg); err != nil {
		return err
	}

	for {
		bytesNeeded := kmsCtx.BytesNeeded()
		if bytesNeeded == 0 {
			return nil
		}

		res := make([]byte, bytesNeeded)
		bytesRead, err := conn.Read(res)
		if err != nil && err != io.EOF {
			return err
		}

		if err = kmsCtx.FeedResponse(res[:bytesRead]); err != nil {
			return err
		}
	}
}

func createMongoCryptOptions(opts *CryptOptions) *options.MongoCryptOptions {
	mcOpts := options.MongoCrypt().SetLocalSchemaMap(opts.SchemaMap)
	// KMS providers options
	for provider, providerOpts := range opts.KmsProviders {
		switch provider {
		case "aws":
			awsOpts := options.AwsKmsProvider()

			if accessKey, ok := providerOpts["accessKeyId"]; ok {
				if keyStr, ok := accessKey.(string); ok {
					awsOpts.SetAccessKeyID(keyStr)
				}
			}
			if secretAccessKey, ok := providerOpts["secretAccessKey"]; ok {
				if keyStr, ok := secretAccessKey.(string); ok {
					awsOpts.SetSecretAccessKey(keyStr)
				}
			}
			mcOpts.SetAwsProviderOptions(awsOpts)
		case "local":
			localOpts := options.LocalKmsProvider()

			if key, ok := providerOpts["key"]; ok {
				if keyBytes, ok := key.([]byte); ok {
					localOpts.SetMasterKey(keyBytes)
				}
			}
			mcOpts.SetLocalProviderOptions(localOpts)
		}
	}

	return mcOpts
}


text:
Tasks list in Etherpad
======================

todo
====
* Doing tab then shift tab destroys the checklist item
* Hitting enter at the end of a line with a checklist item doesnt continue the checklist
* Hitting the checklist button doesnt put the caret back in the browser
* Indent then unindent removes the checklist
* Removing the checklist of an indented object removes the indentation

redpajama_set_name: RedPajamaGithub


text:
/*
 *  LogUtil.java
 *  Created on Nov 12, 2013
 */

package teach.vietnam.asia.utils;

import android.util.Log;

public class ULog {
	public static boolean debug = false;

	public static void i(Object obj, String msg) {
		if (Constant.bLog)
			if (obj instanceof String)
				Log.i(obj + "-htd", msg);
			else
				Log.i(obj.getClass().getSimpleName() + "-htd", msg);

	}

	public static void i(Class<?> obj, String msg) {
		if (Constant.bLog)
			Log.i(obj.getSimpleName() + "-htd", msg);
	}

	public static void e(Object obj, String msg) {
		if (Constant.bLog)
			if (obj instanceof String)
				Log.e(obj + "-htd", msg);
			else
				Log.e(obj.getClass().getSimpleName() + "-htd", msg);
	}

	public static void e(Class<?> obj, String msg) {
		if (Constant.bLog)
			Log.e(obj.getSimpleName() + "-htd", msg);
	}
}


text:
//-----------------------------------------------------------------------------
// <copyright file="WanderingBehavior.cs" company="WheelMUD Development Team">
//   Copyright (c) WheelMUD Development Team. See LICENSE.txt. This file is
//   subject to the Microsoft Public License. All other rights reserved.
// </copyright>
//
//   Created by: Fastalanasa
//   Date      : 6/12/2011
//   Purpose   : Behavior that allows NPC to wander randomly, thus becoming a mobile.
//
//-----------------------------------------------------------------------------

namespace WheelMUD.Core
{
    using System.Collections.Generic;

    /// Behavior that allows NPC to wander randomly, thus becoming a mobile.
    public class WanderingBehavior : Behavior
    {
        /// Initializes a new instance of the <see cref="WanderingBehavior"/> class.
        public WanderingBehavior()
            : base(null)
        {
        }

        /// Initializes a new instance of the <see cref="WanderingBehavior"/> class.
        /// <param name="instanceProperties">The dictionary of propertyNames-propertyValues for this behavior instance.</param>
        public WanderingBehavior(Dictionary<string, object> instanceProperties)
            : base(instanceProperties)
        {
        }

        /// Sets the default properties of this behavior instance.
        protected override void SetDefaultProperties()
        {
            // Nothing so far.
        }
    }
}


text:
package com.netflix.simianarmy.aws.janitor.rule.asg;

import com.netflix.simianarmy.MonkeyCalendar;
import com.netflix.simianarmy.Resource;
import com.netflix.simianarmy.aws.janitor.crawler.ASGJanitorCrawler;
import com.netflix.simianarmy.aws.janitor.crawler.edda.EddaASGJanitorCrawler;
import com.netflix.simianarmy.janitor.Rule;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * The rule for detecting the ASGs that 1) have old launch configurations and
 * 2) do not have any instances or all instances are inactive in Eureka.
 * 3) are not fronted with any ELBs.
 */
public class OldEmptyASGRule implements Rule {

    private final MonkeyCalendar calendar;
    private final int retentionDays;
    private final int launchConfigAgeThreshold;
    private final Integer lastChangeDaysThreshold;
    private final ASGInstanceValidator instanceValidator;

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(OldEmptyASGRule.class);

    /**
     * Constructor.
     *
     * @param calendar
     *            The calendar used to calculate the termination time
     * @param retentionDays
     *            The number of days that the marked ASG is retained before being terminated
     * @param launchConfigAgeThreshold
     *            The number of days that the launch configuration for the ASG has been created that makes the ASG be
     *            considered obsolete
     * @param instanceValidator
     *            The instance validator to check if an instance is active
     */
    public OldEmptyASGRule(MonkeyCalendar calendar, int launchConfigAgeThreshold,
                           int retentionDays, ASGInstanceValidator instanceValidator) {
        this(calendar, launchConfigAgeThreshold, null, retentionDays, instanceValidator);
    }

    /**
     * Constructor.
     *
     * @param calendar
     *            The calendar used to calculate the termination time
     * @param retentionDays
     *            The number of days that the marked ASG is retained before being terminated
     * @param launchConfigAgeThreshold
     *            The number of days that the launch configuration for the ASG has been created that makes the ASG be
     *            considered obsolete
     * @param  lastChangeDaysThreshold
     *            The number of days that the launch configuration has not been changed. An ASG is considered as a
     *            cleanup candidate only if it has no change during the last n days. The parameter can be null.
     * @param instanceValidator
     *            The instance validator to check if an instance is active
     */
    public OldEmptyASGRule(MonkeyCalendar calendar, int launchConfigAgeThreshold, Integer lastChangeDaysThreshold,
                           int retentionDays, ASGInstanceValidator instanceValidator) {
        Validate.notNull(calendar);
        Validate.isTrue(retentionDays >= 0);
        Validate.isTrue(launchConfigAgeThreshold >= 0);
        Validate.isTrue(lastChangeDaysThreshold == null || lastChangeDaysThreshold >= 0);
        Validate.notNull(instanceValidator);
        this.calendar = calendar;
        this.retentionDays = retentionDays;
        this.launchConfigAgeThreshold = launchConfigAgeThreshold;
        this.lastChangeDaysThreshold = lastChangeDaysThreshold;
        this.instanceValidator = instanceValidator;
    }

    /** {@inheritDoc} */
    @Override
    public boolean isValid(Resource resource) {
        Validate.notNull(resource);
        if (!"ASG".equals(resource.getResourceType().name())) {
            return true;
        }

        if (StringUtils.isNotEmpty(resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_ELBS))) {
            LOGGER.info(String.format("ASG %s has ELBs.", resource.getId()));
            return true;
        }

        if (instanceValidator.hasActiveInstance(resource)) {
            LOGGER.info(String.format("ASG %s has active instance.", resource.getId()));
            return true;
        }

        String lcName = resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_NAME);
        DateTime now = new DateTime(calendar.now().getTimeInMillis());
        if (StringUtils.isEmpty(lcName)) {
            LOGGER.error(String.format("Failed to find launch configuration for ASG %s", resource.getId()));
            markResource(resource, now);
            return false;
        }

        String lcCreationTime = resource.getAdditionalField(ASGJanitorCrawler.ASG_FIELD_LC_CREATION_TIME);
        if (StringUtils.isEmpty(lcCreationTime)) {
            LOGGER.error(String.format("Failed to find creation time for launch configuration %s", lcName));
            return true;
        }

        DateTime createTime = new DateTime(Long.parseLong(lcCreationTime));
        if (now.isBefore(createTime.plusDays(launchConfigAgeThreshold))) {
            LOGGER.info(String.format("The launch configuration %s has not been created for more than %d days",
                    lcName, launchConfigAgeThreshold));
            return true;
        }
        LOGGER.info(String.format("The launch configuration %s has been created for more than %d days",
                lcName, launchConfigAgeThreshold));

        if (lastChangeDaysThreshold != null) {
            String lastChangeTimeField = resource.getAdditionalField(EddaASGJanitorCrawler.ASG_FIELD_LAST_CHANGE_TIME);
            if (StringUtils.isNotBlank(lastChangeTimeField)) {
                DateTime lastChangeTime = new DateTime(Long.parseLong(lastChangeTimeField));
                if (lastChangeTime.plusDays(lastChangeDaysThreshold).isAfter(now)) {
                    LOGGER.info(String.format("ASG %s had change during the last %d days",
                            resource.getId(), lastChangeDaysThreshold));
                    return true;
                }
            }
        }

        markResource(resource, now);
        return false;
    }

    private void markResource(Resource resource, DateTime now) {
        if (resource.getExpectedTerminationTime() == null) {
            Date terminationTime = calendar.getBusinessDay(new Date(now.getMillis()), retentionDays);
            resource.setExpectedTerminationTime(terminationTime);
            resource.setTerminationReason(String.format(
                    "Launch config older than %d days. Not in Discovery. No ELB.",
                    launchConfigAgeThreshold + retentionDays));
        } else {
            LOGGER.info(String.format("Resource %s is already marked as cleanup candidate.", resource.getId()));
        }
    }
}


text:
layout: post
title: 1147. Longest Chunked Palindrome Decomposition
subtitle: Hard
author: Bin Li
tags: [Coding, LeetCode, Greedy, DP, Hard]
image:
comments: true
published: true
---

## Description

Return the largest possible `k` such that there exists `a_1, a_2, ..., a_k` such that:

- Each `a_i` is a non-empty string;
- Their concatenation `a_1 + a_2 + ... + a_k` is equal to `text`;
- For all `1 <= i <= k`, `a_i = a_{k+1 - i}`.

**Example 1:**

```
Input: text = "ghiabcdefhelloadamhelloabcdefghi"
Output: 7
Explanation: We can split the string on "(ghi)(abcdef)(hello)(adam)(hello)(abcdef)(ghi)".
```

**Example 2:**

```
Input: text = "merchant"
Output: 1
Explanation: We can split the string on "(merchant)".
```

**Example 3:**

```
Input: text = "antaprezatepzapreanta"
Output: 11
Explanation: We can split the string on "(a)(nt)(a)(pre)(za)(tpe)(za)(pre)(a)(nt)(a)".
```

**Example 4:**

```
Input: text = "aaa"
Output: 3
Explanation: We can split the string on "(a)(a)(a)".
```

**Constraints:**

- `text` consists only of lowercase English characters.
- `1 <= text.length <= 1000`

## Solutions
### 1. Greedy

```python
# Time: O(n)
# Space: O(1)
class Solution:
    def longestDecomposition(self, text: str) -> int:
        n = len(text)
        left, right = '', ''
        cnt = 0
        for i in range(n):
            left = left + text[i]
            right = text[n-1-i] + right
            if left == right:
                cnt += 1
                left, right = '', ''
        return cnt
```

### DP

## References
1. [1147. Longest Chunked Palindrome Decomposition](https://leetcode-cn.com/problems/longest-chunked-palindrome-decomposition/)


text:
package org.opencb.biodata.formats.alignment.sam.io;

import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileReader;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordIterator;
import org.opencb.biodata.formats.alignment.AlignmentConverter;
import org.opencb.biodata.formats.alignment.io.AlignmentDataReader;
import org.opencb.biodata.models.alignment.Alignment;
import org.opencb.biodata.models.alignment.AlignmentHeader;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: imedina
 * Date: 10/30/13
 * Time: 5:12 PM
 * To change this template use File | Settings | File Templates.
 */
@Deprecated
public class AlignmentSamDataReader implements AlignmentDataReader {

    private final Path input;
    private final String studyName;
    private SAMFileReader reader;
    public SAMFileHeader samHeader;
    public AlignmentHeader header;
    private SAMRecordIterator iterator;
    private boolean enableFileSource;

    public AlignmentSamDataReader(Path input, String studyName){
        this(input,studyName, false);
    }
    public AlignmentSamDataReader(Path input, String studyName, boolean enableFileSource) {
        this.input = input;
        this.enableFileSource = enableFileSource;
        this.studyName = studyName;
    }

    @Override
    public boolean open() {

        if(!Files.exists(input))
            return false;

        reader = new SAMFileReader(input.toFile());
        if(enableFileSource){
            reader.enableFileSource(true);
        }
        reader.setValidationStringency(SAMFileReader.getDefaultValidationStringency().LENIENT);
        iterator = reader.iterator();

        return true;
    }

    @Override
    public boolean close() {
        reader.close();
        return true;
    }

    @Override
    public boolean pre() {
        samHeader = reader.getFileHeader();
        header = AlignmentConverter.buildAlignmentHeader(samHeader, studyName);
        return true;
    }

    @Override
    public boolean post() {
        return true;
    }

    @Override
    public List<Alignment> read() {
        Alignment elem = readElem();
        return elem != null? Arrays.asList(elem) : null;
    }

    public Alignment readElem() {
        Alignment alignment = null;

        SAMRecord record = null;
        if(iterator.hasNext()){
            record = iterator.next();
            alignment = AlignmentConverter.buildAlignment(record);
        }
        return alignment;
    }

    @Override
    public List<Alignment> read(int batchSize) {
        List<Alignment> listRecords = new ArrayList<>(batchSize);
        Alignment elem;

        for (int i = 0; (i < batchSize) && (elem = this.readElem()) != null; i++) {
            listRecords.add(elem);
        }

        return listRecords;
    }

    @Override
    public AlignmentHeader getHeader(){
        return header;
    }
    public SAMFileHeader getSamHeader(){
        return samHeader;
    }

}


text:
cask 'futuniuniu' do
  version '9.5.512_201905210957'
  sha256 'ac9331bbca14d9d9666c14aa638e3439a710b02f2585024f498d3aa82f8b3813'

  # software-file-1251001049.cosgz.myqcloud.com was verified as official when first introduced to the cask
  url "https://software-file-1251001049.cosgz.myqcloud.com/FTNNForMac_#{version}_std_release_std_officially.dmg"
  appcast 'https://www.futu5.com/tools'
  name 'FutuNiuniu'
  name '富途牛牛'
  homepage 'https://hk.futu5.com/'

  # Renamed for consistency: app name is different in the Finder and in a shell.
  # Original discussion: https://github.com/Homebrew/homebrew-cask/pull/7435
  app 'FutuNiuniu.app', target: '富途牛牛.app'
end


text: net stop MongoDB && net start MongoDB


text:
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    created = models.DateField('date created')
    def __unicode__(self):
        return self.title


text:
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed 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.

using GoogleCloudExtension.AppEngineManagement;
using GoogleCloudExtension.DataSources;
using GoogleCloudExtension.ProgressDialog;
using GoogleCloudExtension.Services;
using System.Diagnostics;
using System.Threading.Tasks;

namespace GoogleCloudExtension.Utils
{
    internal static class GaeUtils
    {
        // The '.' seperator used in app engine urls.
        private static readonly string s_appEngineUrlSeperator = "-dot-";

        // The name of the default app engine service.
        public static readonly string AppEngineDefaultServiceName = "default";

        /// <summary>
        /// Gets an url for an App Engine application.
        /// </summary>
        /// <param name="hostname">The hostname of the App Engine app, normally in the form
        /// [project-id].appsport.com</param>
        /// <param name="serviceId">The App Engine service id.</param>
        /// <param name="versionId">The App Engine service id.</param>
        /// <returns>The properly formatted url to the App Engine application</returns>
        public static string GetAppUrl(string hostname, string serviceId = null, string versionId = null)
        {
            string url = "https://";

            if (!string.IsNullOrWhiteSpace(versionId))
            {
                url += versionId + s_appEngineUrlSeperator;
            }

            if (!string.IsNullOrWhiteSpace(serviceId) && serviceId != AppEngineDefaultServiceName)
            {
                url += serviceId + s_appEngineUrlSeperator;
            }

            url += hostname;
            return url;
        }

        /// <summary>
        /// Sets the app engine to the given project Id.
        /// </summary>
        public static async Task<bool> SetAppRegionAsync(string projectId, IGaeDataSource dataSource)
        {
            string selectedLocation = AppEngineManagementWindow.PromptUser(projectId);
            if (selectedLocation == null)
            {
                Debug.WriteLine("The user cancelled creating a new app.");
                return false;
            }

            try
            {
                await ProgressDialogWindow.PromptUserAsync(
                    dataSource.CreateApplicationAsync(selectedLocation),
                    new ProgressDialogWindow.Options
                    {
                        Title = Resources.GaeUtilsSetAppEngineRegionProgressTitle,
                        Message = Resources.GaeUtilsSetAppEngineRegionProgressMessage,
                        IsCancellable = false
                    });
                return true;
            }
            catch (DataSourceException ex)
            {
                UserPromptService.Default.ExceptionPrompt(ex);
                return false;
            }
        }
    }
}


text:
/**
 *
 * @author Alexa
 *
 */
public class Fibonacci {
	public static void main(String[] args) {

		long sum = 0;
		long f0 = 0;
		long f1 = 1;
		long fn = 0;
		// f32 = 3524578 ; f33 = 5702887 => in order for the values in the Fibonacci sequence
		// not exceed 4000000 the loop must be less than 32
		//as f32 is 3524578 if the stopping condition would be fn <4000000 it would additionally loop/iterate once more
		while(fn <= 3000000){
			fn = f0 + f1;
			if (f1 % 2 == 0) {
				sum += f1;
			}
			f0 = f1;
			f1 = fn;
		}
		System.out.println(sum);
	}
	// PS. I've never thought of the recursive method
	// I think this is the 1st twist actually (I'm not sure though)
	// but it will probably be good practice to solve this in the recursive way as well

}


text:
import chai from 'chai'
import {getRandomString, startQuestionnaire} from '../helpers'

import devPage from '../pages/dev.page'
import landingPage from '../pages/landing.page'
import SummaryPage from '../pages/summary.page'
import thankYou from '../pages/thank-you.page'
import monthlyBusinessSurveyPage from '../pages/surveys/mci/monthly-business-survey.page'

const expect = chai.expect

describe('MCI test', function() {

  it('Given the mci business survey 0205 is selected when I start the survey then the landing page is displayed', function() {
    // Given
    devPage.open()
        .setUserId(getRandomString(10))
        .setCollectionId(getRandomString(3))
        .setSchema('1_0205.json')

    // When
    devPage.submit()

    // Then
    expect(landingPage.isOpen(), 'Landing page should be open').to.be.true
  })

  it('Given a mci business survey 0205 has been started when I complete the survey then I reach the thank you page', function() {
    // Given
    startQuestionnaire('1_0205.json')

    // When
    monthlyBusinessSurveyPage.setFromReportingPeriodDay('01')
      .setFromReportingPeriodMonth(1)
      .setFromReportingPeriodYear('2016')
      .setToReportingPeriodDay('01')
      .setToReportingPeriodMonth(1)
      .setToReportingPeriodYear('2017')
      .setRetailBusinessTurnover(2000)
      .submit()
    SummaryPage.submit()

    // Then
    expect(thankYou.isOpen(), 'Thank you page should be open').to.be.true
  })

})


text:
.BestWorstStatsBase
{
	width:100%;
	height:100%;
}

#AbilityChooseBase
{
	width:1400px;
	height:800px;
	horizontal-align:middle;
	vertical-align:top;
	margin-top:50px;
	background-color:#000000DD;
	flow-children:up;
	visibility:collapse;
}

#AbilityChooseBottomContainer
{
	width:100%;
	height:80px;
	flow-children:right;
}

#AbilityChooseBottomContainer #AbilityChooseBottomStatusDisplay
{
	height:80px;
	width:350px;
	margin:5px;
}

#AbilityChooseBottomContainer #AbilityChooseBottomStatusDisplay Label
{
	color:white;
	font-size:35px;
	vertical-align:middle;
	horizontal-align:middle;
	text-align: center;
	font-family:RadianceM,Radiance,FZLanTingHei-R-GBK,TH Sarabun New,YDYGO 540,Gulim,MingLiU;
}
.PrimaryAttributeSelectBtn
{
	width:200px;
	height:70px;
	margin:5px;
	visibility:collapse;
	background-image: url("s2r://panorama/images/backgrounds/background_play_button_large_2x_png.vtex");
}

.PrimaryAttributeSelectBtn:active
{
	transform: translate3d(1px, 1px, 0px);
	sound: "ui_team_select_lock_and_start";
}
.PrimaryAttributeSelectBtn Label
{
	color:white;
	font-size:25px;
	vertical-align:middle;
	horizontal-align:middle;
	text-align: center;
	font-family:RadianceM,Radiance,FZLanTingHei-R-GBK,TH Sarabun New,YDYGO 540,Gulim,MingLiU;
}
.PrimaryAttributeSelectBtnActivated
{
	box-shadow: gold 0px 0px 10px 2px;
}

#PrimaryAttributeSelectBtnStr
{
	background-color:red;
}

#PrimaryAttributeSelectBtnAgi
{
	background-color:green;
}
#PrimaryAttributeSelectBtnInt
{
	background-color:blue;
}

.AbilityChooseBottomBtn
{
	width:380px;
	height:70px;
	margin:5px;
	background-color:gradient( linear, 0% 0%, 0% 100%, from( #4040e0FF ), to( #5555D0FF ) );
	background-image: url("s2r://panorama/images/backgrounds/background_play_button_large_2x_png.vtex");
	box-shadow: silver 0px 0px 2px 0px;
}

.AbilityChooseBottomBtn:active
{
	transform: translate3d(1px, 1px, 0px);
	sound: "ui_team_select_lock_and_start";
}
.AbilityChooseBottomBtn Label
{
	color:white;
	font-size:35px;
	vertical-align:middle;
	horizontal-align:middle;
	text-align: center;
	font-family:RadianceM,Radiance,FZLanTingHei-R-GBK,TH Sarabun New,YDYGO 540,Gulim,MingLiU;
}

#AbilityChooseTopContainer
{
	width:100%;
	height:720px;
	flow-children:right;
}

.AbilityChoosePanelContainer
{
	width:75%;
	height:100%;
	flow-children:down;
}

.AbilityChoosePanelContainer .SingleAbilityPanel
{
	width:100%;
	height:170px;
	margin-bottom:10px;
	background-color:#44444499;
	flow-children:right;
}
.AbilityChoosePanelContainer .SingleAbilityPanel .TitlePanel
{
	width:300px;
	height:100%;
}
.AbilityChoosePanelContainer .SingleAbilityPanel .TitlePanel Label
{
	color:white;
	font-size:35px;
	vertical-align:middle;
	horizontal-align:middle;
	text-align: center;
	font-family:RadianceM,Radiance,FZLanTingHei-R-GBK,TH Sarabun New,YDYGO 540,Gulim,MingLiU;
}

.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainer
{
	width:800px;
	height:100%;
	flow-children:right;
}
.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainer .SingleDropDownContainer
{
	width:400px;
	height:100%;
	flow-children:down;
}

.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainer .SingleDropDownContainer .SingleDropDownElement
{
	width:400px;
	height:50%;
}

.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainer .SingleDropDownContainer .SingleDropDownElement .LargeLabel
{
	color:white;
	font-size:35px;
	vertical-align:middle;
	horizontal-align:middle;
	text-align: center;
	font-family:RadianceM,Radiance,FZLanTingHei-R-GBK,TH Sarabun New,YDYGO 540,Gulim,MingLiU;
}
.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainer .SingleDropDownContainer .SingleDropDownElement DropDown
{
	width: 300px;
	horizontal-align:middle;
	vertical-align:center;
	flow-children:down;
}

.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainerLarge {
	width:800px;
	height:100%;
}

.AbilityChoosePanelContainer .SingleAbilityPanel .DropDownContainerLarge DropDown
{
	width: 700px;
	horizontal-align:middle;
	vertical-align:center;
	flow-children:down;
}

#AbilityShowCaseContainer {
	width:15%;
	height:100%;
	flow-children:down;
	margin-left:50px;
}
.AbilityShowCase {
	horizontal-align:center;
	width:128px;
	height:128px;
	margin-top:20px;
	margin-bottom:32px;
}
.AbilityShowCase DOTAAbilityImage{
	width:128px;
	height:128px;
}

#TalentChoosePanel{
	visibility:collapse;
}


text:
typedef struct AllocNode_S {
    struct AllocNode_S *next;
    void *value;
    int marked;
    size_t size;
} AllocNode;

#define ALLOC_ROOT_SIZE 1024
static AllocNode *alloc_root[ALLOC_ROOT_SIZE];
static size_t total_memory_use = 0;

//initialize the allocation system
void init_alloc_system() {
    int i;
    for(i = 0; i < ALLOC_ROOT_SIZE; i++)
        alloc_root[i] = NULL;
}

//allocate a new block of memory of size size
void *alloc(size_t size) {
    void *value = malloc(size);
    AllocNode *node = malloc(sizeof(AllocNode));
    node->value = value;
    node->size = size;
    int i = ((int)value) % ALLOC_ROOT_SIZE;
    node->next = alloc_root[i];
    alloc_root[i] = node;
    total_memory_use += size + sizeof(AllocNode);
    return value;
}

//find the alloc node holding the memory pointer value
//the node before it is put into prev_out, or NULL if there is none
static AllocNode *find_alloc_node(void *value, AllocNode **prev_out) {
    int i = ((int)value) % ALLOC_ROOT_SIZE;
    AllocNode *prev = NULL;
    AllocNode *node = alloc_root[i];
    while(node != NULL) {
        if(node->value == value)
            break;
        prev = node;
        node = node->next;
    }
    if(prev_out != NULL)
        *prev_out = prev;
    return node;
}

//calculates the amount of memory in the alloc table
size_t memory_in_alloc_table() {
    size_t out = 0;
    int i;
    for(i = 0; i < ALLOC_ROOT_SIZE; i++) {
        AllocNode *node = alloc_root[i];
        while(node != NULL) {
            out += node->size + sizeof(AllocNode);
            node = node->next;
        }
    }
    return out;
}

//marks an object and all it's referenced objects (currently hard-coded code) as being live
static void gc_mark(LispObject *obj) {
    AllocNode *an = find_alloc_node(obj, NULL);
    if(an == NULL) {
        if(obj->type != &SymbolType && obj != (LispObject*)nil)
            fprintf(stderr,
                    "Rather horrid error, object at %p of type %s not in alloc_table\n",
                    obj,
                    obj->type->name);
        return;
    }
    if(an->marked)
        return;
    an->marked = true;

    if(obj->type == &ConsCellType) {
        ConsCell *con = (ConsCell*)obj;
        gc_mark(con->car);
        gc_mark(con->cdr);
    } else if(obj->type == &MacroType) {
        Macro *mac = (Macro*)obj;
        gc_mark((LispObject*)mac->args);
        gc_mark((LispObject*)mac->body);
        gc_mark((LispObject*)mac->context);
    } else if(obj->type == &VectorType) {
        Vector *v = (Vector*)obj;
        for(int i = 0; i < v->size; i++)
            gc_mark(vector_getitem(v, i));
    } else if(obj->type == &DictType) {
        Dict *d = (Dict*)obj;
        for(int i = 0; i < d->array_size; i++)
            if(d->keys[i] != NULL) {
                gc_mark(d->keys[i]);
                gc_mark(d->values[i]);
            }
    }
}

//deallocates dead objects and removes their entries from the alloc table
void collect_garbage() {
    int i;
    for(i = 0; i < ALLOC_ROOT_SIZE; i++) {
        AllocNode *node = alloc_root[i];
        while(node != NULL) {
            node->marked = false;
            node = node->next;
        }
    }

    gc_mark((LispObject*)scopes);

    gc_mark((LispObject*)call_stack);

    for(i = 0; i < ALLOC_ROOT_SIZE; i++) {
        AllocNode *prev = NULL;
        AllocNode *node = alloc_root[i];
        AllocNode *tmp;
        while(node != NULL) {
            if(!node->marked) {
                if(ALLOC_VERBOSE) {
                    printf("garbage collecting object of type %s at %p \n",
                           ((LispObject*)node->value)->type->name,
                           node->value);
                    printf("total mem: %d, amt in alloc table: %d, difference: %d\n",
                           total_memory_use,
                           memory_in_alloc_table(),
                           total_memory_use - memory_in_alloc_table());
                }

                if(prev == NULL)
                    alloc_root[i] = node->next;
                else
                    prev->next = node->next;

                total_memory_use -= node->size + sizeof(AllocNode);

                tmp = node->next;
                free(node->value);
                free(node);
                node = tmp;
            } else {
                prev = node;
                node = node->next;
            }
        }
    }
}


text:
package com.sinacloud.storage.model;

import java.util.List;

public class ObjectFileList {
	/**
	 * 对象文件名称列表
	 */
	private List<String> objectList;
	/**
	 * 对象文件数量
	 */
	private int objectCount;
	/**
	 * 修改时间
	 *
	 */
	private String timestamp;
	/**
	 * 暂用空间大小
	 */
	private int totalObjectUsedSize;

	/**
	 * 获取文件列表
	 * @return
	 */
	public List<String> getObjectList() {
		return objectList;
	}
	/**
	 * 设置文件列表
	 * @param objectList
	 */
	public void setObjectList(List<String> objectList) {
		this.objectList = objectList;
	}
	/**
	 * 获取文件数量
	 * @return
	 */
	public int getObjectCount() {
		return objectCount;
	}
	/**
	 * 设置文件数量
	 * @param objectCount
	 */
	public void setObjectCount(int objectCount) {
		this.objectCount = objectCount;
	}
	/**
	 * 获取时间戳
	 * @return
	 */
	public String getTimestamp() {
		return timestamp;
	}
	/**
	 * 设置时间戳
	 * @param timestamp
	 */
	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}
	/**
	 * 获取所有文件的大小
	 * @return
	 */
	public int getTotalObjectUsedSize() {
		return totalObjectUsedSize;
	}
	/**
	 * 设置所有文件大小
	 * @param totalObjectUsedSize
	 */
	public void setTotalObjectUsedSize(int totalObjectUsedSize) {
		this.totalObjectUsedSize = totalObjectUsedSize;
	}
	@Override
	public String toString() {
		return "ObjectFileList [objectList=" + objectList + ", objectCount=" + objectCount + ", timestamp=" + timestamp
				+ ", totalObjectUsedSize=" + totalObjectUsedSize + "]";
	}

}