text:
/*---------------------------------------------------------------------------

    (c) 2004 Scorpio Software
        19 Wittama Drive
        Glenmore Park
        Sydney NSW 2745
        Australia

-----------------------------------------------------------------------------

    $Workfile::                                                           $
    $Revision::                                                           $
        $Date::                                                           $
      $Author::                                                           $

---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#include "pch.h"
#pragma hdrstop
#include "ZXPluginManager.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
//---------------------------------------------------------------------------
__fastcall ZXUndoItem::ZXUndoItem(const KXmlInfo& xmlInfo)
{
    m_XmlInfo = xmlInfo;
}
//---------------------------------------------------------------------------
__fastcall ZXUndoItem::ZXUndoItem(const ZXUndoItem& undoItem)
{
    m_XmlInfo = undoItem.m_XmlInfo;
}
//---------------------------------------------------------------------------
String  __fastcall ZXUndoItem::GetDescription(void)
{
    String sDescription = "Unknown";
    KXmlInfo* pNode = m_XmlInfo.GetNode("Description", 0);
    if (true == SAFE_PTR(pNode))
    {
        sDescription = pNode->GetText();
    }
    return sDescription;
}
//---------------------------------------------------------------------------
String  __fastcall ZXUndoItem::GetPlugin(void)
{
    String sPlugin = "Unknown";
    KXmlInfo* pNode = m_XmlInfo.GetNode("Plugin", 0);
    if (true == SAFE_PTR(pNode))
    {
        sPlugin = pNode->GetText();
    }
    return sPlugin;
}
//---------------------------------------------------------------------------
int __fastcall ZXUndoItem::GetSize(void)
{
    try
    {
        return m_XmlInfo.GetXmlString().Length() + sizeof(this) + sizeof(m_XmlInfo);
    }
    catch(...)
    {
        return 0;
    }
}
//---------------------------------------------------------------------------
void __fastcall ZXUndoItem::Restore(void)
{
    // post item restore operation
    g_PluginManager.Notify(NULL, TZXN_XML_UNDO_RESTORE, (LPDATA)&m_XmlInfo, 0, 0);
}
//---------------------------------------------------------------------------


text:
import re
import sys
import os
import subprocess
from subprocess import PIPE

from termcolor import colored

# TODO: need to create a util to make sure this exists
JIVER_HOME = os.path.expanduser("~/.jiver")
vpn_ip_file = JIVER_HOME + '/vpn_ip'

def __obtain_default_gateway_and_save_to_file():
    cmd = "route -n get default | grep gateway | sed 's/.*gateway: //'"
    p = subprocess.Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()
    default_gateway = output[0].rstrip()

    print colored("Current default gateway: " + default_gateway, 'yellow')
    print colored("Saving to " + vpn_ip_file, 'yellow')
    if not os.path.isdir(JIVER_HOME):
        os.makedirs(JIVER_HOME)

    f = open(vpn_ip_file, 'w')
    f.write(default_gateway)

def __force_all_traffic_through_the_vpn_connection():

    try:
        cmd = "netstat -r | grep  '10\.61' | awk '{print $6}' | sort | uniq"
        p = subprocess.Popen(cmd, shell=True, stdout=PIPE)
        output = p.communicate()
        if len(output) != 2:
            print colored("Found multiple interfaces.", 'red')
            print output
            sys.exit(1)

        interface = output[0].strip()
        print colored("Interface: " + interface, 'yellow')

        cmd = "sudo route change default -link -interface " + interface
        print colored(cmd, 'yellow')
        subprocess.call(cmd.split())
    except KeyboardInterrupt:
        sys.exit(1)

def __get_saved_default_gateway_or_most_likely_value():
    saved_default_gateway = ""
    try:
        f = open(vpn_ip_file, 'r')
        saved_default_gateway = f.read()
    except IOError:
        None # Do nothing

    if not re.search(r'^\d+\.\d+\.\d+\.\d+$', saved_default_gateway):
        print colored("Malformed or missing data in " + vpn_ip_file, 'red')
        print colored("Using 192.168.1.1 for the default gateway.", 'red')
        print colored("Press control-c if you don't want to proceed.", 'red')
        print colored("You can try rebooting your computer instead.", 'red')
        return "192.168.1.1"

    return saved_default_gateway

def __change_default_gateway(gateway):
    cmd = "sudo route change default " + gateway
    print colored(cmd, 'yellow')
    try:
        subprocess.call(cmd.split())
    except KeyboardInterrupt:
        sys.exit(1)

# ==============================================================================
# Public methods
# ==============================================================================
def all():
    __obtain_default_gateway_and_save_to_file()
    __force_all_traffic_through_the_vpn_connection()

def split():
    gateway = __get_saved_default_gateway_or_most_likely_value()
    __change_default_gateway(gateway)

def my_current_gateway():
    cmd = "route -n get default | grep gateway"
    print colored(cmd, 'yellow')
    p = subprocess.Popen(cmd, shell=True, stdout=PIPE)
    print p.communicate()[0]

redpajama_set_name: RedPajamaGithub


text:
package eu.peppol.security.callbacks;

import com.sun.xml.wss.impl.callback.KeyStoreCallback;

import nl.kaninefatendreef.si.SIConfigurationException;
import nl.kaninefatendreef.si.server.config.SpringServerContext;
import nl.kaninefatendreef.si.ssl.TrustStoreManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;

import java.security.KeyStore;

public final class TrustStoreCallbackHandler implements CallbackHandler {

    public static final Logger _logger = LoggerFactory.getLogger(TrustStoreCallbackHandler.class);

    public TrustStoreCallbackHandler() {}

    public void handle(Callback[] callbacks) {

    	_logger.debug("Handling TrustStoreCallbackHandler found in the wsdl  \n" +
    			"<TrustStore wspp:visibility=\"private\" \n " +
                "callbackHandler=\"eu.peppol.security.callbacks.TrustStoreCallbackHandler\"/>");

    	// Spring wire into sun ws wire.
    	TrustStoreManager peppolTrustStore = SpringServerContext.getPeppolTrustStore();

        for (Callback callback : callbacks) {

            if (callback instanceof KeyStoreCallback) {
            	_logger.debug("Returning truststore");
                KeyStore truststore = null;
				try {
					truststore = peppolTrustStore.getTruststore();
				} catch (SIConfigurationException e) {
					_logger.error("Could not find the truststore " + truststore , e);
				}
                ((KeyStoreCallback) callback).setKeystore(truststore);
            }
        }
    }
}


text:
//
//  GTLDriveAbout.h
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Drive API (drive/v2)
// Description:
//   The API to interact with Drive.
// Documentation:
//   https://developers.google.com/drive/
// Classes:
//   GTLDriveAbout (0 custom class methods, 24 custom properties)
//   GTLDriveAboutAdditionalRoleInfoItem (0 custom class methods, 2 custom properties)
//   GTLDriveAboutExportFormatsItem (0 custom class methods, 2 custom properties)
//   GTLDriveAboutFeaturesItem (0 custom class methods, 2 custom properties)
//   GTLDriveAboutImportFormatsItem (0 custom class methods, 2 custom properties)
//   GTLDriveAboutMaxUploadSizesItem (0 custom class methods, 2 custom properties)
//   GTLDriveAboutQuotaBytesByServiceItem (0 custom class methods, 2 custom properties)
//   GTLDriveAboutAdditionalRoleInfoItemRoleSetsItem (0 custom class methods, 2 custom properties)

#if GTL_BUILT_AS_FRAMEWORK
  #import "GTL/GTLObject.h"
#else
  #import "GTLObject.h"
#endif

@class GTLDriveAboutAdditionalRoleInfoItem;
@class GTLDriveAboutAdditionalRoleInfoItemRoleSetsItem;
@class GTLDriveAboutExportFormatsItem;
@class GTLDriveAboutFeaturesItem;
@class GTLDriveAboutImportFormatsItem;
@class GTLDriveAboutMaxUploadSizesItem;
@class GTLDriveAboutQuotaBytesByServiceItem;
@class GTLDriveUser;

// ----------------------------------------------------------------------------
//
//   GTLDriveAbout
//

// An item with user information and settings.

@interface GTLDriveAbout : GTLObject

// Information about supported additional roles per file type. The most specific
// type takes precedence.
@property (nonatomic, retain) NSArray *additionalRoleInfo;  // of GTLDriveAboutAdditionalRoleInfoItem

// The domain sharing policy for the current user. Possible values are:
// - allowed
// - allowedWithWarning
// - incomingOnly
// - disallowed
@property (nonatomic, copy) NSString *domainSharingPolicy;

// The ETag of the item.
@property (nonatomic, copy) NSString *ETag;

// The allowable export formats.
@property (nonatomic, retain) NSArray *exportFormats;  // of GTLDriveAboutExportFormatsItem

// List of additional features enabled on this account.
@property (nonatomic, retain) NSArray *features;  // of GTLDriveAboutFeaturesItem

// The palette of allowable folder colors as RGB hex strings.
@property (nonatomic, retain) NSArray *folderColorPalette;  // of NSString

// The allowable import formats.
@property (nonatomic, retain) NSArray *importFormats;  // of GTLDriveAboutImportFormatsItem

// A boolean indicating whether the authenticated app is installed by the
// authenticated user.
@property (nonatomic, retain) NSNumber *isCurrentAppInstalled;  // boolValue

// This is always drive#about.
@property (nonatomic, copy) NSString *kind;

// The user's language or locale code, as defined by BCP 47, with some
// extensions from Unicode's LDML format (http://www.unicode.org/reports/tr35/).
@property (nonatomic, copy) NSString *languageCode;

// The largest change id.
@property (nonatomic, retain) NSNumber *largestChangeId;  // longLongValue

// List of max upload sizes for each file type. The most specific type takes
// precedence.
@property (nonatomic, retain) NSArray *maxUploadSizes;  // of GTLDriveAboutMaxUploadSizesItem

// The name of the current user.
@property (nonatomic, copy) NSString *name;

// The current user's ID as visible in the permissions collection.
@property (nonatomic, copy) NSString *permissionId;

// The amount of storage quota used by different Google services.
@property (nonatomic, retain) NSArray *quotaBytesByService;  // of GTLDriveAboutQuotaBytesByServiceItem

// The total number of quota bytes.
@property (nonatomic, retain) NSNumber *quotaBytesTotal;  // longLongValue

// The number of quota bytes used by Google Drive.
@property (nonatomic, retain) NSNumber *quotaBytesUsed;  // longLongValue

// The number of quota bytes used by all Google apps (Drive, Picasa, etc.).
@property (nonatomic, retain) NSNumber *quotaBytesUsedAggregate;  // longLongValue

// The number of quota bytes used by trashed items.
@property (nonatomic, retain) NSNumber *quotaBytesUsedInTrash;  // longLongValue

// The type of the user's storage quota. Possible values are:
// - LIMITED
// - UNLIMITED
@property (nonatomic, copy) NSString *quotaType;

// The number of remaining change ids.
@property (nonatomic, retain) NSNumber *remainingChangeIds;  // longLongValue

// The id of the root folder.
@property (nonatomic, copy) NSString *rootFolderId;

// A link back to this item.
@property (nonatomic, copy) NSString *selfLink;

// The authenticated user.
@property (nonatomic, retain) GTLDriveUser *user;

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutAdditionalRoleInfoItem
//

@interface GTLDriveAboutAdditionalRoleInfoItem : GTLObject

// The supported additional roles per primary role.
@property (nonatomic, retain) NSArray *roleSets;  // of GTLDriveAboutAdditionalRoleInfoItemRoleSetsItem

// The content type that this additional role info applies to.
@property (nonatomic, copy) NSString *type;

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutExportFormatsItem
//

@interface GTLDriveAboutExportFormatsItem : GTLObject

// The content type to convert from.
@property (nonatomic, copy) NSString *source;

// The possible content types to convert to.
@property (nonatomic, retain) NSArray *targets;  // of NSString

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutFeaturesItem
//

@interface GTLDriveAboutFeaturesItem : GTLObject

// The name of the feature.
@property (nonatomic, copy) NSString *featureName;

// The request limit rate for this feature, in queries per second.
@property (nonatomic, retain) NSNumber *featureRate;  // doubleValue

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutImportFormatsItem
//

@interface GTLDriveAboutImportFormatsItem : GTLObject

// The imported file's content type to convert from.
@property (nonatomic, copy) NSString *source;

// The possible content types to convert to.
@property (nonatomic, retain) NSArray *targets;  // of NSString

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutMaxUploadSizesItem
//

@interface GTLDriveAboutMaxUploadSizesItem : GTLObject

// The max upload size for this type.
@property (nonatomic, retain) NSNumber *size;  // longLongValue

// The file type.
@property (nonatomic, copy) NSString *type;

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutQuotaBytesByServiceItem
//

@interface GTLDriveAboutQuotaBytesByServiceItem : GTLObject

// The storage quota bytes used by the service.
@property (nonatomic, retain) NSNumber *bytesUsed;  // longLongValue

// The service's name, e.g. DRIVE, GMAIL, or PHOTOS.
@property (nonatomic, copy) NSString *serviceName;

@end

// ----------------------------------------------------------------------------
//
//   GTLDriveAboutAdditionalRoleInfoItemRoleSetsItem
//

@interface GTLDriveAboutAdditionalRoleInfoItemRoleSetsItem : GTLObject

// The supported additional roles with the primary role.
@property (nonatomic, retain) NSArray *additionalRoles;  // of NSString

// A primary permission role.
@property (nonatomic, copy) NSString *primaryRole;

@end


text:
package org.apache.druid.segment;

import com.google.common.primitives.Ints;
import org.apache.druid.collections.bitmap.ImmutableBitmap;
import org.apache.druid.collections.bitmap.MutableBitmap;
import org.apache.druid.common.utils.SerializerUtils;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.java.util.common.io.smoosh.FileSmoosher;
import org.apache.druid.segment.data.BitmapSerdeFactory;
import org.apache.druid.segment.data.ByteBufferWriter;
import org.apache.druid.segment.data.ColumnarFloatsSerializer;
import org.apache.druid.segment.data.CompressionFactory;
import org.apache.druid.segment.data.CompressionStrategy;
import org.apache.druid.segment.writeout.SegmentWriteOutMedium;

import java.io.IOException;
import java.nio.ByteOrder;
import java.nio.channels.WritableByteChannel;

/**
 * Column Serializer for float column.
 * The column is serialized in two parts, first a bitmap indicating the nullability of row values
 * and second the actual row values.
 * This class is unsafe for concurrent use from multiple threads.
 */
public class FloatColumnSerializerV2 implements GenericColumnSerializer<Object>
{
  public static FloatColumnSerializerV2 create(
      String columnName,
      SegmentWriteOutMedium segmentWriteOutMedium,
      String filenameBase,
      CompressionStrategy compression,
      BitmapSerdeFactory bitmapSerdeFactory
  )
  {
    return new FloatColumnSerializerV2(
        columnName,
        segmentWriteOutMedium,
        filenameBase,
        IndexIO.BYTE_ORDER,
        compression,
        bitmapSerdeFactory
    );
  }

  private final String columnName;
  private final SegmentWriteOutMedium segmentWriteOutMedium;
  private final String filenameBase;
  private final ByteOrder byteOrder;
  private final CompressionStrategy compression;
  private final BitmapSerdeFactory bitmapSerdeFactory;

  private ColumnarFloatsSerializer writer;
  private ByteBufferWriter<ImmutableBitmap> nullValueBitmapWriter;
  private MutableBitmap nullRowsBitmap;
  private int rowCount = 0;

  private FloatColumnSerializerV2(
      String columnName,
      SegmentWriteOutMedium segmentWriteOutMedium,
      String filenameBase,
      ByteOrder byteOrder,
      CompressionStrategy compression,
      BitmapSerdeFactory bitmapSerdeFactory
  )
  {
    this.columnName = columnName;
    this.segmentWriteOutMedium = segmentWriteOutMedium;
    this.filenameBase = filenameBase;
    this.byteOrder = byteOrder;
    this.compression = compression;
    this.bitmapSerdeFactory = bitmapSerdeFactory;
  }

  @Override
  public void open() throws IOException
  {
    writer = CompressionFactory.getFloatSerializer(
        columnName,
        segmentWriteOutMedium,
        StringUtils.format("%s.float_column", filenameBase),
        byteOrder,
        compression
    );
    writer.open();
    nullValueBitmapWriter = new ByteBufferWriter<>(
        segmentWriteOutMedium,
        bitmapSerdeFactory.getObjectStrategy()
    );
    nullValueBitmapWriter.open();
    nullRowsBitmap = bitmapSerdeFactory.getBitmapFactory().makeEmptyMutableBitmap();
  }

  @Override
  public void serialize(ColumnValueSelector<?> selector) throws IOException
  {
    if (selector.isNull()) {
      nullRowsBitmap.add(rowCount);
      writer.add(0f);
    } else {
      writer.add(selector.getFloat());
    }
    rowCount++;
  }

  @Override
  public long getSerializedSize() throws IOException
  {
    nullValueBitmapWriter.write(bitmapSerdeFactory.getBitmapFactory().makeImmutableBitmap(nullRowsBitmap));
    long bitmapSize = nullRowsBitmap.isEmpty()
                      ? 0L
                      : nullValueBitmapWriter.getSerializedSize();
    return Integer.BYTES + writer.getSerializedSize() + bitmapSize;
  }

  @Override
  public void writeTo(WritableByteChannel channel, FileSmoosher smoosher) throws IOException
  {
    SerializerUtils.writeInt(channel, Ints.checkedCast(writer.getSerializedSize()));
    writer.writeTo(channel, smoosher);
    if (!nullRowsBitmap.isEmpty()) {
      nullValueBitmapWriter.writeTo(channel, smoosher);
    }
  }
}


text:
package options

import (
	"fmt"
	"net"
	"time"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime/serializer"
	"k8s.io/apiserver/pkg/server"
	utilfeature "k8s.io/apiserver/pkg/util/feature"

	"github.com/spf13/pflag"
)

// ServerRunOptions contains the options while running a generic api server.
type ServerRunOptions struct {
	AdvertiseAddress net.IP

	CorsAllowedOriginList       []string
	ExternalHost                string
	MaxRequestsInFlight         int
	MaxMutatingRequestsInFlight int
	RequestTimeout              time.Duration
	LivezGracePeriod            time.Duration
	MinRequestTimeout           int
	ShutdownDelayDuration       time.Duration
	// We intentionally did not add a flag for this option. Users of the
	// apiserver library can wire it to a flag.
	JSONPatchMaxCopyBytes int64
	// The limit on the request body size that would be accepted and
	// decoded in a write request. 0 means no limit.
	// We intentionally did not add a flag for this option. Users of the
	// apiserver library can wire it to a flag.
	MaxRequestBodyBytes       int64
	TargetRAMMB               int
	EnablePriorityAndFairness bool
}

func NewServerRunOptions() *ServerRunOptions {
	defaults := server.NewConfig(serializer.CodecFactory{})
	return &ServerRunOptions{
		MaxRequestsInFlight:         defaults.MaxRequestsInFlight,
		MaxMutatingRequestsInFlight: defaults.MaxMutatingRequestsInFlight,
		RequestTimeout:              defaults.RequestTimeout,
		LivezGracePeriod:            defaults.LivezGracePeriod,
		MinRequestTimeout:           defaults.MinRequestTimeout,
		ShutdownDelayDuration:       defaults.ShutdownDelayDuration,
		JSONPatchMaxCopyBytes:       defaults.JSONPatchMaxCopyBytes,
		MaxRequestBodyBytes:         defaults.MaxRequestBodyBytes,
		EnablePriorityAndFairness:   true,
	}
}

// ApplyOptions applies the run options to the method receiver and returns self
func (s *ServerRunOptions) ApplyTo(c *server.Config) error {
	c.CorsAllowedOriginList = s.CorsAllowedOriginList
	c.ExternalAddress = s.ExternalHost
	c.MaxRequestsInFlight = s.MaxRequestsInFlight
	c.MaxMutatingRequestsInFlight = s.MaxMutatingRequestsInFlight
	c.LivezGracePeriod = s.LivezGracePeriod
	c.RequestTimeout = s.RequestTimeout
	c.MinRequestTimeout = s.MinRequestTimeout
	c.ShutdownDelayDuration = s.ShutdownDelayDuration
	c.JSONPatchMaxCopyBytes = s.JSONPatchMaxCopyBytes
	c.MaxRequestBodyBytes = s.MaxRequestBodyBytes
	c.PublicAddress = s.AdvertiseAddress

	return nil
}

// DefaultAdvertiseAddress sets the field AdvertiseAddress if unset. The field will be set based on the SecureServingOptions.
func (s *ServerRunOptions) DefaultAdvertiseAddress(secure *SecureServingOptions) error {
	if secure == nil {
		return nil
	}

	if s.AdvertiseAddress == nil || s.AdvertiseAddress.IsUnspecified() {
		hostIP, err := secure.DefaultExternalAddress()
		if err != nil {
			return fmt.Errorf("Unable to find suitable network address.error='%v'. "+
				"Try to set the AdvertiseAddress directly or provide a valid BindAddress to fix this.", err)
		}
		s.AdvertiseAddress = hostIP
	}

	return nil
}

// Validate checks validation of ServerRunOptions
func (s *ServerRunOptions) Validate() []error {
	errors := []error{}
	if s.TargetRAMMB < 0 {
		errors = append(errors, fmt.Errorf("--target-ram-mb can not be negative value"))
	}

	if s.LivezGracePeriod < 0 {
		errors = append(errors, fmt.Errorf("--livez-grace-period can not be a negative value"))
	}

	if s.MaxRequestsInFlight < 0 {
		errors = append(errors, fmt.Errorf("--max-requests-inflight can not be negative value"))
	}
	if s.MaxMutatingRequestsInFlight < 0 {
		errors = append(errors, fmt.Errorf("--max-mutating-requests-inflight can not be negative value"))
	}

	if s.RequestTimeout.Nanoseconds() < 0 {
		errors = append(errors, fmt.Errorf("--request-timeout can not be negative value"))
	}

	if s.MinRequestTimeout < 0 {
		errors = append(errors, fmt.Errorf("--min-request-timeout can not be negative value"))
	}

	if s.ShutdownDelayDuration < 0 {
		errors = append(errors, fmt.Errorf("--shutdown-delay-duration can not be negative value"))
	}

	if s.JSONPatchMaxCopyBytes < 0 {
		errors = append(errors, fmt.Errorf("--json-patch-max-copy-bytes can not be negative value"))
	}

	if s.MaxRequestBodyBytes < 0 {
		errors = append(errors, fmt.Errorf("--max-resource-write-bytes can not be negative value"))
	}

	return errors
}

// AddUniversalFlags adds flags for a specific APIServer to the specified FlagSet
func (s *ServerRunOptions) AddUniversalFlags(fs *pflag.FlagSet) {
	// Note: the weird ""+ in below lines seems to be the only way to get gofmt to
	// arrange these text blocks sensibly. Grrr.

	fs.IPVar(&s.AdvertiseAddress, "advertise-address", s.AdvertiseAddress, ""+
		"The IP address on which to advertise the apiserver to members of the cluster. This "+
		"address must be reachable by the rest of the cluster. If blank, the --bind-address "+
		"will be used. If --bind-address is unspecified, the host's default interface will "+
		"be used.")

	fs.StringSliceVar(&s.CorsAllowedOriginList, "cors-allowed-origins", s.CorsAllowedOriginList, ""+
		"List of allowed origins for CORS, comma separated.  An allowed origin can be a regular "+
		"expression to support subdomain matching. If this list is empty CORS will not be enabled.")

	fs.IntVar(&s.TargetRAMMB, "target-ram-mb", s.TargetRAMMB,
		"Memory limit for apiserver in MB (used to configure sizes of caches, etc.)")

	fs.StringVar(&s.ExternalHost, "external-hostname", s.ExternalHost,
		"The hostname to use when generating externalized URLs for this master (e.g. Swagger API Docs or OpenID Discovery).")

	deprecatedMasterServiceNamespace := metav1.NamespaceDefault
	fs.StringVar(&deprecatedMasterServiceNamespace, "master-service-namespace", deprecatedMasterServiceNamespace, ""+
		"DEPRECATED: the namespace from which the Kubernetes master services should be injected into pods.")

	fs.IntVar(&s.MaxRequestsInFlight, "max-requests-inflight", s.MaxRequestsInFlight, ""+
		"The maximum number of non-mutating requests in flight at a given time. When the server exceeds this, "+
		"it rejects requests. Zero for no limit.")

	fs.IntVar(&s.MaxMutatingRequestsInFlight, "max-mutating-requests-inflight", s.MaxMutatingRequestsInFlight, ""+
		"The maximum number of mutating requests in flight at a given time. When the server exceeds this, "+
		"it rejects requests. Zero for no limit.")

	fs.DurationVar(&s.RequestTimeout, "request-timeout", s.RequestTimeout, ""+
		"An optional field indicating the duration a handler must keep a request open before timing "+
		"it out. This is the default request timeout for requests but may be overridden by flags such as "+
		"--min-request-timeout for specific types of requests.")

	fs.DurationVar(&s.LivezGracePeriod, "livez-grace-period", s.LivezGracePeriod, ""+
		"This option represents the maximum amount of time it should take for apiserver to complete its startup sequence "+
		"and become live. From apiserver's start time to when this amount of time has elapsed, /livez will assume "+
		"that unfinished post-start hooks will complete successfully and therefore return true.")

	fs.IntVar(&s.MinRequestTimeout, "min-request-timeout", s.MinRequestTimeout, ""+
		"An optional field indicating the minimum number of seconds a handler must keep "+
		"a request open before timing it out. Currently only honored by the watch request "+
		"handler, which picks a randomized value above this number as the connection timeout, "+
		"to spread out load.")

	fs.BoolVar(&s.EnablePriorityAndFairness, "enable-priority-and-fairness", s.EnablePriorityAndFairness, ""+
		"If true and the APIPriorityAndFairness feature gate is enabled, replace the max-in-flight handler with an enhanced one that queues and dispatches with priority and fairness")

	fs.DurationVar(&s.ShutdownDelayDuration, "shutdown-delay-duration", s.ShutdownDelayDuration, ""+
		"Time to delay the termination. During that time the server keeps serving requests normally and /healthz "+
		"returns success, but /readyz immediately returns failure. Graceful termination starts after this delay "+
		"has elapsed. This can be used to allow load balancer to stop sending traffic to this server.")

	utilfeature.DefaultMutableFeatureGate.AddFlag(fs)
}


text:
"""
All possible errors.
"""

class AssimpError(BaseException):
    """
    If an internal error occurs.
    """
    pass


text:
import pytz

import logging
import requests
from dateutil.parser import parse
from datetime import datetime, timedelta

from website.app import init_app
from scripts.analytics.base import SummaryAnalytics

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

LOG_THRESHOLD = 11

class PreprintSummary(SummaryAnalytics):

    @property
    def collection_name(self):
        return 'preprint_summary'

    def get_events(self, date):
        super(PreprintSummary, self).get_events(date)
        from osf.models import PreprintProvider

        # Convert to a datetime at midnight for queries and the timestamp
        timestamp_datetime = datetime(date.year, date.month, date.day).replace(tzinfo=pytz.UTC)
        query_datetime = timestamp_datetime + timedelta(1)

        elastic_query = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "match": {
                                "type": "preprint"
                            }
                        },
                        {
                            "match": {
                                "sources": None
                            }
                        }
                    ],
                    'filter': [
                        {
                            "range": {
                                "date": {
                                    "lte": "{}||/d".format(query_datetime.strftime('%Y-%m-%d'))
                                }
                            }
                        }
                    ]
                }
            }
        }

        counts = []
        for preprint_provider in PreprintProvider.objects.all():
            name = preprint_provider.name if preprint_provider.name != 'Open Science Framework' else 'OSF'
            elastic_query['query']['bool']['must'][1]['match']['sources'] = name
            resp = requests.post('https://share.osf.io/api/v2/search/creativeworks/_search', json=elastic_query).json()
            counts.append({
                'keen': {
                    'timestamp': timestamp_datetime.isoformat()
                },
                'provider': {
                    'name': preprint_provider.name,
                    'total': resp['hits']['total'],
                },
            })

        return counts

def get_class():
    return PreprintSummary

if __name__ == '__main__':
    init_app()

    preprint_summary = PreprintSummary()
    args = preprint_summary.parse_args()
    yesterday = args.yesterday
    if yesterday:
        date = (datetime.today() - timedelta(1)).date()
    else:
        date = parse(args.date).date() if args.date else None
    events = preprint_summary.get_events(date)
    preprint_summary.send_events(events)


text:
var baseValues = require('./_baseValues'),
    keys = require('./keys');

/**
 * Creates an array of the own enumerable string keyed property values of `object`.
 *
 * **Note:** Non-object values are coerced to objects.
 *
 * @static
 * @since 0.1.0
 * @memberOf _
 * @category Object
 * @param {Object} object The object to query.
 * @returns {Array} Returns the array of property values.
 * @example
 *
 * function Foo() {
 *   this.a = 1;
 *   this.b = 2;
 * }
 *
 * Foo.prototype.c = 3;
 *
 * _.values(new Foo);
 * // => [1, 2] (iteration order is not guaranteed)
 *
 * _.values('hi');
 * // => ['h', 'i']
 */
function values(object) {
    return object == null ? [] : baseValues(object, keys(object));
}

module.exports = values;


text:
module AthenaHealth
  class UserMedicationCollection < BaseModel
    attribute :lastupdated, String
    attribute :medications, Array[UserMedication]
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<sect1 id="learning.quickstart.create-project">
    <title>プロジェクトを作成</title>

    <para>
        プロジェクトを作成するには、まず、Zend Frameworkをダウンロードして、解凍しなければいけません。
    </para>

    <sect2 id="learning.quickstart.create-project.install-zf">
        <title>Zend Framework をインストール</title>

        <para>
            全部揃った <acronym>PHP</acronym> スタックと一緒に Zend Framework
            を手に入れる最も簡単な方法は、<ulink
             url="http://www.zend.co.jp/product/zendserver.html">Zend Server</ulink>
            をインストールすることです。Zend Server には、
            多くの Linux ディストリビューションと互換性のある一般的なインストール・パッケージだけでなく、
            Mac OSX、Windows、Fedora Core および Ubuntu 用のネイティブのインストーラーがあります。
        </para>

        <para>
            Zend Server をインストールし終わると、Mac OSX および Linux の場合は
            <filename>/usr/local/zend/share/ZendFramework</filename> 配下に、
            Windows の場合は
            <filename>C:\Program Files\Zend\ZendServer\share\ZendFramework</filename>
            配下にフレームワークのファイルが見つかるでしょう。
            <constant>include_path</constant>は、Zend Frameworkを含むように構成済みです。
        </para>

        <para>
            あるいは、<ulink
             url="http://framework.zend.com/download/latest">Zend Framework の最新版</ulink>
            をダウンロードして内容を解凍することができます。
            make a note of where you have done so.
        </para>

        <para>
            <filename>php.ini</filename> の <constant>include_path</constant> 設定に
            アーカイブの<filename>library/</filename>サブディレクトリへのパスを任意に追加できます。
        </para>

        <para>
            これで終わりです。これで Zend Framework がインストールされ、使えるようになりました。
        </para>
    </sect2>

    <sect2 id="learning.quickstart.create-project.create-project">
        <title>プロジェクトを作成</title>

        <note>
            <title>zf コマンドラインツール</title>

            <para>
                Zend Framework インストール先には <filename>bin/</filename> サブディレクトリがあり、
                UNIX ベースおよび Windows ベースのユーザーのために、それぞれスクリプト
                <filename>zf.sh</filename> および <filename>zf.bat</filename> を含みます。
                このスクリプトに絶対パスを書きとめてください。
            </para>

            <para>
                <command>zf</command> コマンドとの関係がわかっている場所ではどこでも
                スクリプトへの絶対パスに置き換えてください。Unix のようなシステムでは、シェルのエイリアス機能を使いたいかもしれません。
                <command>alias zf.sh=path/to/ZendFramework/bin/zf.sh</command>
            </para>

            <para>
                <command>zf</command> コマンドラインツール設定中に問題があった場合は、
                <link linkend="zend.tool.framework.clitool">マニュアル</link> を参照してください。
            </para>
        </note>

        <para>
            ターミナルを開きます。(Windows では<command>スタート -> ファイル名を指定して実行</command>
            、それから <command>cmd</command> を使用します)
            プロジェクトを開始したいディレクトリに進みます。それから、適切なスクリプトへのパスを使用して、下記のいずれかを実行します。
        </para>

        <programlisting language="shell"><![CDATA[
% zf create project quickstart
]]></programlisting>

        <para>
            このコマンドを実行すると、基本的なサイト構造が作成されます。そこには基になるコントローラやビューが含まれます。
            ツリーは下記のように見えます。
        </para>

        <programlisting language="text"><![CDATA[
quickstart
|-- application
|   |-- Bootstrap.php
|   |-- configs
|   |   `-- application.ini
|   |-- controllers
|   |   |-- ErrorController.php
|   |   `-- IndexController.php
|   |-- models
|   `-- views
|       |-- helpers
|       `-- scripts
|           |-- error
|           |   `-- error.phtml
|           `-- index
|               `-- index.phtml
|-- library
|-- public
|   |-- .htaccess
|   `-- index.php
`-- tests
    |-- application
    |   `-- bootstrap.php
    |-- library
    |   `-- bootstrap.php
    `-- phpunit.xml
]]></programlisting>

        <para>
            もしこの時点で Zend Framework を <constant>include_path</constant>
            に追加していないなら、<filename>library/</filename> ディレクトリにコピーするか、または symlink することを勧めます。
            いずれにせよ、Zend Framework インストール先の <filename>library/Zend/</filename>
            ディレクトリをプロジェクトの <filename>library/</filename> ディレクトリに再帰的にコピーするか、
            または symlink することが必要になるでしょう。Unix のようなシステムでは、それは下記のいずれかのように見えます。
        </para>

        <programlisting language="shell"><![CDATA[
# Symlink:
% cd library; ln -s path/to/ZendFramework/library/Zend .

# Copy:
% cd library; cp -r path/to/ZendFramework/library/Zend .
]]></programlisting>

        <para>
            Windows システムでは、これをエクスプローラから行なうのが最も簡単かもしれません。
        </para>

        <para>
            Now that the project is created, the main artifacts to begin understanding are the
            bootstrap, configuration, action controllers, and views.
        </para>
    </sect2>

    <sect2 id="learning.quickstart.create-project.bootstrap">
        <title>The Bootstrap</title>

        <para>
            Your <classname>Bootstrap</classname> class defines what resources and components to
            initialize. By default, Zend Framework's <link linkend="zend.controller.front">Front
                Controller</link> is initialized, and it uses the
            <filename>application/controllers/</filename> as the default directory in which to look
            for action controllers (more on that later). そのクラスは下記のように見えます。
        </para>

        <programlisting language="php"><![CDATA[
// application/Bootstrap.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
}
]]></programlisting>

        <para>
            As you can see, not much is necessary to begin with.
        </para>
    </sect2>

    <sect2 id="learning.quickstart.create-project.configuration">
        <title>Configuration</title>

        <para>
            While Zend Framework is itself configurationless, you often need to configure your
            application. The default configuration is placed in
            <filename>application/configs/application.ini</filename>, and contains some basic
            directives for setting your <acronym>PHP</acronym> environment (for instance, turning
            error reporting on and off), indicating the path to your bootstrap class (as well as its
            class name), and the path to your action controllers. それは下記のようになります。
        </para>

        <programlisting language="ini"><![CDATA[
; application/configs/application.ini

[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0

[staging : production]

[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
]]></programlisting>

        <para>
            Several things about this file should be noted. First, when using
            <acronym>INI</acronym>-style configuration, you can reference constants directly and
            expand them; <constant>APPLICATION_PATH</constant> is actually a constant. Additionally
            note that there are several sections defined: production, staging, testing, and
            development. The latter three inherit settings from the "production" environment. This
            is a useful way to organize configuration to ensure that appropriate settings are
            available in each stage of application development.
        </para>
    </sect2>

    <sect2 id="learning.quickstart.create-project.action-controllers">
        <title>Action Controllers</title>

        <para>
            Your application's <emphasis>action controllers</emphasis> contain your application
            workflow, and do the work of mapping your requests to the appropriate models and views.
        </para>

        <para>
            An action controller should have one or more methods ending in "Action"; these methods
            may then be requested via the web. By default, Zend Framework URLs follow the schema
            <constant>/controller/action</constant>, where "controller" maps to the action
            controller name (minus the "Controller" suffix) and "action" maps to an action method
            (minus the "Action" suffix).
        </para>

        <para>
            Typically, you always need an <classname>IndexController</classname>, which is a
            fallback controller and which also serves the home page of the site, and an
            <classname>ErrorController</classname>, which is used to indicate things such as
            <acronym>HTTP</acronym> 404 errors (controller or action not found) and
            <acronym>HTTP</acronym> 500 errors (application errors).
        </para>

        <para>
            デフォルトの <classname>IndexController</classname> は下記の通りです。
        </para>

        <programlisting language="php"><![CDATA[
// application/controllers/IndexController.php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }
}
]]></programlisting>

        <para>
            そして、デフォルトの <classname>ErrorController</classname> は下記の通りです。
        </para>

        <programlisting language="php"><![CDATA[
// application/controllers/ErrorController.php

class ErrorController extends Zend_Controller_Action
{

    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;
        }

        $this->view->exception = $errors->exception;
        $this->view->request   = $errors->request;
    }
}
]]></programlisting>

        <para>
            You'll note that (1) the <classname>IndexController</classname> contains no real code,
            and (2) the <classname>ErrorController</classname> makes reference to a "view" property.
            That leads nicely into our next subject.
        </para>
    </sect2>

    <sect2 id="learning.quickstart.create-project.views">
        <title>Views</title>

        <para>
            Views in Zend Framework are written in plain old <acronym>PHP</acronym>. View scripts
            are placed in <filename>application/views/scripts/</filename>, where they are further
            categorized using the controller names. In our case, we have an
            <classname>IndexController</classname> and an <classname>ErrorController</classname>,
            and thus we have corresponding <filename>index/</filename> and
            <filename>error/</filename> subdirectories within our view scripts directory. Within
            these subdirectories, you will then find and create view scripts that correspond to each
            controller action exposed; in the default case, we thus have the view scripts
            <filename>index/index.phtml</filename> and <filename>error/error.phtml</filename>.
        </para>

        <para>
            View scripts may contain any markup you want, and use the <emphasis><?php</emphasis>
            opening tag and <emphasis>?></emphasis> closing tag to insert <acronym>PHP</acronym>
            directives.
        </para>

        <para>
            The following is what we install by default for the
            <filename>index/index.phtml</filename> view script:
        </para>

        <programlisting language="php"><![CDATA[

Welcome to the Zend Framework!

This is your project's main page

            Helpful Links:

            Zend Framework Website |
            Zend Framework
                Manual

]]></programlisting>

        <para>
            The <filename>error/error.phtml</filename> view script is slightly more interesting as
            it uses some <acronym>PHP</acronym> conditionals:
        </para>

        <programlisting language="php"><![CDATA[

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN";
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Zend Framework Default Application</title>

An error occurred

<?php echo $this->message ?>

  <?php if ('development' == $this->env): ?>

Exception information:

      Message: <?php echo $this->exception->getMessage() ?>

Stack trace:

<?php echo $this->exception->getTraceAsString() ?>

Request Parameters:

<?php echo var_export($this->request->getParams(), 1) ?>

  <?php endif ?>

]]></programlisting>
    </sect2>

    <sect2 id="learning.quickstart.create-project.vhost">
        <title>バーチャル・ホストを作成</title>

        <para>
            このクイックスタートの必要上、<ulink url="http://httpd.apache.org/">Apache Web サーバー</ulink>
            を使用すると仮定しています。Zend Framework は、他の Web サーバーでも申し分なく動作します。
            それには、Microsoft Internet Information Server、lighttpd、nginx などを含みます。
            しかし、大抵の開発者は少なくとも Apache をよく知っていなければなりません。
            そして、それはZend Framework のディレクトリ構造とリライト能力への簡単な導入を提示します。
        </para>

        <para>
            vhost を作成するには、<filename>httpd.conf</filename> ファイルの位置を知る必要があります。
            その場所には他の構成ファイルが格納されている可能性があります。いくつかの一般的な場所はこうです。
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <filename>/etc/httpd/httpd.conf</filename> (Fedora や RHEL など)
                </para>
            </listitem>

            <listitem>
                <para>
                    <filename>/etc/apache2/httpd.conf</filename> (Debian や Ubuntu など)
                </para>
            </listitem>

            <listitem>
                <para>
                    <filename>/usr/local/zend/etc/httpd.conf</filename> (Linux 版 Zend Server)
                </para>
            </listitem>

            <listitem>
                <para>
                    <filename>C:\Program Files\Zend\Apache2\conf</filename> (Windows 版 Zend Server)
                </para>
            </listitem>
        </itemizedlist>

        <para>
            <filename>httpd.conf</filename> (一部のシステムでは <filename>httpd-vhosts.conf</filename>)
            内で行なうべきことが2つあります。
            1つ目は、<varname>NameVirtualHost</varname> が定義されていることを確実にすることです。
            一般的にはそれを "*:80" という値に設定します。
            2つ目は、バーチャル・ホストを定義することです。
        </para>

        <programlisting language="apache"><![CDATA[
<VirtualHost *:80>
    ServerName quickstart.local
    DocumentRoot /path/to/quickstart/public

    SetEnv APPLICATION_ENV "development"

    <Directory /path/to/quickstart/public>
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>
]]></programlisting>

        <para>
            There are several things to note. First, note that the <varname>DocumentRoot</varname>
            setting specifies the <filename>public</filename> subdirectory of our project; this
            means that only files under that directory can ever be served directly by the server.
            Second, note the <varname>AllowOverride</varname>, <varname>Order</varname>, and
            <varname>Allow</varname> directives; these are to allow us to use
            <filename>htacess</filename> files within our project. During development, this is a
            good practice, as it prevents the need to constantly restart the web server as you make
            changes to your site directives; however, in production, you should likely push the
            content of your <filename>htaccess</filename> file into your server configuration and
            disable this. Third, note the <varname>SetEnv</varname> directive. What we are doing
            here is setting an environment variable for your virtual host; this variable will be
            picked up in the <filename>index.php</filename> and used to set the
            <constant>APPLICATION_ENV</constant> constant for our Zend Framework application. In
            production, you can omit this directive (in which case it will default to the value
            "production") or set it explicitly to "production".
        </para>

        <para>
            Finally, you will need to add an entry in your <filename>hosts</filename> file
            corresponding to the value you place in your <varname>ServerName</varname> directive. On
            *nix-like systems, this is usually <filename>/etc/hosts</filename>; on Windows, you'll
            typically find it in <filename>C:\WINDOWS\system32\drivers\etc</filename>. Regardless of
            the system, the entry will look like the following:
        </para>

        <programlisting language="text"><![CDATA[
127.0.0.1 quickstart.local
]]></programlisting>

        <para>
            Start your webserver (or restart it), and you should be ready to go.
        </para>
    </sect2>

    <sect2 id="learning.quickstart.create-project.checkpoint">
        <title>Checkpoint</title>

        <para>
            At this point, you should be able to fire up your initial Zend Framework application.
            Point your browser to the server name you configured in the previous section; you should
            be able to see a welcome page at this point.
        </para>
    </sect2>
</sect1>


text:
require 'rspec'
# require 'fakefs'
require 'fakefs/spec_helpers'
require 'gasciiart'

RSpec.configure do |config|
  config.include FakeFS::SpecHelpers

  config.color_enabled = true
  config.formatter     = 'documentation'
end


text:
package org.axonframework.eventhandling.replay;

import org.axonframework.domain.DomainEventMessage;
import org.axonframework.domain.EventMessage;
import org.axonframework.eventhandling.Cluster;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;

/**
 * IncomingMessageHandler implementation that simply discards all messages dispatch during a replay process. This
 * handler is typically useful when not expecting to perform a replay while the cluster is actively listening to events
 * on a command bus, for example when performing an offline replay.
 *
 * @author Allard Buijze
 * @since 2.0
 */
public class DiscardingIncomingMessageHandler implements IncomingMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(DiscardingIncomingMessageHandler.class);

    @Override
    public void prepareForReplay(Cluster destination) {
    }

    @Override
    public List<EventMessage> onIncomingMessages(Cluster destination, EventMessage... messages) {
        if (messages != null && messages.length > 0 && logger.isInfoEnabled()) {
            final StringBuilder msg = new StringBuilder("Discarding ")
                    .append(messages.length)
                    .append(" messages on cluster [")
                    .append(destination.getName())
                    .append("] during an event replay: [");
            boolean firstClass = true;
            for (EventMessage message : messages) {
                if (!firstClass) {
                    msg.append(", ");
                }
                msg.append(message.getPayloadType().getSimpleName());
                firstClass = false;
            }
            msg.append("]");
            logger.info(msg.toString());
        }
        return messages == null ? null : Arrays.asList(messages);
    }

    @Override
    public List<EventMessage> releaseMessage(Cluster destination, DomainEventMessage message) {
        // do nothing
        return null;
    }

    @Override
    public void processBacklog(Cluster destination) {
        // do nothing
    }

    @Override
    public void onReplayFailed(Cluster destination, Throwable cause) {
        // do nothing
    }
}


text:
package com.taobao.tddl.common.utils.convertor;

import com.taobao.tddl.common.exception.TddlRuntimeException;
import com.taobao.tddl.common.exception.code.ErrorCode;

public class ConvertorException extends TddlRuntimeException {

    private static final long serialVersionUID = 3270080439323296921L;

    public ConvertorException(String... params){
        super(ErrorCode.ERR_CONVERTOR, params);
    }

    public ConvertorException(Throwable cause, String... params){
        super(ErrorCode.ERR_CONVERTOR, cause, params);
    }

}


text:
Parameter Server
================

This document walks through how to implement simple synchronous and asynchronous
parameter servers using actors. To run the application, first install some
dependencies.

.. code-block:: bash

  pip install tensorflow

You can view the `code for this example`_.

.. _`code for this example`: https://github.com/ray-project/ray/tree/master/examples/parameter_server

The examples can be run as follows.

.. code-block:: bash

  # Run the asynchronous parameter server.
  python ray/examples/parameter_server/async_parameter_server.py --num-workers=4

  # Run the synchronous parameter server.
  python ray/examples/parameter_server/sync_parameter_server.py --num-workers=4

Note that this examples uses distributed actor handles, which are still
considered experimental.

Asynchronous Parameter Server
-----------------------------

The asynchronous parameter server itself is implemented as an actor, which
exposes the methods ``push`` and ``pull``.

.. code-block:: python

  @ray.remote
  class ParameterServer(object):
      def __init__(self, keys, values):
          values = [value.copy() for value in values]
          self.weights = dict(zip(keys, values))

      def push(self, keys, values):
          for key, value in zip(keys, values):
              self.weights[key] += value

      def pull(self, keys):
          return [self.weights[key] for key in keys]

We then define a worker task, which take a parameter server as an argument and
submits tasks to it. The structure of the code looks as follows.

.. code-block:: python

  @ray.remote
  def worker_task(ps):
      while True:
          # Get the latest weights from the parameter server.
          weights = ray.get(ps.pull.remote(keys))

          # Compute an update.
          ...

          # Push the update to the parameter server.
          ps.push.remote(keys, update)

Then we can create a parameter server and initiate training as follows.

.. code-block:: python

  ps = ParameterServer.remote(keys, initial_values)
  worker_tasks = [worker_task.remote(ps) for _ in range(4)]

Synchronous Parameter Server
----------------------------

The parameter server is implemented as an actor, which exposes the
methods ``apply_gradients`` and ``get_weights``. A constant linear scaling
rule is applied by scaling the learning rate by the number of workers.

.. code-block:: python

  @ray.remote
  class ParameterServer(object):
      def __init__(self, learning_rate):
          self.net = model.SimpleCNN(learning_rate=learning_rate)

      def apply_gradients(self, *gradients):
          self.net.apply_gradients(np.mean(gradients, axis=0))
          return self.net.variables.get_flat()

      def get_weights(self):
          return self.net.variables.get_flat()

Workers are actors which expose the method ``compute_gradients``.

.. code-block:: python

  @ray.remote
  class Worker(object):
      def __init__(self, worker_index, batch_size=50):
          self.worker_index = worker_index
          self.batch_size = batch_size
          self.mnist = input_data.read_data_sets("MNIST_data", one_hot=True,
                                                 seed=worker_index)
          self.net = model.SimpleCNN()

      def compute_gradients(self, weights):
          self.net.variables.set_flat(weights)
          xs, ys = self.mnist.train.next_batch(self.batch_size)
          return self.net.compute_gradients(xs, ys)

Training alternates between computing the gradients given the current weights
from the parameter server and updating the parameter server's weights with the
resulting gradients.

.. code-block:: python

  while True:
      gradients = [worker.compute_gradients.remote(current_weights)
                   for worker in workers]
      current_weights = ps.apply_gradients.remote(*gradients)

Both of these examples implement the parameter server using a single actor,
however they can be easily extended to **split the parameters across multiple
actors**.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.apache.poi.ss.formula.constant (POI API Documentation)
</TITLE>

<META NAME="date" CONTENT="2012-11-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.poi.ss.formula.constant

Classes

ConstantValueParser

ErrorConstant


text:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class Main extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage stage) {
    Group group = new Group();
    Scene scene = new Scene(group, 300, 400);
    stage.setScene(scene);
    stage.setTitle("Vaheetapp 2 - Külalisteraamat");

    GridPane grid = new GridPane();
    grid.setPadding(new Insets(5, 5, 5, 5));

    grid.setVgap(5);
    grid.setHgap(5);

    scene.setRoot(grid);

    TextField name = new TextField();
    name.setPromptText("Sisesta oma nimi");
    name.setPrefColumnCount(10);
    GridPane.setConstraints(name, 0, 0);
    grid.getChildren().add(name);

    TextField comments = new TextField();
    comments.setPrefColumnCount(15);
    comments.setPromptText("Lisa kommentaar");
    GridPane.setConstraints(comments, 0, 1);
    grid.getChildren().add(comments);

    Button submit = new Button("Sisesta");
    GridPane.setConstraints(submit, 1, 0);
    grid.getChildren().add(submit);

    Button clear = new Button("Tühjenda");
    GridPane.setConstraints(clear, 1, 1);
    grid.getChildren().add(clear);

    Label label = new Label();
    GridPane.setConstraints(label, 0, 2);
    GridPane.setColumnSpan(label, 2);
    grid.getChildren().add(label);

    submit.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent e) {
        if ((comments.getText() != null && !comments.getText().isEmpty())) {
          label.setText(label.getText() + "\n" + name.getText() + ": " + comments.getText());
        }
      }
    });

    clear.setOnAction(new EventHandler<ActionEvent>() {
      @Override
      public void handle(ActionEvent e) {
        name.clear();
        comments.clear();
      }
    });

    stage.show();
  }
}


text:
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Copyright (c) 2000 World Wide Web Consortium,
 * (Massachusetts Institute of Technology, Institut National de
 * Recherche en Informatique et en Automatique, Keio University). All
 * Rights Reserved. This program is distributed under the W3C's Software
 * Intellectual Property License. This program is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.
 * See W3C License http://www.w3.org/Consortium/Legal/ for more details.
 */

package org.w3c.dom.css;

import org.w3c.dom.Element;
import org.w3c.dom.views.AbstractView;

/**
 *  This interface represents a CSS view. The getComputedStyle
 * method provides a read only access to the computed values of an element.
 *
 The expectation is that an instance of the ViewCSS
 * interface can be obtained by using binding-specific casting methods on an
 * instance of the AbstractView interface.
 *
 Since a computed style is related to an Element node, if
 * this element is removed from the document, the associated
 * CSSStyleDeclaration and CSSValue related to
 * this declaration are no longer valid.
 *
See also the Document Object Model (DOM) Level 2 Style Specification.
 * @since DOM Level 2
 */
public interface ViewCSS extends AbstractView {
    /**
     *  This method is used to get the computed style as it is defined in [CSS2].
     * @param elt  The element whose style is to be computed. This parameter
     *   cannot be null.
     * @param pseudoElt  The pseudo-element or null if none.
     * @return  The computed style. The CSSStyleDeclaration is
     *   read-only and contains only absolute values.
     */
    public CSSStyleDeclaration getComputedStyle(Element elt,
                                                String pseudoElt);

}


text:
//
//  AudioPlayer.m
//  player
//
//  Created by 李玉峰 on 2018/4/13.
//  Copyright © 2018年 cai. All rights reserved.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>

NSString * AudioPlayerStopNotification = @"AudioPlayerStopNotification";

@interface AudioPlayer()

@property (nonatomic, strong)NSURL * mediaUrl;

@property (nonatomic, assign)NSTimeInterval currentTime;
@property (nonatomic, assign)NSTimeInterval loadedTime;
@property (nonatomic, assign)NSTimeInterval totalTime;

@property (nonatomic, strong)AVURLAsset * urlAsset;
@property (nonatomic, strong)AVPlayerItem * playerItem;
@property (nonatomic, strong)AVPlayer * player;
@property (nonatomic, strong) id timeObserve;

@end

@implementation AudioPlayer

+ (instancetype)sharePlayer{
    static AudioPlayer * share;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        share = [[AudioPlayer alloc]init];
    });
    return share;
}

- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (void)playURL:(NSURL *)url{
    [self resetPlayer];
    self.mediaUrl = url;
    [self configPlayer];
}

- (void)pause{
    if (self.state == AudioPlayerStatePlaying) {
        self.state = AudioPlayerStatePause;
    }
    [self.player pause];
}
- (void)play{
    if (self.state == AudioPlayerStatePause) {
        self.state = AudioPlayerStatePlaying;
    }
    [self.player play];
}

- (void)configPlayer{
    self.urlAsset = [AVURLAsset assetWithURL:self.mediaUrl];
    self.playerItem = [AVPlayerItem playerItemWithAsset:self.urlAsset];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    [self createTimer];
    [self configureVolume];
    [self addNotifications];
    if ([self.mediaUrl.scheme isEqualToString:@"file"]) {
        self.state = AudioPlayerStatePlaying;
    } else {
        self.state = AudioPlayerStateBuffering;
    }
    [self play];
}

- (void)createTimer {
    __weak typeof(self) weakSelf = self;
    self.timeObserve = [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, 1) queue:nil usingBlock:^(CMTime time){
        AVPlayerItem *currentItem = weakSelf.playerItem;
        NSArray *loadedRanges = currentItem.seekableTimeRanges;
        if (loadedRanges.count > 0 && currentItem.duration.timescale != 0) {
            NSInteger currentTime = (NSInteger)CMTimeGetSeconds([currentItem currentTime]);
            CGFloat totalTime     = (CGFloat)currentItem.duration.value / currentItem.duration.timescale;
            __strong typeof(weakSelf)strongSelf = weakSelf;
            strongSelf.currentTime = currentTime;
            if (strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(player:updateCurrentTime:totalTime:)]) {
                [strongSelf.delegate player:strongSelf updateCurrentTime:currentTime totalTime:totalTime];
            }
        }
    }];
}

/**
 *  获取系统音量
 */
- (void)configureVolume {
    NSError *setCategoryError = nil;
    BOOL success = [[AVAudioSession sharedInstance]
                    setCategory: AVAudioSessionCategoryPlayback
                    error: &setCategoryError];

    if (!success) { /* handle the error in setCategoryError */ }
}

- (void)resetPlayer{
    if (self.timeObserve) {
        [self.player removeTimeObserver:self.timeObserve];
        self.timeObserve = nil;
    }
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.player pause];
    self.player = nil;
    self.currentTime = 0;
    self.loadedTime = 0;
    self.totalTime = 0;
}

- (void)addNotifications {
    // app退到后台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:NSExtensionHostWillResignActiveNotification object:nil];
    // app进入前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterPlayground) name:NSExtensionHostDidBecomeActiveNotification object:nil];
    // 监听耳机插入和拔掉通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];
}

- (void)setPlayerItem:(AVPlayerItem *)playerItem {
    if (_playerItem == playerItem) {return;}
    if (_playerItem) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
        [_playerItem removeObserver:self forKeyPath:@"status"];
        [_playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [_playerItem removeObserver:self forKeyPath:@"playbackBufferEmpty"];
        [_playerItem removeObserver:self forKeyPath:@"playbackLikelyToKeepUp"];
    }
    _playerItem = playerItem;
    if (playerItem) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];
        [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
        [playerItem addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil];
        [playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
    }
}

/**
 *  设置播放的状态
 *
 *  @param state ZFPlayerState
 */
- (void)setState:(AudioPlayerState)state {
    _state = state;
    NSLog(@"%ld",state);
    if (self.delegate && [self.delegate respondsToSelector:@selector(player:didChangeState:)]) {
        [self.delegate player:self didChangeState:state];
    }
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.player.currentItem) {
        if ([keyPath isEqualToString:@"status"]) {

            if (self.player.currentItem.status == AVPlayerItemStatusReadyToPlay) {
                self.totalTime = CMTimeGetSeconds(self.player.currentItem.duration);
                self.state = AudioPlayerStatePlaying;
            } else if (self.player.currentItem.status == AVPlayerItemStatusFailed) {
                self.state = AudioPlayerStateFailed;
            }
        } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {

            // 计算缓冲进度
            NSTimeInterval timeInterval = [self availableDuration];
            CMTime duration             = self.playerItem.duration;
            CGFloat totalDuration       = CMTimeGetSeconds(duration);
            self.loadedTime = timeInterval;
            if (self.delegate && [self.delegate respondsToSelector:@selector(player:updateLoadedTime:totalTime:)]) {
                [self.delegate player:self updateLoadedTime:timeInterval totalTime:totalDuration];
            }
        } else if ([keyPath isEqualToString:@"playbackBufferEmpty"]) {
            if (self.playerItem.playbackBufferEmpty) {
                self.state = AudioPlayerStateBuffering;
            }
        } else if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
            if (self.playerItem.playbackLikelyToKeepUp && self.state == AudioPlayerStateBuffering){
                self.state = AudioPlayerStatePlaying;
            }
        }
    }
}

#pragma mark - 计算缓冲进度

/**
 *  计算缓冲进度
 *
 *  @return 缓冲进度
 */
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    CMTimeRange timeRange     = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds        = CMTimeGetSeconds(timeRange.start);
    float durationSeconds     = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result     = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

/**
 *  播放完了
 *
 *  @param notification 通知
 */
- (void)moviePlayDidEnd:(NSNotification *)notification {
    if (notification.object == self.playerItem) {
        self.state = AudioPlayerStateStopped;
        [[NSNotificationCenter defaultCenter]postNotificationName:AudioPlayerStopNotification object:nil];
    }
}

/**
 *  应用退到后台
 */
- (void)appDidEnterBackground {

}

/**
 *  应用进入前台
 */
- (void)appDidEnterPlayground {

}

/**
 *  耳机插入、拔出事件
 */
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification {
    NSDictionary *interuptionDict = notification.userInfo;

    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];

    switch (routeChangeReason) {

        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            // 耳机插入
            break;

        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable: {
            // 耳机拔掉
            [self play];
        }
            break;

        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}

@end


text:
package person.daizhongde.virtue.assemble.hql;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import person.daizhongde.virtue.configutils.ConfigDocument_SQL;

public class HQLAssembleR {

	private static Logger log = LogManager.getLogger(HQLAssembleR.class.getName() );

//	/** value in the config file
There only used when refer to Nest sql  **/
//	private AbstractConstant absc;
	/** virtue sql document  **/
	private ConfigDocument_SQL sqlDoc;

	/** parameter pass in by constructor,usually config in *.sql file **/
	private String selectHQL;
	/** parameter pass in by constructor
eg:{C_MNAME: 'system manage'} **/
	private Map condition;
	/** parameter pass in by constructor
eg:{C_MNAME: equal} **/
	private Map operator;//= != > >= < <=  like s%  like %s   like %s%
	/** parameter pass in by constructor , type: int value
<String, Integer>
eg:{C_MNAME: 12} **/
	private Map columnTypes2;
	/** parameter pass in by constructor, front to column name
eg:{c_mname: 'C_MNAME'} **/
	private Map front2back;

	private String whereBackHQL = "";// n_mid>1 and n_mlevel>1 and c_mname not like '%管理%'
	/**  target result sql **/
	private String HQL;

	/**Target HQL parameters map  **/
	private Map map = new HashMap();
	/** Object[] parameter invoke in dao can use, also reservered for extra use  **/
	private Object[] values = new Object[0];

	public HQLAssembleR(ConfigDocument_SQL  sqlDoc, String selectHQL, Map condition, Map operator, Map columnTypes2,  Map front2back ){
		this.sqlDoc = sqlDoc;
		this.selectHQL = selectHQL;
		this.condition = condition;
		this.operator = operator;
		this.columnTypes2 = columnTypes2;
		this.front2back = front2back;

		readInitialize();
	}

	public void readInitialize(){
		boolean withAlias = selectHQL.indexOf(" t1 ")==-1?false:true;

		this.whereBackHQL = HQLUtil.getWhereBackHQL( this.condition, this.operator,
				this.front2back, this.columnTypes2,
				this.map, withAlias, sqlDoc
			);

		this.values = this.map.values().toArray();

		if( this.condition == null || this.condition.size() == 0 ){
			this.HQL = selectHQL;
		}else{
			if( selectHQL.indexOf(" where ") != -1){
				this.HQL = selectHQL + " and " + this.whereBackHQL;
			}else{
				this.HQL = selectHQL + " where " + this.whereBackHQL;
			}
		}
		log.debug( this.HQL );
	}

	public ConfigDocument_SQL getSqlDoc() {
		return sqlDoc;
	}

	public void setSqlDoc(ConfigDocument_SQL sqlDoc) {
		this.sqlDoc = sqlDoc;
	}

	public String getSelectHQL() {
		return selectHQL;
	}

	public void setSelectHQL(String selectHQL) {
		this.selectHQL = selectHQL;
	}

	public Map getCondition() {
		return condition;
	}

	public void setCondition(Map condition) {
		this.condition = condition;
	}

	public Map getOperator() {
		return operator;
	}

	public void setOperator(Map operator) {
		this.operator = operator;
	}

	public Map getColumnTypes2() {
		return columnTypes2;
	}

	public void setColumnTypes2(Map columnTypes2) {
		this.columnTypes2 = columnTypes2;
	}

	public Map getFront2back() {
		return front2back;
	}

	public void setFront2back(Map front2back) {
		this.front2back = front2back;
	}

	public String getWhereBackHQL() {
		return whereBackHQL;
	}

	public void setWhereBackHQL(String whereBackHQL) {
		this.whereBackHQL = whereBackHQL;
	}

	public String getHQL() {
		return HQL;
	}

	public void setHQL(String sQL) {
		HQL = sQL;
	}

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	public Object[] getValues() {
		return values;
	}

	public void setValues(Object[] values) {
		this.values = values;
	}

//	public static void main(String args[]){
//		String jdata = "{act:\"read\",	operator : {nmid : 1,cmname : 11,nmlevel : 13,cmtarget : 13}, condition:{nmid:1, cmname:\"模块名称\", nmlevel:[1,2,3], cmtarget:[\"R\",\"B\"]}}";
//		JSONObject jsonObject = JSONObject.fromObject(jdata);
//		AbstractConstant absConstant = new AuthorityModule();
//		HQLAssembleR sqlA = new HQLAssembleR( jsonObject, absConstant );
//		String WhereBackHQL = sqlA.getWhereBackHQL();
//		Object[] values= sqlA.getValues();
//		System.out.println("WhereBackHQL:"+WhereBackHQL);
//	}
}


text:
/**
 * Óö¯»¼ä½ÓʵÏÖһЩAPI 11+ÖеÄView API
 */
package bos.consoar.ninebynine.support;

import android.view.View;

import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;

public class GBTools {
	public static void GBsetTranslation(View view, int x, int y) {
		ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationX", x
				- view.getLeft());
		anim.setDuration(0);
		ObjectAnimator anim2 = ObjectAnimator.ofFloat(view, "translationY", y
				- view.getTop());
		anim2.setDuration(0);
		AnimatorSet set = new AnimatorSet();
		set.play(anim).with(anim2);
		set.start();
	}

	public static void GBsetAlpha(View view, float alpha) {
		ObjectAnimator anim = ObjectAnimator.ofFloat(view, "alpha", alpha);
		anim.setDuration(0);
		AnimatorSet set = new AnimatorSet();
		set.play(anim);
		set.start();
	}
}


text: export { default } from 'ember-apollo-client/services/apollo';


text:
package jenkins.telemetry.impl.java11;

import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

@Restricted(NoExternalUse.class)
public class CatcherClassLoader extends ClassLoader {

    public CatcherClassLoader(ClassLoader parent) {
        super(parent);
    }

    /**
     * Usually, the {@link ClassLoader} calls its parent and finally this method. So if we are here, it's the last
     * element of the chain. It doesn't happen in {@link jenkins.util.AntClassLoader} so it has an special management
     * on {@link hudson.ClassicPluginStrategy}
     *
     *
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        ClassNotFoundException e = new ClassNotFoundException(name);
        MissingClassTelemetry.reportException(name, e);
        throw e;
    }
}


text:
.class Lcom/baidu/service/power/Policy$1;
.super Landroid/os/AsyncTask;
.source "Policy.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/baidu/service/power/Policy;->doAction(Landroid/content/Context;I)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Landroid/os/AsyncTask",
        "<",
        "Ljava/lang/Void;",
        "Ljava/lang/Void;",
        "Ljava/util/ArrayList",
        "<",
        "Ljava/lang/String;",
        ">;>;"
    }
.end annotation

# instance fields
.field final synthetic this$0:Lcom/baidu/service/power/Policy;

.field final synthetic val$context:Landroid/content/Context;

.field final synthetic val$value:I

# direct methods
.method constructor <init>(Lcom/baidu/service/power/Policy;Landroid/content/Context;I)V
    .locals 0
    .parameter
    .parameter
    .parameter

    .prologue
    .line 227
    iput-object p1, p0, Lcom/baidu/service/power/Policy$1;->this$0:Lcom/baidu/service/power/Policy;

    iput-object p2, p0, Lcom/baidu/service/power/Policy$1;->val$context:Landroid/content/Context;

    iput p3, p0, Lcom/baidu/service/power/Policy$1;->val$value:I

    invoke-direct {p0}, Landroid/os/AsyncTask;-><init>()V

    return-void
.end method

# virtual methods
.method protected bridge synthetic doInBackground([Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 227
    check-cast p1, [Ljava/lang/Void;

    .end local p1
    invoke-virtual {p0, p1}, Lcom/baidu/service/power/Policy$1;->doInBackground([Ljava/lang/Void;)Ljava/util/ArrayList;

    move-result-object v0

    return-object v0
.end method

.method protected varargs doInBackground([Ljava/lang/Void;)Ljava/util/ArrayList;
    .locals 1
    .parameter "params"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "([",
            "Ljava/lang/Void;",
            ")",
            "Ljava/util/ArrayList",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation

    .prologue
    .line 231
    iget-object v0, p0, Lcom/baidu/service/power/Policy$1;->val$context:Landroid/content/Context;

    invoke-static {v0}, Lcom/baidu/service/power/PowerStatsUtil;->getTopApp(Landroid/content/Context;)Ljava/util/ArrayList;

    move-result-object v0

    return-object v0
.end method

.method protected bridge synthetic onPostExecute(Ljava/lang/Object;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 227
    check-cast p1, Ljava/util/ArrayList;

    .end local p1
    invoke-virtual {p0, p1}, Lcom/baidu/service/power/Policy$1;->onPostExecute(Ljava/util/ArrayList;)V

    return-void
.end method

.method protected onPostExecute(Ljava/util/ArrayList;)V
    .locals 3
    .parameter
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/util/ArrayList",
            "<",
            "Ljava/lang/String;",
            ">;)V"
        }
    .end annotation

    .prologue
    .line 236
    .local p1, result:Ljava/util/ArrayList;,"Ljava/util/ArrayList<Ljava/lang/String;>;"
    const-string v0, "SmartPowerService"

    new-instance v1, Ljava/lang/StringBuilder;

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

    const-string/jumbo v2, "onPostExecute "

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

    move-result-object v1

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

    move-result-object v1

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

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 237
    iget-object v0, p0, Lcom/baidu/service/power/Policy$1;->this$0:Lcom/baidu/service/power/Policy;

    iget-object v1, p0, Lcom/baidu/service/power/Policy$1;->val$context:Landroid/content/Context;

    iget v2, p0, Lcom/baidu/service/power/Policy$1;->val$value:I

    invoke-virtual {v0, v1, v2, p1}, Lcom/baidu/service/power/Policy;->showAlertDialog(Landroid/content/Context;ILjava/util/ArrayList;)V

    .line 238
    iget-object v0, p0, Lcom/baidu/service/power/Policy$1;->this$0:Lcom/baidu/service/power/Policy;

    iget-object v1, p0, Lcom/baidu/service/power/Policy$1;->val$context:Landroid/content/Context;

    #calls: Lcom/baidu/service/power/Policy;->playLowBatterySound(Landroid/content/Context;)V
    invoke-static {v0, v1}, Lcom/baidu/service/power/Policy;->access$000(Lcom/baidu/service/power/Policy;Landroid/content/Context;)V

    .line 239
    return-void
.end method


text:
one_flow_template 'test_tpl_opts_from_hash' do
  action :delete
end


text:
/*!
 *  Copyright (c) 2015-2017 by Contributors
 * \file broadcast_reduce_customized-inl.h
 * \brief CPU-specific Function definition of broadcast and reduce operators
 */
#ifndef MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_
#define MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_

#include "../../tensor/broadcast_reduce-inl.h"

namespace mxnet {
namespace op {
namespace broadcast {
using namespace mshadow;

template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP>
MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto,
                                          const DType* __restrict big, OType *small,
                                          const Shape<ndim>& bshape, const Shape<ndim>& sshape,
                                          const Shape<ndim>& rshape, const Shape<ndim>& rstride,
                                          Reducer* reducer) {
  Shape<ndim> coord = unravel(idx, sshape);
  index_t j = ravel(coord, bshape);
  AType val, residual;
  reducer->SetInitValue(val, residual);
  for (size_t k = 0; k < M; ++k) {
    coord = unravel(k, rshape);
    reducer->Reduce(val, AType(OP::Map(big[j + dot(coord, rstride)])), residual);
  }
  reducer->Finalize(val, residual);
  assign(&small[idx], addto, OType(val));
}

#ifdef __CUDACC__
#include "broadcast_reduce_customized-inl.cuh"
#include "../../tensor/broadcast_reduce-inl.cuh"

#else

template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP>
void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto,
                           const DType *big, OType *small, const Shape<ndim> bshape,
                           const Shape<ndim> sshape, const Shape<ndim> rshape,
                           const Shape<ndim> rstride,
                           Reducer* reducer) {
  #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
  for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
    seq_reduce_assign_wr<Reducer, ndim, AType, DType, OType, OP>(idx, M, addto, big, small,
        bshape, sshape, rshape, rstride, reducer);
  }
}

template <typename Reducer, int ndim, typename DType, typename OP, bool safe_acc = false>
void ReduceWithReducer(Stream<cpu>* s, const TBlob& small, const OpReqType req,
                       const Tensor<cpu, 1, char>& workspace, const TBlob& big,
                       Reducer* reducer) {
  if (req == kNullOp) return;
  Shape<ndim> rshape, rstride;
  diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
  size_t N = small.shape_.Size(), M = rshape.Size();
  if (!safe_acc) {
    seq_reduce_compute_wr<Reducer, ndim, DType, DType, DType, OP>(
      N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(),
      big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer);
  } else {
    MXNET_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, {
      typedef typename std::conditional<safe_acc, AType, DataType>::type AccType;
      MSHADOW_TYPE_SWITCH_WITH_BOOL(small.type_flag_, OType, {
        typedef typename std::conditional<safe_acc, OType, DataType>::type OutType;
        seq_reduce_compute_wr<Reducer, ndim, AccType, DataType, OutType, OP>(
          N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(),
          big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer);
      });
    });
  }
}

template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto,
                                          const DType* __restrict big, const DType* __restrict lhs,
                                          const DType* __restrict rhs, DType *small,
                                          const Shape<ndim>& big_shape,
                                          const Shape<ndim>& lhs_shape0,
                                          const Shape<ndim>& rhs_shape0,
                                          const Shape<ndim>& small_shape, const Shape<ndim>& rshape,
                                          const Shape<ndim>& lhs_shape,
                                          const Shape<ndim>& rhs_shape,
                                          const Shape<ndim>& rstride, const Shape<ndim>& lhs_stride,
                                          const Shape<ndim>& rhs_stride,
                                          Reducer* reducer) {
  Shape<ndim> coord = unravel(idx, small_shape);
  const index_t idx_big0 = ravel(coord, big_shape);
  const index_t idx_lhs0 = ravel(coord, lhs_shape0);
  const index_t idx_rhs0 = ravel(coord, rhs_shape0);
  DType val, residual;
  reducer->SetInitValue(val, residual);
  for (size_t k = 0; k < M; ++k) {
    Shape<ndim> coord_big = unravel(k, rshape);
    index_t idx_big = idx_big0 + dot(coord_big, rstride);

    Shape<ndim> coord_lhs = unravel(k, lhs_shape);
    index_t idx_lhs = idx_lhs0 + dot(coord_lhs, lhs_stride);

    Shape<ndim> coord_rhs = unravel(k, rhs_shape);
    index_t idx_rhs = idx_rhs0 + dot(coord_rhs, rhs_stride);

    reducer->Reduce(val, OP1::Map(big[idx_big], OP2::Map(lhs[idx_lhs], rhs[idx_rhs])), residual);
  }
  reducer->Finalize(val, residual);
  assign(&small[idx], addto, val);
}

template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto,
                           const DType *big, const DType *lhs, const DType *rhs, DType *small,
                           const Shape<ndim> big_shape, const Shape<ndim> small_shape,
                           const Shape<ndim> rshape, const Shape<ndim> rstride,
                           const Shape<ndim> lhs_shape, const Shape<ndim> lhs_stride,
                           const Shape<ndim> rhs_shape, const Shape<ndim> rhs_stride,
                           const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0,
                           Reducer* reducer) {
  #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount())
  for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) {
    seq_reduce_assign_wr<Reducer, ndim, DType, OP1, OP2>(idx, M, addto, big, lhs, rhs, small,
      big_shape, lhs_shape0, rhs_shape0, small_shape, rshape, lhs_shape, rhs_shape, rstride,
      lhs_stride, rhs_stride, reducer);
  }
}

template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2>
void ReduceWithReducer(Stream<cpu> *s, const TBlob& small, const OpReqType req,
                       const Tensor<cpu, 1, char>& workspace, const TBlob& big, const TBlob& lhs,
                       const TBlob& rhs, Reducer* reducer) {
  if (req == kNullOp) return;
  Shape<ndim> rshape, rstride;
  diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride);
  size_t N = small.shape_.Size();
  size_t M = rshape.Size();

  Shape<ndim> lhs_shape, lhs_stride;
  diff(small.shape_.get<ndim>(), lhs.shape_.get<ndim>(), &lhs_shape, &lhs_stride);

  Shape<ndim> rhs_shape, rhs_stride;
  diff(small.shape_.get<ndim>(), rhs.shape_.get<ndim>(), &rhs_shape, &rhs_stride);

  seq_reduce_compute_wr<Reducer, ndim, DType, OP1, OP2>(
    N, M, req == kAddTo,
    big.dptr<DType>(), lhs.dptr<DType>(), rhs.dptr<DType>(), small.dptr<DType>(),
    big.shape_.get<ndim>(), small.shape_.get<ndim>(),
    rshape, rstride,
    lhs_shape, lhs_stride,
    rhs_shape, rhs_stride,
    lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>(),
    reducer);
}

#endif
}  // namespace broadcast
}  // namespace op
}  // namespace mxnet

#endif  // MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_


text:
require 'spec_helper'

describe DatabaseTypesController do
  render_views
  let(:user) { User.make! }

  before(:each) do
    sign_in user
    @cloud = Cloud.make!(:cloud_provider => CloudProvider.make!)
    @database_type =  DatabaseType.make!
    @database_types = [@database_type]
  end

  it "should render index with database types" do
    cloud_cost_structure = CloudCostStructure.make!
    CloudCostTier.make!(:cloud_cost_structure => cloud_cost_structure)
    CloudCostScheme.make!(:cloud => @cloud, :cloud_resource_type => @database_type, :cloud_cost_structure => cloud_cost_structure)

    get :index, :cloud_id => @cloud.id
    response.code.should == "200"
    assigns(:database_types).should == DatabaseType.all
    response.should render_template("index")
  end
end


text:
class MoabTorqueBehavior extends BQBehavior {

  val torqueBehavior = new TorqueBehavior
  val moabBehavior = new MoabBehavior

  ///////////////////////////////////////////////////
  //
  // submit
  //
  ///////////////////////////////////////////////////
  def submit(command: String, options: String, environment: Map[String,String]): BQSubmitResult = {

    // Submit the job with Torque
    torqueBehavior.submit(command, options, environment)

  }

  ///////////////////////////////////////////////////
  //
  // status
  //
  ///////////////////////////////////////////////////
  def status(jobs: List[String]): BQStatusResult = {

    // Ask Torque for the job status
    val torqueResult = torqueBehavior.status(jobs)

    // Get a list of jobs that Torque didn't find
    val missingJobs = torqueResult match {
      case BQStatusResult(Some(torqueJobs), None) => jobs.filterNot(torqueJobs.keys.toList contains _)
      case BQStatusResult(None, Some(error)) => jobs
    }

    if (missingJobs.isEmpty) {
      // If Torque found all the jobs, return the result
      torqueResult
    } else {
      // Otherwise, ask Moab for the status of the missing jobs
      val moabResult = moabBehavior.status(missingJobs)
      moabResult match {
        case BQStatusResult(Some(moabJobs), None) => BQStatusResult(Some(torqueResult.jobMap.getOrElse(Map[String,BQJob]()) ++ moabJobs), torqueResult.error)
        case BQStatusResult(None, Some(error)) => BQStatusResult(torqueResult.jobMap, Some(error))
      }
    }

  }

}


text:
from keystore.keybag import Keybag
from keystore.effaceable import EffaceableLockers
from util.ramdiskclient import RamdiskToolClient
import plistlib

COMPLEXITY={
            0: "4 digits",
            1: "n digits",
            2: "n alphanum"
            }

def checkPasscodeComplexity(data_volume):
    pl = data_volume.readFile("/mobile/Library/ConfigurationProfiles/UserSettings.plist", returnString=True)
    if not pl:
        print "Failed to read UserSettings.plist, assuming simple passcode"
        return 0
    pl = plistlib.readPlistFromString(pl)
    #print "passcodeKeyboardComplexity :", pl["restrictedValue"]["passcodeKeyboardComplexity"]
    value =  pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"]
    print "passcodeKeyboardComplexity %d => %s" % (value, COMPLEXITY.get(value))
    return pl["restrictedValue"]["passcodeKeyboardComplexity"]["value"]

def loadKeybagFromVolume(volume, device_infos):
    systembag = volume.readFile("/keybags/systembag.kb", returnString=True)
    if not systembag or not systembag.startswith("bplist"):
        print "FAIL: could not read /keybags/systembag.kb from data partition"
        return False
    lockers = EffaceableLockers(device_infos["lockers"].data)
    bag1key = lockers.get("BAG1")[-32:]
    keybag = Keybag.createWithSystemkbfile(systembag, bag1key, device_infos.get("key835", "").decode("hex"))
    keybag.setDKey(device_infos)
    if device_infos.has_key("passcodeKey"):
        keybag.unlockWithPasscodeKey(device_infos.get("passcodeKey").decode("hex"))
    return keybag

def bruteforcePasscode(device_infos, data_volume):
    if device_infos.has_key("passcode"):
        print "Passcode already found, no bruteforce required"
        return False
    kb = data_volume.keybag
    if not kb:
        return False

    rd = RamdiskToolClient.get()
    if rd.device_infos.udid != device_infos.udid:
        print "Wrong device connected"
        return

    print "Enter passcode or leave blank for bruteforce:"
    z = raw_input()
    bf = rd.getPasscodeKey(kb.KeyBagKeys, z)
    if kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex")):
        print "Passcode \"%s\" OK" % z
    else:
        if z != "":
            print "Wrong passcode, trying to bruteforce !"
        if checkPasscodeComplexity(data_volume) != 0:
            print "Complex passcode used, not bruteforcing"
            return False

        bf = rd.bruteforceKeyBag(kb.KeyBagKeys)
        if bf and kb.unlockWithPasscodeKey(bf.get("passcodeKey").decode("hex")):
            print "Bruteforce successful, passcode : %s" % bf["passcode"]
            print "Passcode key : %s" % bf.get("passcodeKey")
    if kb.unlocked:
        device_infos.update(bf)
        device_infos["classKeys"] = kb.getClearClassKeysDict()
        device_infos["KeyBagKeys"] = plistlib.Data(kb.KeyBagKeys)
        return True
    return False


text:
#include "SettingsBackend.hpp"

// no constexpr, because QString is not a literal type
const QString SettingsBackend::globalName = "ShaderSandbox";
const QString SettingsBackend::globalDir = "Live Code Editor";

/**
 * @brief SettingsBackend::getSettingsFor
 * @param key
 * @param defaultOption
 * @param id
 * @return the settings requested
 *
 * Takes a key, a default option and the index of
 * the requesting child window. Gets the settings
 * for the key or returns defaultOption.
 */
QVariant SettingsBackend::getSettingsFor(const QString key,
                                         const QVariant defaultOption,
                                         const int id) noexcept{
    QString relevantSubdir(globalDir + "/" + QString::number(id));
    QSettings set(globalName, relevantSubdir);
    return set.value(key, defaultOption);
}

/**
 * @brief SettingsBackend::getSettingsFor
 * @param key
 * @param defaultOption
 * @return the settings requested
 *
 * Takes a key and a default option. Gets the
 * settings for the key or returns defaultOption.
 */
QVariant SettingsBackend::getSettingsFor(const QString key, const QVariant &defaultOption) noexcept{
    return QSettings(globalName, globalDir).value(key, defaultOption);
}

/**
 * @brief SettingsBackend::getSettings
 * @param id
 * @return the settings as a QHash
 *
 * gets the settings for a child window and
 * translates it to a QHash that is returned.
 */
QHash<QString, QVariant> SettingsBackend::getSettings(const int id) noexcept{
    QHash<QString, QVariant> settings;
    QString relevantSubdir(globalDir + "/" + QString::number(id));
    QSettings set(globalName, relevantSubdir);
    for(auto &key : set.childKeys())
        settings.insert(key, set.value(key));
    return settings;
}

/**
 * @brief SettingsBackend::addSettings
 * @param key
 * @param value
 *
 * Adds an entry to the global settings.
 */
void SettingsBackend::addSettings(const QString key, const QVariant value) noexcept{
    QSettings settings(globalName, globalDir);
    settings.setValue(key, value);
}

/**
 * @brief SettingsBackend::saveSettings
 * @param id
 * @param key
 * @param value
 *
 * Saves the settings of a instance.
 */
void SettingsBackend::saveSettingsFor(const int id, const QString &key, const QVariant &value) noexcept{
    QString relevantSubdir(globalDir + "/" + QString::number(id));
    QSettings set(globalName, relevantSubdir);
    set.setValue(key, value);
}

void SettingsBackend::saveSettingsFor(const int id, const QHash<QString, QVariant> &settings) noexcept{
    QString relevantSubdir(globalDir + "/" + QString::number(id));
    QSettings set(globalName, relevantSubdir);
    for(auto &key : settings.keys())
        set.setValue(key, settings[key]);
}

/**
 * @brief SettingsBackend::removeSettings
 * @param id
 *
 * Removes the settings of a child.
 */
void SettingsBackend::removeSettings(const int id) noexcept{
    QString relevantSubdir(globalDir + "/" + QString::number(id));
    QSettings set(globalName, relevantSubdir);
    set.clear();
}


text:
spring-mvc-thymeleaf-gradle-base
================================


text:
layout: page
title: Gregory Scholar Entertainment Dinner
date: 2016-05-24
author: Wayne Gillespie
tags: weekly links, java
status: published
summary: Ut accumsan tellus massa, sed rhoncus massa interdum.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 02/23/2018
  endDate: 02/26/2018
  ctyhocn: BHMFDHX
  groupCode: GSED
published: true
---
Fusce eget rutrum felis. Mauris eget rutrum risus. Praesent at velit quis sem euismod ultrices. Praesent ultrices tortor eu eros tristique semper. Etiam faucibus felis sit amet ligula ultricies, at sagittis ligula bibendum. Maecenas nec eleifend ante, id ultrices metus. Fusce sed cursus sem, non rhoncus turpis. Cras quis blandit tellus. Nam laoreet arcu ligula. Proin nunc elit, pulvinar at magna et, scelerisque scelerisque neque. Duis sit amet volutpat orci, ac pretium eros. Proin tincidunt dapibus volutpat. Proin id ultrices eros. Quisque iaculis elit eget arcu bibendum, ut luctus arcu ultrices. Nam ut lectus urna.

* Etiam ac turpis sodales, laoreet eros ut, semper libero.

Quisque luctus cursus maximus. Nam risus odio, imperdiet at odio eget, cursus iaculis ex. In ullamcorper urna ut nisi facilisis, quis laoreet mauris euismod. Nam blandit nulla eget elit vulputate facilisis. Sed venenatis et metus id porta. Morbi placerat fringilla diam non gravida. Vivamus id sem et tellus semper aliquam luctus quis sapien. Mauris ut tristique libero. Vestibulum sodales mi diam, vel placerat urna ultrices ut. In finibus urna non elit iaculis, id fringilla urna semper. Ut sagittis vitae mauris vel venenatis. Sed quis lorem vulputate, finibus neque faucibus, interdum leo.