text:
package org.jitsi.jicofo.discovery;

import net.java.sip.communicator.impl.protocol.jabber.extensions.health.*;
import net.java.sip.communicator.impl.protocol.jabber.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.*;

import org.jitsi.protocol.xmpp.*;
import org.jitsi.xmpp.util.*;

import org.jivesoftware.smack.packet.*;

import java.util.*;

/**
 * Utility class for feature discovery.
 *
 * @author Pawel Domas
 */
public class DiscoveryUtil
{
    /**
     * The logger
     */
    private final static Logger logger
        = Logger.getLogger(DiscoveryUtil.class);

    /**
     * List contains default feature set.
     */
    private static ArrayList<String> defaultFeatures;

    /**
     * Audio RTP feature name.
     */
    public final static String FEATURE_AUDIO
            = "urn:xmpp:jingle:apps:rtp:audio";

    /**
     * Video RTP feature name.
     */
    public final static String FEATURE_VIDEO
            = "urn:xmpp:jingle:apps:rtp:video";

    /**
     * ICE feature name.
     */
    public final static String FEATURE_ICE
            = "urn:xmpp:jingle:transports:ice-udp:1";

    /**
     * DTLS/SCTP feature name.
     */
    public final static String FEATURE_SCTP
            = "urn:xmpp:jingle:transports:dtls-sctp:1";

    /**
     * RTX (RFC4588) support.
     */
    public final static String FEATURE_RTX
        = "urn:ietf:rfc:4588";

    /**
     * The Jingle DTLS feature name (XEP-0320).
     */
    public final static String FEATURE_DTLS = "urn:xmpp:jingle:apps:dtls:0";

    /**
     * RTCP mux feature name.
     */
    public final static String FEATURE_RTCP_MUX = "urn:ietf:rfc:5761";

    /**
     * RTP bundle feature name.
     */
    public final static String FEATURE_RTP_BUNDLE = "urn:ietf:rfc:5888";

    /**
     * Heath checks feature namespace.
     */
    public final static String FEATURE_HEALTH_CHECK = HealthCheckIQ.NAMESPACE;

    /**
     * A namespace for our custom "lip-sync" feature. Advertised by the clients
     * that support all of the functionality required for doing the lip-sync
     * properly.
     */
    public final static String FEATURE_LIPSYNC
        = "http://jitsi.org/meet/lipsync";

    /**
     * Array constant which can be used to check for Version IQ support.
     */
    public final static String[] VERSION_FEATURES = new String[]
        {
            ProtocolProviderServiceJabberImpl.URN_XMPP_IQ_VERSION
        };

    /**
     * Gets the list of features supported by participant. If we fail to
     * obtain it due to network failure default feature list is returned.
     * @param protocolProvider protocol provider service instance that will
     *        be used for discovery.
     * @param address XMPP address of the participant.
     */
    public static List<String> discoverParticipantFeatures
        (ProtocolProviderService protocolProvider, String address)
    {
        OperationSetSimpleCaps disco
            = protocolProvider.getOperationSet(OperationSetSimpleCaps.class);
        if (disco == null)
        {
            logger.error(
                "Service discovery not supported by " + protocolProvider);
            return getDefaultParticipantFeatureSet();
        }

        // Discover participant feature set
        List<String> participantFeatures = disco.getFeatures(address);
        if (participantFeatures == null)
        {
            logger.error(
                "Failed to discover features for "+ address
                        + " assuming default feature set.");

            return getDefaultParticipantFeatureSet();
        }

        logger.info(address +", features: ");
        for (String feature : participantFeatures)
        {
            logger.info(feature);
        }

        return participantFeatures;
    }

    /**
     * Discovers version of given <tt>jid</tt>.
     *
     * @param xmppOpSet the direct smack operation set which will be used to
     *                  send the query.
     * @param jid       the JID to which version query wil be sent.
     * @param features  the list of <tt>jid</tt> feature which will be used to
     *                  determine support for the version IQ.
     *
     * @return {@link Version} if given <tt>jid</tt> supports version IQ and if
     *         we the query was successful or <tt>null</tt> otherwise.
     */
    static public Version discoverVersion(
            OperationSetDirectSmackXmpp    xmppOpSet,
            String                               jid,
            List<String>                    features )
    {
        // If the bridge supports version IQ query it's version
        if (DiscoveryUtil.checkFeatureSupport(VERSION_FEATURES, features))
        {
            Version versionIq = new Version();
            versionIq.setType(IQ.Type.GET);
            versionIq.setTo(jid);

            Packet response;
            try
            {
                response
                    = xmppOpSet
                        .getXmppConnection()
                        .sendPacketAndGetReply(versionIq);
            }
            catch (OperationFailedException e)
            {
                logger.error(
                    "Failed to discover component version - XMPP disconnected",
                    e);
                return null;
            }

            if (response instanceof Version)
            {
                return  (Version) response;
            }
            else
            {
                logger.error(
                        "Failed to discover version, req: " + versionIq.toXML()
                            + ", response: "
                            + IQUtils.responseToXML(response));
            }
        }
        return null;
    }

    /**
     * Returns default participant feature set(all features).
     */
    static public List<String> getDefaultParticipantFeatureSet()
    {
        if (defaultFeatures == null)
        {
            defaultFeatures = new ArrayList<String>(7);
            defaultFeatures.add(FEATURE_AUDIO);
            defaultFeatures.add(FEATURE_VIDEO);
            defaultFeatures.add(FEATURE_ICE);
            defaultFeatures.add(FEATURE_SCTP);
            defaultFeatures.add(FEATURE_DTLS);
            defaultFeatures.add(FEATURE_RTCP_MUX);
            defaultFeatures.add(FEATURE_RTP_BUNDLE);
        }
        return defaultFeatures;
    }

    /**
     * Checks if all of the features given on <tt>reqFeatures</tt> array exist
     * on declared list of <tt>capabilities</tt>.
     * @param reqFeatures array of required features to check.
     * @param capabilities the list of features supported by the client.
     * @return <tt>true</tt> if all features from <tt>reqFeatures</tt> array
     *         exist on <tt>capabilities</tt> list.
     */
    static public boolean checkFeatureSupport(String[] reqFeatures,
                                              List<String> capabilities)
    {
        for (String toCheck : reqFeatures)
        {
            if (!capabilities.contains(toCheck))
                return false;
        }
        return true;
    }

    /**
     * Returns <tt>true</tt> if <tt>list1</tt> and <tt>list2</tt> contain the
     * same elements where items order is not relevant.
     * @param list1 the first list of <tt>String</tt> to be compared against
     *              the second list.
     * @param list2 the second list of <tt>String</tt> to be compared against
     *              the first list.
     */
    static public boolean areTheSame(List<String> list1, List<String> list2)
    {
        return list1.size() == list2.size() && list2.containsAll(list1);
    }
}


text:
module.exports = function(gulp, config, watch) {

	return function(done) {
		if(!config.patternlab) return done()
		var c = require('better-console')
		c.info('WATCH: patternlab')

		// Watch patterns
		watch(config.patternlab.patterns.source + '/**/*.{html,hbs,mustache,json}', function() {
			gulp.start('patternlab')
		})

		// Watch styleguide template
		watch(config.patternlab.styleguide + '/**', function() {
			gulp.start('patternlab')
		})

		done()
	}

}

redpajama_set_name: RedPajamaGithub


text:
            {{username}} /
            {{repo}} /
            {{branch}} /
            {{path}}

            {{> author _embedded.cont:commit.0}} wrote {{> date}} -
            {{_embedded.cont:commit.0.message}}

             Raw
             History

Info

author	{{> author}}

created	{{> date}}

size	{{size content}}kb

words	{{wordcount content}}

            {{#if metadata}}

Metadata

                    {{#each metadata}}

{{@key}}	{{truncate this}}

                    {{/each}}

            {{/if}}

    {{{markdown content}}}


text:
package de.konsultaner.wordClock;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

import java.util.Calendar;
import java.util.List;

import static org.junit.Assert.*;

public class WordClockTest {
    @Test
    public void testConcatMatrix() throws Exception {
        int[][] matrixA = new int[][]{
            {1,0,1},{0,1,0},{1,0,0}
        };
        int[][] matrixB = new int[][]{
            {1,1,0,0},{0,1,0,0},{1,1,1,1}
        };

        int[][]result = WordClock.concatMatrix(matrixA,matrixB);
        assertThat("Should have concatenated correctly",result.length,CoreMatchers.equalTo(3));
        assertThat("Should have concatenated correctly",result[0].length,CoreMatchers.equalTo(4));

        assertThat("Should have concatenated correctly",result[0][0],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[0][1],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[0][2],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[0][3],CoreMatchers.equalTo(0));

        assertThat("Should have concatenated correctly",result[1][0],CoreMatchers.equalTo(0));
        assertThat("Should have concatenated correctly",result[1][1],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[1][2],CoreMatchers.equalTo(0));
        assertThat("Should have concatenated correctly",result[1][3],CoreMatchers.equalTo(0));

        assertThat("Should have concatenated correctly",result[2][0],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[2][1],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[2][2],CoreMatchers.equalTo(1));
        assertThat("Should have concatenated correctly",result[2][3],CoreMatchers.equalTo(1));
    }

    @Test
    public void testGetIntervalsByDate() throws Exception {
        WordClock wordClock = new WordClock();
        int[][] matrix1 = new int[10][10];
        matrix1[0][0] = 1;
        matrix1[1][0] = 1;
        matrix1[2][0] = 1;
        matrix1[3][0] = 1;
        wordClock.addInterval(new WordClock.Interval(1,1, 0, 59, matrix1));

        int[][] matrix2 = new int[10][10];
        matrix2[0][0] = 1;
        matrix2[1][3] = 1;
        matrix2[2][3] = 1;
        matrix2[3][3] = 1;
        wordClock.addInterval(new WordClock.Interval(9,18, 0, 59, matrix2));

        int[][] matrix3 = new int[10][10];
        matrix3[0][9] = 1;
        matrix3[9][1] = 1;
        matrix3[8][1] = 1;
        matrix3[7][1] = 1;
        wordClock.addInterval(new WordClock.Interval(1,1, 0, 15, matrix3));

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,1);
        calendar.set(Calendar.MINUTE,0);
        List<WordClock.Interval> intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find 1 and 3",intervals.size(), CoreMatchers.equalTo(2));
        assertThat("Should find 1 and 3",intervals.get(0).matrix, CoreMatchers.equalTo(matrix1));
        assertThat("Should find 1 and 3",intervals.get(1).matrix, CoreMatchers.equalTo(matrix3));

        calendar.set(Calendar.MINUTE,15);
        intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find 1 and 3",intervals.size(), CoreMatchers.equalTo(2));
        assertThat("Should find 1 and 3",intervals.get(0).matrix, CoreMatchers.equalTo(matrix1));
        assertThat("Should find 1 and 3",intervals.get(1).matrix, CoreMatchers.equalTo(matrix3));

        calendar.set(Calendar.MINUTE,16);
        intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find 1",intervals.size(), CoreMatchers.equalTo(1));
        assertThat("Should find 1",intervals.get(0).matrix, CoreMatchers.equalTo(matrix1));

        calendar.set(Calendar.HOUR_OF_DAY,8);
        intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find nothing",intervals.size(), CoreMatchers.equalTo(0));

        calendar.set(Calendar.HOUR_OF_DAY,9);
        intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find 2",intervals.size(), CoreMatchers.equalTo(1));
        assertThat("Should find 2",intervals.get(0).matrix, CoreMatchers.equalTo(matrix2));

        calendar.set(Calendar.HOUR_OF_DAY,18);
        calendar.set(Calendar.MINUTE,59);
        intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find 2",intervals.size(), CoreMatchers.equalTo(1));
        assertThat("Should find 2",intervals.get(0).matrix, CoreMatchers.equalTo(matrix2));

        calendar.set(Calendar.HOUR_OF_DAY,19);
        calendar.set(Calendar.MINUTE,0);
        intervals = wordClock.getIntervalsByDate(calendar.getTime());

        assertThat("Should find nothing",intervals.size(), CoreMatchers.equalTo(0));
    }

    @Test
    public void testGetMatrixByDate() throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,1);
        calendar.set(Calendar.MINUTE,0);

        WordClock wordClock = new WordClock();
        int[][] matrix1 = new int[4][1];
        matrix1[0][0] = 1;
        matrix1[1][0] = 1;
        matrix1[2][0] = 1;
        matrix1[3][0] = 1;
        wordClock.addInterval(new WordClock.Interval(1,1, 0, 59, matrix1));

        int[][] matrix = wordClock.getMatrixByDate(calendar.getTime());

        assertThat("Should have a 4x1 matrix equal to matrix 1",matrix.length,CoreMatchers.equalTo(4));
        assertThat("Should have a 4x1 matrix equal to matrix 1",matrix[0].length,CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[0][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[1][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[2][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[3][0],CoreMatchers.equalTo(1));

        int[][] matrix2 = new int[4][4];
        matrix2[0][0] = 0;
        matrix2[1][3] = 1;
        matrix2[2][3] = 1;
        matrix2[3][3] = 1;
        wordClock.addInterval(new WordClock.Interval(1,1, 0, 59, matrix2));

        matrix = wordClock.getMatrixByDate(calendar.getTime());

        assertThat("Should have a 4x4 matrix equal to matrix 2",matrix.length,CoreMatchers.equalTo(4));
        assertThat("Should have a 4x4 matrix equal to matrix 2",matrix[0].length,CoreMatchers.equalTo(4));
        assertThat("Should have the correct copied values",matrix[0][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[1][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[2][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[3][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[1][3],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[2][3],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[3][3],CoreMatchers.equalTo(1));

        int[][] matrix3 = new int[5][4];
        matrix3[4][0] = 1;
        wordClock.addInterval(new WordClock.Interval(1,1, 0, 59, matrix3));

        matrix = wordClock.getMatrixByDate(calendar.getTime());

        assertThat("Should have a 4x4 matrix equal to matrix 2",matrix.length,CoreMatchers.equalTo(5));
        assertThat("Should have a 4x4 matrix equal to matrix 2",matrix[0].length,CoreMatchers.equalTo(4));
        assertThat("Should have the correct copied values",matrix[0][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[1][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[2][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[3][0],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[1][3],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[2][3],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[3][3],CoreMatchers.equalTo(1));
        assertThat("Should have the correct copied values",matrix[4][0],CoreMatchers.equalTo(1));
    }

    @Test
    public void testGetFilteredClockMatrix() throws Exception {
        String[] clockMatrix = new String[]{
            "ESKISTLRMITTAGSIABENDS",
            "FRÜHAMLFÜNFZEHNZWANZIG",
            "DREIVIERTELTGNACHVORJM",
            "HALBQZWÖLFPZWEINSIEBEN",
            "KDREIRHFÜNFELFNEUNVIER",
            "WACHTZEHNRSBSECHSFMUHR",
            "AFMOLDIWMIRDOPFRLSAKSO"
        };
        WordClockMatrix wordClockMatrix = new WordClockMatrix(clockMatrix);
        WordClock wordClock = wordClockMatrix.getWorclockDecorator()
            .addSentence(13,13,0,4,"ES IST MITTAGS EIN UHR")
            .addSentence(13,13,5,9,"ES IST MITTAGS FÜNF NACH EIN UHR")
            .addSentence(13,13,10,14,"ES IST MITTAGS ZEHN NACH EIN UHR")
            .getWordClock();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,13);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);

        String[] filteredMatrix = wordClock.getFilteredClockMatrix(clockMatrix,calendar.getTime());
        for (String row:filteredMatrix) {
            System.out.println(row);
        }
        assertThat(filteredMatrix[0],CoreMatchers.equalTo("ES IST  MITTAGS       "));
        assertThat(filteredMatrix[1],CoreMatchers.equalTo("                      "));
        assertThat(filteredMatrix[2],CoreMatchers.equalTo("                      "));
        assertThat(filteredMatrix[3],CoreMatchers.equalTo("             EIN      "));
        assertThat(filteredMatrix[4],CoreMatchers.equalTo("                      "));
        assertThat(filteredMatrix[5],CoreMatchers.equalTo("                   UHR"));
        assertThat(filteredMatrix[6],CoreMatchers.equalTo("                      "));

        calendar.set(Calendar.MINUTE,7);
        filteredMatrix = wordClock.getFilteredClockMatrix(clockMatrix,calendar.getTime());
        for (String row:filteredMatrix) {
            System.out.println(row);
        }

        assertThat(filteredMatrix[0],CoreMatchers.equalTo("ES IST  MITTAGS       "));
        assertThat(filteredMatrix[1],CoreMatchers.equalTo("       FÜNF           "));
        assertThat(filteredMatrix[2],CoreMatchers.equalTo("             NACH     "));
        assertThat(filteredMatrix[3],CoreMatchers.equalTo("             EIN      "));
        assertThat(filteredMatrix[4],CoreMatchers.equalTo("                      "));
        assertThat(filteredMatrix[5],CoreMatchers.equalTo("                   UHR"));
        assertThat(filteredMatrix[6],CoreMatchers.equalTo("                      "));

        calendar.set(Calendar.MINUTE,10);
        filteredMatrix = wordClock.getFilteredClockMatrix(clockMatrix,calendar.getTime());
        for (String row:filteredMatrix) {
            System.out.println(row);
        }

        assertThat(filteredMatrix[0],CoreMatchers.equalTo("ES IST  MITTAGS       "));
        assertThat(filteredMatrix[1],CoreMatchers.equalTo("           ZEHN       "));
        assertThat(filteredMatrix[2],CoreMatchers.equalTo("             NACH     "));
        assertThat(filteredMatrix[3],CoreMatchers.equalTo("             EIN      "));
        assertThat(filteredMatrix[4],CoreMatchers.equalTo("                      "));
        assertThat(filteredMatrix[5],CoreMatchers.equalTo("                   UHR"));
        assertThat(filteredMatrix[6],CoreMatchers.equalTo("                      "));
    }
}


text:
title: Getting started tutorial
subtitle: This tutorial is for people who are new to Dataform and want to be taught how to set up a new project. We will show you how to create your own data model, how to test and document it and how to run schedules on it.
priority: 4
icon: tick
---


text:
/*
dialog_ie7.css
===============

This file contains styles to used by Internet Explorer 7 only.
*/

/* Base it on dialog_ie.css, overriding it with styles defined in this file. */
@import url("dialog_ie.css");

.cke_dialog_title
{
	margin-bottom: 22px;
}
.cke_single_page .cke_dialog_title
{
	margin-bottom: 10px;
}
.cke_single_page .cke_dialog_footer
{
	margin-top: 22px;
}
.cke_dialog_footer .cke_resizer
{
	margin-top: 27px;
}
.cke_dialog_tabs
{
	top: 33px;
}
/* IE7 needs position static #6806 */
.cke_dialog_footer_buttons
{
	position: static;
}

.cke_rtl .cke_dialog_close_button
{
	margin-top: 0;
	position: absolute;
	left: 10px;
	top: 5px;
}

span.cke_dialog_ui_buttonm
{
	margin: 2px 0;
}

/* Predefined border to avoid visual size change impact. */
.cke_dialog_ui_checkbox_input,
.cke_dialog_ui_ratio_input,
.cke_btn_reset,
.cke_btn_locked,
.cke_btn_unlocked
{
	border: 1px solid transparent !important;
}

/* The absolute position is required for IE7 on text inputs not to stretch dialog horizontally. (#8971)*/
input.cke_dialog_ui_input_text,
input.cke_dialog_ui_input_password
{
	position: absolute;
}

div.cke_dialog_ui_input_text,
div.cke_dialog_ui_input_password
{
	height:14px;
	position: relative;
}


text: <textarea #input [(ngModel)]="value"></textarea>


text:
import { connect } from 'react-redux';
import { currentUserSelector } from 'modules/data/ducks/selectors';

import Certs from './certs';

export default connect(
  (state) => ({ user: currentUserSelector(state) }),
)(Certs);


text:
import Adaptive from 'ember-simple-auth/session-stores/adaptive';

export default Adaptive.extend();


text:
@layout('master')

@section('container')

List of expenses

{{ HTML::link_to_action('expenses@new', 'Create a New Expense', array(), array('class' => 'btn btn-primary create-btn')) }}

			Date
			ID
			Account
			Remark
			Amount
			Category
			Action

	@forelse ($expenses as $expense)

			{{ date('Y-m-d', strtotime($expense->expense_date)) }}
			{{ $expense->id }}
			{{ $expense->account->name }}
			{{ $expense->remark }}
			{{ AppHelper::idr_format($expense->amount) }}
			{{ $expense->category->name }}

				{{ HTML::link_to_action('expenses@edit', 'Edit', array($expense->id), array('class' => 'btn btn-warning')) }}
				{{ HTML::link_to_action('expenses@destroy', 'Delete', array($expense->id), array('class' => 'btn btn-danger', 'data-method' => 'delete')) }}

	@empty
	@endforelse

@endsection

@section('javascript')

@endsection


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.maps.search.models;

import com.azure.core.annotation.Immutable;
import com.fasterxml.jackson.annotation.JsonProperty;

/** POI category. */
@Immutable
public final class PointOfInterestCategorySet {
    /*
     * Category ID
     */
    @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY)
    private Integer id;

    /**
     * Get the id property: Category ID.
     *
     * @return the id value.
     */
    public Integer getId() {
        return this.id;
    }
}


text:
.class public Lcom/android/server/am/PowerOffAlarmUtility;
.super Ljava/lang/Object;
.source "PowerOffAlarmUtility.java"

# static fields
.field private static final ALARM_BOOT_DONE:Ljava/lang/String; = "android.intent.action.normal.boot.done"

.field private static final REMOVE_IPOWIN:Ljava/lang/String; = "alarm.boot.remove.ipowin"

.field private static final TAG:Ljava/lang/String; = "PowerOffAlarm"

.field private static mInstance:Lcom/android/server/am/PowerOffAlarmUtility;

# instance fields
.field private mAmPlus:Lcom/android/server/am/ActivityManagerPlus;

.field private mContext:Landroid/content/Context;

.field public mFirstBoot:Z

.field private mRollback:Z

.field private mStack:Lcom/android/server/am/ActivityStack;

# direct methods
.method private constructor <init>(Landroid/content/Context;Lcom/android/server/am/ActivityStack;Lcom/android/server/am/ActivityManagerPlus;)V
    .locals 3
    .param p1, "ctx"    # Landroid/content/Context;
    .param p2, "aStack"    # Lcom/android/server/am/ActivityStack;
    .param p3, "amPlus"    # Lcom/android/server/am/ActivityManagerPlus;

    .prologue
    const/4 v2, 0x0

    .line 97
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 63
    iput-boolean v2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    .line 64
    iput-boolean v2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mFirstBoot:Z

    .line 98
    iput-object p1, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    .line 99
    iput-object p3, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mAmPlus:Lcom/android/server/am/ActivityManagerPlus;

    .line 100
    iput-object p2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mStack:Lcom/android/server/am/ActivityStack;

    .line 101
    iget-object v1, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    invoke-direct {p0, v1}, Lcom/android/server/am/PowerOffAlarmUtility;->registerNormalBootReceiver(Landroid/content/Context;)V

    .line 102
    const-string v1, "persist.sys.ams.recover"

    invoke-static {v1, v2}, Landroid/os/SystemProperties;->getBoolean(Ljava/lang/String;Z)Z

    move-result v0

    .line 104
    .local v0, "recover":Z
    if-eqz v0, :cond_0

    .line 105
    const/4 v1, 0x1

    invoke-virtual {p0, v1, v2}, Lcom/android/server/am/PowerOffAlarmUtility;->checkFlightMode(ZZ)V

    .line 107
    :cond_0
    return-void
.end method

.method static synthetic access$000(Lcom/android/server/am/PowerOffAlarmUtility;)Z
    .locals 1
    .param p0, "x0"    # Lcom/android/server/am/PowerOffAlarmUtility;

    .prologue
    .line 58
    iget-boolean v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    return v0
.end method

.method static synthetic access$100(Lcom/android/server/am/PowerOffAlarmUtility;)Lcom/android/server/am/ActivityStack;
    .locals 1
    .param p0, "x0"    # Lcom/android/server/am/PowerOffAlarmUtility;

    .prologue
    .line 58
    iget-object v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mStack:Lcom/android/server/am/ActivityStack;

    return-object v0
.end method

.method static synthetic access$200(Lcom/android/server/am/PowerOffAlarmUtility;)Lcom/android/server/am/ActivityManagerPlus;
    .locals 1
    .param p0, "x0"    # Lcom/android/server/am/PowerOffAlarmUtility;

    .prologue
    .line 58
    iget-object v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mAmPlus:Lcom/android/server/am/ActivityManagerPlus;

    return-object v0
.end method

.method static synthetic access$300(Lcom/android/server/am/PowerOffAlarmUtility;)Landroid/content/Context;
    .locals 1
    .param p0, "x0"    # Lcom/android/server/am/PowerOffAlarmUtility;

    .prologue
    .line 58
    iget-object v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    return-object v0
.end method

.method public static getInstance(Landroid/content/Context;Lcom/android/server/am/ActivityStack;Lcom/android/server/am/ActivityManagerPlus;)Lcom/android/server/am/PowerOffAlarmUtility;
    .locals 1
    .param p0, "ctx"    # Landroid/content/Context;
    .param p1, "aStack"    # Lcom/android/server/am/ActivityStack;
    .param p2, "amPlus"    # Lcom/android/server/am/ActivityManagerPlus;

    .prologue
    .line 80
    sget-object v0, Lcom/android/server/am/PowerOffAlarmUtility;->mInstance:Lcom/android/server/am/PowerOffAlarmUtility;

    if-eqz v0, :cond_0

    .line 81
    sget-object v0, Lcom/android/server/am/PowerOffAlarmUtility;->mInstance:Lcom/android/server/am/PowerOffAlarmUtility;

    .line 86
    :goto_0
    return-object v0

    .line 83
    :cond_0
    if-eqz p0, :cond_1

    if-eqz p1, :cond_1

    if-eqz p2, :cond_1

    .line 84
    new-instance v0, Lcom/android/server/am/PowerOffAlarmUtility;

    invoke-direct {v0, p0, p1, p2}, Lcom/android/server/am/PowerOffAlarmUtility;-><init>(Landroid/content/Context;Lcom/android/server/am/ActivityStack;Lcom/android/server/am/ActivityManagerPlus;)V

    sput-object v0, Lcom/android/server/am/PowerOffAlarmUtility;->mInstance:Lcom/android/server/am/PowerOffAlarmUtility;

    .line 86
    :cond_1
    sget-object v0, Lcom/android/server/am/PowerOffAlarmUtility;->mInstance:Lcom/android/server/am/PowerOffAlarmUtility;

    goto :goto_0
.end method

.method public static isAlarmBoot()Z
    .locals 1

    .prologue
    .line 145
    const/4 v0, 0x0

    return v0
.end method

.method private final registerNormalBootReceiver(Landroid/content/Context;)V
    .locals 2
    .param p1, "context"    # Landroid/content/Context;

    .prologue
    .line 155
    new-instance v0, Landroid/content/IntentFilter;

    invoke-direct {v0}, Landroid/content/IntentFilter;-><init>()V

    .line 156
    .local v0, "filter":Landroid/content/IntentFilter;
    const-string v1, "android.intent.action.normal.boot"

    invoke-virtual {v0, v1}, Landroid/content/IntentFilter;->addAction(Ljava/lang/String;)V

    .line 157
    const-string v1, "android.intent.action.normal.shutdown"

    invoke-virtual {v0, v1}, Landroid/content/IntentFilter;->addAction(Ljava/lang/String;)V

    .line 158
    const-string v1, "android.intent.action.normal.boot.done"

    invoke-virtual {v0, v1}, Landroid/content/IntentFilter;->addAction(Ljava/lang/String;)V

    .line 159
    const-string v1, "alarm.boot.remove.ipowin"

    invoke-virtual {v0, v1}, Landroid/content/IntentFilter;->addAction(Ljava/lang/String;)V

    .line 160
    const/4 v1, 0x1

    iput-boolean v1, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mFirstBoot:Z

    .line 162
    new-instance v1, Lcom/android/server/am/PowerOffAlarmUtility$1;

    invoke-direct {v1, p0}, Lcom/android/server/am/PowerOffAlarmUtility$1;-><init>(Lcom/android/server/am/PowerOffAlarmUtility;)V

    invoke-virtual {p1, v1, v0}, Landroid/content/Context;->registerReceiver(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;

    .line 203
    return-void
.end method

# virtual methods
.method public checkFlightMode(ZZ)V
    .locals 6
    .param p1, "recover"    # Z
    .param p2, "shutdown"    # Z

    .prologue
    const/4 v2, 0x1

    const/4 v1, 0x0

    .line 210
    const-string v3, "PowerOffAlarm"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "mRollback = "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-boolean v5, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, ", recover = "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, p1}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I

    .line 212
    if-eqz p1, :cond_1

    .line 213
    const-string v2, "PowerOffAlarm"

    const-string v3, "since system crash, switch flight mode to off"

    invoke-static {v2, v3}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I

    .line 214
    iget-object v2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    invoke-virtual {v2}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string v3, "airplane_mode_on"

    invoke-static {v2, v3, v1}, Landroid/provider/Settings$Global;->putInt(Landroid/content/ContentResolver;Ljava/lang/String;I)Z

    .line 216
    const-string v2, "persist.sys.ams.recover"

    const-string v3, "false"

    invoke-static {v2, v3}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V

    .line 245
    :cond_0
    :goto_0
    return-void

    .line 220
    :cond_1
    iget-boolean v3, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    if-eqz v3, :cond_2

    .line 221
    iput-boolean v1, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    .line 222
    const-string v2, "persist.sys.ams.recover"

    const-string v3, "false"

    invoke-static {v2, v3}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V

    .line 223
    iget-object v2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    invoke-virtual {v2}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string v3, "airplane_mode_on"

    invoke-static {v2, v3, v1}, Landroid/provider/Settings$Global;->putInt(Landroid/content/ContentResolver;Ljava/lang/String;I)Z

    .line 226
    if-nez p2, :cond_0

    .line 227
    new-instance v0, Landroid/content/Intent;

    const-string v2, "android.intent.action.AIRPLANE_MODE"

    invoke-direct {v0, v2}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    .line 228
    .local v0, "intent":Landroid/content/Intent;
    const/high16 v2, 0x20000000

    invoke-virtual {v0, v2}, Landroid/content/Intent;->addFlags(I)Landroid/content/Intent;

    .line 229
    const-string v2, "state"

    invoke-virtual {v0, v2, v1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Z)Landroid/content/Intent;

    .line 230
    iget-object v2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    invoke-virtual {v2, v0}, Landroid/content/Context;->sendBroadcast(Landroid/content/Intent;)V

    goto :goto_0

    .line 233
    .end local v0    # "intent":Landroid/content/Intent;
    :cond_2
    iget-object v3, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    invoke-virtual {v3}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v3

    const-string v4, "airplane_mode_on"

    invoke-static {v3, v4, v1}, Landroid/provider/Settings$Global;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I

    move-result v3

    if-eqz v3, :cond_3

    move v1, v2

    .line 237
    .local v1, "mode":Z
    :cond_3
    if-nez v1, :cond_0

    .line 238
    const-string v3, "PowerOffAlarm"

    const-string v4, "turn on flight mode"

    invoke-static {v3, v4}, Landroid/util/Log;->v(Ljava/lang/String;Ljava/lang/String;)I

    .line 239
    const-string v3, "persist.sys.ams.recover"

    const-string v4, "true"

    invoke-static {v3, v4}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V

    .line 240
    iput-boolean v2, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    .line 241
    iget-object v3, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    invoke-virtual {v3}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v3

    const-string v4, "airplane_mode_on"

    invoke-static {v3, v4, v2}, Landroid/provider/Settings$Global;->putInt(Landroid/content/ContentResolver;Ljava/lang/String;I)Z

    goto :goto_0
.end method

.method public launchPowrOffAlarm(Ljava/lang/Boolean;Ljava/lang/Boolean;)V
    .locals 3
    .param p1, "recover"    # Ljava/lang/Boolean;
    .param p2, "shutdown"    # Ljava/lang/Boolean;

    .prologue
    .line 118
    if-eqz p1, :cond_0

    if-eqz p2, :cond_0

    .line 119
    invoke-virtual {p1}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v0

    invoke-virtual {p2}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v1

    invoke-virtual {p0, v0, v1}, Lcom/android/server/am/PowerOffAlarmUtility;->checkFlightMode(ZZ)V

    .line 121
    :cond_0
    iget-object v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    new-instance v1, Landroid/content/Intent;

    const-string v2, "android.intent.action.LAUNCH_POWEROFF_ALARM"

    invoke-direct {v1, v2}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    invoke-virtual {v0, v1}, Landroid/content/Context;->sendBroadcast(Landroid/content/Intent;)V

    .line 123
    return-void
.end method

.method public launchPowrOffAlarmIPO(Ljava/lang/Boolean;)V
    .locals 3
    .param p1, "mFlightModeOn"    # Ljava/lang/Boolean;

    .prologue
    .line 126
    invoke-virtual {p1}, Ljava/lang/Boolean;->booleanValue()Z

    move-result v0

    if-eqz v0, :cond_0

    .line 127
    const/4 v0, 0x1

    iput-boolean v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mRollback:Z

    .line 129
    :cond_0
    iget-object v0, p0, Lcom/android/server/am/PowerOffAlarmUtility;->mContext:Landroid/content/Context;

    new-instance v1, Landroid/content/Intent;

    const-string v2, "android.intent.action.LAUNCH_POWEROFF_ALARM"

    invoke-direct {v1, v2}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    invoke-virtual {v0, v1}, Landroid/content/Context;->sendBroadcast(Landroid/content/Intent;)V

    .line 131
    return-void
.end method


text:
package com.navercorp.pinpoint.common.trace;

import java.util.Objects;

/**
 * @author emeroad
 */
public class DefaultServiceTypeInfo implements ServiceTypeInfo {

    private final ServiceType serviceType;
    private final AnnotationKeyMatcher annotationKeyMatcher;

    public DefaultServiceTypeInfo(ServiceType serviceType, AnnotationKeyMatcher annotationKeyMatcher) {
        this.serviceType = Objects.requireNonNull(serviceType, "serviceType");
        this.annotationKeyMatcher = Objects.requireNonNull(annotationKeyMatcher, "annotationKeyMatcher");
    }

    public DefaultServiceTypeInfo(ServiceType serviceType) {
        this.serviceType = Objects.requireNonNull(serviceType, "serviceType");
        this.annotationKeyMatcher = null;
    }

    public AnnotationKeyMatcher getPrimaryAnnotationKeyMatcher() {
        return annotationKeyMatcher;
    }

    public ServiceType getServiceType() {
        return serviceType;
    }
}


text:
{% extends "nexus/module.html" %}

{% load gargoyle_helpers %}

{% block head %}
    {{ block.super }}
    <link rel="stylesheet" href="{% url nexus:media 'gargoyle' 'css/gargoyle.css' %}">

{% endblock %}

{% block content %}

        <button class="button addSwitch">Add a Switch</button>

            <input type="text" placeholder="search">

                Date Created

                Date Modified

                Label

        You do not have any switches yet. Add the first one.

        {% for switch in switches %}

{% if switch.label %}{{ switch.label }}{% else %}{{ switch.key|title }}{% endif %} ({{ switch.key }})

                    {% if sorted_by|sort_field == 'date_created' %}
                        Created {{ switch.date_created|timesince }} ago
                    {% else %}
                        Last modified {{ switch.date_created|timesince }} ago
                    {% endif %}

                    {% if switch.description %}

{{ switch.description }}

                    {% endif %}

                        {% for group in switch.conditions %}

                                {{ group.label }}
                                {% for field, value, display, is_exclude in group.conditions %}

                                        <nobr>{% if is_exclude %}not {% endif %}{{ display }}

                                        </nobr>

                                {% endfor %}

                        {% endfor %}

Add a condition

                <button class="xtrasmall button {% if switch.status == 4 %}toggled{% endif %}" data-status="4">
                    Inherit
                </button>

                <button class="xtrasmall button {% if switch.status == 3 %}toggled{% endif %}" data-status="3">
                    Global
                </button>

                <button class="xtrasmall button {% if switch.status == 2 %}toggled{% endif %}" data-status="2">
                    Selective
                </button>

                <button class="xtrasmall button {% if switch.status == 1 %}toggled{% endif %}" data-status="1">
                    Disabled
                </button>

                        ({{ switch.statusLabel }})

                <button class="edit xtrasmall button"></button>
                <button class="delete xtrasmall button"></button>

        {% endfor %}

    {% raw %}

    {% endraw %}

{% endblock %}


text:
namespace i18n {
namespace addressinput {

namespace {

const char kKey[] = "data/CA";

// Empty data that the downloader can return.
const char kEmptyData[] = "{}";

// The MD5 checksum for kEmptyData. Retriever uses MD5 to validate data
// integrity.
const char kEmptyDataChecksum[] = "99914b932bd37a50b983c5e7c90ae93b";

scoped_ptr<std::string> Wrap(const std::string& data,
                             const std::string& checksum,
                             const std::string& timestamp) {
  return make_scoped_ptr(new std::string(
      data + "\n" + "checksum=" + checksum + "\n" + "timestamp=" + timestamp));
}

}  // namespace

// Tests for Retriever object.
class RetrieverTest : public testing::Test {
 protected:
  RetrieverTest()
      : storage_(NULL),
        retriever_(),
        success_(false),
        key_(),
        data_() {
    ResetRetriever(FakeDownloader::kFakeDataUrl);
  }

  virtual ~RetrieverTest() {}

  scoped_ptr<Retriever::Callback> BuildCallback() {
    return ::i18n::addressinput::BuildCallback(
        this, &RetrieverTest::OnDataReady);
  }

  void ResetRetriever(const std::string& url) {
    storage_ = new FakeStorage;
    retriever_.reset(
        new Retriever(url,
                      scoped_ptr<Downloader>(new FakeDownloader),
                      scoped_ptr<Storage>(storage_)));
  }

  std::string GetUrlForKey(const std::string& key) {
    return retriever_->GetUrlForKey(key);
  }

  std::string GetKeyForUrl(const std::string& url) {
    return retriever_->GetKeyForUrl(url);
  }

  Storage* storage_;  // Owned by |retriever_|.
  scoped_ptr<Retriever> retriever_;
  bool success_;
  std::string key_;
  std::string data_;

 private:
  void OnDataReady(bool success,
                   const std::string& key,
                   const std::string& data) {
    success_ = success;
    key_ = key;
    data_ = data;
  }
};

TEST_F(RetrieverTest, RetrieveData) {
  retriever_->Retrieve(kKey, BuildCallback());

  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_FALSE(data_.empty());
  EXPECT_NE(kEmptyData, data_);
}

TEST_F(RetrieverTest, ReadDataFromStorage) {
  retriever_->Retrieve(kKey, BuildCallback());
  retriever_->Retrieve(kKey, BuildCallback());

  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_FALSE(data_.empty());
  EXPECT_NE(kEmptyData, data_);
}

TEST_F(RetrieverTest, MissingKeyReturnsEmptyData) {
  static const char kMissingKey[] = "junk";

  retriever_->Retrieve(kMissingKey, BuildCallback());

  EXPECT_TRUE(success_);
  EXPECT_EQ(kMissingKey, key_);
  EXPECT_EQ(kEmptyData, data_);
}

// The downloader that always fails.
class FaultyDownloader : public Downloader {
 public:
  FaultyDownloader() {}
  virtual ~FaultyDownloader() {}

  // Downloader implementation.
  virtual void Download(const std::string& url,
                        scoped_ptr<Callback> downloaded) {
    (*downloaded)(false, url, make_scoped_ptr(new std::string("garbage")));
  }
};

TEST_F(RetrieverTest, FaultyDownloader) {
  Retriever bad_retriever(FakeDownloader::kFakeDataUrl,
                          scoped_ptr<Downloader>(new FaultyDownloader),
                          scoped_ptr<Storage>(new FakeStorage));
  bad_retriever.Retrieve(kKey, BuildCallback());

  EXPECT_FALSE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_TRUE(data_.empty());
}

TEST_F(RetrieverTest, FaultyDownloaderFallback) {
  Retriever bad_retriever(FakeDownloader::kFakeDataUrl,
                          scoped_ptr<Downloader>(new FaultyDownloader),
                          scoped_ptr<Storage>(new FakeStorage));
  const char kFallbackDataKey[] = "data/US";
  bad_retriever.Retrieve(kFallbackDataKey, BuildCallback());

  EXPECT_TRUE(success_);
  EXPECT_EQ(kFallbackDataKey, key_);
  EXPECT_FALSE(data_.empty());
  EXPECT_NE(kEmptyData, data_);
}

TEST_F(RetrieverTest, NoChecksumAndTimestampWillRedownload) {
  storage_->Put(kKey, make_scoped_ptr(new std::string(kEmptyData)));
  retriever_->Retrieve(kKey, BuildCallback());
  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_FALSE(data_.empty());
  EXPECT_NE(kEmptyData, data_);
}

TEST_F(RetrieverTest, ChecksumAndTimestampWillNotRedownload) {
  storage_->Put(kKey,
                Wrap(kEmptyData, kEmptyDataChecksum, TimeToString(time(NULL))));
  retriever_->Retrieve(kKey, BuildCallback());
  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_EQ(kEmptyData, data_);
}

TEST_F(RetrieverTest, OldTimestampWillRedownload) {
  storage_->Put(kKey, Wrap(kEmptyData, kEmptyDataChecksum, "0"));
  retriever_->Retrieve(kKey, BuildCallback());
  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_FALSE(data_.empty());
  EXPECT_NE(kEmptyData, data_);
}

TEST_F(RetrieverTest, OldTimestampOkIfDownloadFails) {
  storage_ = new FakeStorage;
  Retriever bad_retriever(FakeDownloader::kFakeDataUrl,
                          scoped_ptr<Downloader>(new FaultyDownloader),
                          scoped_ptr<Storage>(storage_));
  storage_->Put(kKey, Wrap(kEmptyData, kEmptyDataChecksum, "0"));
  bad_retriever.Retrieve(kKey, BuildCallback());
  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_EQ(kEmptyData, data_);
}

TEST_F(RetrieverTest, WrongChecksumWillRedownload) {
  static const char kNonEmptyData[] = "{\"non-empty\": \"data\"}";
  storage_->Put(
      kKey,
      Wrap(kNonEmptyData, kEmptyDataChecksum, TimeToString(time(NULL))));
  retriever_->Retrieve(kKey, BuildCallback());
  EXPECT_TRUE(success_);
  EXPECT_EQ(kKey, key_);
  EXPECT_FALSE(data_.empty());
  EXPECT_NE(kNonEmptyData, data_);
}

// The downloader that doesn't get back to you.
class HangingDownloader : public Downloader {
 public:
  HangingDownloader() {}
  virtual ~HangingDownloader() {}

  // Downloader implementation.
  virtual void Download(const std::string& url,
                        scoped_ptr<Callback> downloaded) {}
};

TEST_F(RetrieverTest, RequestsDontStack) {
  Retriever slow_retriever(FakeDownloader::kFakeDataUrl,
                           scoped_ptr<Downloader>(new HangingDownloader),
                           scoped_ptr<Storage>(new FakeStorage));

  slow_retriever.Retrieve(kKey, BuildCallback());
  EXPECT_FALSE(success_);
  EXPECT_TRUE(key_.empty());

  EXPECT_NO_FATAL_FAILURE(slow_retriever.Retrieve(kKey, BuildCallback()));
}

TEST_F(RetrieverTest, GetUrlForKey) {
  ResetRetriever("test:///");
  EXPECT_EQ("test:///", GetUrlForKey(""));
  EXPECT_EQ("test:///data", GetUrlForKey("data"));
  EXPECT_EQ("test:///data/US", GetUrlForKey("data/US"));
  EXPECT_EQ("test:///data/CA--fr", GetUrlForKey("data/CA--fr"));
}

TEST_F(RetrieverTest, GetKeyForUrl) {
  ResetRetriever("test:///");
  EXPECT_EQ("", GetKeyForUrl("test://"));
  EXPECT_EQ("", GetKeyForUrl("http://www.google.com/"));
  EXPECT_EQ("", GetKeyForUrl(""));
  EXPECT_EQ("", GetKeyForUrl("test:///"));
  EXPECT_EQ("data", GetKeyForUrl("test:///data"));
  EXPECT_EQ("data/US", GetKeyForUrl("test:///data/US"));
  EXPECT_EQ("data/CA--fr", GetKeyForUrl("test:///data/CA--fr"));
}

TEST_F(RetrieverTest, NullCallbackNoCrash) {
  ASSERT_NO_FATAL_FAILURE(
      retriever_->Retrieve(kKey, scoped_ptr<Retriever::Callback>()));
  ASSERT_NO_FATAL_FAILURE(
      retriever_->Retrieve(kKey, scoped_ptr<Retriever::Callback>()));
}

}  // namespace addressinput
}  // namespace i18n


text:
#include <sys/types.h>  // Include something that will define __GLIBC__.

#if defined(__native_client__)
#  if defined(__GLIBC__)
#    include "kernel_wrap_glibc.cc"
#  else  // !__GLIBC__
#    include "kernel_wrap_newlib.cc"
#  endif
#elif defined(WIN32)
#  include "kernel_wrap_win.cc"
#else
#  error Kernel wrapping not supported on your platform!
#endif


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Cake.Core;
using Cake.Core.IO;

namespace Cake.Common.Solution
{
    /// <summary>
    /// The MSBuild solution file parser.
    /// </summary>
    public sealed class SolutionParser
    {
        private readonly IFileSystem _fileSystem;
        private readonly ICakeEnvironment _environment;

        /// <summary>
        /// Initializes a new instance of the <see cref="SolutionParser"/> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        public SolutionParser(IFileSystem fileSystem, ICakeEnvironment environment)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }
            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }
            _fileSystem = fileSystem;
            _environment = environment;
        }

        /// <summary>
        /// Parses a MSBuild solution.
        /// </summary>
        /// <param name="solutionPath">The solution path.</param>
        /// <returns>A parsed solution.</returns>
        public SolutionParserResult Parse(FilePath solutionPath)
        {
            if (solutionPath == null)
            {
                throw new ArgumentNullException(nameof(solutionPath));
            }
            if (solutionPath.IsRelative)
            {
                solutionPath = solutionPath.MakeAbsolute(_environment);
            }

            // Get the release notes file.
            var file = _fileSystem.GetFile(solutionPath);
            if (!file.Exists)
            {
                const string format = "Solution file '{0}' does not exist.";
                var message = string.Format(CultureInfo.InvariantCulture, format, solutionPath.FullPath);
                throw new CakeException(message);
            }

            string
                version = null,
                visualStudioVersion = null,
                minimumVisualStudioVersion = null;
            var projects = new List<SolutionProject>();
            bool inNestedProjectsSection = false;
            foreach (var line in file.ReadLines(Encoding.UTF8))
            {
                var trimmed = line.Trim();

                if (trimmed == string.Empty)
                {
                    continue;
                }

                if (line.StartsWith("Project(\"{"))
                {
                    var project = ParseSolutionProjectLine(file, line);
                    if (StringComparer.OrdinalIgnoreCase.Equals(project.Type, SolutionFolder.TypeIdentifier))
                    {
                        projects.Add(new SolutionFolder(project.Id, project.Name, project.Path));
                        continue;
                    }
                    projects.Add(project);
                }
                else if (line.StartsWith("Microsoft Visual Studio Solution File, "))
                {
                    version = string.Concat(line.Skip(39));
                }
                else if (line.StartsWith("VisualStudioVersion = "))
                {
                    visualStudioVersion = string.Concat(line.Skip(22));
                }
                else if (line.StartsWith("MinimumVisualStudioVersion = "))
                {
                    minimumVisualStudioVersion = string.Concat(line.Skip(29));
                }
                else if (trimmed.StartsWith("GlobalSection(NestedProjects)"))
                {
                    inNestedProjectsSection = true;
                }
                else if (inNestedProjectsSection && trimmed.StartsWith("EndGlobalSection"))
                {
                    inNestedProjectsSection = false;
                }
                else if (inNestedProjectsSection)
                {
                    ParseNestedProjectLine(projects, trimmed);
                }
            }
            var solutionParserResult = new SolutionParserResult(
                version,
                visualStudioVersion,
                minimumVisualStudioVersion,
                projects.AsReadOnly());
            return solutionParserResult;
        }

        private static SolutionProject ParseSolutionProjectLine(IFile file, string line)
        {
            var withinQuotes = false;
            var projectTypeBuilder = new StringBuilder();
            var nameBuilder = new StringBuilder();
            var pathBuilder = new StringBuilder();
            var idBuilder = new StringBuilder();
            var result = new[]
            {
                projectTypeBuilder,
                nameBuilder,
                pathBuilder,
                idBuilder
            };
            var position = 0;
            foreach (var c in line.Skip(8))
            {
                if (c == '"')
                {
                    withinQuotes = !withinQuotes;
                    if (!withinQuotes)
                    {
                        if (position++ >= result.Length)
                        {
                            break;
                        }
                    }
                    continue;
                }
                if (!withinQuotes)
                {
                    continue;
                }
                result[position].Append(c);
            }

            var projectPath = new FilePath(pathBuilder.ToString());

            var projectFullPath = projectPath.IsRelative ?
                file.Path.GetDirectory().CombineWithFilePath(projectPath) :
                projectPath;

            return new SolutionProject(
                idBuilder.ToString(),
                nameBuilder.ToString(),
                projectFullPath,
                projectTypeBuilder.ToString());
        }

        private static void ParseNestedProjectLine(List<SolutionProject> projects, string line)
        {
            // pattern: {Child} = {Parent}
            var projectIds = line.Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries);
            var child = projects.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Id, projectIds[0].Trim()));
            if (child == null)
            {
                return;
            }

            // Parent should be a folder
            var parent = projects.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Id, projectIds[1].Trim())) as SolutionFolder;
            if (parent == null)
            {
                return;
            }

            parent.Items.Add(child);
            child.Parent = parent;
        }
    }
}


text:
namespace Urho3D
{

Localization::Localization(Context* context) :
    Object(context),
    languageIndex_(-1)
{
}

Localization::~Localization()
{
}

int Localization::GetLanguageIndex(const String& language)
{
    if (language.Empty())
    {
        URHO3D_LOGWARNING("Localization::GetLanguageIndex(language): language name is empty");
        return -1;
    }
    if (GetNumLanguages() == 0)
    {
        URHO3D_LOGWARNING("Localization::GetLanguageIndex(language): no loaded languages");
        return -1;
    }
    for (int i = 0; i < GetNumLanguages(); i++)
    {
        if (languages_[i] == language)
            return i;
    }
    return -1;
}

String Localization::GetLanguage()
{
    if (languageIndex_ == -1)
    {
        URHO3D_LOGWARNING("Localization::GetLanguage(): no loaded languages");
        return String::EMPTY;
    }
    return languages_[languageIndex_];
}

String Localization::GetLanguage(int index)
{
    if (GetNumLanguages() == 0)
    {
        URHO3D_LOGWARNING("Localization::GetLanguage(index): no loaded languages");
        return String::EMPTY;
    }
    if (index < 0 || index >= GetNumLanguages())
    {
        URHO3D_LOGWARNING("Localization::GetLanguage(index): index out of range");
        return String::EMPTY;
    }
    return languages_[index];
}

void Localization::SetLanguage(int index)
{
    if (GetNumLanguages() == 0)
    {
        URHO3D_LOGWARNING("Localization::SetLanguage(index): no loaded languages");
        return;
    }
    if (index < 0 || index >= GetNumLanguages())
    {
        URHO3D_LOGWARNING("Localization::SetLanguage(index): index out of range");
        return;
    }
    if (index != languageIndex_)
    {
        languageIndex_ = index;
        VariantMap& eventData = GetEventDataMap();
        SendEvent(E_CHANGELANGUAGE, eventData);
    }
}

void Localization::SetLanguage(const String& language)
{
    if (language.Empty())
    {
        URHO3D_LOGWARNING("Localization::SetLanguage(language): language name is empty");
        return;
    }
    if (GetNumLanguages() == 0)
    {
        URHO3D_LOGWARNING("Localization::SetLanguage(language): no loaded languages");
        return;
    }
    int index = GetLanguageIndex(language);
    if (index == -1)
    {
        URHO3D_LOGWARNING("Localization::SetLanguage(language): language not found");
        return;
    }
    SetLanguage(index);
}

String Localization::Get(const String& id)
{
    if (id.Empty())
        return String::EMPTY;
    if (GetNumLanguages() == 0)
    {
        URHO3D_LOGWARNING("Localization::Get(id): no loaded languages");
        return id;
    }
    String result = strings_[StringHash(GetLanguage())][StringHash(id)];
    if (result.Empty())
    {
        URHO3D_LOGWARNING("Localization::Get(\"" + id + "\") not found translation, language=\"" + GetLanguage() + "\"");
        return id;
    }
    return result;
}

void Localization::Reset()
{
    languages_.Clear();
    languageIndex_ = -1;
    strings_.Clear();
}

void Localization::LoadJSON(const JSONValue& source)
{
    for (JSONObject::ConstIterator i = source.Begin(); i != source.End(); ++i)
    {
        String id = i->first_;
        if (id.Empty())
        {
            URHO3D_LOGWARNING("Localization::LoadJSON(source): string ID is empty");
            continue;
        }
        const JSONValue& langs = i->second_;
        for (JSONObject::ConstIterator j = langs.Begin(); j != langs.End(); ++j)
        {
            const String& lang = j->first_;
            if (lang.Empty())
            {
                URHO3D_LOGWARNING("Localization::LoadJSON(source): language name is empty, string ID=\"" + id + "\"");
                continue;
            }
            const String& string = j->second_.GetString();
            if (string.Empty())
            {
                URHO3D_LOGWARNING(
                    "Localization::LoadJSON(source): translation is empty, string ID=\"" + id + "\", language=\"" + lang + "\"");
                continue;
            }
            if (strings_[StringHash(lang)][StringHash(id)] != String::EMPTY)
            {
                URHO3D_LOGWARNING(
                    "Localization::LoadJSON(source): override translation, string ID=\"" + id + "\", language=\"" + lang + "\"");
            }
            strings_[StringHash(lang)][StringHash(id)] = string;
            if (!languages_.Contains(lang))
                languages_.Push(lang);
            if (languageIndex_ == -1)
                languageIndex_ = 0;
        }
    }
}

void Localization::LoadJSONFile(const String& name)
{
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    JSONFile* jsonFile = cache->GetResource<JSONFile>(name);
    if (jsonFile)
        LoadJSON(jsonFile->GetRoot());
}

}


text:
FROM xavierdutreilh/python-gettext:3.7.0

ADD . /app

WORKDIR /app

RUN pip install -r requirements/production.txt
RUN python manage.py collectstatic --noinput
RUN python manage.py compilemessages


text:
layout: default
title: "Brewing"
description:
permalink: /category/brewing/
---
{% include category.html %}


text:
/* CSS declarations go here */
.remove {
  cursor: pointer;
}

.verb-edit {
  overflow-x: auto;
}


text:
require 'thread'
require 'capistrano/processable'

module Capistrano
  # The Capistrano::Shell class is the guts of the "shell" task. It implements
  # an interactive REPL interface that users can employ to execute tasks and
  # commands. It makes for a GREAT way to monitor systems, and perform quick
  # maintenance on one or more machines.
  class Shell
    include Processable

    # A Readline replacement for platforms where readline is either
    # unavailable, or has not been installed.
    class ReadlineFallback #:nodoc:
      HISTORY = []

      def self.readline(prompt)
        STDOUT.print(prompt)
        STDOUT.flush
        STDIN.gets
      end
    end

    # The configuration instance employed by this shell
    attr_reader :configuration

    # Instantiate a new shell and begin executing it immediately.
    def self.run(config)
      new(config).run!
    end

    # Instantiate a new shell
    def initialize(config)
      @configuration = config
    end

    # Start the shell running. This method will block until the shell
    # terminates.
    def run!
      setup

      puts <<-INTRO
====================================================================
Welcome to the interactive Capistrano shell! This is an experimental
feature, and is liable to change in future releases. Type 'help' for
a summary of how to use the shell.
--------------------------------------------------------------------
INTRO

      loop do
        break if !read_and_execute
      end

      @bgthread.kill
    end

    def read_and_execute
      command = read_line

      case command
        when "?", "help" then help
        when "quit", "exit" then
          puts "exiting"
          return false
        when /^set -(\w)\s*(\S+)/
          set_option($1, $2)
        when /^(?:(with|on)\s*(\S+))?\s*(\S.*)?/i
          process_command($1, $2, $3)
        else
          raise "eh?"
      end

      return true
    end

    private

      # Present the prompt and read a single line from the console. It also
      # detects ^D and returns "exit" in that case. Adds the input to the
      # history, unless the input is empty. Loops repeatedly until a non-empty
      # line is input.
      def read_line
        loop do
          command = reader.readline("cap> ")

          if command.nil?
            command = "exit"
            puts(command)
          else
            command.strip!
          end

          unless command.empty?
            reader::HISTORY << command
            return command
          end
        end
      end

      # Display a verbose help message.
      def help
        puts <<-HELP
--- HELP! ---------------------------------------------------
"Get me out of this thing. I just want to quit."
-> Easy enough. Just type "exit", or "quit". Or press ctrl-D.

"I want to execute a command on all servers."
-> Just type the command, and press enter. It will be passed,
   verbatim, to all defined servers.

"What if I only want it to execute on a subset of them?"
-> No problem, just specify the list of servers, separated by
   commas, before the command, with the `on' keyword:

   cap> on app1.foo.com,app2.foo.com echo ping

"Nice, but can I specify the servers by role?"
-> You sure can. Just use the `with' keyword, followed by the
   comma-delimited list of role names:

   cap> with app,db echo ping

"Can I execute a Capistrano task from within this shell?"
-> Yup. Just prefix the task with an exclamation mark:

   cap> !deploy
HELP
      end

      # Determine which servers the given task requires a connection to, and
      # establish connections to them if necessary. Return the list of
      # servers (names).
      def connect(task)
        servers = configuration.find_servers_for_task(task)
        needing_connections = servers - configuration.sessions.keys
        unless needing_connections.empty?
          puts "[establishing connection(s) to #{needing_connections.join(', ')}]"
          configuration.establish_connections_to(needing_connections)
        end
        servers
      end

      # Execute the given command. If the command is prefixed by an exclamation
      # mark, it is assumed to refer to another capistrano task, which will
      # be invoked. Otherwise, it is executed as a command on all associated
      # servers.
      def exec(command)
        @mutex.synchronize do
          if command[0] == ?!
            exec_tasks(command[1..-1].split)
          else
            servers = connect(configuration.current_task)
            exec_command(command, servers)
          end
        end
      ensure
        STDOUT.flush
      end

      # Given an array of task names, invoke them in sequence.
      def exec_tasks(list)
        list.each do |task_name|
          task = configuration.find_task(task_name)
          raise Capistrano::NoSuchTaskError, "no such task `#{task_name}'" unless task
          connect(task)
          configuration.execute_task(task)
        end
      rescue Capistrano::NoMatchingServersError, Capistrano::NoSuchTaskError => error
        warn "error: #{error.message}"
      end

      # Execute a command on the given list of servers.
      def exec_command(command, servers)
        command = command.gsub(/\bsudo\b/, "sudo -p '#{configuration.sudo_prompt}'")
        processor = configuration.sudo_behavior_callback(Configuration.default_io_proc)
        sessions = servers.map { |server| configuration.sessions[server] }
        options = configuration.add_default_command_options({})
        cmd = Command.new(command, sessions, options.merge(:logger => configuration.logger), &processor)
        previous = trap("INT") { cmd.stop! }
        cmd.process!
      rescue Capistrano::Error => error
        warn "error: #{error.message}"
      ensure
        trap("INT", previous)
      end

      # Return the object that will be used to query input from the console.
      # The returned object will quack (more or less) like Readline.
      def reader
        @reader ||= begin
          require 'readline'
          Readline
        rescue LoadError
          ReadlineFallback
        end
      end

      # Prepare every little thing for the shell. Starts the background
      # thread and generally gets things ready for the REPL.
      def setup
        configuration.logger.level = Capistrano::Logger::INFO

        @mutex = Mutex.new
        @bgthread = Thread.new do
          loop do
            @mutex.synchronize { process_iteration(0.1) }
          end
        end
      end

      # Set the given option to +value+.
      def set_option(opt, value)
        case opt
          when "v" then
            puts "setting log verbosity to #{value.to_i}"
            configuration.logger.level = value.to_i
          when "o" then
            case value
            when "vi" then
              puts "using vi edit mode"
              reader.vi_editing_mode
            when "emacs" then
              puts "using emacs edit mode"
              reader.emacs_editing_mode
            else
              puts "unknown -o option #{value.inspect}"
            end
          else
            puts "unknown setting #{opt.inspect}"
        end
      end

      # Process a command. Interprets the scope_type (must be nil, "with", or
      # "on") and the command. If no command is given, then the scope is made
      # effective for all subsequent commands. If the scope value is "all",
      # then the scope is unrestricted.
      def process_command(scope_type, scope_value, command)
        env_var = case scope_type
            when "with" then "ROLES"
            when "on"   then "HOSTS"
          end

        old_var, ENV[env_var] = ENV[env_var], (scope_value == "all" ? nil : scope_value) if env_var
        if command
          begin
            exec(command)
          ensure
            ENV[env_var] = old_var if env_var
          end
        else
          puts "scoping #{scope_type} #{scope_value}"
        end
      end
    end

    # All open sessions, needed to satisfy the Command::Processable include
    def sessions
      configuration.sessions.values
    end
end


text:
package kamatera

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"k8s.io/autoscaler/cluster-autoscaler/version"
	"k8s.io/klog/v2"
	"strings"
)

const (
	userAgent = "kubernetes/cluster-autoscaler/" + version.ClusterAutoscalerVersion
)

// NewKamateraApiClientRest factory to create new Rest API Client struct
func NewKamateraApiClientRest(clientId string, secret string, url string) (client KamateraApiClientRest) {
	return KamateraApiClientRest{
		userAgent: userAgent,
		clientId:  clientId,
		secret:    secret,
		url:       url,
	}
}

// KamateraServerPostRequest struct for Kamatera server post request
type KamateraServerPostRequest struct {
	ServerName string `json:"name"`
}

// KamateraServerTerminatePostRequest struct for Kamatera server terminate post request
type KamateraServerTerminatePostRequest struct {
	ServerName string `json:"name"`
	Force      bool   `json:"force"`
}

// KamateraServerCreatePostRequest struct for Kamatera server create post request
type KamateraServerCreatePostRequest struct {
	Name               string `json:"name"`
	Password           string `json:"password"`
	PasswordValidate   string `json:"passwordValidate"`
	SshKey             string `json:"ssh-key"`
	Datacenter         string `json:"datacenter"`
	Image              string `json:"image"`
	Cpu                string `json:"cpu"`
	Ram                string `json:"ram"`
	Disk               string `json:"disk"`
	Dailybackup        string `json:"dailybackup"`
	Managed            string `json:"managed"`
	Network            string `json:"network"`
	Quantity           int    `json:"quantity"`
	BillingCycle       string `json:"billingCycle"`
	MonthlyPackage     string `json:"monthlypackage"`
	Poweronaftercreate string `json:"poweronaftercreate"`
	ScriptFile         string `json:"script-file"`
	UserdataFile       string `json:"userdata-file"`
	Tag                string `json:"tag"`
}

// KamateraApiClientRest is the struct to perform API calls
type KamateraApiClientRest struct {
	userAgent string
	clientId  string
	secret    string
	url       string
}

// ListServers returns a list of all servers in the relevant account and fetches their tags
func (c *KamateraApiClientRest) ListServers(ctx context.Context, instances map[string]*Instance) ([]Server, error) {
	res, err := request(
		ctx,
		ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
		"GET",
		"/service/servers",
		nil,
	)
	if err != nil {
		return nil, err
	}
	var servers []Server
	for _, server := range res.([]interface{}) {
		server := server.(map[string]interface{})
		serverName := server["name"].(string)
		serverPowerOn := server["power"].(string) == "on"
		serverTags, err := c.getServerTags(ctx, serverName, instances)
		if err != nil {
			return nil, err
		}
		servers = append(servers, Server{
			Name:    serverName,
			Tags:    serverTags,
			PowerOn: serverPowerOn,
		})
	}
	return servers, nil
}

// DeleteServer deletes a server according to the given name
func (c *KamateraApiClientRest) DeleteServer(ctx context.Context, name string) error {
	res, err := request(
		ctx,
		ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
		"POST",
		"/service/server/poweroff",
		KamateraServerPostRequest{ServerName: name},
	)
	if err == nil {
		commandId := res.([]interface{})[0].(string)
		_, err = waitCommand(
			ctx,
			ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
			commandId,
		)
		if err != nil {
			return err
		}
	} else {
		klog.V(1).Infof("Failed to power off server but will attempt to terminate anyway %s: %v", name, err)
	}
	_, err = request(
		ctx,
		ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
		"POST",
		"/service/server/terminate",
		KamateraServerTerminatePostRequest{ServerName: name, Force: true},
	)
	if err != nil {
		return err
	}
	return nil
}

// CreateServers creates new servers according to the given configuration
func (c *KamateraApiClientRest) CreateServers(ctx context.Context, count int, config ServerConfig) ([]Server, error) {
	var tags []string
	for _, tag := range config.Tags {
		tags = append(tags, tag)
	}
	Tag, err := kamateraRequestArray(tags)
	if err != nil {
		return nil, err
	}
	Network, err := kamateraRequestArray(config.Networks)
	if err != nil {
		return nil, err
	}
	Disk, err := kamateraRequestArray(config.Disks)
	if err != nil {
		return nil, err
	}
	serverNameCommandIds := make(map[string]string)
	for i := 0; i < count; i++ {
		serverName := kamateraServerName(config.NamePrefix)
		res, err := request(
			ctx,
			ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
			"POST",
			"/service/server",
			KamateraServerCreatePostRequest{
				Name:               serverName,
				Password:           config.Password,
				PasswordValidate:   config.Password,
				SshKey:             config.SshKey,
				Datacenter:         config.Datacenter,
				Image:              config.Image,
				Cpu:                config.Cpu,
				Ram:                config.Ram,
				Disk:               Disk,
				Dailybackup:        kamateraRequestBool(config.Dailybackup),
				Managed:            kamateraRequestBool(config.Managed),
				Network:            Network,
				Quantity:           1,
				BillingCycle:       config.BillingCycle,
				MonthlyPackage:     config.MonthlyPackage,
				Poweronaftercreate: "yes",
				ScriptFile:         config.ScriptFile,
				UserdataFile:       config.UserdataFile,
				Tag:                Tag,
			},
		)
		if err != nil {
			return nil, err
		}
		if config.Password == "__generate__" {
			resData := res.(map[string]interface{})
			klog.V(2).Infof("Generated password for server %s: %s", serverName, resData["password"].(string))
			serverNameCommandIds[serverName] = resData["commandIds"].([]interface{})[0].(string)
		} else {
			serverNameCommandIds[serverName] = res.([]interface{})[0].(string)
		}
	}
	results, err := waitCommands(
		ctx,
		ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
		serverNameCommandIds,
	)
	if err != nil {
		return nil, err
	}
	var servers []Server
	for serverName := range results {
		servers = append(servers, Server{
			Name: serverName,
			Tags: tags,
		})
	}
	return servers, nil
}

func (c *KamateraApiClientRest) getServerTags(ctx context.Context, serverName string, instances map[string]*Instance) ([]string, error) {
	if instances[serverName] == nil {
		res, err := request(
			ctx,
			ProviderConfig{ApiUrl: c.url, ApiClientID: c.clientId, ApiSecret: c.secret},
			"POST",
			"/server/tags",
			KamateraServerPostRequest{ServerName: serverName},
		)
		if err != nil {
			return nil, err
		}
		var tags []string
		for _, row := range res.([]interface{}) {
			row := row.(map[string]interface{})
			tags = append(tags, row["tag name"].(string))
		}
		return tags, nil
	}
	return instances[serverName].Tags, nil
}

func kamateraRequestBool(val bool) string {
	if val {
		return "yes"
	}
	return "no"
}

func kamateraRequestArray(val []string) (string, error) {
	for _, v := range val {
		if strings.Contains(v, " ") {
			return "", fmt.Errorf("invalid Kamatera server configuration array value (\"%s\"): ,must not contain spaces", v)
		}
	}
	return strings.Join(val, " "), nil
}

func kamateraServerName(namePrefix string) string {
	if len(namePrefix) > 0 {
		namePrefix = fmt.Sprintf("%s-", namePrefix)
	}
	return fmt.Sprintf("%s%s", namePrefix, strings.ReplaceAll(uuid.New().String(), "-", ""))
}


text:
package ca.uhn.hapi.fhir.docs;

import ca.uhn.fhir.interceptor.api.Hook;
import ca.uhn.fhir.interceptor.api.Interceptor;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.interceptor.model.RequestPartitionId;
import ca.uhn.fhir.jpa.model.config.PartitionSettings;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.rest.server.tenant.UrlBaseTenantIdentificationStrategy;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.r4.model.Observation;
import org.hl7.fhir.r4.model.Patient;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@SuppressWarnings("InnerClassMayBeStatic")
public class PartitionExamples {

	public void multitenantServer() {

	}

	// START SNIPPET: partitionInterceptorRequestPartition
	@Interceptor
	public class RequestTenantPartitionInterceptor {

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_CREATE)
		public RequestPartitionId PartitionIdentifyCreate(ServletRequestDetails theRequestDetails) {
			return extractPartitionIdFromRequest(theRequestDetails);
		}

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_READ)
		public RequestPartitionId PartitionIdentifyRead(ServletRequestDetails theRequestDetails) {
			return extractPartitionIdFromRequest(theRequestDetails);
		}

		private RequestPartitionId extractPartitionIdFromRequest(ServletRequestDetails theRequestDetails) {
			// We will use the tenant ID that came from the request as the partition name
			String tenantId = theRequestDetails.getTenantId();
			return RequestPartitionId.fromPartitionName(tenantId);
		}

	}
	// END SNIPPET: partitionInterceptorRequestPartition

	// START SNIPPET: partitionInterceptorHeaders
	@Interceptor
	public class CustomHeaderBasedPartitionInterceptor {

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_CREATE)
		public RequestPartitionId PartitionIdentifyCreate(ServletRequestDetails theRequestDetails) {
			String partitionName = theRequestDetails.getHeader("X-Partition-Name");
			return RequestPartitionId.fromPartitionName(partitionName);
		}

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_READ)
		public RequestPartitionId PartitionIdentifyRead(ServletRequestDetails theRequestDetails) {
			String partitionName = theRequestDetails.getHeader("X-Partition-Name");
			return RequestPartitionId.fromPartitionName(partitionName);
		}

	}
	// END SNIPPET: partitionInterceptorHeaders

	// START SNIPPET: partitionInterceptorResourceContents
	@Interceptor
	public class ResourceTypePartitionInterceptor {

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_CREATE)
		public RequestPartitionId PartitionIdentifyCreate(IBaseResource theResource) {
			if (theResource instanceof Patient) {
				return RequestPartitionId.fromPartitionName("PATIENT");
			} else if (theResource instanceof Observation) {
					return RequestPartitionId.fromPartitionName("OBSERVATION");
			} else {
				return RequestPartitionId.fromPartitionName("OTHER");
			}
		}

	}
	// END SNIPPET: partitionInterceptorResourceContents

	// START SNIPPET: partitionInterceptorReadAllPartitions
	@Interceptor
	public class PartitionInterceptorReadAllPartitions {

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_READ)
		public RequestPartitionId readPartition() {
			return RequestPartitionId.allPartitions();
		}

	}
	// END SNIPPET: partitionInterceptorReadAllPartitions

	// START SNIPPET: partitionInterceptorReadBasedOnScopes
	@Interceptor
	public class PartitionInterceptorReadPartitionsBasedOnScopes {

		@Hook(Pointcut.STORAGE_PARTITION_IDENTIFY_READ)
		public RequestPartitionId readPartition(ServletRequestDetails theRequest) {

			HttpServletRequest servletRequest = theRequest.getServletRequest();
			Set<String> approvedScopes = (Set<String>) servletRequest.getAttribute("ca.cdr.servletattribute.session.oidc.approved_scopes");

			String partition = approvedScopes
				.stream()
				.filter(t->t.startsWith("partition-"))
				.map(t->t.substring("partition-".length()))
				.findFirst()
				.orElseThrow(()->new InvalidRequestException("No partition scopes found in request"));
			return RequestPartitionId.fromPartitionName(partition);

		}

	}
	// END SNIPPET: partitionInterceptorReadBasedOnScopes

	// START SNIPPET: multitenantServer
	public class MultitenantServer extends RestfulServer {

		@Autowired
		private PartitionSettings myPartitionSettings;

		@Override
		protected void initialize() {

			// Enable partitioning
			myPartitionSettings.setPartitioningEnabled(true);

			// Set the tenant identification strategy
			setTenantIdentificationStrategy(new UrlBaseTenantIdentificationStrategy());

			// Use the tenant ID supplied by the tenant identification strategy
			// to serve as the partitioning ID
			registerInterceptor(new RequestTenantPartitionInterceptor());

			// ....Register some providers and other things....

		}
	}
	// END SNIPPET: multitenantServer

}


text:
package org.fugerit.java.core.web.servlet.config;

import java.util.Properties;

import org.fugerit.java.core.cfg.ConfigException;
import org.fugerit.java.core.cfg.helpers.PropertiesConfigurableObject;
import org.fugerit.java.core.xml.dom.DOMUtils;
import org.w3c.dom.Element;

public abstract class BasicConfig extends PropertiesConfigurableObject {

	/**
	 *
	 */
	private static final long serialVersionUID = 7942370774582080658L;

	private ConfigContext configContext;

	public ConfigContext getConfigContext() {
		return configContext;
	}

	public void setConfigContext(ConfigContext configContext) {
		this.configContext = configContext;
	}

	public void configure(Element tag) throws ConfigException {
		this.configure( DOMUtils.attributesToProperties( tag ) );
	}

	public abstract void configure(Properties props) throws ConfigException;

}


text:
package forestdb

import (
	"github.com/couchbase/goforestdb"
)

type Iterator struct {
	store    *Store
	snapshot *forestdb.KVStore
	iterator *forestdb.Iterator
	curr     *forestdb.Doc
	valid    bool
}

func newIterator(store *Store) *Iterator {
	itr, err := store.dbkv.IteratorInit([]byte{}, nil, forestdb.ITR_NONE)
	rv := Iterator{
		store:    store,
		iterator: itr,
		valid:    err == nil,
	}
	return &rv
}

func newIteratorWithSnapshot(store *Store, snapshot *forestdb.KVStore) *Iterator {
	itr, err := snapshot.IteratorInit([]byte{}, nil, forestdb.ITR_NONE)
	rv := Iterator{
		store:    store,
		iterator: itr,
		valid:    err == nil,
	}
	return &rv
}

func newIteratorWithSnapshotAndRange(store *Store, snapshot *forestdb.KVStore, start, end []byte) *Iterator {
	itr, err := snapshot.IteratorInit(start, end, forestdb.ITR_NONE)
	rv := Iterator{
		store:    store,
		iterator: itr,
		valid:    err == nil,
	}
	return &rv
}

func (i *Iterator) SeekFirst() {
	err := i.iterator.SeekMin()
	if err != nil {
		i.valid = false
		return
	}
	if i.curr != nil {
		i.curr.Close()
	}
	i.curr, err = i.iterator.Get()
	if err != nil {
		i.valid = false
	}
}

func (i *Iterator) Seek(key []byte) {
	err := i.iterator.Seek(key, forestdb.FDB_ITR_SEEK_HIGHER)
	if err != nil {
		i.valid = false
		return
	}
	if i.curr != nil {
		i.curr.Close()
	}
	i.curr, err = i.iterator.Get()
	if err != nil {
		i.valid = false
		return
	}
}

func (i *Iterator) Next() {
	err := i.iterator.Next()
	if err != nil {
		i.valid = false
		return
	}
	if i.curr != nil {
		i.curr.Close()
	}
	i.curr, err = i.iterator.Get()
	if err != nil {
		i.valid = false
	}
}

func (i *Iterator) Current() ([]byte, []byte, bool) {
	if i.Valid() {
		return i.Key(), i.Value(), true
	}
	return nil, nil, false
}

func (i *Iterator) Key() []byte {
	return i.curr.Key()
}

func (i *Iterator) Value() []byte {
	return i.curr.Body()
}

func (i *Iterator) Valid() bool {
	return i.valid
}

func (i *Iterator) Close() error {
	i.valid = false
	if i.curr != nil {
		i.curr.Close()
	}
	return i.iterator.Close()
}


text:
package z.sye.space.library;

import android.content.Context;

/**
 * Created by Syehunter on 2016/1/11.
 */
public class DimensUtils {

    public static int dp2px(Context context, int dip) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f * (dip >= 0 ? 1 : -1));
    }

    public static int px2dp(Context context, int px) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f * (px >= 0 ? 1 : -1));
    }

    public static int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }
}


text:
BASEPATH=${1:-"/usr/local/openresty"}

sudo apt-get install libpcre3-dev build-essential libssl-dev sudo libreadline-dev postgresql libpq-dev libncurses5-dev libpcre3-dev libssl-dev perl make

wget http://openresty.org/download/ngx_openresty-1.4.3.9.tar.gz
tar xzvf ngx*.tar.gz
cd ngx_*
./configure --prefix=$BASEPATH --with-luajit --with-http_postgres_module
make
sudo make install

echo
echo Customize nginx/conf/nginx.conf
echo
echo Customize init.sql and run 'su - postgres psql -f init.sql'
echo
echo Copy the files in the nginx directory to the corresponding places in your new OpenResty install
echo
echo Start the server with the command .$BASEPATH/nginx/bin/nginx


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.WindowsAzure.Management.RecoveryServicesVaultUpgrade.Models;

namespace Microsoft.Azure.Commands.RecoveryServices
{
    /// <summary>
    /// Check vault upgrade prerequisites response.
    /// </summary>
    public enum CheckVaultUpgradePrerequisitesResponse
    {
        /// <summary>
        /// Represents succeeded scenario.
        /// </summary>
        Succeeded,

        /// <summary>
        /// Represents failed scenario.
        /// </summary>
        Failed,

        /// <summary>
        /// Represents succeeded scenario with warnings.
        /// </summary>
        SucceededWithWarnings
    }

    /// <summary>
    /// Represents vault upgrade operation's result.
    /// </summary>
    public enum VaultUpgradeOperationResult
    {
        /// <summary>
        /// Represents default state.
        /// </summary>
        Unavailable,

        /// <summary>
        /// Represents succeeded state.
        /// </summary>
        Succeeded,

        /// <summary>
        /// Represents failed scenario.
        /// </summary>
        Failed,

        /// <summary>
        /// Represents timed out state.
        /// </summary>
        TimedOut,

        /// <summary>
        /// Represents in progress state.
        /// </summary>
        InProgress
    }

    /// <summary>
    /// Represents the error type.
    /// </summary>
    public enum ErrorType
    {
        /// <summary>
        /// Represents that the given error can't be ignored.
        /// </summary>
        Error,

        /// <summary>
        /// Represents that the given error can be ignored.
        /// </summary>
        Warning
    }

    /// <summary>
    /// Recovery services vault upgrade response.
    /// </summary>
    public class ASRVaultUpgradeResponse
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ASRVaultUpgradeResponse" /> class.
        /// </summary>
        public ASRVaultUpgradeResponse()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ASRVaultUpgradeResponse" /> class with required
        /// parameters.
        /// </summary>
        /// <param name="resourceUpgradeDetails">Resource upgrade details.</param>
        /// <param name="operationResult">Vault upgrade operation result.</param>
        /// <param name="operationStatus">Vault upgrade operation status.</param>
        /// <param name="message">Upgrade status.</param>
        public ASRVaultUpgradeResponse(ResourceUpgradeDetails resourceUpgradeDetails, string operationResult, string operationStatus, string message)
        {
            this.OperationId = resourceUpgradeDetails.OperationId;
            this.StartTimeUtc = resourceUpgradeDetails.StartTimeUtc;
            this.OperationResult = operationResult;
            this.OperationStatus = operationStatus;
            this.UpgradeStatus = message;
        }

        #region Properties
        /// <summary>
        /// Gets or sets Operation ID.
        /// </summary>
        public string OperationId { get; set; }

        /// <summary>
        /// Gets or sets start time.
        /// </summary>
        public DateTime StartTimeUtc { get; set; }

        /// <summary>
        /// Gets or sets the operation result.
        /// </summary>
        public string OperationResult { get; set; }

        /// <summary>
        /// Gets or sets the operation response.
        /// </summary>
        public string OperationStatus { get; set; }

        /// <summary>
        /// Gets or sets the upgrade status.
        /// </summary>
        public string UpgradeStatus { get; set; }
        #endregion
    }

    /// <summary>
    /// Test vault upgrade response.
    /// </summary>
    [SuppressMessage(
        "Microsoft.StyleCop.CSharp.MaintainabilityRules",
        "SA1402:FileMayOnlyContainASingleClass",
        Justification = "Keeping all related classes together.")]
    public class ASRTestVaultUpgradeResponse
    {
        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="ASRTestVaultUpgradeResponse" /> class
        /// </summary>
        public ASRTestVaultUpgradeResponse()
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the operation's response.
        /// </summary>
        public string Response { get; set; }

        #endregion
    }

    /// <summary>
    /// Object to be returned after categorizing all the errors properly
    /// received as part of vault upgrade operations.
    /// </summary>
    [SuppressMessage(
        "Microsoft.StyleCop.CSharp.MaintainabilityRules",
        "SA1402:FileMayOnlyContainASingleClass",
        Justification = "Keeping all related objects together.")]
    public class ExceptionDetails
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionDetails" />
        /// class with required parameters.
        /// </summary>
        /// <param name="errorDetails">Error details.</param>
        /// <param name="warningDetails">Warning details.</param>
        /// <param name="errorCodes">List of error code associated with the errors received.</param>
        public ExceptionDetails(string errorDetails, string warningDetails, HashSet<string> errorCodes)
        {
            this.ErrorDetails = errorDetails;
            this.WarningDetails = warningDetails;
            this.ErrorCodes = errorCodes;
        }

        #region Properties
        /// <summary>
        /// Gets or sets the string containing details of all the errors.
        /// </summary>
        public string ErrorDetails { get; set; }

        /// <summary>
        /// Gets or sets the string containing details of all the warnings.
        /// </summary>
        public string WarningDetails { get; set; }

        /// <summary>
        /// Gets or sets the list of error code.
        /// </summary>
        public HashSet<string> ErrorCodes { get; set; }
        #endregion
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "tg_bloguser".
 *
 * @property integer $tg_id
 * @property string $tg_username
 * @property string $tg_password
 * @property string $tg_confirmPassword
 * @property string $tg_email
 * @property string $tg_sex
 * @property string $tg_face
 * @property string $tg_reg_time
 * @property string $logo_file
 */
class Blogger extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tg_bloguser';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['tg_username', 'tg_password', 'tg_confirmPassword', 'tg_email', 'tg_sex', 'tg_reg_time'], 'required'],
            [['tg_reg_time'], 'safe'],
            [['tg_username', 'tg_password', 'tg_confirmPassword', 'tg_email', 'tg_sex', 'tg_face'], 'string', 'max' => 40]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'tg_id' => 'ID',
            'tg_username' => '用户名',
            'tg_password' => '密码',
            'tg_confirmPassword' => 'Tg Confirm Password',
            'tg_email' => '邮箱',
            'tg_sex' => '性别',
            'tg_face' => '头像',
            'tg_reg_time' => '注册时间',
        ];
    }
}