text:
// Class header file
#include "KeyTable.hpp"

#include <memory>

#include <xalanc/XalanDOM/XalanElement.hpp>
#include <xalanc/XalanDOM/XalanNamedNodeMap.hpp>
#include <xalanc/XalanDOM/XalanNode.hpp>
#include <xalanc/XalanDOM/XalanNodeList.hpp>

#include <xalanc/PlatformSupport/XalanMessageLoader.hpp>

#include <xalanc/DOMSupport/DOMServices.hpp>

#include <xalanc/XPath/XPath.hpp>

#include "KeyDeclaration.hpp"
#include "StylesheetExecutionContext.hpp"
#include "XSLTProcessorException.hpp"

XALAN_CPP_NAMESPACE_BEGIN

const MutableNodeRefList    KeyTable::s_dummyList(XalanMemMgrs::getDummyMemMgr());

KeyTable::KeyTable(
            XalanNode*                          startNode,
            const PrefixResolver&               resolver,
            const KeyDeclarationVectorType&     keyDeclarations,
            StylesheetExecutionContext&         executionContext) :
    m_keys(executionContext.getMemoryManager())
{
    XalanNode*  pos = startNode;

    const KeyDeclarationVectorType::size_type   nDeclarations =
            keyDeclarations.size();

    // Do a non-recursive pre-walk over the tree.
    while(0 != pos)
    {
        // We're going to have to walk the attribute list
        // if it's an element, so get the attributes.
        const XalanNamedNodeMap*    attrs = 0;

        int                         nNodes = 0;

        if(XalanNode::ELEMENT_NODE == pos->getNodeType())
        {
            attrs = pos->getAttributes();

            nNodes = attrs->getLength();

            if(0 == nNodes)
            {
                attrs = 0;
            }
        }

        // Walk the primary node, and each of the attributes.
        // This loop is a little strange... it is meant to always
        // execute once, then execute for each of the attributes.
        XalanNode*  testNode = pos;

        for(int nodeIndex = -1; nodeIndex < nNodes;)
        {
            // Walk through each of the declarations made with xsl:key
            for(unsigned int i = 0; i < nDeclarations; ++i)
            {
                const KeyDeclaration&   kd = keyDeclarations[i];

                // See if our node matches the given key declaration according to
                // the match attribute on xsl:key.
                assert(kd.getMatchPattern() != 0);

                const XPath::eMatchScore    score =
                        kd.getMatchPattern()->getMatchScore(
                            testNode,
                            resolver,
                            executionContext);

                if(score != XPath::eMatchScoreNone)
                {
                    processKeyDeclaration(
                        m_keys,
                        kd,
                        testNode,
                        resolver,
                        executionContext);
                }
            } // end for(int i = 0; i < nDeclarations; ++i)

            ++nodeIndex;

            if(0 != attrs)
            {
                testNode = attrs->item(nodeIndex);
            }
        } // for(int nodeIndex = -1; nodeIndex < nNodes;)

        // The rest of this is getting the next pre-walk position in
        // the tree.
        XalanNode*  nextNode = pos->getFirstChild();

        while(0 == nextNode)
        {
            if(startNode == pos)
            {
                break;
            }
            else
            {
                nextNode = pos->getNextSibling();

                if(0 == nextNode)
                {
                    pos = pos->getParentNode();

                    if((startNode == pos) || (0 == pos))
                    {
                        nextNode = 0;
                        break;
                    }
                }
            }
        }

        pos = nextNode;
    } // while(0 != pos)

    if (m_keys.empty() == false)
    {
        const KeysMapType::iterator     theEnd = m_keys.end();
        KeysMapType::iterator           theCurrent = m_keys.begin();
        assert(theCurrent != theEnd);

        do
        {
            NodeListMapType&    theCurrentNodeListMap = (*theCurrent).second;

            if (theCurrentNodeListMap.empty() == false)
            {
                const NodeListMapType::iterator     theEnd = theCurrentNodeListMap.end();
                NodeListMapType::iterator           theCurrent = theCurrentNodeListMap.begin();
                assert(theCurrent != theEnd);

                do
                {
                    (*theCurrent).second.setDocumentOrder();

                    ++theCurrent;
                }
                while(theCurrent != theEnd);
            }

            ++theCurrent;
        }
        while(theCurrent != theEnd);
    }
} // end constructor

KeyTable*
KeyTable::create(MemoryManagerType& theManager,
            XalanNode*                          startNode,
            const PrefixResolver&               resolver,
            const KeyDeclarationVectorType&     keyDeclarations,
            StylesheetExecutionContext&         executionContext)
{
    typedef KeyTable ThisType;

    XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType)));

    ThisType* theResult = theGuard.get();

    new (theResult) ThisType( startNode,
                               resolver,
                               keyDeclarations,
                              executionContext);
   theGuard.release();

    return theResult;
}

KeyTable::~KeyTable()
{
}

const MutableNodeRefList&
KeyTable::getNodeSetByKey(
                      const XalanQName&         qname,
                      const XalanDOMString&     ref) const
{
    const KeysMapType::const_iterator   i = m_keys.find(qname);

    if (i != m_keys.end())
    {
        const NodeListMapType&  theMap = (*i).second;

        const NodeListMapType::const_iterator   j = theMap.find(ref);

        if (j != theMap.end())
        {
            return (*j).second;
        }
    }

    // It makes things much easier if we always return
    // a list of nodes.  So this is just an empty one
    // to return when the ref is not found.
    return s_dummyList;
}

inline void
addIfNotFound(
            StylesheetExecutionContext&     executionContext,
            MutableNodeRefList&             theNodeList,
            XalanNode*                      theNode)
{
    theNodeList.addNodeInDocOrder(theNode, executionContext);
}

static const NodeRefList    theEmptyList(XalanMemMgrs::getDummyMemMgr());

void
KeyTable::processKeyDeclaration(
            KeysMapType&                    theKeys,
            const KeyDeclaration&           kd,
            XalanNode*                      testNode,
            const PrefixResolver&           resolver,
            StylesheetExecutionContext&     executionContext)
{
    // Query from the node, according the the select pattern in the
    // use attribute in xsl:key.
    assert(kd.getUse() != 0);

    const XObjectPtr    xuse(kd.getUse()->execute(testNode, resolver, theEmptyList, executionContext));

    if(xuse->getType() != XObject::eTypeNodeSet)
    {
        assert(kd.getQName() != 0);

        addIfNotFound(
            executionContext,
            theKeys[*kd.getQName()][xuse->str()],
            testNode);
    }
    else
    {
        const NodeRefListBase&  nl = xuse->nodeset();

        // Use each node in the node list as a key value that we'll be
        // able to use to look up the given node.
        const NodeRefListBase::size_type    nUseValues = nl.getLength();

        StylesheetExecutionContext::GetAndReleaseCachedString   theGuard(executionContext);

        XalanDOMString&     nodeData = theGuard.get();

        // Use each node in the node list as a key value that we'll be
        // able to use to look up the given node.
        for(unsigned int i = 0; i < nUseValues; ++i)
        {
            // Get the string value of the node to use as the result of the
            // expression.
            assert(nl.item(i) != 0);

            DOMServices::getNodeData(*nl.item(i), nodeData);

            assert(kd.getQName() != 0);

            addIfNotFound(
                executionContext,
                theKeys[*kd.getQName()][nodeData],
                testNode);

            clear(nodeData);
        }
    }
}

XALAN_CPP_NAMESPACE_END


text:
package com.google.appengine.tools.mapreduce.bigqueryjobs;

import com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest;
import com.google.api.client.googleapis.services.json.CommonGoogleJsonClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.bigquery.Bigquery;
import com.google.api.services.bigquery.BigqueryRequest;
import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobReference;
import com.google.api.services.bigquery.model.TableSchema;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.appengine.tools.mapreduce.GoogleCloudStorageFileSet;
import com.google.appengine.tools.mapreduce.Marshallers;
import com.google.appengine.tools.mapreduce.impl.BigQueryConstants;
import com.google.appengine.tools.mapreduce.impl.util.SerializableValue;
import com.google.appengine.tools.mapreduce.outputs.BigQueryStoreResult;
import com.google.appengine.tools.pipeline.FutureValue;
import com.google.appengine.tools.pipeline.Job1;
import com.google.appengine.tools.pipeline.Value;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A pipeline job that loads files stored in Google Cloud Storage into a bigquery table.
 */
public final class BigQueryLoadGoogleCloudStorageFilesJob extends
    Job1<List<BigQueryLoadJobReference>, BigQueryStoreResult<GoogleCloudStorageFileSet>> {

  private static final long serialVersionUID = 4162438273017726233L;
  private final String dataset;
  private final String tableName;
  private final String projectId;

  private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
  private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();

  private static final Logger log =
      Logger.getLogger(BigQueryLoadGoogleCloudStorageFilesJob.class.getName());

  static Bigquery getBigquery() {
    List<String> scopes = Lists.newArrayList();
    scopes.add(BigQueryConstants.BQ_SCOPE);
    AppIdentityCredential credential = new AppIdentityCredential.Builder(scopes).build();
    GoogleClientRequestInitializer initializer = new CommonGoogleJsonClientRequestInitializer() {
      @SuppressWarnings("unused")
      public void initialize(
          @SuppressWarnings("rawtypes") AbstractGoogleJsonClientRequest request) {
        @SuppressWarnings("rawtypes")
        BigqueryRequest bigqueryRequest = (BigqueryRequest) request;
        bigqueryRequest.setPrettyPrint(true);
      }
    };
    return new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
        .setHttpRequestInitializer(credential).setGoogleClientRequestInitializer(initializer)
        .build();
  }

  /**
   * @param dataset the name of the bigquery dataset.
   * @param tableName name of the bigquery table to load data.
   * @param projectId bigquery project Id.
   */
  public BigQueryLoadGoogleCloudStorageFilesJob(String dataset, String tableName,
      String projectId) {
    this.dataset = dataset;
    this.tableName = tableName;
    this.projectId = projectId;
  }

  /**
   * Divides the files into bundles having size less than or equal to the maximum size allowed per
   * bigquery load {@link Job} and then starts separate pipeline jobs for each of the bundles.
   * Returns a list of {@link JobReference}s.
   */
  @Override
  public Value<List<BigQueryLoadJobReference>> run(
      BigQueryStoreResult<GoogleCloudStorageFileSet> bigQueryStoreResult) throws Exception {
    BigQueryStoreResult<GoogleCloudStorageFileSet> outputResult = bigQueryStoreResult;
    List<GcsFilename> files = outputResult.getResult().getFiles();
    List<List<GcsFilename>> bundles =
        bundleFiles(files, BigQueryConstants.BIGQUERY_LOAD_DATA_SIZE_LIMIT);
    List<FutureValue<BigQueryLoadJobReference>> jobReferenceList = new ArrayList<>();
    for (List<GcsFilename> bundle : bundles) {
      jobReferenceList.add(futureCall(new BigQueryLoadFileSetJob(dataset, tableName, projectId,
          bundle, SerializableValue.of(Marshallers.getGenericJsonMarshaller(TableSchema.class),
              outputResult.getSchema())), immediate(Integer.valueOf(0))));
    }
    return futureList(jobReferenceList);
  }

  /**
   * @param files list of gcs files to load into bigquery.
   * @param bundleSizeLimit size limit of the bundle of files.
   * @return List of files bundled together so that the combined size of the files is less than the
   *         specified bundle size limit.
   * @throws IOException
   */
  private List<List<GcsFilename>> bundleFiles(List<GcsFilename> files, long bundleSizeLimit)
      throws IOException {
    List<List<GcsFilename>> bundles = new ArrayList<>();
    List<GcsFilename> currentBundle = new ArrayList<>();
    long currentBundleSize = 0;
    GcsService GCS_SERVICE = GcsServiceFactory.createGcsService();
    for (GcsFilename file : files) {
      long fileSize = GCS_SERVICE.getMetadata(file).getLength();
      if (currentBundleSize + fileSize > bundleSizeLimit) {
        bundles.add(ImmutableSet.copyOf(currentBundle).asList());
        currentBundle = new ArrayList<>();
        currentBundleSize = 0;
      }
      currentBundle.add(file);
      currentBundleSize += fileSize;
    }
    bundles.add(ImmutableSet.copyOf(currentBundle).asList());
    return bundles;
  }

  public Value<BigQueryStoreResult<GoogleCloudStorageFileSet>> handleException(Throwable t)
      throws Throwable {
    log.log(Level.SEVERE, "Bigquery data load job failed because of : ", t);
    throw t;
  }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
	"time"

	"github.com/coreos/etcd/pkg/fileutil"
	"github.com/coreos/etcd/pkg/netutil"
	"github.com/coreos/etcd/tools/functional-tester/etcd-agent/client"
)

const (
	stateUninitialized = "uninitialized"
	stateStarted       = "started"
	stateStopped       = "stopped"
	stateTerminated    = "terminated"
)

type Agent struct {
	state string // the state of etcd process

	cmd     *exec.Cmd
	logfile *os.File

	cfg AgentConfig
}

type AgentConfig struct {
	EtcdPath      string
	LogDir        string
	FailpointAddr string
	UseRoot       bool
}

func newAgent(cfg AgentConfig) (*Agent, error) {
	// check if the file exists
	_, err := os.Stat(cfg.EtcdPath)
	if err != nil {
		return nil, err
	}

	c := exec.Command(cfg.EtcdPath)

	err = fileutil.TouchDirAll(cfg.LogDir)
	if err != nil {
		return nil, err
	}

	var f *os.File
	f, err = os.Create(filepath.Join(cfg.LogDir, "etcd.log"))
	if err != nil {
		return nil, err
	}

	return &Agent{state: stateUninitialized, cmd: c, logfile: f, cfg: cfg}, nil
}

// start starts a new etcd process with the given args.
func (a *Agent) start(args ...string) error {
	args = append(args, "--data-dir", a.dataDir())
	a.cmd = exec.Command(a.cmd.Path, args...)
	a.cmd.Env = []string{"GOFAIL_HTTP=" + a.cfg.FailpointAddr}
	a.cmd.Stdout = a.logfile
	a.cmd.Stderr = a.logfile
	err := a.cmd.Start()
	if err != nil {
		return err
	}

	a.state = stateStarted
	return nil
}

// stop stops the existing etcd process the agent started.
func (a *Agent) stopWithSig(sig os.Signal) error {
	if a.state != stateStarted {
		return nil
	}

	err := stopWithSig(a.cmd, sig)
	if err != nil {
		return err
	}

	a.state = stateStopped
	return nil
}

func stopWithSig(cmd *exec.Cmd, sig os.Signal) error {
	err := cmd.Process.Signal(sig)
	if err != nil {
		return err
	}

	errc := make(chan error)
	go func() {
		_, ew := cmd.Process.Wait()
		errc <- ew
		close(errc)
	}()

	select {
	case <-time.After(5 * time.Second):
		cmd.Process.Kill()
	case e := <-errc:
		return e
	}
	err = <-errc
	return err
}

// restart restarts the stopped etcd process.
func (a *Agent) restart() error {
	return a.start(a.cmd.Args[1:]...)
}

func (a *Agent) cleanup() error {
	// exit with stackstrace
	if err := a.stopWithSig(syscall.SIGQUIT); err != nil {
		return err
	}
	a.state = stateUninitialized

	a.logfile.Close()
	if err := archiveLogAndDataDir(a.cfg.LogDir, a.dataDir()); err != nil {
		return err
	}

	if err := fileutil.TouchDirAll(a.cfg.LogDir); err != nil {
		return err
	}

	f, err := os.Create(filepath.Join(a.cfg.LogDir, "etcd.log"))
	if err != nil {
		return err
	}
	a.logfile = f

	// https://www.kernel.org/doc/Documentation/sysctl/vm.txt
	// https://github.com/torvalds/linux/blob/master/fs/drop_caches.c
	cmd := exec.Command("/bin/sh", "-c", `echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh`)
	if err := cmd.Run(); err != nil {
		plog.Infof("error when cleaning page cache (%v)", err)
	}
	return nil
}

// terminate stops the exiting etcd process the agent started
// and removes the data dir.
func (a *Agent) terminate() error {
	err := a.stopWithSig(syscall.SIGTERM)
	if err != nil {
		return err
	}
	err = os.RemoveAll(a.dataDir())
	if err != nil {
		return err
	}
	a.state = stateTerminated
	return nil
}

func (a *Agent) dropPort(port int) error {
	if !a.cfg.UseRoot {
		return nil
	}
	return netutil.DropPort(port)
}

func (a *Agent) recoverPort(port int) error {
	if !a.cfg.UseRoot {
		return nil
	}
	return netutil.RecoverPort(port)
}

func (a *Agent) setLatency(ms, rv int) error {
	if !a.cfg.UseRoot {
		return nil
	}
	if ms == 0 {
		return netutil.RemoveLatency()
	}
	return netutil.SetLatency(ms, rv)
}

func (a *Agent) status() client.Status {
	return client.Status{State: a.state}
}

func (a *Agent) dataDir() string {
	return filepath.Join(a.cfg.LogDir, "etcd.data")
}

func existDir(fpath string) bool {
	st, err := os.Stat(fpath)
	if err != nil {
		if os.IsNotExist(err) {
			return false
		}
	} else {
		return st.IsDir()
	}
	return false
}

func archiveLogAndDataDir(logDir string, datadir string) error {
	dir := filepath.Join(logDir, "failure_archive", time.Now().Format(time.RFC3339))
	if existDir(dir) {
		dir = filepath.Join(logDir, "failure_archive", time.Now().Add(time.Second).Format(time.RFC3339))
	}
	if err := fileutil.TouchDirAll(dir); err != nil {
		return err
	}
	if err := os.Rename(filepath.Join(logDir, "etcd.log"), filepath.Join(dir, "etcd.log")); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	}
	if err := os.Rename(datadir, filepath.Join(dir, filepath.Base(datadir))); err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	}
	return nil
}


text:
      <report-filters
        [enabledControls]="enabledControls"
        [(monthString)]="startDate"
        [reportName]="reportName"
        [reportType]="reportType"
        [parentIsBusy]="isLoadingReport"
        (onselectedLocationChange)="getLocations($event)"
        (onMonthChange)="onMonthChange($event)"
        (locationTypeChange)="locationTypeChange($event)"
        (generateReport)="generateReport()"
      >
      </report-filters>


text:
PrivacySandboxDialogHandler::PrivacySandboxDialogHandler(
    base::OnceClosure close_callback,
    base::OnceCallback<void(int)> resize_callback,
    base::OnceClosure show_dialog_callback,
    base::OnceClosure open_settings_callback,
    PrivacySandboxService::PromptType prompt_type)
    : close_callback_(std::move(close_callback)),
      resize_callback_(std::move(resize_callback)),
      show_dialog_callback_(std::move(show_dialog_callback)),
      open_settings_callback_(std::move(open_settings_callback)),
      prompt_type_(prompt_type) {
  DCHECK(close_callback_);
  DCHECK(resize_callback_);
  DCHECK(show_dialog_callback_);
  DCHECK(open_settings_callback_);
}

PrivacySandboxDialogHandler::~PrivacySandboxDialogHandler() {
  DisallowJavascript();
}

void PrivacySandboxDialogHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback(
      "promptActionOccurred",
      base::BindRepeating(
          &PrivacySandboxDialogHandler::HandlePromptActionOccurred,
          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "resizeDialog",
      base::BindRepeating(&PrivacySandboxDialogHandler::HandleResizeDialog,
                          base::Unretained(this)));
  web_ui()->RegisterMessageCallback(
      "showDialog",
      base::BindRepeating(&PrivacySandboxDialogHandler::HandleShowDialog,
                          base::Unretained(this)));
}

void PrivacySandboxDialogHandler::OnJavascriptAllowed() {
  // Initialize the service reference here because `web_ui()` was already
  // initialized. `web_ui()` isn't ready in the constructor.
  privacy_sandbox_service_ =
      PrivacySandboxServiceFactory::GetForProfile(Profile::FromWebUI(web_ui()));
  DCHECK(privacy_sandbox_service_);
}

void PrivacySandboxDialogHandler::OnJavascriptDisallowed() {
  if (did_user_make_decision_)
    return;

  // If user hasn't made a decision, notify the service.
  if (prompt_type_ == PrivacySandboxService::PromptType::kConsent) {
    NotifyServiceAboutPromptAction(
        PrivacySandboxService::PromptAction::kConsentClosedNoDecision);
  } else {
    NotifyServiceAboutPromptAction(
        PrivacySandboxService::PromptAction::kNoticeClosedNoInteraction);
  }
}

void PrivacySandboxDialogHandler::HandlePromptActionOccurred(
    const base::Value::List& args) {
  if (!IsJavascriptAllowed())
    return;

  CHECK_EQ(1U, args.size());
  auto action =
      static_cast<PrivacySandboxService::PromptAction>(args[0].GetInt());

  if (action == PrivacySandboxService::PromptAction::kNoticeOpenSettings)
    std::move(open_settings_callback_).Run();

  switch (action) {
    case PrivacySandboxService::PromptAction::kNoticeAcknowledge:
    case PrivacySandboxService::PromptAction::kNoticeDismiss:
    case PrivacySandboxService::PromptAction::kNoticeOpenSettings:
    case PrivacySandboxService::PromptAction::kConsentAccepted:
    case PrivacySandboxService::PromptAction::kConsentDeclined: {
      did_user_make_decision_ = true;
      DisallowJavascript();
      std::move(close_callback_).Run();
      break;
    }
    default:
      break;
  }

  NotifyServiceAboutPromptAction(action);
}

void PrivacySandboxDialogHandler::HandleResizeDialog(
    const base::Value::List& args) {
  AllowJavascript();

  const base::Value& callback_id = args[0];
  int height = args[1].GetInt();
  DCHECK(resize_callback_);
  std::move(resize_callback_).Run(height);

  ResolveJavascriptCallback(callback_id, base::Value());
}

void PrivacySandboxDialogHandler::HandleShowDialog(
    const base::Value::List& args) {
  AllowJavascript();

  // Notify the service that the DOM was loaded and the dialog was shown to
  // user.
  if (prompt_type_ == PrivacySandboxService::PromptType::kConsent) {
    NotifyServiceAboutPromptAction(
        PrivacySandboxService::PromptAction::kConsentShown);
  } else {
    NotifyServiceAboutPromptAction(
        PrivacySandboxService::PromptAction::kNoticeShown);
  }

  DCHECK(show_dialog_callback_);
  std::move(show_dialog_callback_).Run();
}

void PrivacySandboxDialogHandler::NotifyServiceAboutPromptAction(
    PrivacySandboxService::PromptAction action) {
  DCHECK(privacy_sandbox_service_);
  privacy_sandbox_service_->PromptActionOccurred(action);
}


text:
<TITLE>Review for Jacquot de Nantes (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Jacquot de Nantes (1991)

reviewed by
James Berardinelli

                                     JACQUOT
                       A film review by James Berardinelli
                        Copyright 1993 James Berardinelli

Rating (Linear 0 to 10):  6.1

Date Released:  varies
Running Length:  1:58
Rated:  PG

Starring:  Philippe Maron, Edouard Joubeaud, Laurent Monnier,
           Brigitte de Villepoix, Daniel Dublet
Director:  Agnes Varda
Screenplay:  Agnes Varda based on the memoirs of Jacques Demy
Music:  Joanna Bruzdowicz
Released by Sony Pictures Classics
In French with English subtitles

     JACQUOT is a tribute from one lover to another, a project that
started out as a collaboration but became a both an homage and a means
of saying farewell.

     French film maker Jacques Demy (who is best known for his
surrealistic, often-offbeat musicals) died in October 1990, when
production on JACQUOT was nearing an end.  A filmed chronicle of Demy's
childhood memoirs put together by Agnes Varda, his companion of more
than thirty years, JACQUOT (the title refers to the young Jacques'
nickname) is a look at how the influences of childhood steer a man's
creative spirit.  During the course of the film, we meet Demy and his
friends and family, see his love for the cinema, and observe his first
attempts at creating.

     JACQUOT succeeds in engaging the intellect, but is less triumphant
in touching the emotions.  Despite the detail and care with which
Demy's memories have been committed to film, there is a quality about
them that distances the audience.  We understand his desires, needs,
and the everyday difficulties of his life, but little about this film
is stirring.  For all that the story is about Jacquot, there's a
question of how much of the inner person we get to know.  The film
seems more concerned with presentation than identification.

     The most intriguing and enjoyable parts of the movie are, by far,
those that deal with the young Demy's early forays into movie-making.
A fair amount of time is spent chronicling the development of a couple
of animated shorts that Jacquot shows to his family in a home-made
theater.  In these scenes, we are given a peek at the creative genius
of Demy, and it is through them that JACQUOT attains its goal.

     It's always difficult to film someone else's memories without
either missing the mark entirely or waxing nostalgic.  JACQUOT falls
into both traps at times, even as it occasionally hits the mark.  Some
of the most historically important incidents, such as the Nazi
occupation of France and the subsequent bombing raids, fail to bring
out the horror and fear that Demy must have felt.  The truest moments
are often those that seem almost thrown in as an afterthought.

     Writer/director Agnes Varda uses color to supplement the normal
black-and-white in which JACQUOT is presented.  Several scenes explode
to life in a vivid display of hues, accenting a particular emotion or
highlighting a scene.  For the most part, it's an effective technique,
although one that is possibly a little overused.  Also in color are
numerous clips from Demy's films.  The inclusion of these works very
well, showing how incidents from the man's real life impacted the
movies he was to make.

     The acting is solid from top to bottom, with the three young
actors who play the growing Jacquot (Philippe Maron, Edouard Joubeaud,
and Laurent Monnier) giving consistent performances that make for a
smooth transition from one to the next.  The occasional appearances of
the real Jacques Demy on-screen lends JACQUOT a bittersweet quality
that it might not otherwise have had.  In some ways, the scenes with
him, lovingly filmed by Ms. Varda, are the most moving of the picture.

     The sense of period in JACQUOT is excellent, from the streets and
countryside of World War II France to the garage and attic of the Demy
house.  As mentioned, detail is crucial to this movie and, at least in
rolling back the years, such obvious care brings dividends.

     Even for those who, like me, have never seen anything by Demy, the
depiction of the relationship between his memories and work is a source
of fascination  The clips from eleven films help immeasurably in this
respect, yet even without them, there are enough moments in JACQUOT to
warrant it a look from those who don't lose patience with this kind of
simple, relaxed style.

- James Berardinelli (blake7@cc.bellcore.com)

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

namespace DmMailerTest\Factory\Manager;

use DmMailer\Factory\Manager\Unsubscribe;

use DmTest\ServiceManager\ServiceLocatorDummy;

class UnsubscribeTest extends \PHPUnit_Framework_TestCase
{
    /** @var Unsubscribe */
    private $sut;

    public function setUp()
    {
        $this->sut = new Unsubscribe;
    }

    /**
     * @covers DmMailer\Factory\Manager\Unsubscribe
     */
    public function testCreateService()
    {
        $serviceLocator = new ServiceLocatorDummy($this);

        $serviceLocator->set('request', $serviceLocator->get('Zend\Http\PhpEnvironment\Request'));

        $result = $this->sut->createService($serviceLocator);

        $this->assertInstanceOf('DmMailer\Manager\Unsubscribe', $result);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="pl.cba.adamsprogs.clok">

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        tools:ignore="AllowBackup">

        <activity
            android:name=".RootList"
            android:label="@string/app_name_settings">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".IndividualMenu"
            android:label="@string/title_activity_indiv_menu"
            android:parentActivityName=".RootList"
            tools:ignore="UnusedAttribute">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".RootList" />

            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
            </intent-filter>
        </activity>
        <activity
            android:name=".IndividualColourChange"
            android:label="@string/app_name_settings"
            android:parentActivityName=".IndividualMenu"
            tools:ignore="UnusedAttribute">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".IndividualMenu" />
        </activity>

        <receiver
            android:name=".Clok"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
        </receiver>

        <service
            android:name=".UpdateService"
            android:enabled="true"
            android:exported="false" />
    </application>

</manifest>


text:
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import saleor.thumbnail.models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ("product", "0170_rewrite_digitalcontenturl_orderline_relation"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name="Thumbnail",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("image", models.ImageField(upload_to="thumbnails")),
                (
                    "size",
                    models.PositiveIntegerField(
                        validators=[saleor.thumbnail.models.validate_thumbnail_size]
                    ),
                ),
                (
                    "format",
                    models.CharField(
                        blank=True, choices=[("webp", "WebP")], max_length=32, null=True
                    ),
                ),
                (
                    "category",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="thumbnails",
                        to="product.category",
                    ),
                ),
                (
                    "collection",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="thumbnails",
                        to="product.collection",
                    ),
                ),
                (
                    "product_media",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="thumbnails",
                        to="product.productmedia",
                    ),
                ),
                (
                    "user",
                    models.ForeignKey(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="thumbnails",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
        ),
    ]


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>org.apache.lucene.index (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.lucene.index

Support for testing of indexes.

See: Description

Interface Summary

Interface
Description

RandomIndexWriter.TestPoint

Simple interface that is executed for each <tt>TP</tt> InfoStream component
 message.

Class Summary

Class
Description

AlcoholicMergePolicy

 Merge policy for testing, it is like an alcoholic.

AllDeletedFilterReader

Filters the incoming reader and makes all documents appear deleted.

AssertingDirectoryReader

A DirectoryReader that wraps all its subreaders with
 AssertingLeafReader

AssertingLeafReader

A FilterLeafReader that can be used to apply
 additional checks for tests.

AssertingLeafReader.AssertingBinaryDocValues

Wraps a BinaryDocValues but with additional asserts

AssertingLeafReader.AssertingBits

Wraps a Bits but with additional asserts

AssertingLeafReader.AssertingFields

Wraps a Fields but with additional asserts

AssertingLeafReader.AssertingNumericDocValues

Wraps a NumericDocValues but with additional asserts

AssertingLeafReader.AssertingPostingsEnum

Wraps a docsenum with additional checks

AssertingLeafReader.AssertingRandomAccessOrds

Wraps a RandomAccessOrds but with additional asserts

AssertingLeafReader.AssertingSortedDocValues

Wraps a SortedDocValues but with additional asserts

AssertingLeafReader.AssertingSortedNumericDocValues

Wraps a SortedSetDocValues but with additional asserts

AssertingLeafReader.AssertingSortedSetDocValues

Wraps a SortedSetDocValues but with additional asserts

AssertingLeafReader.AssertingTerms

Wraps a Terms but with additional asserts

BaseCompoundFormatTestCase

Abstract class to do basic tests for a compound format.

BaseCompressingDocValuesFormatTestCase

Extends BaseDocValuesFormatTestCase to add compression checks.

BaseDocValuesFormatTestCase

Abstract class to do basic tests for a docvalues format.

BaseFieldInfoFormatTestCase

Abstract class to do basic tests for fis format.

BaseMergePolicyTestCase

Base test case for MergePolicy.

BaseNormsFormatTestCase

Abstract class to do basic tests for a norms format.

BasePointsFormatTestCase

Abstract class to do basic tests for a points format.

BasePostingsFormatTestCase

Abstract class to do basic tests for a postings format.

BaseSegmentInfoFormatTestCase

Abstract class to do basic tests for si format.

BaseStoredFieldsFormatTestCase

Base class aiming at testing stored fields formats.

BaseTermVectorsFormatTestCase

Base class aiming at testing term vectors formats.

BaseTermVectorsFormatTestCase.RandomTokenStream

Produces a random TokenStream based off of provided terms.

BaseTestCheckIndex

Base class for CheckIndex tests.

FieldFilterLeafReader

A FilterLeafReader that exposes only a subset
 of fields from the underlying wrapped reader.

ForceMergePolicy

A MergePolicy that only returns forced merges.

IndexWriterMaxDocsChanger

Accessor to make some package protected methods in IndexWriter available for testing.

MismatchedDirectoryReader

A DirectoryReader that wraps all its subreaders with
 MismatchedLeafReader

MismatchedLeafReader

Shuffles field numbers around to try to trip bugs where field numbers
 are assumed to always be consistent across segments.

MockRandomMergePolicy

MergePolicy that makes random decisions for testing.

PerThreadPKLookup

Utility class to do efficient primary-key (only 1 doc contains the
  given term) lookups by segment, re-using the enums.

RandomCodec

Codec that assigns per-field random postings formats.

RandomIndexWriter

Silly class that randomizes the indexing experience.

RandomPostingsTester

Helper class extracted from BasePostingsFormatTestCase to exercise a postings format.

RandomPostingsTester.FieldAndTerm

Holds one field, term and ord.

RandomPostingsTester.SeedPostings

Given the same random seed this always enumerates the
  same random postings

SuppressingConcurrentMergeScheduler

A ConcurrentMergeScheduler that ignores AlreadyClosedException.

ThreadedIndexingAndSearchingTestCase

Utility class that spawns multiple indexing and
  searching threads.

Enum Summary

Enum
Description

BaseTermVectorsFormatTestCase.Options

A combination of term vectors options.

RandomPostingsTester.Option

Which features to test.

Package org.apache.lucene.index Description

Support for testing of indexes.

The primary classes are:

RandomIndexWriter: Randomizes the indexing experience.

MockRandomMergePolicy: MergePolicy that makes random decisions.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Package

Next Package

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">

    <org.ayo.ui.sample.view_learn.RichBackgroundTextView
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:textColor="#000000"
        android:gravity="center"
        android:layout_gravity="center"
        android:text="oooo 1" />

</FrameLayout>


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Web;
using AspxCommerce.Core;
using SageFrame.Web.Utilities;

namespace AuthorizeNetAIM
{
    public class AIMController
    {
        public List<AIMAuthorizeSettingInfo> GetAllAuthorizedNetAIMSetting(int paymentGatewayID, AspxCommonInfo aspxCommonObj)
        {
            try
            {
                var parameterCollection = new List<KeyValuePair<string, object>>();
                parameterCollection.Add(new KeyValuePair<string, object>("@PaymentGatewayTypeID", paymentGatewayID));
                parameterCollection.Add(new KeyValuePair<string, object>("@StoreID", aspxCommonObj.StoreID));
                parameterCollection.Add(new KeyValuePair<string, object>("@PortalID", aspxCommonObj.PortalID));
                var sqLh = new SQLHandler();
                return sqLh.ExecuteAsList<AIMAuthorizeSettingInfo>("usp_Aspx_AIMAuthorizeNETSettingsGetAll", parameterCollection);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string SendPaymentInfoAIM(OrderDetailsCollection OrderDetail, string TemplateName, string addressPath)
        {

            var objRequest = new WebClient();
            var objInf = new System.Collections.Specialized.NameValueCollection(30);

            string strError;

            //OrderDetail.ObjOrderDetails.CustomerID = int.Parse(Crypto.GenerateCustomerID());
            OrderDetail.ObjOrderDetails.InvoiceNumber = Crypto.GenerateInvoiceNumber();
            OrderDetail.ObjOrderDetails.PurchaseOrderNumber = Crypto.GeneratePurchaseOrderNumber();

            //merchant generated field
            objInf.Add("x_version", OrderDetail.ObjOrderDetails.Version);
            objInf.Add("x_delim_data", "True");
            objInf.Add("x_login", OrderDetail.ObjOrderDetails.APILogin);
            objInf.Add("x_tran_key", OrderDetail.ObjOrderDetails.TransactionKey);
            objInf.Add("x_relay_response", "False");
            objInf.Add("x_delim_char", ",");
            objInf.Add("x_encap_char", "|");
            objInf.Add("x_invoice_num", OrderDetail.ObjOrderDetails.InvoiceNumber);
            objInf.Add("x_cust_id", OrderDetail.ObjOrderDetails.CustomerID.ToString(CultureInfo.InvariantCulture));
            objInf.Add("x_po_num", OrderDetail.ObjOrderDetails.PurchaseOrderNumber);

            // Billing Address
            objInf.Add("x_first_name", OrderDetail.ObjBillingAddressInfo.FirstName);
            objInf.Add("x_last_name", OrderDetail.ObjBillingAddressInfo.LastName);
            objInf.Add("x_company", OrderDetail.ObjBillingAddressInfo.CompanyName);
            objInf.Add("x_email", OrderDetail.ObjBillingAddressInfo.EmailAddress);
            objInf.Add("x_address", OrderDetail.ObjBillingAddressInfo.Address);
            objInf.Add("x_city", OrderDetail.ObjBillingAddressInfo.City);
            objInf.Add("x_state", OrderDetail.ObjBillingAddressInfo.State);
            objInf.Add("x_zip", OrderDetail.ObjBillingAddressInfo.Zip);
            objInf.Add("x_country", OrderDetail.ObjBillingAddressInfo.Country);
            objInf.Add("x_phone", OrderDetail.ObjBillingAddressInfo.Phone);
            objInf.Add("x_fax", OrderDetail.ObjBillingAddressInfo.Fax);
            objInf.Add("x_email_customer", OrderDetail.ObjOrderDetails.IsEmailCustomer);

            if (OrderDetail.ObjOrderDetails.IsMultipleCheckOut == false)
            {
                //shipping address
                objInf.Add("x_ship_to_first_name", OrderDetail.ObjShippingAddressInfo.FirstName);
                objInf.Add("x_ship_to_last_name", OrderDetail.ObjShippingAddressInfo.LastName);
                objInf.Add("x_ship_to_company", OrderDetail.ObjShippingAddressInfo.CompanyName);
                objInf.Add("x_ship_to_address", OrderDetail.ObjShippingAddressInfo.Address);
                objInf.Add("x_ship_to_city", OrderDetail.ObjShippingAddressInfo.City);
                objInf.Add("x_ship_to_state", OrderDetail.ObjShippingAddressInfo.State);
                objInf.Add("x_ship_to_zip", OrderDetail.ObjShippingAddressInfo.Zip);
                objInf.Add("x_ship_to_country", OrderDetail.ObjShippingAddressInfo.Country);
            }
            // Card Details
            objInf.Add("x_card_num", OrderDetail.ObjPaymentInfo.CardNumber);
            objInf.Add("x_card_type", OrderDetail.ObjPaymentInfo.CardType);
            objInf.Add("x_exp_date", OrderDetail.ObjPaymentInfo.ExpireDate);

            var ssc = new StoreSettingConfig();
            double rate;
            string mainCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, OrderDetail.ObjCommonInfo.StoreID, OrderDetail.ObjCommonInfo.PortalID, OrderDetail.ObjCommonInfo.CultureName);
            const string gateWayCurrency = "USD";
            AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
            aspxCommonObj.CustomerID = OrderDetail.ObjOrderDetails.CustomerID;
            aspxCommonObj.SessionCode = OrderDetail.ObjOrderDetails.SessionCode;
            aspxCommonObj.StoreID = OrderDetail.ObjCommonInfo.StoreID;
            aspxCommonObj.PortalID = OrderDetail.ObjCommonInfo.PortalID;

            if (gateWayCurrency.ToLower().Trim() == mainCurrency.ToLower().Trim())
            {
                rate = 1;
            }
            else
            {
                AspxCoreController acc = new AspxCoreController();
                rate = acc.GetCurrencyRateOnChange(aspxCommonObj, mainCurrency, gateWayCurrency.Trim(), "en-US");
            }
            //double amountTotal = double.Parse(HttpContext.Current.Session["GrandTotalAll"].ToString()) * rate;
            double amountTotal = double.Parse( CheckOutSessions.Get<Double>("GrandTotalAll", 0).ToString()) * rate;
            decimal amount = decimal.Parse(amountTotal.ToString(CultureInfo.InvariantCulture));

            //string amount = Regex.Replace(OrderDetail.ObjOrderDetails.GrandTotal.ToString("0.00"), @"[A-Z]", String.Empty);
            objInf.Add("x_amount", Math.Round(amount, 2).ToString(CultureInfo.InvariantCulture));
            objInf.Add("x_test_request", "False");
            if (OrderDetail.ObjPaymentInfo.PaymentMethodCode == "CC")
            {
                // Authorization code of the card (CCV)
                objInf.Add("x_card_code", OrderDetail.ObjPaymentInfo.CardCode.Trim());
                objInf.Add("x_method", OrderDetail.ObjPaymentInfo.PaymentMethodCode.Trim());
                objInf.Add("x_type", OrderDetail.ObjPaymentInfo.TransactionType.Trim());
                // string amount = Regex.Replace(OrderDetail.ObjOrderDetails.GrandTotal.ToString("0.00"), @"[A-Z]", String.Empty);
                // objInf.Add("x_amount", amount);
                objInf.Add("x_description", OrderDetail.ObjOrderDetails.Remarks.Trim());

            }
            else
            {
                //bank
                objInf.Add("x_bank_aba_code", OrderDetail.ObjPaymentInfo.RoutingNumber.Trim());
                objInf.Add("x_bank_acct_num", OrderDetail.ObjPaymentInfo.AccountNumber.Trim());
                objInf.Add("x_bank_acct_type", OrderDetail.ObjPaymentInfo.AccountType.Trim());
                objInf.Add("x_bank_name", OrderDetail.ObjPaymentInfo.BankName.Trim());
                objInf.Add("x_bank_acct_name", OrderDetail.ObjPaymentInfo.AccountHolderName.Trim());
                objInf.Add("x_echeck_type", OrderDetail.ObjPaymentInfo.ChequeType.Trim());
                objInf.Add("x_bank_check_number", OrderDetail.ObjPaymentInfo.ChequeNumber.Trim());
            }

            // Currency setting. Check the guide for other supported currencies
            objInf.Add("x_currency_code", OrderDetail.ObjOrderDetails.CurrencyCode.Trim());

            if (OrderDetail.ObjOrderDetails.IsTest.ToLower().Trim() == "true" || OrderDetail.ObjOrderDetails.IsTest.ToLower() == "1")
            {
                objRequest.BaseAddress = "https://test.authorize.net/gateway/transact.dll";
            }
            else
            {
                objRequest.BaseAddress = "https://secure.authorize.net/gateway/transact.dll";
            }

            try
            {
                // POST request

                byte[] objRetBytes = objRequest.UploadValues(objRequest.BaseAddress, "POST", objInf);
                string[] objRetVals = System.Text.Encoding.ASCII.GetString(objRetBytes).Split(",".ToCharArray());

                // Process Return Values
                OrderDetail.ObjOrderDetails.ResponseCode = int.Parse(objRetVals[0].Trim(char.Parse("|")));
                OrderDetail.ObjOrderDetails.ResponseReasonCode = int.Parse(objRetVals[2].Trim(char.Parse("|")));

                if (objRetVals[0].Trim(char.Parse("|")) == "1")
                {
                    // Returned Authorisation Code
                    //response.AuthorizationCode = objRetVals[4].Trim(char.Parse("|"));
                    // Returned Transaction ID
                    OrderDetail.ObjOrderDetails.TransactionID = Convert.ToString(objRetVals[6].Trim(char.Parse("|")));
                    strError = "Transaction completed successfully.";

                    AspxCoreController acc = new AspxCoreController();
                    OrderDetail.ObjOrderDetails.OrderStatusID = 8;
                    OrderDetail.ObjOrderDetails.TransactionID = Convert.ToString(objRetVals[6].Trim(char.Parse("|")));
                    acc.AddOrderDetails(OrderDetail);
                    HttpContext.Current.Session["TransDetailsAIM"] = OrderDetail.ObjOrderDetails.InvoiceNumber + "#" + OrderDetail.ObjOrderDetails.TransactionID + "#" + "AIM Authorize.Net";
                    if (HttpContext.Current.Session["OrderCollection"] != null)
                    {

                        OrderDetailsCollection orderdata2 = new OrderDetailsCollection();
                        if (HttpContext.Current.Session["OrderCollection"] != null)
                        {
                            orderdata2 = (OrderDetailsCollection)HttpContext.Current.Session["OrderCollection"];

                        }

                        AspxOrderController.UpdateItemQuantity(orderdata2);
                        AspxGiftCardController.IssueGiftCard(orderdata2.LstOrderItemsInfo, orderdata2.ObjOrderDetails.OrderID, true, aspxCommonObj);
                        if (orderdata2.GiftCardDetail != null && HttpContext.Current.Session["UsedGiftCard"] != null)
                        {   //updating giftcard used in chekout
                            AspxGiftCardController.UpdateGiftCardUsage(orderdata2.GiftCardDetail, orderdata2.ObjCommonInfo.StoreID,
                                                 orderdata2.ObjCommonInfo.PortalID, orderdata2.ObjOrderDetails.OrderID, orderdata2.ObjCommonInfo.AddedBy,
                                                 orderdata2.ObjCommonInfo.CultureName);
                            HttpContext.Current.Session.Remove("UsedGiftCard");
                        }

                        var tinfo = new TransactionLogInfo();
                        var tlog = new TransactionLog();

                        tinfo.TransactionID = OrderDetail.ObjOrderDetails.TransactionID;
                        tinfo.AuthCode = objRetVals[4].Trim(char.Parse("|"));//auth Code
                        tinfo.TotalAmount = OrderDetail.ObjOrderDetails.GrandTotal;
                        tinfo.ResponseCode = "1";
                        tinfo.ResponseReasonText = strError;
                        tinfo.OrderID = orderdata2.ObjOrderDetails.OrderID;
                        tinfo.StoreID = OrderDetail.ObjCommonInfo.StoreID;
                        tinfo.PortalID = OrderDetail.ObjCommonInfo.PortalID;
                        tinfo.AddedBy = OrderDetail.ObjCommonInfo.AddedBy;
                        tinfo.CustomerID = OrderDetail.ObjOrderDetails.CustomerID;
                        tinfo.SessionCode = OrderDetail.ObjOrderDetails.SessionCode;
                        tinfo.PaymentGatewayID = OrderDetail.ObjOrderDetails.PaymentGatewayTypeID;
                        tinfo.PaymentStatus = "Processed";
                        tinfo.PayerEmail = OrderDetail.ObjBillingAddressInfo.EmailAddress;
                        tinfo.CreditCard = OrderDetail.ObjPaymentInfo.CardNumber;
                        tinfo.CurrencyCode = gateWayCurrency.Trim();
                        tlog.SaveTransactionLog(tinfo);
                    }

                    var cms = new AspxCommerce.Core.CartManageSQLProvider();
                    cms.ClearCartAfterPayment(aspxCommonObj);

                    // StoreSettingConfig ssc = new StoreSettingConfig();
                    string sendEmailFrom = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailsFrom, OrderDetail.ObjCommonInfo.StoreID, OrderDetail.ObjCommonInfo.PortalID, OrderDetail.ObjCommonInfo.CultureName);
                    string sendOrderNotice = ssc.GetStoreSettingsByKey(StoreSetting.SendOrderNotification, OrderDetail.ObjCommonInfo.StoreID, OrderDetail.ObjCommonInfo.PortalID, OrderDetail.ObjCommonInfo.CultureName);

                    if (sendOrderNotice.ToLower() == "true")
                    {
                        try
                        {
                            EmailTemplate.SendEmailForOrder(OrderDetail.ObjCommonInfo.PortalID, OrderDetail, addressPath,
                                                            TemplateName, OrderDetail.ObjOrderDetails.TransactionID);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    acc.ClearSessionVariable("OrderCollection");
                    CheckOutHelper cHelper = new CheckOutHelper();
                    cHelper.ClearSessions();
                }
                else
                {
                    // Error!
                    strError = objRetVals[3].Trim(char.Parse("|")) + " (" +
                               objRetVals[2].Trim(char.Parse("|")) + ")";

                    if (objRetVals[2].Trim(char.Parse("|")) == "44")
                    {
                        // CCV transaction decline
                        strError += "Our Card Code Verification (CCV) returned " +
                                    "the following error: ";

                        switch (objRetVals[38].Trim(char.Parse("|")))
                        {
                            case "N":
                                strError += "Card Code does not match.";
                                break;
                            case "P":
                                strError += "Card Code was not processed.";
                                break;
                            case "S":
                                strError += "Card Code should be on card but was not indicated.";
                                break;
                            case "U":
                                strError += "Issuer was not certified for Card Code.";
                                break;
                        }
                    }

                    if (objRetVals[2].Trim(char.Parse("|")) == "45")
                    {
                        if (strError.Length > 1)
                            strError += "<br />n";

                        // AVS transaction decline
                        strError += "Our Address Verification System (AVS) " +
                                    "returned the following error: ";

                        switch (objRetVals[5].Trim(char.Parse("|")))
                        {
                            case "A":
                                strError += " the zip code entered does not match " +
                                            "the billing address.";
                                break;
                            case "B":
                                strError += " no information was provided for the AVS check.";
                                break;
                            case "E":
                                strError += " a general error occurred in the AVS system.";
                                break;
                            case "G":
                                strError += " the credit card was issued by a non-US bank.";
                                break;
                            case "N":
                                strError += " neither the entered street address nor zip " +
                                            "code matches the billing address.";
                                break;
                            case "P":
                                strError += " AVS is not applicable for this transaction.";
                                break;
                            case "R":
                                strError += " please retry the transaction; the AVS system " +
                                            "was unavailable or timed out.";
                                break;
                            case "S":
                                strError += " the AVS service is not supported by your " +
                                            "credit card issuer.";
                                break;
                            case "U":
                                strError += " address information is unavailable for the " +
                                            "credit card.";
                                break;
                            case "W":
                                strError += " the 9 digit zip code matches, but the " +
                                            "street address does not.";
                                break;
                            case "Z":
                                strError += " the zip code matches, but the address does not.";
                                break;
                        }
                    }
                    var tinfo = new TransactionLogInfo();
                    var tlog = new TransactionLog();

                    tinfo.TransactionID = "";
                    tinfo.AuthCode = objRetVals[4].Trim(char.Parse("|"));//auth Code
                    tinfo.TotalAmount = amount;
                    tinfo.ResponseCode = objRetVals[2].Trim(char.Parse("|"));
                    tinfo.ResponseReasonText = strError;
                    tinfo.OrderID = OrderDetail.ObjOrderDetails.OrderID;
                    tinfo.StoreID = OrderDetail.ObjCommonInfo.StoreID;
                    tinfo.PortalID = OrderDetail.ObjCommonInfo.PortalID;
                    tinfo.AddedBy = OrderDetail.ObjCommonInfo.AddedBy;
                    tinfo.CustomerID = OrderDetail.ObjOrderDetails.CustomerID;
                    tinfo.SessionCode = OrderDetail.ObjOrderDetails.SessionCode;
                    tinfo.PaymentGatewayID = OrderDetail.ObjOrderDetails.PaymentGatewayTypeID;
                    tinfo.PaymentStatus = "Failed";
                    tinfo.PayerEmail = OrderDetail.ObjBillingAddressInfo.EmailAddress;
                    tinfo.CreditCard = OrderDetail.ObjPaymentInfo.CardNumber;
                    tinfo.CurrencyCode = gateWayCurrency.Trim();
                    tlog.SaveTransactionLog(tinfo);
                }
            }
            catch (Exception ex)
            {
                strError = ex.Message;
            }
            OrderDetail.ObjOrderDetails.ResponseReasonText = strError;
            return OrderDetail.ObjOrderDetails.ResponseReasonText;
        }

        public List<AuthorizeNetAIM.CardType> GetCardType(AspxCommonInfo aspxCommonObj)
        {
            try
            {
                var paraMeter = new List<KeyValuePair<string, object>>();
                paraMeter.Add(new KeyValuePair<string, object>("@StoreID", aspxCommonObj.StoreID));
                paraMeter.Add(new KeyValuePair<string, object>("@PortalID", aspxCommonObj.PortalID));
                paraMeter.Add(new KeyValuePair<string, object>("@CultureName", aspxCommonObj.CultureName));
                var sqlH = new SQLHandler();
                return sqlH.ExecuteAsList<AuthorizeNetAIM.CardType>("usp_Aspx_GetCardType", paraMeter);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<AuthorizeNetAIM.TransactionType> GetTransactionType(AspxCommonInfo aspxCommonObj)
        {
            try
            {
                var paraMeter = new List<KeyValuePair<string, object>>();
                paraMeter.Add(new KeyValuePair<string, object>("@StoreID", aspxCommonObj.StoreID));
                paraMeter.Add(new KeyValuePair<string, object>("@PortalID", aspxCommonObj.PortalID));
                paraMeter.Add(new KeyValuePair<string, object>("@CultureName", aspxCommonObj.CultureName));
                var sqlH = new SQLHandler();
                return sqlH.ExecuteAsList<AuthorizeNetAIM.TransactionType>("usp_Aspx_GetTransactionType", paraMeter);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


text:
<meta>
	<info name="Achievement System" author="BinSlayer" version="1.0" description="Adds challenges to accomplish." type="script" addon="race" />
	<script src="achievements_server.lua" type="server" />
	<script src="achievements_client.lua" type="client" protected="true"/>
	<export function="addPlayerAchievement" type="server"/>
</meta>


text:
import copy
import datetime
import json
import random
import string

import webob
import webob.dec
from paste import urlmap

from glance import client as glance_client
from glance.common import exception as glance_exc

from nova import context
from nova import exception as exc
from nova import flags
from nova import utils
import nova.api.openstack.auth
from nova.api import openstack
from nova.api.openstack import auth
from nova.api.openstack import versions
from nova.api.openstack import limits
from nova.auth.manager import User, Project
from nova.image import glance
from nova.image import local
from nova.image import service
from nova.tests import fake_flags
from nova.wsgi import Router

class Context(object):
    pass

class FakeRouter(Router):
    def __init__(self):
        pass

    @webob.dec.wsgify
    def __call__(self, req):
        res = webob.Response()
        res.status = '200'
        res.headers['X-Test-Success'] = 'True'
        return res

def fake_auth_init(self, application):
    self.db = FakeAuthDatabase()
    self.context = Context()
    self.auth = FakeAuthManager()
    self.application = application

@webob.dec.wsgify
def fake_wsgi(self, req):
    req.environ['nova.context'] = context.RequestContext(1, 1)
    return self.application

def wsgi_app(inner_app10=None, inner_app11=None):
    if not inner_app10:
        inner_app10 = openstack.APIRouterV10()
    if not inner_app11:
        inner_app11 = openstack.APIRouterV11()
    mapper = urlmap.URLMap()
    api10 = openstack.FaultWrapper(auth.AuthMiddleware(
              limits.RateLimitingMiddleware(inner_app10)))
    api11 = openstack.FaultWrapper(auth.AuthMiddleware(
              limits.RateLimitingMiddleware(inner_app11)))
    mapper['/v1.0'] = api10
    mapper['/v1.1'] = api11
    mapper['/'] = openstack.FaultWrapper(versions.Versions())
    return mapper

def stub_out_key_pair_funcs(stubs, have_key_pair=True):
    def key_pair(context, user_id):
        return [dict(name='key', public_key='public_key')]

    def no_key_pair(context, user_id):
        return []

    if have_key_pair:
        stubs.Set(nova.db, 'key_pair_get_all_by_user', key_pair)
    else:
        stubs.Set(nova.db, 'key_pair_get_all_by_user', no_key_pair)

def stub_out_image_service(stubs):
    def fake_image_show(meh, context, id):
        return dict(kernelId=1, ramdiskId=1)

    stubs.Set(local.LocalImageService, 'show', fake_image_show)

def stub_out_auth(stubs):
    def fake_auth_init(self, app):
        self.application = app

    stubs.Set(nova.api.openstack.auth.AuthMiddleware,
        '__init__', fake_auth_init)
    stubs.Set(nova.api.openstack.auth.AuthMiddleware,
        '__call__', fake_wsgi)

def stub_out_rate_limiting(stubs):
    def fake_rate_init(self, app):
        super(limits.RateLimitingMiddleware, self).__init__(app)
        self.application = app

    stubs.Set(nova.api.openstack.limits.RateLimitingMiddleware,
        '__init__', fake_rate_init)

    stubs.Set(nova.api.openstack.limits.RateLimitingMiddleware,
        '__call__', fake_wsgi)

def stub_out_networking(stubs):
    def get_my_ip():
        return '127.0.0.1'
    stubs.Set(nova.flags, '_get_my_ip', get_my_ip)

def stub_out_compute_api_snapshot(stubs):
    def snapshot(self, context, instance_id, name):
        return 123
    stubs.Set(nova.compute.API, 'snapshot', snapshot)

def stub_out_glance_add_image(stubs, sent_to_glance):
    """
    We return the metadata sent to glance by modifying the sent_to_glance dict
    in place.
    """
    orig_add_image = glance_client.Client.add_image

    def fake_add_image(context, metadata, data=None):
        sent_to_glance['metadata'] = metadata
        sent_to_glance['data'] = data
        return orig_add_image(metadata, data)

    stubs.Set(glance_client.Client, 'add_image', fake_add_image)

def stub_out_glance(stubs, initial_fixtures=None):

    class FakeGlanceClient:

        def __init__(self, initial_fixtures):
            self.fixtures = initial_fixtures or []

        def fake_get_images(self):
            return [dict(id=f['id'], name=f['name'])
                    for f in self.fixtures]

        def fake_get_images_detailed(self):
            return copy.deepcopy(self.fixtures)

        def fake_get_image_meta(self, image_id):
            image = self._find_image(image_id)
            if image:
                return copy.deepcopy(image)
            raise glance_exc.NotFound

        def fake_add_image(self, image_meta, data=None):
            image_meta = copy.deepcopy(image_meta)
            image_id = ''.join(random.choice(string.letters)
                               for _ in range(20))
            image_meta['id'] = image_id
            self.fixtures.append(image_meta)
            return copy.deepcopy(image_meta)

        def fake_update_image(self, image_id, image_meta, data=None):
            for attr in ('created_at', 'updated_at', 'deleted_at', 'deleted'):
                if attr in image_meta:
                    del image_meta[attr]

            f = self._find_image(image_id)
            if not f:
                raise glance_exc.NotFound

            f.update(image_meta)
            return copy.deepcopy(f)

        def fake_delete_image(self, image_id):
            f = self._find_image(image_id)
            if not f:
                raise glance_exc.NotFound

            self.fixtures.remove(f)

        def _find_image(self, image_id):
            for f in self.fixtures:
                if f['id'] == image_id:
                    return f
            return None

    GlanceClient = glance_client.Client
    fake = FakeGlanceClient(initial_fixtures)

    stubs.Set(GlanceClient, 'get_images', fake.fake_get_images)
    stubs.Set(GlanceClient, 'get_images_detailed',
              fake.fake_get_images_detailed)
    stubs.Set(GlanceClient, 'get_image_meta', fake.fake_get_image_meta)
    stubs.Set(GlanceClient, 'add_image', fake.fake_add_image)
    stubs.Set(GlanceClient, 'update_image', fake.fake_update_image)
    stubs.Set(GlanceClient, 'delete_image', fake.fake_delete_image)

class FakeToken(object):
    # FIXME(sirp): let's not use id here
    id = 0

    def __init__(self, **kwargs):
        FakeToken.id += 1
        self.id = FakeToken.id
        for k, v in kwargs.iteritems():
            setattr(self, k, v)

class FakeRequestContext(object):
    def __init__(self, user, project, *args, **kwargs):
        self.user_id = 1
        self.project_id = 1

class FakeAuthDatabase(object):
    data = {}

    @staticmethod
    def auth_token_get(context, token_hash):
        return FakeAuthDatabase.data.get(token_hash, None)

    @staticmethod
    def auth_token_create(context, token):
        fake_token = FakeToken(created_at=datetime.datetime.now(), **token)
        FakeAuthDatabase.data[fake_token.token_hash] = fake_token
        FakeAuthDatabase.data['id_%i' % fake_token.id] = fake_token
        return fake_token

    @staticmethod
    def auth_token_destroy(context, token_id):
        token = FakeAuthDatabase.data.get('id_%i' % token_id)
        if token and token.token_hash in FakeAuthDatabase.data:
            del FakeAuthDatabase.data[token.token_hash]
            del FakeAuthDatabase.data['id_%i' % token_id]

class FakeAuthManager(object):
    #NOTE(justinsb): Accessing static variables through instances is FUBAR
    #NOTE(justinsb): This should also be private!
    auth_data = []
    projects = {}

    @classmethod
    def clear_fakes(cls):
        cls.auth_data = []
        cls.projects = {}

    @classmethod
    def reset_fake_data(cls):
        u1 = User('id1', 'guy1', 'acc1', 'secret1', False)
        cls.auth_data = [u1]
        cls.projects = dict(testacct=Project('testacct',
                                             'testacct',
                                             'id1',
                                             'test',
                                              []))

    def add_user(self, user):
        FakeAuthManager.auth_data.append(user)

    def get_users(self):
        return FakeAuthManager.auth_data

    def get_user(self, uid):
        for user in FakeAuthManager.auth_data:
            if user.id == uid:
                return user
        return None

    def get_user_from_access_key(self, key):
        for user in FakeAuthManager.auth_data:
            if user.access == key:
                return user
        return None

    def delete_user(self, uid):
        for user in FakeAuthManager.auth_data:
            if user.id == uid:
                FakeAuthManager.auth_data.remove(user)
        return None

    def create_user(self, name, access=None, secret=None, admin=False):
        u = User(name, name, access, secret, admin)
        FakeAuthManager.auth_data.append(u)
        return u

    def modify_user(self, user_id, access=None, secret=None, admin=None):
        user = self.get_user(user_id)
        if user:
            user.access = access
            user.secret = secret
            if admin is not None:
                user.admin = admin

    def is_admin(self, user):
        return user.admin

    def is_project_member(self, user, project):
        return ((user.id in project.member_ids) or
                (user.id == project.project_manager_id))

    def create_project(self, name, manager_user, description=None,
                       member_users=None):
        member_ids = [User.safe_id(m) for m in member_users] \
                     if member_users else []
        p = Project(name, name, User.safe_id(manager_user),
                                 description, member_ids)
        FakeAuthManager.projects[name] = p
        return p

    def delete_project(self, pid):
        if pid in FakeAuthManager.projects:
            del FakeAuthManager.projects[pid]

    def modify_project(self, project, manager_user=None, description=None):
        p = FakeAuthManager.projects.get(project)
        p.project_manager_id = User.safe_id(manager_user)
        p.description = description

    def get_project(self, pid):
        p = FakeAuthManager.projects.get(pid)
        if p:
            return p
        else:
            raise exc.NotFound

    def get_projects(self, user=None):
        if not user:
            return FakeAuthManager.projects.values()
        else:
            return [p for p in FakeAuthManager.projects.values()
                    if (user.id in p.member_ids) or
                       (user.id == p.project_manager_id)]

class FakeRateLimiter(object):
    def __init__(self, application):
        self.application = application

    @webob.dec.wsgify
    def __call__(self, req):
        return self.application


text:
FactoryGirl.define do
  factory :binary_blob do
  end
end


text:
package org.appng.tools.image;

import java.io.File;

/**
 * @author herlitzius.matthias
 */
public class ImageMetaData {

	private final File file;
	private final int width;
	private final int height;

	public ImageMetaData(File file, int width, int height) {
		this.file = file;
		this.width = width;
		this.height = height;
	}

	public File getFile() {
		return file;
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public long getFileSize() {
		return file.length();
	}

	public String toString() {
		return file + " (" + width + "x" + height + ", " + getFileSize() + " bytes)";
	}
}


text:
"""
#
# Authors:
# OsChina:
# Purpose:
# Install:
#
"""

import time
import socket
import httplib
import json
import pprint
import sys
import re
import os

# 当前目录下存在filename文件则删除,不存在则创建空文件
def file_path(filename):
    filename = os.path.join(os.getcwd(), filename)  # 只连接
    if os.path.exists(filename):
        os.remove(filename)
        os.mknod(filename)
    else:
        os.mknod(filename)
    return filename

# 通过域名获取ip
def get_ip_by_domain(server_domain):
    ips_list = []
    try:
        results = socket.getaddrinfo(server_domain, None)
    except socket.error, e:
        return 1, server_domain + ': %s' % e
    for ipaddr in results:
        ips_list.append(ipaddr[4][0])
        # pprint.pprint(ipaddr[4][0])
    return 0, ips_list[0]

def device_auth_status(host, port, **kwargs):
    # 1. 建立连接
    try:
        conn = httplib.HTTPConnection(host, port)
    except socket.error, e:
        return 1, 'Connected auth server failed: %s' % e

    body = {
        'AuthProtocol': {
            'Header': {
                'Version': '1.0',
                'CSeq': '1',
                'MessageType': 'MSG_AUTH_CODE_QUERY_REQ',
            },
            'Body': {
                'UserName': 'test',
                'SecretKey': '123456',
                'SerialNumber': '%s' % kwargs['SerialNumber'],
                'Attitude': 'Read',
            }
        }
    }
    body = json.dumps(body)     # json 编码
    header = {
        'Host': host,
        'Port': port,
    }
    # 2. 发送POST请求
    try:
        conn.request('POST', '/ ', body, headers=header)
    except socket.error, e:
        return 1, 'auth request failed: %s' % e
    # 3. 获取响应参数
    try:
        resp = conn.getresponse()
    except socket.error, e:
        return 1, 'auth getresponse failed: %s' % e
    # 4. 正确返回时对结果进行解码操作
    if resp.status == 200:
        resp_body = json.loads(resp.read())     # json 解码
        if resp_body['AuthProtocol']['Header']['ErrorNum'] == u'200':   # u表示Unicode字符串
            print ('AuthCode: ' + resp_body['AuthProtocol']['Body']['AuthCode'])
            return 0, resp_body['AuthProtocol']['Body']['AuthCode']
        else:
            return 1, 'AuthCode: ' + resp_body['AuthProtocol']['Header']['ErrorString']
    else:
        return 1, 'getresponse status: %s' % resp.status

def chk_device_status(host, port, **kwargs):
    # host, port = dss['status']
    try:
        conn = httplib.HTTPConnection(host, port)
    except socket.error, e:
        return 1, 'Connected status server failed: %s' % e
    body = {
        'StatusProtocol': {
            'Header': {
                'Version': '1.0',
                'CSeq': '1',
                'MessageType': 'MSG_STATUS_MULTIQUERY_REQ',
            },
            'Body': [{
                'SerialNumber': '%s' % kwargs['SerialNumber'],
                'AuthCode': '%s' % kwargs['AuthCode'],
            },
            ]
        }
    }
    body = json.dumps(body)
    head = {'Host': host, 'Port': port}
    try:
        conn.request('POST', '/ ', body, head)
    except socket.error, e:
        return 1, 'client check device status request with error: %s' % e
    try:
        resp = conn.getresponse()
    except socket.error, e:
        return 1, 'client check device status response with error: %s' % e
    if resp.status == 200:
        try:
            data = json.loads(resp.read())
        except ValueError, e:
            return 1, 'client check device status response not json: %s' % e
        errnum = data['StatusProtocol']['Header']['ErrorNum']
        if errnum == u'200':
            print ('Device Status: ' + data['StatusProtocol']['Body'][0]['Status'])
            return 0, ''
        return 1, data['StatusProtocol']['Header']['ErrorString']
    else:
        return 1, 'status getresponse: '.join(resp.status)

# 发送开始数据
def send_start_stream(host, port, **kwargs):
    try:
        conn = httplib.HTTPConnection(host, port)
    except socket.error, e:
        return 1, 'Connected pub server failed: %s' % e

    head = {'Host': host, 'Port': port}
    try:
        conn.request('GET', '/hls/%s/%s/1_1.m3u8' % (kwargs['AuthCode'], kwargs['SerialNumber']), headers=head)
    except socket.error, e:
        return 1, 'client request pub for start stream with error: %s' % e
    try:
        resp = conn.getresponse()
    except socket.error, e:
        return 1, 'client request pub get response with error: %s' % e
    sdata = resp.read()
    status = resp.status
    if status == 200:
        match = re.search('(?<=http://)([^:]+):([^/]+)(?=/.*)', sdata)
        dssstream = match.groups()
        dssstream = (dssstream[0], int(dssstream[1]))
        return 0, '', dssstream[0], dssstream[1]
    else:
        return 1, 'send start stream failed: ' + status

def client_receive(host, port, **kwargs):
    try:
        conn = httplib.HTTPConnection(host, port)
    except socket.error, e:
        return 1, 'Connected stream server failed: %s' % e
    head = {'Host': host, 'Port': port}
    for k in range(0, 5, 1):
        agent = {'User-Agent': 'XAPP'}
        head.update(agent)
        if k > 0:
            match = {'If-None-Match': '%s' % etag}
            head.update(match)
        try:
            conn.request('GET', '/download/%s/%s/1.ts' % (kwargs['AuthCode'], kwargs['SerialNumber']), headers=head)
        except socket.error, e:
            return 1, 'device download to stream with error%s: %s' % (k, e)
        try:
            resp = conn.getresponse()
        except socket.error, e:
            return 1, 'device download to stream get response with error%s: %s' % (k, e)
        data = resp.read()
        status = resp.status
        if status == 200:
            etag = resp.getheaders()[5][1]
            f_down = open(file_path('dss_download_%s.ts' % k), 'w')
            f_down.write(data)
            f_down.close()
            print 'file%s: Download successful!' % k
            time.sleep(1)
        elif status == 304:
            if k < 4:
                print 'file%s: 304' % k
                time.sleep(1)
                continue
            return 1, 'file%s: 304' % k
        else:
            return 1, status
    return 0, ''

def service_debug_dss_status(add_data=None):
    exec_ret_dicts = {
        'status': 0,
        'target': 0,
        'errors': ''
        }
    num = 0
    while True:
        serial = raw_input('Please input your serialnumber: ')
        if len(serial) == 16:
            break
        print 'Error SerialNumber!' + os.linesep
        num += 1
        if num > 2:
            print 'Sorry!You are a thief.About to exit!!!'
            time.sleep(5)
            return 'Goodbye!'
        continue
    auth_server_port = 9901
    auth_server_domain = 'auth-dss.secu100.net'
    status_server_domain = 'status-dss.secu100.net'
    status_server_port = 7701
    pub_server_domain = 'pub-dss-hls.secu100.net'
    pub_server_port = 8080
    SerialNumber = serial
    res_domain = get_ip_by_domain(auth_server_domain)
    if res_domain[0] != 0:
        exec_ret_dicts.update({
            'status': res_domain[0],
            'target': res_domain[0],
            'errors': res_domain[1]
        })
        return exec_ret_dicts
    res_auth = device_auth_status(res_domain[1], auth_server_port,
                                  SerialNumber=SerialNumber)
    if res_auth[0] != 0:
        exec_ret_dicts.update({
            'status': res_auth[0],
            'target': res_auth[0],
            'errors': res_auth[1]
        })
        return exec_ret_dicts
    res_domain = get_ip_by_domain(status_server_domain)
    if res_domain[0] != 0:
        exec_ret_dicts.update({
            'status': res_domain[0],
            'target': res_domain[0],
            'errors': res_domain[1]
        })
        return exec_ret_dicts
    res_chk = chk_device_status(res_domain[1], status_server_port,
                                SerialNumber=SerialNumber, AuthCode=res_auth[1])
    if res_chk[0] != 0:
        exec_ret_dicts.update({
            'status': res_chk[0],
            'target': res_chk[0],
            'errors': res_chk[1]
        })
        return exec_ret_dicts
    res_domain = get_ip_by_domain(pub_server_domain)
    if res_domain[0] != 0:
        exec_ret_dicts.update({
            'status': res_domain[0],
            'target': res_domain[0],
            'errors': res_domain[1]
        })
        return exec_ret_dicts
    print 'start stream!'
    res_sta = send_start_stream(res_domain[1], pub_server_port,
                                SerialNumber=SerialNumber, AuthCode=res_auth[1])
    if res_sta[0] != 0:
        exec_ret_dicts.update({
            'status': res_sta[0],
            'target': res_sta[0],
            'errors': res_sta[1]
        })
        return exec_ret_dicts
    print 'start download!'
    res_down = client_receive(res_sta[2], res_sta[3],
                              SerialNumber=SerialNumber, AuthCode=res_auth[1])
    if res_down[0] != 0:
        exec_ret_dicts.update({
            'status': res_down[0],
            'target': res_down[0],
            'errors': res_down[1]
        })
        return exec_ret_dicts
    return exec_ret_dicts

if __name__ == '__main__':
    pprint.pprint(service_debug_dss_status())
    # while True:
    #     file_log = os.getcwd() + '/test.log'
    #     f_log = open(file_log, 'a')
    # # for i in range(1, len(sys.argv)):
    #     print ('SerialNumber: ' + serial)
    #     res_log = service_debug_dss_status(serial)
    #     f_log.write(time.ctime() + ' ' + json.dumps(res_log) + os.linesep)
    #     f_log.close()
    #     time.sleep(300)


text:
<!--
   This file is part of the X12Parser library that provides tools to
   manipulate X12 messages using Ruby native syntax.

   http://x12parser.rubyforge.org

   Copyright (C) 2009 APP Design, Inc.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library 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 the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

   $Id: CBS.xml 78 2009-05-12 22:27:26Z ikk $
-->

<Segment name="CBS" comment="To identify and quantify each line item being proposed">
  <Field name="AssignedIdentification" min="1" max="20" comment="Alphanumeric characters assigned for differentiation within a transaction set"/>
  <Field name="Quantity" type="double" min="1" max="15" comment="Numeric value of quantity"/>
  <Field name="CompositeUnitOfMeasure" type="C001" min="0" max="inf" comment="To identify a composite unit of measure (See Figures Appendix for examples of use)"/>
</Segment>


text:
class AddPublicToAlbum < ActiveRecord::Migration
  def change
    add_column :albums, :public, :boolean
  end
end


text:
package com.swip.api.lang.environment;

import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.swip.api.lang.ApplicationException;
import com.swip.api.lang.Element;
import com.swip.api.lang.Properties;

/**
 * A key-valued collection of properties defining the environment.
 *
 * The attributes of the extended {@link Element} class holds the Environment's
 * meta information.
 *
 * An environment has the capability of translating a whole String by replacing
 * any present environment-keys into its value. See {@link #translate(String)}.
 *
 * @author Otávio Biasutti
 */
public interface Environment extends Properties, Element {

	String DEFAULT_KEY_SEPARATOR = ".";

	/**
	 * Placeholder representation of the key. Default implementation uses the
	 * "${key}" format.
	 *
	 * @param key
	 *            the key to be transformed
	 * @return transforms the key to a placeholder to be used inside messages.
	 */
	default String toPlaceholder(final String key) {

		if (key != null) {

			return "${" + key.trim() + "}";
		}

		throw new ApplicationException("The placeholder's key cannot be empty");
	}

	/**
	 * Translates the message by replacing recursively any key present by its
	 * value.
	 *
	 * @param message
	 *            the message to be translated
	 * @return the message translated by this environment.
	 */
	default String translate(final String message) {

		if (message != null) {

			if (this.toKeyValueMap() == null || this.toKeyValueMap().isEmpty()) {

				throw new ApplicationException(
						"No properties in environment [" + this + "] to translate the message [" + message + "].");
			}

			String result = message;

			for (final Entry<String, String> entry : this.toKeyValueMap().entrySet()) {

				result = result.replaceAll(Pattern.quote(toPlaceholder(entry.getKey())),
						Matcher.quoteReplacement(entry.getValue()));
			}

			if (message.equals(result)) {

				return result;
			}

			return translate(result);
		}

		return null;
	}
}


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

    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>
	<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
	<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>

    <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
      	<encoder>
			<pattern>${FILE_LOG_PATTERN}</pattern>
        </encoder>
        <file>${LOG_FILE}</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">

            <!-- daily rollover -->
            <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <maxFileSize>100MB</maxFileSize>
            <maxHistory>60</maxHistory>
            <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>
    </appender>

    <root level="INFO">
		<appender-ref ref="CONSOLE"/>
		<appender-ref ref="ROLLING"/>
	</root>

</configuration>


text:
<?php declare(strict_types=1);

namespace DrdPlus\Tests\Skills;

use DrdPlus\Person\ProfessionLevels\ProfessionFirstLevel;
use DrdPlus\Person\ProfessionLevels\ProfessionLevel;
use DrdPlus\Skills\Skill;
use DrdPlus\Skills\SkillPoint;
use DrdPlus\Skills\SkillRank;
use Granam\Integer\PositiveInteger;
use Mockery\MockInterface;
use Granam\TestWithMockery\TestWithMockery;

abstract class SkillRankTest extends TestWithMockery
{

    /**
     * @test
     * @dataProvider provideAllowedSkillRankValues
     * @param int $skillRankValue
     */
    public function I_can_create_skill_rank($skillRankValue)
    {
        $sutClass = self::getSutClass();
        /** @var SkillRank $skillRank */
        $skillRank = new $sutClass(
            $this->createOwningSkill(),
            $skillPoint = $this->createSkillPoint($skillRankValue > 0 ? 1 : 0),
            $this->createRequiredRankValue($skillRankValue)
        );

        self::assertSame($skillRankValue, $skillRank->getValue());
        self::assertSame((string)$skillRankValue, (string)$skillRank);
        self::assertSame($skillPoint->getProfessionLevel(), $skillRank->getProfessionLevel());
        self::assertSame($skillPoint, $skillRank->getSkillPoint());
    }

    public function provideAllowedSkillRankValues()
    {
        return [[0], [1], [2], [3]];
    }

    abstract protected function createOwningSkill(): Skill;

    protected function addProfessionLevelGetter(MockInterface $mock)
    {
        $mock->shouldReceive('getProfessionLevel')
            ->andReturn($this->mockery(ProfessionLevel::class));
    }

    /**
     * @return MockInterface|ProfessionFirstLevel
     */
    protected function createProfessionFirstLevel()
    {
        return $this->mockery(ProfessionFirstLevel::class);
    }

    /**
     * @test
     */
    public function I_can_not_create_negative_skill_rank()
    {
        $this->expectException(\LogicException::class);
        /** @var SkillRank $sutClass */
        $sutClass = self::getSutClass();
        new $sutClass(
            $this->createOwningSkill(),
            $this->createSkillPoint(0),
            $this->createRequiredRankValue(-1)
        );
    }

    /**
     * @test
     */
    public function I_can_not_create_skill_rank_with_value_of_four()
    {
        $this->expectException(\LogicException::class);
        $sutClass = self::getSutClass();
        new $sutClass(
            $this->createOwningSkill(),
            $this->createSkillPoint(1),
            $this->createRequiredRankValue(4)
        );
    }

    /**
     * @param $value
     * @return \Mockery\MockInterface|SkillPoint
     */
    abstract protected function createSkillPoint($value = null);

    /**
     * @param int $value
     * @return \Mockery\MockInterface|PositiveInteger
     */
    private function createRequiredRankValue($value)
    {
        $requiredRankValue = $this->mockery(PositiveInteger::class);
        $requiredRankValue->shouldReceive('getValue')
            ->atLeast()->once()
            ->andReturn($value);

        return $requiredRankValue;
    }

    /**
     * @test
     */
    public function Skill_has_to_be_set_in_descendant_constructor_first()
    {
        $this->expectException(\DrdPlus\Skills\Exceptions\CanNotVerifyOwningSkill::class);
        /** @var PositiveInteger $requiredRankValue */
        $requiredRankValue = $this->mockery(PositiveInteger::class);

        new BrokenBecauseOfSkillNotSetInConstructor(
            $this->createOwningSkill(),
            $this->createSkillPoint(),
            $requiredRankValue
        );
    }

    /**
     * @test
     */
    public function Skill_point_has_to_be_set_in_descendant_constructor_first()
    {
        $this->expectException(\DrdPlus\Skills\Exceptions\CanNotVerifyPaidSkillPoint::class);
        /** @var PositiveInteger $requiredRankValue */
        $requiredRankValue = $this->mockery(PositiveInteger::class);

        new BrokenBecauseOfSkillPointNotSetInConstructor(
            $this->createOwningSkill(),
            $this->createSkillPoint(),
            $requiredRankValue
        );
    }

    /**
     * @test
     */
    public function I_can_not_pay_for_zero_skill_rank_by_non_zero_skill_point()
    {
        $this->expectException(\DrdPlus\Skills\Exceptions\WastedSkillPoint::class);
        /** @var SkillRank|string $sutClass */
        $sutClass = self::getSutClass();
        new $sutClass(
            $this->createOwningSkill(),
            $this->createSkillPoint(1),
            $this->createRequiredRankValue(0)
        );
    }
}

class BrokenBecauseOfSkillNotSetInConstructor extends SkillRank
{
    public function __construct(
        Skill $owningSkill,
        SkillPoint $skillPoint,
        PositiveInteger $requiredRankValue
    )
    {
        parent::__construct($owningSkill, $skillPoint, $requiredRankValue);
    }

    public function getSkillPoint(): SkillPoint
    {
        return \Mockery::mock(SkillPoint::class);
    }

    public function getSkill(): Skill
    {
        return \Mockery::mock(Skill::class);
    }

}

class BrokenBecauseOfSkillPointNotSetInConstructor extends SkillRank
{
    private $skill;

    public function __construct(
        Skill $owningSkill,
        SkillPoint $skillPoint,
        PositiveInteger $requiredRankValue
    )
    {
        $this->skill = $owningSkill;
        parent::__construct($owningSkill, $skillPoint, $requiredRankValue);
    }

    public function getSkillPoint(): SkillPoint
    {
        return \Mockery::mock(SkillPoint::class);
    }

    public function getSkill(): Skill
    {
        return $this->skill;
    }

}