text:
package org.openprovenance.prov.xml;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import org.openprovenance.prov.xml.builder.Equals;
import org.openprovenance.prov.xml.builder.HashCode;
import org.openprovenance.prov.xml.builder.ToString;
import org.openprovenance.prov.model.DOMProcessing;
import org.openprovenance.prov.model.QualifiedName;

/**
 *
Java class for Location complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Location">
 *   <simpleContent>
 *     <extension base="<http://www.w3.org/2001/XMLSchema>anySimpleType">
 *       <attribute name="type" type="{http://www.w3.org/2001/XMLSchema}QName" />
 *     </extension>
 *   </simpleContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Role", namespace = "http://www.w3.org/ns/prov#")
public class Label extends TypedValue implements Equals, HashCode, ToString,
	org.openprovenance.prov.model.Label,
	org.openprovenance.prov.model.Attribute {

    private static final AttributeKind PROV_LABEL_KIND = org.openprovenance.prov.model.Attribute.AttributeKind.PROV_LABEL;
    private static final QualifiedName PROV_LABEL_QualifiedName = ProvFactory.getFactory().getName().PROV_LABEL;

    @Override
    public QualifiedName getElementName() {
	return PROV_LABEL_QualifiedName;
    }

    @Override
    public AttributeKind getKind() {
	return PROV_LABEL_KIND;
    }

    @Override
    public String toNotationString() {
	return DOMProcessing.qualifiedNameToString(getElementName()) + " = "
		+ ProvUtilities.valueToNotationString(getValue(), null); //getType());
    }

}


text:
<phpunit bootstrap="vendor/autoload.php">
    <php>
        <var name="DB_DRIVER" value="pdo_cassandra" />
        <var name="DB_HOST" value="172.31.44.125" />
        <var name="DB_PORT" value="9160" />
        <var name="DB_CQLVERSION" value="3.0.0" />
        <var name="DB_USER" value="lumenaki" />
        <var name="DB_PASSWD" value="guitar" />
        <var name="DB_DBNAME" value="lumenaki" />
    </php>
    <testsuites>
        <testsuite name="CassandraPDO4Doctrine">
            <directory>tests/src</directory>
        </testsuite>
    </testsuites>

    <logging>
        <log type="coverage-html"
             target="target/report/phpunit/coverage/html/"
             lowUpperBound="35"
             highLowerBound="70"
        />
    </logging>

</phpunit>

redpajama_set_name: RedPajamaGithub


text:
using Syntaxiom.Symbols.Factories;

namespace Syntaxiom.Symbols.Parsers
{
    public class FloatSymbolParser : ISymbolParser
    {
        private readonly ISymbolFactory _symbolFactory;

        public FloatSymbolParser(ISymbolFactory symbolFactory)
        {
            _symbolFactory = symbolFactory;
        }

        public bool TryParseSymbol(string source, out ISymbol result)
        {
            result = null;

            float floatResult;
            if (!float.TryParse(source, out floatResult))
                return false;

            result = _symbolFactory.CreateConstant(floatResult);
            return true;
        }
    }
}


text:
from functools import partial
from enum import Enum
from os import rename
import subprocess

SOURCE_FILE_NAME = 'packages.txt'
OUTPUT_FILE_NAME = 'packages.results.txt'
OLD_FILE_NAME = 'packages.old.txt'

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

class PkgMinipultor:

    class Status(Enum):
        UNDECIDED = 0
        KEEP = 1
        REMOVE = 2

    def __init__(self, name):
        self.name = name
        self.rdeps = None
        self.rrdeps = None
        self.show = None
        self.status = PkgMinipultor.Status.UNDECIDED

    def has_rdeps(self):
        if self.rdeps == None:
            self.get_rdeps()

        return self.rdeps.stdout.decode('utf-8').count('\n') > 2

    def get_show_info(self):
        if self.show == None:
            self.show = subprocess.run(['apt-cache', 'show', self.name], stdout=subprocess.PIPE)

        return self.show.stdout.decode('utf-8')

    def mark_auto(self):
        term_auto = subprocess.run(['sudo', 'apt-mark', 'auto', self.name], stdout=subprocess.PIPE)
        self.mark_remove()
        return term_auto.stdout.decode('utf-8')

    def mark_keep(self):
        self.status = PkgMinipultor.Status.KEEP

    def mark_remove(self):
        self.status = PkgMinipultor.Status.REMOVE

    def get_rdeps(self):
        if self.rdeps == None:
            self.rdeps = subprocess.run(['apt', 'rdepends', '--installed', self.name], stdout=subprocess.PIPE)

        return self.rdeps.stdout.decode('utf-8')

    def get_rrdeps(self):
        if self.rrdeps == None:
            self.rrdeps = subprocess.run(['apt', 'rdepends', '--installed', '--recurse', self.name],  stdout=subprocess.PIPE)

        return self.rrdeps.stdout.decode('utf-8')

class Menu:

    def __init__(self):
        self.quit = False

    def __str__(self):
        return ("  s -> apt show package\n"
                "  p -> pass on package (do nothing)\n"
                "  h -> help\n"
                "  a -> sudo apt-make auto package\n"
                "  c -> confirm manual\n"
                "  q -> quit\n"
                "  r -> apt rdepends --installed\n"
                "  rr -> apt rdepends --installed --recurse\n")

    def handle_response(self, pkg):

        def respond_quit():
            self.quit = True

        responses = {
            'h': partial(print, str(self)),
            's': partial(print, pkg.get_show_info()),
            'r': partial(print, pkg.get_rdeps()),
            'rr': partial(print, pkg.get_rrdeps()),
            'p': pkg.mark_keep,
            'a': pkg.mark_auto,
            'c': pkg.mark_remove,
            'q': respond_quit,
        }

        while (not self.quit) and pkg.status == PkgMinipultor.Status.UNDECIDED:
            response = input(bcolors.BOLD + 'Enter a command (h for help): ' + bcolors.ENDC)

            try:
                responses[response]()
            except:
                print('Invalid response')

with open(SOURCE_FILE_NAME) as source_file, open(OUTPUT_FILE_NAME, 'w+') as output_file:
    menu = Menu()
    for line in source_file:

        pkg = PkgMinipultor(line.strip())

        if (not menu.quit) and pkg.has_rdeps():
            print(pkg.get_rdeps())
            menu.handle_response(pkg)

            if pkg.status == PkgMinipultor.Status.REMOVE:
                continue    # Do not write pkg to output_file.

        output_file.write(line)

rename(SOURCE_FILE_NAME, OLD_FILE_NAME)
rename(OUTPUT_FILE_NAME, SOURCE_FILE_NAME)


text:
<?php

use Anomaly\Streams\Platform\Database\Migration\Migration;

/**
 * Class AnomalyModuleAppearanceCreateAppearanceFields
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 */
class AnomalyModuleAppearance_1_0_0_CreateAppearanceFields extends Migration
{

    /**
     * Fields to install.
     *
     * @var array
     */
    protected $fields = [
        'key'   => [
            'type' => 'anomaly.field_type.text'
        ],
        'value' => [
            'type' => 'anomaly.field_type.textarea'
        ]
    ];

}


text:
package de.pfabulist.lindwurm.sub;

import de.pfabulist.kleinod.nio.PathLimits;
import de.pfabulist.kleinod.nio.PathSpec;
import de.pfabulist.kleinod.nio.Pathss;
import de.pfabulist.kleinod.os.OS;
import de.pfabulist.lindwurm.eighty.EightyUtils;
import de.pfabulist.lindwurm.eighty.path.EightyPath;
import de.pfabulist.lindwurm.niotest.tests.AllTests;
import de.pfabulist.lindwurm.niotest.tests.FSDescription;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;

import static de.pfabulist.lindwurm.niotest.tests.descriptionbuilders.CombinedBuilder.build;
import static org.assertj.core.api.Assertions.assertThat;

public class SubTest extends AllTests {

    private static FSDescription capa;

    @BeforeClass
    public static void beforeClass() throws IOException {
        Path host = Pathss.getTmpDir( "subtest" );
        Files.createDirectories( host );
        FileSystem fs = SubFileSystemProvider.getUrim().getOrCreateFS( host, Collections.emptyMap() );

        // path limits are inherited from host
        // but maxpath is shortened by guest root length
        OS os = new OS();
        PathSpec pspec = PathSpec.byOS( os );
        int pathLength = pspec.getMaxPathLength() - pspec.getPathLength( host.toString() );

        if ( os.isOSX() ) {
            capa = build().
                    unix().hfsPlus().noPermissionChecks().next().
                    pathConstraints().pathLength( pathLength ).next().
                    playground().set( fs.getPath( "/testing" ) ).
                    secondFS().no().
                    hardlinks().no().
                    closable().no().
                    symlinks().no().
                    watchable().no().
                    fileStores().no().
                    fileChannel().no().
                    time().noCreationTime().noLastAccessTime().attributeDelay( 2000 ).next().
                    bug( "testReadAttributesViewFutureExistingFile" ).
                    bug( "testMoveLinkDoesNotChangeLastModifiedTime" ).
                    bug( "testMoveWhileWriting" ).
                    bug( "testReadChannelOfDirDoesNotThrow" ).
                    bug( "testFileKeyIsKeptInMove" ). // move impl via copy delete
                    bug( "testTruncateOnAppendChannelThrows" ).  // inherited from host
                    done();
        } else if ( os.isUnix() ) {
                capa = build().
                        unix().noPermissionChecks().next().
                        playground().set( fs.getPath( "/testing" ) ).
                        pathConstraints().pathLength( pathLength ).next().
                        hardlinks().no().
                        closable().no().
                        symlinks().no().
                        watchable().no().
                        fileStores().no().
                        fileChannel().no().
                        time().noCreationTime().noLastAccessTime().next().
                        bug( "testReadAttributesViewFutureExistingFile" ).
                        bug( "testMoveLinkDoesNotChangeLastModifiedTime" ).
                        bug( "testMoveWhileWriting" ).
                        bug( "testReadChannelOfDirDoesNotThrow" ).
                        bug( "testFileKeyIsKeptInMove" ). // move impl via copy delete
                        bug( "testTruncateOnAppendChannelThrows" ).  // inherited from host
                        done();
        } else if ( os.isWindows()) {
//            capa = build().
//                    windows().next().
//                    playground().set( fs.getPath( "/testing" ) ).
//                    time().nolastAccessTime( !os.isWindows() ).yes().
//                    hardlinks().no().
//                    closeable().no().
//                    fileChannels( false ).
//                    symlinks().no().
//                    watchService().no().
//                    fileChannels( false ).
//                    fileStores().no().
//                    time().lastAccessTime( false ).creationTime( !os.isUnix() ).yes().
//                    readOnly().no().
//                    bug( "testEveryChannelWriteUpdatesLastModifiedTime", os.isWindows() ).
//                    bug( "testReadAttributesViewFutureExistingFile" ).
//                    bug( "testMoveLinkDoesNotChangeLastModifiedTime" ).
//                    bug( "testMoveWhileWriting" ).
//                    build();

        }

    }

    public SubTest() {
        super( capa );
    }

    @Test
    public void testRootHasNoFileNameString() throws Exception {
        assertThat( ((EightyPath)defaultRoot()).getFileNameString()).isNull();
    }

    @Test
    public void testFileNameStringIsLastName() throws Exception {
        assertThat( EightyUtils.getFilenameString( relABC())).isEqualTo( relABC().getName( 2 ).toString());
    }

    @Test
    public void testFilenameStringOfDefaultIsEmptyString() throws Exception {
        assertThat( EightyUtils.getFilenameString( pathDefault())).isEqualTo( "" );
    }

}


text:
#include "0root/root.h"

#include <string.h>

// Always verify that a file of level N does not include headers > N!
#include "1base/error.h"
#include "1globals/callbacks.h"
#include "2page/page.h"
#include "3page_manager/page_manager.h"
#include "3btree/btree_index.h"
#include "3btree/btree_index_factory.h"
#include "3btree/btree_node_proxy.h"
#include "4db/db.h"
#include "4env/env.h"
#include "4cursor/cursor.h"

#ifndef UPS_ROOT_H
#  error "root.h was not included"
#endif

namespace upscaledb {

Page *
BtreeIndex::root_page(Context *context)
{
  if (unlikely(state.root_page == 0))
    state.root_page = state.page_manager->fetch(context,
                            state.btree_header->root_address);
  else
    context->changeset.put(state.root_page);
  return state.root_page;
}

void
BtreeIndex::create(Context *context, PBtreeHeader *btree_header,
                    DbConfig *dbconfig)
{
  LocalEnv *env = (LocalEnv *)state.db->env;
  state.page_manager = env->page_manager.get();
  state.btree_header = btree_header;
  state.leaf_traits.reset(BtreeIndexFactory::create(state.db, true));
  state.internal_traits.reset(BtreeIndexFactory::create(state.db, false));

  /* allocate a new root page */
  set_root_page(state.page_manager->alloc(context, Page::kTypeBroot,
                        PageManager::kClearWithZero));

  /* initialize the root page */
  PBtreeNode *node = PBtreeNode::from_page(state.root_page);
  node->set_flags(PBtreeNode::kLeafNode);

  persist_configuration(context, dbconfig);
}

void
BtreeIndex::open(PBtreeHeader *btree_header, DbConfig *dbconfig)
{
  LocalEnv *env = (LocalEnv *)state.db->env;
  state.page_manager = env->page_manager.get();
  state.btree_header = btree_header;

  /* merge the non-persistent database flag with the persistent flags from
   * the btree index */
  dbconfig->flags |= btree_header->flags;
  dbconfig->key_size = btree_header->key_size;
  dbconfig->key_type = btree_header->key_type;
  dbconfig->key_compressor = btree_header->key_compression();
  dbconfig->record_type = btree_header->record_type;
  dbconfig->record_size = btree_header->record_size;
  dbconfig->record_compressor = btree_header->record_compression();

  assert(dbconfig->key_size > 0);

  state.leaf_traits.reset(BtreeIndexFactory::create(state.db, true));
  state.internal_traits.reset(BtreeIndexFactory::create(state.db, false));
}

void
BtreeIndex::persist_configuration(Context *context, const DbConfig *dbconfig)
{
  if (unlikely(ISSET(dbconfig->flags, UPS_READ_ONLY)))
    return;

  state.btree_header->dbname = state.db->name();
  state.btree_header->key_size = dbconfig->key_size;
  state.btree_header->key_type = dbconfig->key_type;
  state.btree_header->record_size = dbconfig->record_size;
  state.btree_header->record_type = dbconfig->record_type;
  state.btree_header->flags = dbconfig->flags; // TODO nur die "interessanten"!
  state.btree_header->compare_hash
          = CallbackManager::hash(dbconfig->compare_name);
  state.btree_header->set_record_compression(dbconfig->record_compressor);
  state.btree_header->set_key_compression(dbconfig->key_compressor);
}

Page *
BtreeIndex::find_lower_bound(Context *context, Page *page, const ups_key_t *key,
                uint32_t page_manager_flags, int *idxptr)
{
  BtreeNodeProxy *node = get_node_from_page(page);

  // make sure that we're not in a leaf page, and that the
  // page is not empty
  assert(node->left_child() != 0);

  uint64_t record_id;
  int slot = node->find_lower_bound(context, (ups_key_t *)key, &record_id);

  if (idxptr)
    *idxptr = slot;

  return state.page_manager->fetch(context, record_id, page_manager_flags);
}

//
// visitor object for estimating / counting the number of keys
///
struct CalcKeysVisitor : public BtreeVisitor
{
  CalcKeysVisitor(LocalDb *db_, bool distinct_)
    : db(db_), distinct(distinct_), count(0) {
  }

  virtual bool is_read_only() const {
    return true;
  }

  virtual void operator()(Context *context, BtreeNodeProxy *node) {
    size_t length = node->length();

    if (distinct || NOTSET(db->flags(), UPS_ENABLE_DUPLICATE_KEYS)) {
      count += length;
      return;
    }

    for (size_t i = 0; i < length; i++)
      count += node->record_count(context, i);
  }

  LocalDb *db;
  bool distinct;
  uint64_t count;
};

uint64_t
BtreeIndex::count(Context *context, bool distinct)
{
  CalcKeysVisitor visitor(state.db, distinct);
  visit_nodes(context, visitor, false);
  return visitor.count;
}

//
// visitor object to free all allocated blobs
///
struct FreeBlobsVisitor : public BtreeVisitor
{
  FreeBlobsVisitor(PageManager *page_manager_)
    : page_manager(page_manager_) {
  }

  virtual void operator()(Context *context, BtreeNodeProxy *node) {
    node->erase_everything(context);
    page_manager->del(context, node->page, 1);
  }

  virtual bool is_read_only() const {
    return false;
  }

  PageManager *page_manager;
};

void
BtreeIndex::drop(Context *context)
{
  FreeBlobsVisitor visitor(state.page_manager);
  visit_nodes(context, visitor, true);
}

} // namespace upscaledb


text:
var http = require('request');
var cors = require('cors');
var uuid = require('uuid');
var url = require('url');
var R = require('ramda');

// This is the heart of your HipChat Connect add-on. For more information,
// take a look at https://developer.atlassian.com/hipchat/tutorials/getting-started-with-atlassian-connect-express-node-js
module.exports = function (app, addon) {
  var hipchat = require('../lib/hipchat')(addon);
  var pains = require('../lib/pains')(addon);

  // simple healthcheck
  app.get('/healthcheck', function (req, res) {
    res.send('OK');
  });

  // Root route. This route will serve the `addon.json` unless a homepage URL is
  // specified in `addon.json`.
  app.get('/',
    function (req, res) {
      // Use content-type negotiation to choose the best way to respond
      res.format({
        // If the request content-type is text-html, it will decide which to serve up
        'text/html': function () {
          var homepage = url.parse(addon.descriptor.links.homepage);
          if (homepage.hostname === req.hostname && homepage.path === req.path) {
            res.render('homepage', addon.descriptor);
          } else {
            res.redirect(addon.descriptor.links.homepage);
          }
        },
        // This logic is here to make sure that the `addon.json` is always
        // served up when requested by the host
        'application/json': function () {
          res.redirect('/atlassian-connect.json');
        }
      });
    }
    );

  // This is an example route that's used by the default for the configuration page
  // https://developer.atlassian.com/hipchat/guide/configuration-page
  app.get('/config',
    // Authenticates the request using the JWT token in the request
    addon.authenticate(),
    function (req, res) {
      // The `addon.authenticate()` middleware populates the following:
      // * req.clientInfo: useful information about the add-on client such as the
      //   clientKey, oauth info, and HipChat account info
      // * req.context: contains the context data accompanying the request like
      //   the roomId
      res.render('config', req.context);
    }
    );

  // This is an example glance that shows in the sidebar
  // https://developer.atlassian.com/hipchat/guide/glances
  app.get('/glance',
    cors(),
    addon.authenticate(),
    function (req, res) {
      res.json({
        "label": {
          "type": "html",
          "value": "Hello World!"
        },
        "status": {
          "type": "lozenge",
          "value": {
            "label": "NEW",
            "type": "error"
          }
        }
      });
    }
    );

  // This is an example end-point that you can POST to to update the glance info
  // Room update API: https://www.hipchat.com/docs/apiv2/method/room_addon_ui_update
  // Group update API: https://www.hipchat.com/docs/apiv2/method/addon_ui_update
  // User update API: https://www.hipchat.com/docs/apiv2/method/user_addon_ui_update
  app.post('/update_glance',
    cors(),
    addon.authenticate(),
    function (req, res) {
      res.json({
        "label": {
          "type": "html",
          "value": "Hello World!"
        },
        "status": {
          "type": "lozenge",
          "value": {
            "label": "All good",
            "type": "success"
          }
        }
      });
    }
    );

  // This is an example sidebar controller that can be launched when clicking on the glance.
  // https://developer.atlassian.com/hipchat/guide/dialog-and-sidebar-views/sidebar
  app.get('/sidebar',
    addon.authenticate(),
    function (req, res) {
      res.render('sidebar', {
        identity: req.identity
      });
    }
    );

  // This is an example dialog controller that can be launched when clicking on the glance.
  // https://developer.atlassian.com/hipchat/guide/dialog-and-sidebar-views/dialog
  app.get('/dialog',
    addon.authenticate(),
    function (req, res) {
      res.render('dialog', {
        identity: req.identity
      });
    }
    );

  // Sample endpoint to send a card notification back into the chat room
  // See https://developer.atlassian.com/hipchat/guide/sending-messages
  app.post('/send_notification',
    addon.authenticate(),
    function (req, res) {
      var card = {
        "style": "link",
        "url": "https://www.hipchat.com",
        "id": uuid.v4(),
        "title": req.body.messageTitle,
        "description": "Great teams use HipChat: Group and private chat, file sharing, and integrations",
        "icon": {
          "url": "https://hipchat-public-m5.atlassian.com/assets/img/hipchat/bookmark-icons/favicon-192x192.png"
        }
      };
      var msg = '' + card.title + ': ' + card.description;
      var opts = { 'options': { 'color': 'yellow' } };
      hipchat.sendMessage(req.clientInfo, req.identity.roomId, msg, opts, card);
      res.json({ status: "ok" });
    }
    );

  var getTableOfTop5Pains = function(painList) {
    if (R.either(R.isNil, R.isEmpty)(painList)) {
      return "No! You're pain free?!";
    } else {
      var appendPainToList = function(html, pain) {
        var reporterInitials = R.compose(
          R.join(', '),
          R.map(R.compose(
            R.toUpper,
            R.join(''),
            R.map(R.head),
            R.split(/\s+/),
            R.prop('name')
          ))
        )(pain.reporters);
        return html + '
' +
          '' + pain.description + '	' +
          '' + reporterInitials + '	' +
          '' + pain.id + '	' +
          '
';
      };
      var painListHeaders = 'The top 5 pains right now:

' +
        'Pain	' +
        'Reporters	' +
        'ID	' +
        '
';
      return R.compose(
        R.reduce(appendPainToList, painListHeaders),
        R.take(5),
        R.reverse,
        R.sortBy(R.compose(
          R.length,
          R.prop('reporters')
        ))
      )(painList) + '
';
    }
  };
  var painReportResponses = [
    'You had it coming!',
    'Oh! That hardly hurts at all.',
    "So you're in a world of pain? That's wonderful!",
    'Oh yes!',
    'So begins the reign of pain.',
    'All aboard the pain train!',
    'Tell me exactly how it hurts.',
    'Suffer!',
    'Sweet pain.',
    'Scream!',
    'Pain builds character.',
    'I love a struggle.',
  ];
  var randomPainReportResponse = function() {
    return painReportResponses[Math.floor(Math.random()*painReportResponses.length)];
  };

  // This is an example route to handle an incoming webhook
  // https://developer.atlassian.com/hipchat/guide/webhooks
  app.post('/webhooks/pains',
    addon.authenticate(),
    function (req, res) {
      pains.listPains(req.clientInfo.clientKey).then(function success(painList) {
        return hipchat.sendMessage(
          req.clientInfo,
          req.identity.roomId,
          getTableOfTop5Pains(painList),
          {options: {color: 'gray'}}
        );
      }, function failure(error) {
        console.error('Failed to list pains', req.body.item.message, error);
        return hipchat.sendMessage(
          req.clientInfo,
          req.identity.roomId,
          "I'm afraid something went wrong and I wasn't able to fetch all the pains.",
          {options: {color: 'red'}}
        );
      }).then(function (data) {
          res.sendStatus(200);
        }).catch(function(error) {
          console.error('Failed to send a response to hipchat', error);
          res.sendStatus(500);
          return RSVP.Promise.reject(error);
        });
    }
  );
  app.post('/webhooks/ouch',
    addon.authenticate(),
    function (req, res) {
      var clientKey = req.clientInfo.clientKey;
      var pain = {
        id: req.body.item.message.id,
        description: R.compose(
          R.trim,
          R.replace(/^\/ouch/, '')
        )(req.body.item.message.message),
      };
      var reporter = R.pick(['id', 'mention_name',  'name'], req.body.item.message.from);

      pains.reportPain(clientKey, pain, reporter).then(function success() {
        return hipchat.sendMessage(
          req.clientInfo,
          req.identity.roomId,
          randomPainReportResponse()
        );
      }, function failure(error) {
        console.error('Failed to report a pain', req.body.item.message, error);
        return hipchat.sendMessage(
          req.clientInfo,
          req.identity.roomId,
          "I'm afraid something went wrong and I wasn't able to record your pain.",
          {options: {color: 'red'}}
        );
      }).then(function (data) {
          res.sendStatus(200);
        }).catch(function(error) {
          console.error('Failed to send a response to hipchat', error);
          res.sendStatus(500);
          return RSVP.Promise.reject(error);
        });
    }
  );
  app.post('/webhooks/heal',
    addon.authenticate(),
    function (req, res) {
      var clientKey = req.clientInfo.clientKey;
      var description = R.compose(
        R.trim,
        R.replace(/^\/heal/, '')
      )(req.body.item.message.message);
      var healerName = req.body.item.message.from.name;

      pains.healPain(clientKey, description).then(function success(healedPain) {
        var healedNames = R.compose(
          R.join(', '),
          R.map(function(name) {return '@' + name;}),
          R.map(R.prop('mention_name'))
        )(healedPain.reporters);
        return hipchat.sendMessage(
          req.clientInfo,
          req.identity.roomId,
          healedNames + ', rejoice! ' + healerName + ' has healed your pain!',
          {
            options: {
              color: 'green',
              format: 'text',
            }
          }
        );
      }, function failure(error) {
        console.error('Failed to heal a pain', req.body.item.message, error);
        return hipchat.sendMessage(
          req.clientInfo,
          req.identity.roomId,
          "Hmm. Something went wrong. Are you sure someone has reported that pain?",
          {options: {color: 'red'}}
        );
      }).then(function (data) {
          res.sendStatus(200);
        }).catch(function(error) {
          console.error('Failed to send a response to hipchat', error);
          res.sendStatus(500);
          return RSVP.Promise.reject(error);
        });
    }
  );

  // Notify the room that the add-on was installed. To learn more about
  // Connect's install flow, check out:
  // https://developer.atlassian.com/hipchat/guide/installation-flow
  addon.on('installed', function (clientKey, clientInfo, req) {
    hipchat.sendMessage(clientInfo, req.body.roomId, 'The ' + addon.descriptor.name + ' add-on has been installed in this room');
  });

  // Clean up clients when uninstalled
  addon.on('uninstalled', function (id) {
    addon.settings.client.keys(id + ':*', function (err, rep) {
      rep.forEach(function (k) {
        addon.logger.info('Removing key:', k);
        addon.settings.client.del(k);
      });
    });
  });

};


text:
module TwentyfourSevenOfficeLegacy
  class RelationData < Model

    attributes [
      :contact_id,
      :customer_id,
      :title,
      :email,
      :phone,
      :mobile
    ]

     def to_hash
      { "relation" => TwentyfourSevenOfficeLegacy.to_xml_data(self) }
    end
  end
end


text:
import argparse
import sys
import string
import signal

signal.signal( signal.SIGPIPE, signal.SIG_DFL )

base = '/work/scripts/'

def list(s):
	try:
		return s.split(',')
	except:
		raise argparse.ArgumentTypeError("Must be a comma separated list of characters")

def replace( index, oldValue, newValue ):
	valueList = []
	for i in oldValue:
		valueList.append(i)
	valueList[index] = newValue
	s = "".join(valueList)
	return s

def toList( string ):
	list = []
	for i in string:
		list.append(i)
	return list

def parseArgs():
	parser = argparse.ArgumentParser(description='Print a sequence of numbers with a custom range.', add_help=False, formatter_class=argparse.RawTextHelpFormatter)

	info = parser.add_argument_group('Program Info')
	info.add_argument('-h', '--help', action='help', help='show this help message and exit')
	info.add_argument('-v', '--version', action='version', version='1.0.0')

	required = parser.add_argument_group('Required arguments')

	optional = parser.add_argument_group('Optional arguments')
	optional.add_argument('first', nargs='?', default=False, help='first number in sequence')
	optional.add_argument('last', nargs='?', default=False, help='last number in sequence')
	optional.add_argument('-r', '--range', metavar='LIST', type=list, default='0,1,2,3,4,5,6,7,8,9', help='comma separated list you wish to sequence.')
	optional.add_argument('-s', '--separator', metavar='STRING', default='\n', help='use STRING to separate numbers (default:\\n)')

	a = parser.parse_args()
	print ("first "+ a.first)
	print ("last "+ a.last)
	print ("range ")
	print  (a.range)
	if not a.first == False and not a.last == False:
		pass
	elif a.last == False and not a.first == False:
		a.last = a.first
		a.first = a.range[0]
		for x in range(0,len(a.last)-1):
			a.first += a.range[0]
	else:
		a.first = a.range[0]
		a.last = a.range[len(a.range)-1] + a.range[len(a.range)-1] + a.range[len(a.range)-1] + a.range[len(a.range)-1]
		for x in range(0,len(a.last)-1):
			a.first += a.range[0]
	return a

def iterate( args ):
	iterations = []
	while not args.first == args.last:
		iterations.append(args.first)
		for i in reversed(range(0,len(args.last))):
			charAt = toList(args.first)[i]
			x = args.range.index(charAt)
			x += 1
			x = x % len(args.range)
			args.first = replace(i,args.first,args.range[x])
			if not (x == 0):
				break
	iterations.append(args.last)
	print (args.separator.join(iterations))
if __name__ == "__main__":
	args = parseArgs()
	iterate(args)


text:
<?php

namespace Application;

use Zend\EventManager\EventInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\Mvc\ModuleRouteListener;

class Module implements BootstrapListenerInterface
{
    const VERSION = '3.0.2dev';

    public function getConfig()
    {
        return include __DIR__ . '/../config/module.config.php';
    }

    /**
     * Listen to the bootstrap event
     *
     * @param EventInterface $e
     * @return array
     */
    public function onBootstrap(EventInterface $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

        $e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\MVC\Controller\AbstractActionController', 'dispatch', function($e) {
            $controller = $e->getTarget();
            $controllerClass = get_class($controller);
            $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
            $config = $e->getApplication()->getServiceManager()->get('config');
            $action = $e->getRouteMatch()->getParam('action');
            if(isset($config['module_layouts'][$action])) {
                $controller->layout($config['module_layouts'][$action]);
            } elseif(isset($config['module_layouts'][$moduleNamespace])) {
                $controller->layout($config['module_layouts'][$moduleNamespace]);
            }
        }, 100);
    }
}


text:
module MobileCenterApi
  module Models
    #
    # Model object.
    #
    #
    class AndroidProject
      # @return [Array<AndroidModule>] Android Gradle modules
      attr_accessor :android_modules

      # @return [String] The path of the Gradle wrapper
      attr_accessor :gradle_wrapper_path

      #
      # Mapper for AndroidProject class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          required: false,
          serialized_name: 'AndroidProject',
          type: {
            name: 'Composite',
            class_name: 'AndroidProject',
            model_properties: {
              android_modules: {
                required: true,
                serialized_name: 'androidModules',
                type: {
                  name: 'Sequence',
                  element: {
                      required: false,
                      serialized_name: 'AndroidModuleElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'AndroidModule'
                      }
                  }
                }
              },
              gradle_wrapper_path: {
                required: false,
                serialized_name: 'gradleWrapperPath',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Sauce-0.11.0: Member List</title>

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

Sauce-0.11.0

A C++ Dependency Injection Framework

Main Page

Classes

Files

Class List

Class Hierarchy

Class Members

sauce

internal

OpaqueBinding

sauce::internal::OpaqueBinding Member List

This is the complete list of members for sauce::internal::OpaqueBinding, including all inherited members.

eagerlyInject(OpaqueBindingPtr, sauce::shared_ptr< Injector >) const =0	sauce::internal::OpaqueBinding	 [pure virtual]

getKey() const =0	sauce::internal::OpaqueBinding	 [pure virtual]

getName() const =0	sauce::internal::OpaqueBinding	 [pure virtual]

getScopeKey() const =0	sauce::internal::OpaqueBinding	 [pure virtual]

isModifier() const 	sauce::internal::OpaqueBinding	 [inline, virtual]

setDynamicDependencyNames(std::vector< std::string > const &)=0	sauce::internal::OpaqueBinding	 [pure virtual]

setName(std::string const)=0	sauce::internal::OpaqueBinding	 [pure virtual]

~OpaqueBinding() (defined in sauce::internal::OpaqueBinding)	sauce::internal::OpaqueBinding	 [inline, virtual]

<address class="footer">
Generated by

 1.7.6.1
</address>


text:
package ${topLevelDomain}.${companyName}.${productName}.model.repository.user;

import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Test;

public class TestPasswordGeneratorRepository extends TestCase {
    private static final String ONE_UPPER = "^(?=.*[A-Z]).+\$";
    private static final String ONE_NUMBER = "^(?=.*\\\\d).+\$";

    @Test
    public void testGenerate() {
        PasswordGeneratorRepository passwordGenerator = new PasswordGeneratorRepositoryImpl();
        final String password = passwordGenerator.generate();
        Assert.assertTrue("Missing Uppercase Letter", password.matches(ONE_UPPER));
        Assert.assertTrue("Missing number", password.matches(ONE_NUMBER));
        System.out.println(password);
    }
}


text:
<html>
<head>
<script src="js/amberd.js" type="text/javascript"></script>
<style> body { margin: 0; } </style>
</head>
<body>
<script type="text/javascript">
       loadAmber({
               files: ['Ludus.deploy.js' , 'SmallCave.deploy.js'],
               prefix: 'js',
               ready: function() {
                       smalltalk.SmallCave._start();
               }});
</script>
</body>
</html>


text:
    <title>Example</title>

    <form>
      Frame rate:

      <input type="range" id="slider" min="1" max="60" value="5" onchange="slider_change(event)"></input>
      5 fps

    </form>


text:
package com.lerx.user.vo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lerx.article.vo.ArticleGroup;
import com.lerx.qa.vo.QaNav;
import com.lerx.sys.util.vo.UserCookie;
import com.lerx.user.dao.IInterconnectionDao;
import com.lerx.user.dao.IUserDao;
import com.opensymphony.xwork2.ActionSupport;

public class ChkUtilVo {

	private IInterconnectionDao interconnectionDaoImp;
	private IUserDao userDaoImp;
	private ArticleGroup ag;
	private UserCookie uc;
	private int mode;
	private boolean pwdMD5ToLowerCase;
	private ActionSupport as;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private QaNav qn;

	public QaNav getQn() {
		return qn;
	}
	public void setQn(QaNav qn) {
		this.qn = qn;
	}
	public IUserDao getUserDaoImp() {
		return userDaoImp;
	}
	public void setUserDaoImp(IUserDao userDaoImp) {
		this.userDaoImp = userDaoImp;
	}
	public IInterconnectionDao getInterconnectionDaoImp() {
		return interconnectionDaoImp;
	}
	public void setInterconnectionDaoImp(IInterconnectionDao interconnectionDaoImp) {
		this.interconnectionDaoImp = interconnectionDaoImp;
	}
	public ArticleGroup getAg() {
		return ag;
	}
	public void setAg(ArticleGroup ag) {
		this.ag = ag;
	}
	public UserCookie getUc() {
		return uc;
	}
	public void setUc(UserCookie uc) {
		this.uc = uc;
	}
	public int getMode() {
		return mode;
	}
	public void setMode(int mode) {
		this.mode = mode;
	}
	public boolean isPwdMD5ToLowerCase() {
		return pwdMD5ToLowerCase;
	}
	public void setPwdMD5ToLowerCase(boolean pwdMD5ToLowerCase) {
		this.pwdMD5ToLowerCase = pwdMD5ToLowerCase;
	}
	public ActionSupport getAs() {
		return as;
	}
	public void setAs(ActionSupport as) {
		this.as = as;
	}
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
}


text:
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { deleteCards, createOpen } from 'modules/cards/reducer'
import { getSelectedCards, isCreateOpen } from 'modules/cards/selectors'

import CreateCardButton from './create-card-button'
import DeleteCardButton from './delete-card-button'

class CardActionButton extends PureComponent {
  render() {
    const { selectedCards, deleteCards, isCreateOpen, createOpen } = this.props
    let className = ''

    if (!isCreateOpen) {
      if (selectedCards.length > 0) {
        className = 'show-delete-card'
      } else {
        className = 'show-create-card'
      }
    }

    return (
      <div className={`${className}`}>
          <DeleteCardButton onClick={() => deleteCards(selectedCards)} />
          <CreateCardButton onClick={createOpen} />
      </div>
    )
  }
}

export default connect(state => ({
  selectedCards: getSelectedCards(state),
  isCreateOpen: isCreateOpen(state),
}), {
  deleteCards,
  createOpen,
})(CardActionButton)


text:
package stardust.handler;

import java.util.Arrays;

/*
 * A Fast SSI Parser
 */
public class SDSScript
{
static final String _TAG_BEGIN = "<!--#";
static final String _TAG_END   = " -->";

private static final short         S = 0;
private static final short      TEXT = 1;
private static final short TAG_BEGIN = 2;
private static final short  TAG_NAME = 3;
private static final short   TAG_END = 4;

private static final String[] stateName = {"S","TEXT","TAG_BEGIN","TAG_NAME","TAG_END"};

private static final short[][] states = {
                /* S         => */{TEXT,TAG_BEGIN},
                /* TEXT      => */{TAG_BEGIN},
                /* TAG_BEGIN => */{TAG_NAME},
                /* TAG_NAME  => */{TAG_END},
                /* TAG_END   => */{TEXT,TAG_BEGIN}
                };

private static  boolean acceptsNextState(int currentState, int nextState) {
    for (short state : states[currentState]) if (state == nextState) return true;
    return false;
}

private static  boolean conformsSet(short toState,int a,int pos) {

    switch(toState) {
        case TEXT       : return true;
        case TAG_BEGIN  : return pos < _TAG_BEGIN.length() &&  _TAG_BEGIN.charAt(pos) == (char)a;
        case TAG_NAME   : return (a >= 'a' && a <= 'z') || a == '_';
        case TAG_END    : return pos < _TAG_END.length() && _TAG_END.charAt(pos) == (char)a;
    }
    return false;
}

private static boolean isFinal(short toState,int a, int pos) {
    switch(toState) {
        case TEXT       : return a != '<';
        case TAG_BEGIN  : return pos == _TAG_BEGIN.length();
        case TAG_NAME   : return a != 'a';
        case TAG_END    : return pos == _TAG_END.length();
    }
    return false;
}

public  void stateChanged(int previous, int current, String[] data) {
    if (current == TAG_END) {
//        System.out.println("\n( "+stateName[previous]+"->"+stateName[current]+" )\n\nNAME: "+data[TAG_NAME]);
    }
}

private String out="";
public void step(short current,char c, short[] conflits,String[] buffer,String scriptname, int pos, int length) {
    if ((current == TEXT && conflits[TAG_BEGIN] == 0)) {
        System.out.print(c);
    }
}

public  void run (String code) {
   short smatch[] = {0,0,0,0,0};
   String hold[] = {"","","","",""};

   short cs = TEXT;

    for (int i = 0 ; i < code.length() ; i++ ) {
        char a = code.charAt(i);
//        System.out.print(" "+a+" ("+stateName[cs]+") ");
        for (short c = 0 ; c< states.length ; c++) {
            if (acceptsNextState(cs,c)) {
                if (conformsSet(c,(int)a,smatch[c])) {
                    ++smatch[c];
                    hold[c]+=a;
                } else {
                    smatch[c] = 0;
                    hold[c]="";
                }
//                System.out.print("  "+stateName[c] + "="+smatch[c]);
                if (isFinal(c,(int)a,smatch[c])) {
//                    System.out.print("[>] "+hold[c]);
                    if (hold[c].length()>0) {
                        hold[cs] = hold[cs].substring(0, hold[cs].length()-hold[c].length()+1);
                    }
                    stateChanged(cs,c,hold);
                    cs=c;
                    hold[cs] += a;
                    Arrays.fill(smatch, (short)0);
                    Arrays.fill(hold,"");
                    break;
                }
            } else if (c == cs) {
                hold[cs] += a;
            }
        }
        step(cs,a,smatch,hold,"<native>",i,code.length());
//        System.out.println();
    }
}

}


text:
package org.ray.api;

import org.ray.api.id.ActorId;
import org.ray.api.id.UniqueId;

/**
 * A handle to an actor.
 *
 * @param <T> The type of the concrete actor class.
 */
public interface RayActor<T> {

  /**
   * @return The id of this actor.
   */
  ActorId getId();

  /**
   * @return The id of this actor handle.
   */
  UniqueId getHandleId();

}


text:
using System.Collections.Generic;

using Soloco.Composition.Example.Repositories;

namespace Soloco.Composition.Examples.Repositories.Tests
{
    public static class TestProductFactory
    {
        public static IEnumerable<Product> CreateList()
        {
            return new List<Product>
                       {
                           new Product { Name = "Product1", Price = 15},
                           new Product { Name = "Product2", Price = 20}
                       };
        }

        public static Product Create()
        {
            return new Product { Name = "Product1", Price = 15};
        }
    }
}


text:
/*
 * php_screw
 * (C) 2007, Kunimasa Noda/PM9.com, Inc. <http://www.pm9.com,  kuni@pm9.com>
 * see file LICENSE for license details
 */

#include "php.h"
#include "php_ini.h"
#include "ext/standard/file.h"
#include "ext/standard/info.h"

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "php_screw.h"
#include "my_screw.h"

PHP_MINIT_FUNCTION(php_screw);
PHP_MSHUTDOWN_FUNCTION(php_screw);
PHP_MINFO_FUNCTION(php_screw);

FILE *pm9screw_ext_fopen(FILE *fp)
{
	struct	stat	stat_buf;
	char	*datap, *newdatap;
	int	datalen, newdatalen;
	int	cryptkey_len = sizeof pm9screw_mycryptkey / 2;
	int	i;

	fstat(fileno(fp), &stat_buf);
	datalen = stat_buf.st_size - PM9SCREW_LEN;
	datap = (char*)malloc(datalen);
	fread(datap, datalen, 1, fp);
	fclose(fp);

	for(i=0; i<datalen; i++) {
		datap[i] = (char)pm9screw_mycryptkey[(datalen - i) % cryptkey_len] ^ (~(datap[i]));
	}

	newdatap = zdecode(datap, datalen, &newdatalen);

	fp = tmpfile();
	fwrite(newdatap, newdatalen, 1, fp);

	free(datap);
	free(newdatap);

	rewind(fp);
	return fp;
}

ZEND_API zend_op_array *(*org_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC);

ZEND_API zend_op_array *pm9screw_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
	FILE	*fp;
	char	buf[PM9SCREW_LEN + 1];
	char	fname[32];

	memset(fname, 0, sizeof fname);
	if (zend_is_executing(TSRMLS_C)) {
		if (get_active_function_name(TSRMLS_C)) {
			strncpy(fname, get_active_function_name(TSRMLS_C), sizeof fname - 2);
		}
	}
	if (fname[0]) {
		if ( strcasecmp(fname, "show_source") == 0
		  || strcasecmp(fname, "highlight_file") == 0) {
			return NULL;
		}
	}

	fp = fopen(file_handle->filename, "r");
	if (!fp) {
		return org_compile_file(file_handle, type);
	}

	fread(buf, PM9SCREW_LEN, 1, fp);
	if (memcmp(buf, PM9SCREW, PM9SCREW_LEN) != 0) {
		fclose(fp);
		return org_compile_file(file_handle, type);
	}

	if (file_handle->type == ZEND_HANDLE_FP) fclose(file_handle->handle.fp);
	if (file_handle->type == ZEND_HANDLE_FD) close(file_handle->handle.fd);
	file_handle->handle.fp = pm9screw_ext_fopen(fp);
	file_handle->type = ZEND_HANDLE_FP;
	file_handle->opened_path = expand_filepath(file_handle->filename, NULL TSRMLS_CC);

	return org_compile_file(file_handle, type);
}

zend_module_entry php_screw_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
	STANDARD_MODULE_HEADER,
#endif
	"php_screw",
	NULL,
	PHP_MINIT(php_screw),
	PHP_MSHUTDOWN(php_screw),
	NULL,
	NULL,
	PHP_MINFO(php_screw),
#if ZEND_MODULE_API_NO >= 20010901
	"1.5.0", /* Replace with version number for your extension */
#endif
	STANDARD_MODULE_PROPERTIES
};

ZEND_GET_MODULE(php_screw);

PHP_MINFO_FUNCTION(php_screw)
{
	php_info_print_table_start();
	php_info_print_table_header(2, "php_screw support", "enabled");
	php_info_print_table_end();
}

PHP_MINIT_FUNCTION(php_screw)
{
	// CG(extended_info) = 1;

	org_compile_file = zend_compile_file;
	zend_compile_file = pm9screw_compile_file;
	return SUCCESS;
}

PHP_MSHUTDOWN_FUNCTION(php_screw)
{
	// CG(extended_info) = 1;
	zend_compile_file = org_compile_file;
	return SUCCESS;
}


text:
require 'spec_helper'

RSpec.describe Services::Nest::Interface do
  let(:client) do
    instance_double('NestAPI::Client')
  end
  let(:structure_response) do
    JSON.parse(File.read('spec/support/nest/structure.json'))
  end
  let(:device_response) do
    JSON.parse(File.read('spec/support/nest/device.json'))
  end

  before do
    allow(client).to receive_messages(
      devices: device_response,
      structures: structure_response
    )
  end

  describe '#new' do
    let(:interface) { described_class.new(client) }
    it 'properly initializes' do
      expect(interface.devices).to_not be_empty
    end
  end
end


text:
package us.kbase.kidl;

import java.util.Map;

/**
 * Element of module declaration. This could be Typedef of Funcdef (or Auth string in some cases).
 * @author rsutormin
 */
public interface KbModuleComp {
	public Object toJson();
	public Map<String, Object> forTemplates();
}


text:
                © Copyright {{ .Site.Copyright }}

                Mediumish Theme by WowThemes.net


text:
package com.shejiaomao.weibo.service.task;

import java.util.ArrayList;
import java.util.List;

import com.shejiaomao.maobo.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.cattong.commons.LibException;
import com.cattong.commons.Logger;
import com.cattong.commons.util.ListUtil;
import com.cattong.entity.BaseUser;
import com.cattong.weibo.Weibo;
import com.shejiaomao.common.ResourceBook;
import com.shejiaomao.weibo.common.GlobalVars;
import com.shejiaomao.weibo.db.LocalAccount;
import com.shejiaomao.weibo.db.LocalGroup;
import com.shejiaomao.weibo.db.UserDao;
import com.shejiaomao.weibo.db.UserGroup;
import com.shejiaomao.weibo.db.UserGroupDao;
import com.shejiaomao.weibo.service.adapter.GroupMemberListAdapter;

public class GroupMemberAddTask extends AsyncTask<Void, BaseUser, List<BaseUser>> {
	private static final String TAG = "GroupMemberAddTask";

	private Context context;
    private GroupMemberListAdapter adapter;
    private LocalGroup group;
    private List<BaseUser> userList;

    private LocalAccount account;
    private Weibo microBlog;

    private ProgressDialog dialog;
    private String resultMsg;
	public GroupMemberAddTask(GroupMemberListAdapter adapter, LocalGroup group, List<BaseUser> userList) {
		this.adapter = adapter;
		this.group = group;
		this.userList = userList;
		this.context = adapter.getContext();
		this.account = adapter.getAccount();
		this.microBlog = GlobalVars.getMicroBlog(account);
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		List<BaseUser> targetList = new ArrayList<BaseUser>();
		UserGroupDao dao = new UserGroupDao(context);
		StringBuffer sb = new StringBuffer();
		for (BaseUser user : userList) {
			boolean isExist = dao.isExist(group, user);
			if (!isExist) {
				targetList.add(user);
			} else {
				sb.append(user.getMentionName() + " ");
			}
		}
		userList = targetList;
		if (sb.length() > 0) {
			String msg = context.getString(R.string.msg_group_member_exist, sb.toString());
			Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
		}

		if (ListUtil.isNotEmpty(userList)) {
		    dialog = ProgressDialog.show(context, null,
		    	context.getString(R.string.msg_group_member_add));
	        dialog.setCancelable(true);
	        dialog.setOnCancelListener(onCancelListener);
	        dialog.setOwnerActivity((Activity)context);
		} else {
			cancel(true);
		}
	}

	@Override
	protected List<BaseUser> doInBackground(Void... params) {
		if (ListUtil.isEmpty(userList)
			|| microBlog == null) {
			return null;
		}

		List<BaseUser> addedUserList = new ArrayList<BaseUser>();
		for (BaseUser user : userList) {
			try {
		         microBlog.createGroupMember(group.getSpGroupId(), user.getUserId());
		         addedUserList.add(user);
		    } catch (LibException e) {
			    if (Logger.isDebug()) Log.e(TAG, "Task", e);
			    resultMsg = ResourceBook.getResultCodeValue(e.getErrorCode(), context);
			    this.publishProgress(user);
		    }
		}

		return addedUserList;
	}

	@Override
	protected void onProgressUpdate(BaseUser... values) {
		super.onProgressUpdate(values);
		BaseUser user = values[0];
		if (user == null) {
			return;
		}

		String msg = context.getString(R.string.msg_group_member_add_failed,
			user.getDisplayName(), resultMsg);
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onPostExecute(List<BaseUser> result) {
		super.onPostExecute(result);
		try {
		     dialog.dismiss();
		} catch (Exception e) {}

		if (ListUtil.isEmpty(result)) {
			return;
		}

		UserGroupDao ugDao = new UserGroupDao(context);
		UserDao userDao = new UserDao(context);
		for (BaseUser user : result) {
		    userDao.save(user);

		    UserGroup ug = new UserGroup();
		    ug.setUserId(user.getUserId());
		    ug.setGroupId(group.getGroupId());
		    ug.setServiceProviderNo(account.getServiceProviderNo());
		    ug.setState(UserGroup.STATE_ADDED);
		    ugDao.save(ug);
	    }

		adapter.addCacheToFirst(result);

		String msg = context.getString(R.string.msg_group_member_add_success, result.size());
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}

	private OnCancelListener onCancelListener = new OnCancelListener() {
		public void onCancel(DialogInterface dialog) {
			GroupMemberAddTask.this.cancel(true);
		}
	};
}


text:
<#  MIT License

    Copyright (c) 2018 fvanroie, NetwiZe.be

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
#>

Function Backup-OPNsenseConfig {
    # .EXTERNALHELP ../../PS_OPNsense.psd1-Help.xml
    [CmdletBinding()]
    Param (
        [switch]$RRDdata = $false,

        [ValidateNotNullOrEmpty()]
        [parameter(Mandatory = $false)]
        [SecureString]$Password
    )

    if ($DebugPreference -eq "Inquire") { $DebugPreference = "Continue" }

    $SkipCertificateCheck = $MyInvocation.MyCommand.Module.PrivateData['OPNsenseSkipCert']
    $Credential = $MyInvocation.MyCommand.Module.PrivateData['WebCredentials']
    $Uri = $MyInvocation.MyCommand.Module.PrivateData['OPNsenseUri']

    if (-not $Credential) {
        Throw "No web password has been set."
    }

    if ($PSBoundParameters.ContainsKey('Password')) {
        $encrypt = $true
    } else {
        $encrypt = $false
    }

    if ($PSVersionTable.PSEdition -ne 'Core' -And [bool]::Parse($SkipCertificateCheck)) {
        $CertPolicy = Get-CertificatePolicy -Verbose:$VerbosePreference
        Disable-CertificateValidation -Verbose:$VerbosePreference
    }

    Try {
        if ($PSVersionTable.PSEdition -eq 'Core') {
            $webpage = Invoke-WebRequest -Uri $Uri -SessionVariable cookieJar -SkipCertificateCheck:$SkipCertificateCheck
        } else {
            $webpage = Invoke-WebRequest -Uri $Uri -SessionVariable cookieJar
        }

        $xssToken = $webpage.InputFields | Where-Object { $_.type -eq 'hidden'}
        $form = @{
            $xssToken.name = $xssToken.value;
            usernamefld = $Credential.Username;
            passwordfld = $Credential.GetNetworkCredential().Password;
            login = 1
        }
        if ($PSVersionTable.PSEdition -eq 'Core') {
            $webpage = Invoke-WebRequest -Uri "$Uri/index.php" -WebSession $cookieJar -Method POST -Body $form -SkipCertificateCheck:$SkipCertificateCheck
        } else {
            $webpage = Invoke-WebRequest -Uri "$Uri/index.php" -WebSession $cookieJar -Method POST -Body $form
        }

        # check logged in
        if ($webpage.ParsedHtml.title -eq 'Login') {
            Throw 'Unable to login to the OPNsense Web GUI. Make sure the WebCredential parameter is set and correct.'
        }

        if ($PSVersionTable.PSEdition -eq 'Core') {
            $webpage = Invoke-WebRequest -Uri "$Uri/diag_backup.php" -WebSession $cookieJar -Method POST -Body $form -SkipCertificateCheck:$SkipCertificateCheck
        } else {
            $webpage = Invoke-WebRequest -Uri "$Uri/diag_backup.php" -WebSession $cookieJar -Method POST -Body $form
        }
        $xssToken = $webpage.InputFields | Where-Object { $_.type -eq 'hidden'}

        $form = @{
            $xssToken[0].name = $xssToken[0].value ;
            donotbackuprrd = if ([bool]::Parse($RRDdata)) { '' } else { 'on' } ;
            encrypt = if ($encrypt) { 'on' } else { '' };
            encrypt_password = if ($encrypt) { $Password.GetNetworkCredential().Password } else { '' };
            encrypt_passconf = if ($encrypt) { $Password.GetNetworkCredential().Password } else { '' };
            download = "Download configuration"
        }
        if ($PSVersionTable.PSEdition -eq 'Core') {
            $backupxml = Invoke-WebRequest "$Uri/diag_backup.php" -WebSession $cookieJar -Method POST -Body $form -SkipCertificateCheck:$SkipCertificateCheck
        } else {
            $backupxml = Invoke-WebRequest "$Uri/diag_backup.php" -WebSession $cookieJar -Method POST -Body $form
        }
        $Result = $backupxml.RawContent.Substring($backupxml.RawContent.Length - $backupxml.RawContentLength, $backupxml.RawContentLength)
    } Catch {
        $ErrorMessage = $_.Exception.Message
        Write-Error "An error Occured while connecting to the OPNsense server: $ErrorMessage"
    }
    # Always restore the built-in .NET certificate policy
    Finally {
        if ($PSVersionTable.PSEdition -ne 'Core' -And [bool]::Parse($SkipCertificateCheck)) {
            Set-CertificatePolicy $CertPolicy -Verbose:$VerbosePreference
        }
    }
    Return $Result
}


text:
module m_copy
  !! Contains fundamental routines to copy arrays to new memory locations while maintaining both copies
  !!
  !! See [[copy]] for more information.
  use variableKind
  use m_errors, only: eMsg
  use m_allocate, only: allocate

  private

  public :: copy
  interface copy
    !! Copies an array to new memory (no pointers), The output array size will be changed to match the copy.
    !!
    !! Example usage
    !!```fortran
    !!use variableKind, only: r64
    !!use m_allocate, only: allocate
    !!use m_copy, only: copy
    !!
    !!real(r64),allocatable :: a1D(:), a2D(:,:), a3D(:,:,:)
    !!real(r64),allocatable :: b1D(:), b2D(:,:), b3D(:,:,:)
    !!call allocate(a1D, 20)
    !!call allocate(a2D, [20,20])
    !!call allocate(a3D, [20,20,20])
    !!a1D = 1.d0
    !!a2D = 2.d0
    !!a3D = 3.d0
    !!call copy(a1D, b1D)
    !!call copy(a2D, b2D)
    !!call copy(a3D, b3D)
    !!write(*,'(a)') 'a1D equals b1D: '//str(all(a1D == b1D))
    !!write(*,'(a)') 'a2D equals b2D: '//str(all(a2D == b2D))
    !!write(*,'(a)') 'a3D equals b3D: '//str(all(a3D == b3D))
    !!call deallocate(a1D)
    !!call deallocate(a2D)
    !!call deallocate(a3D)
    !!call deallocate(b1D)
    !!call deallocate(b2D)
    !!call deallocate(b3D)
    !!```
    !====================================================================!
    module subroutine copy_r1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      real(r32), allocatable, intent(in) :: this(:) !! Copy this array
      real(r32), allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_r2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      real(r32), allocatable, intent(in) :: this(:,:) !! Copy this array
      real(r32), allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_r3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      real(r32), allocatable, intent(in) :: this(:,:,:) !! Copy this array
      real(r32), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

    !====================================================================!
    module subroutine copy_d1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      real(r64), allocatable, intent(in) :: this(:) !! Copy this array
      real(r64), allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_d2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      real(r64), allocatable, intent(in) :: this(:,:) !! Copy this array
      real(r64), allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_d3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      real(r64), allocatable, intent(in) :: this(:,:,:) !! Copy this array
      real(r64), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

    !====================================================================!
    module subroutine copy_i1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      integer(i32), allocatable, intent(in) :: this(:) !! Copy this array
      integer(i32), allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_i2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      integer(i32), allocatable, intent(in) :: this(:,:) !! Copy this array
      integer(i32), allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_i3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      integer(i32), allocatable, intent(in) :: this(:,:,:) !! Copy this array
      integer(i32), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

    !====================================================================!
    module subroutine copy_id1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      integer(i64), allocatable, intent(in) :: this(:) !! Copy this array
      integer(i64), allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_id2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      integer(i64), allocatable, intent(in) :: this(:,:) !! Copy this array
      integer(i64), allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_id3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      integer(i64), allocatable, intent(in) :: this(:,:,:) !! Copy this array
      integer(i64), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

    !====================================================================!
    module subroutine copy_c1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      complex(r32), allocatable, intent(in) :: this(:) !! Copy this array
      complex(r32), allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_c2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      complex(r32), allocatable, intent(in) :: this(:,:) !! Copy this array
      complex(r32), allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_c3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      complex(r32), allocatable, intent(in) :: this(:,:,:) !! Copy this array
      complex(r32), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

    !====================================================================!
    module subroutine copy_z1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      complex(r64), allocatable, intent(in) :: this(:) !! Copy this array
      complex(r64), allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_z2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      complex(r64), allocatable, intent(in) :: this(:,:) !! Copy this array
      complex(r64), allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_z3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      complex(r64), allocatable, intent(in) :: this(:,:,:) !! Copy this array
      complex(r64), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

    !====================================================================!
    module subroutine copy_l1D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      logical, allocatable, intent(in) :: this(:) !! Copy this array
      logical, allocatable, intent(inout)  :: that(:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_l2D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      logical, allocatable, intent(in) :: this(:,:) !! Copy this array
      logical, allocatable, intent(inout) :: that(:,:) !! Copy of this
    end subroutine
    !====================================================================!
    !====================================================================!
    module subroutine copy_l3D(this,that)
    !====================================================================!
      !! Interfaced with [[copy]]
      logical, allocatable, intent(in) :: this(:,:,:) !! Copy this array
      logical, allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    end subroutine
    !====================================================================!

  end interface

contains
  !====================================================================!
  module subroutine copy_r1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    real(r32), allocatable, intent(in) :: this(:) !! Copy this array
    real(r32), allocatable, intent(inout)  :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_r1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_r2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    real(r32), allocatable, intent(in) :: this(:,:) !! Copy this array
    real(r32), allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_r2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_r3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    real(r32), allocatable, intent(in) :: this(:,:,:) !! Copy this array
    real(r32), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_r3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_d1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    real(r64), allocatable, intent(in) :: this(:) !! Copy this array
    real(r64), allocatable, intent(inout) :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_d1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_d2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    real(r64), allocatable, intent(in) :: this(:,:) !! Copy this array
    real(r64), allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_d2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_d3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    real(r64), allocatable, intent(in) :: this(:,:,:) !! Copy this array
    real(r64), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_d3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_i1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    integer(i32), allocatable, intent(in) :: this(:) !! Copy this array
    integer(i32), allocatable, intent(inout) :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_i1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_i2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    integer(i32), allocatable, intent(in) :: this(:,:) !! Copy this array
    integer(i32), allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_i2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_i3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    integer(i32), allocatable, intent(in) :: this(:,:,:) !! Copy this array
    integer(i32), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_i3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_id1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    integer(i64), allocatable, intent(in) :: this(:) !! Copy this array
    integer(i64), allocatable, intent(inout) :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_id1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_id2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    integer(i64), allocatable, intent(in) :: this(:,:) !! Copy this array
    integer(i64), allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_id2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_id3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    integer(i64), allocatable, intent(in) :: this(:,:,:) !! Copy this array
    integer(i64), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_id3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_c1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    complex(r32), allocatable, intent(in) :: this(:) !! Copy this array
    complex(r32), allocatable, intent(inout)  :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_c1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_c2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    complex(r32), allocatable, intent(in) :: this(:,:) !! Copy this array
    complex(r32), allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_c2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_c3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    complex(r32), allocatable, intent(in) :: this(:,:,:) !! Copy this array
    complex(r32), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_c3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_z1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    complex(r64), allocatable, intent(in) :: this(:) !! Copy this array
    complex(r64), allocatable, intent(inout)  :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_z1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_z2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    complex(r64), allocatable, intent(in) :: this(:,:) !! Copy this array
    complex(r64), allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_z2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_z3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    complex(r64), allocatable, intent(in) :: this(:,:,:) !! Copy this array
    complex(r64), allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_z3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_l1D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    logical, allocatable, intent(in) :: this(:) !! Copy this array
    logical, allocatable, intent(inout)  :: that(:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_l1D:Array to be copied is not allocated')
    call allocate(that,size(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_l2D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    logical, allocatable, intent(in) :: this(:,:) !! Copy this array
    logical, allocatable, intent(inout) :: that(:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_l2D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
  !====================================================================!
  module subroutine copy_l3D(this,that)
  !====================================================================!
    !! Interfaced with [[copy]]
    logical, allocatable, intent(in) :: this(:,:,:) !! Copy this array
    logical, allocatable, intent(inout) :: that(:,:,:) !! Copy of this
    if (.not. allocated(this)) call eMsg('copy_l3D:Array to be copied is not allocated')
    call allocate(that,shape(this))
    that = this
  end subroutine
  !====================================================================!
end module


text:
package org.apache.rahas.impl;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.rahas.TrustException;

import javax.xml.namespace.QName;
import java.io.FileInputStream;

/**
 *
 */
public class TokenCancelerConfig {

    /*
    <parameter name="token-canceler-config">
        <token-canceler-config>
            <proofToken>EncryptedKey</proofToken>
            <cryptoProperties>sctIssuer.properties</cryptoProperties>
            <addRequestedAttachedRef />
        </stoken-canceler-config>
    </parameter>
    */
    public final static QName TOKEN_CANCELER_CONFIG = new QName("token-canceler-config");

    private TokenCancelerConfig(OMElement elem) throws TrustException {
        /*OMElement proofTokenElem =
                elem.getFirstChildWithName(new QName("proofToken"));
        if (proofTokenElem != null) {
            this.proofTokenType = proofTokenElem.getText().trim();
        }

        OMElement cryptoPropertiesElem = elem
                .getFirstChildWithName(new QName("cryptoProperties"));

        if (!SCTIssuer.BINARY_SECRET.equals(proofTokenType)
            && cryptoPropertiesElem == null) {
            throw new TrustException("sctIssuerCryptoPropertiesMissing");
        }

        this.addRequestedAttachedRef = elem
                .getFirstChildWithName(ADD_REQUESTED_ATTACHED_REF) != null;
        this.addRequestedUnattachedRef = elem
                .getFirstChildWithName(ADD_REQUESTED_UNATTACHED_REF) != null;

        this.cryptoPropertiesFile = cryptoPropertiesElem.getText().trim();*/
    }

    public static TokenCancelerConfig load(OMElement elem) throws TrustException {
        return new TokenCancelerConfig(elem);
    }

    public static TokenCancelerConfig load(String configFilePath)
            throws TrustException {
        FileInputStream fis;
        OMXMLParserWrapper builder;
        try {
            fis = new FileInputStream(configFilePath);
            builder = OMXMLBuilderFactory.createOMBuilder(fis);
        } catch (Exception e) {
            throw new TrustException("errorLoadingConfigFile", new String[] { configFilePath });
        }
        return load(builder.getDocumentElement());
    }
}


text:
package pt.up.fe.comp.fsa;

import org.junit.Test;

import java.util.LinkedHashSet;

import static junit.framework.TestCase.*;

public class FSACartesian {

    @Test
    public void TestCartesianGenericUnion() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //ef
            aut1.addEdge("q0", 'e', "q1");
            aut1.addEdge("q1", 'f', "q2");
            aut1.addFinalState("q2");

            FSA aut2 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //a*bb*
            aut2.addEdge("q0", 'a', "q0");
            aut2.addEdge("q0", 'b', "q1");
            aut2.addEdge("q1", 'b', "q1");
            aut2.addFinalState("q1");

            FSA aut3 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //aa*bc*
            aut3.addEdge("q0", 'a', "q1");
            aut3.addEdge("q1", 'a', "q1");
            aut3.addEdge("q1", 'b', "q2");
            aut3.addEdge("q2", 'c', "q2");
            aut3.addFinalState("q2");

            FSA automaton = aut1.cartesian(aut2, FSA.CartesianType.UNION).cartesian(aut3, FSA.CartesianType.UNION);

            assertTrue(automaton.accepts("ef"));
            assertTrue(automaton.accepts("abc"));
            assertTrue(automaton.accepts("aaabccccc"));
            assertTrue(automaton.accepts("aaabbbbbb"));
            assertTrue(automaton.accepts("abbbb"));
            assertTrue(automaton.accepts("bbbb"));

            assertFalse(automaton.accepts(""));
            assertFalse(automaton.accepts("e"));
            assertFalse(automaton.accepts("eff"));
            assertFalse(automaton.accepts("abbc"));
            assertFalse(automaton.accepts("bcccc"));
            assertFalse(automaton.accepts("sfgddd"));
            assertFalse(automaton.accepts("aaacccc"));

        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestCartesianUnionWithComplement() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>());
            aut1.addEdge("q0", 'e', "q1");
            aut1.addEdge("q1", 'f', "q2");
            aut1.addEdge("q2", 'a', "q3");
            aut1.addEdge("q3", 'c', "q4");
            aut1.addEdge("q4", 'l', "q5");
            aut1.addFinalState("q2");

            FSA aut1complement = new FSA(aut1);
            aut1complement.complement();

            FSA automaton = aut1.cartesian(aut1complement, FSA.CartesianType.UNION);

            assertTrue(automaton.acceptsAlphabetKleeneStar());

        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestGenericCartesianIntersection() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //(abc)*
            aut1.addEdge("q0", 'a', "q0");
            aut1.addEdge("q0", 'b', "q0");
            aut1.addEdge("q0", 'c', "q0");
            aut1.addFinalState("q0");

            FSA aut2 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //(ab)*
            aut2.addEdge("q0", 'a', "q0");
            aut2.addEdge("q0", 'b', "q0");
            aut2.addFinalState("q0");

            FSA aut3 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //a*
            aut3.addEdge("q0", 'a', "q0");
            aut3.addFinalState("q0");

            FSA aut4 = aut1.cartesian(aut2, FSA.CartesianType.INTERSECTION);
            FSA automaton = aut4.cartesian(aut3, FSA.CartesianType.INTERSECTION);

            automaton.minimize();

            assertTrue(aut1.accepts("a"));
            assertTrue(aut1.accepts("aa"));
            assertTrue(aut1.accepts(""));
            assertTrue(aut1.accepts("b"));
            assertTrue(aut1.accepts("bb"));
            assertTrue(aut1.accepts("c"));
            assertTrue(aut1.accepts("cc"));

            assertTrue(aut4.accepts("a"));
            assertTrue(aut4.accepts("aa"));
            assertTrue(aut4.accepts(""));
            assertTrue(aut4.accepts("b"));
            assertTrue(aut4.accepts("bb"));
            assertFalse(aut4.accepts("c"));
            assertFalse(aut4.accepts("cc"));

            assertTrue(automaton.accepts("a"));
            assertTrue(automaton.accepts("aa"));
            assertTrue(automaton.accepts(""));
            assertFalse(automaton.accepts("b"));
            assertFalse(automaton.accepts("bb"));
            assertFalse(automaton.accepts("c"));
            assertFalse(automaton.accepts("cc"));

        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestCartesianIntersectionNFAWithDFA() {
        try {
            FSA a = FSALoader.LoadFromFile("dot_dfa_examples/COMP_HW1.gv");
            FSA b = FSALoader.LoadFromFile("dot_dfa_examples/COMP_HW1_NFA.gv");

            FSA automaton = a.cartesian(b, FSA.CartesianType.INTERSECTION);

            assertTrue(automaton.accepts("ef"));
            assertTrue(automaton.accepts("abc"));
            assertTrue(automaton.accepts("aaabccccc"));
            assertTrue(automaton.accepts("aaabbbbbb"));
            assertTrue(automaton.accepts("abbbb"));
            assertTrue(automaton.accepts("bbbb"));

            assertFalse(automaton.accepts(""));
            assertFalse(automaton.accepts("e"));
            assertFalse(automaton.accepts("eff"));
            assertFalse(automaton.accepts("abbc"));
            assertFalse(automaton.accepts("bcccc"));
            assertFalse(automaton.accepts("sfgddd"));
            assertFalse(automaton.accepts("aaacccc"));

        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestCartesianIntersectionWithComplement() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>());
            aut1.addEdge("q0", 'e', "q1");
            aut1.addEdge("q1", 'f', "q2");
            aut1.addEdge("q2", 'a', "q3");
            aut1.addEdge("q3", 'c', "q4");
            aut1.addEdge("q4", 'l', "q5");
            aut1.addFinalState("q2");

            FSA aut1complement = new FSA(aut1);
            aut1complement.complement();

            FSA automaton = aut1.cartesian(aut1complement, FSA.CartesianType.INTERSECTION);

            assertTrue(automaton.doesNotAcceptAnything());
        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestGenericCartesianDifference() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //(abc)*
            aut1.addEdge("q0", 'a', "q0");
            aut1.addFinalState("q0");

            FSA aut2 = new FSA("aut1", "q0", new LinkedHashSet<String>()); //(ab)*
            aut2.addEdge("q0", 'a', "q1");
            aut2.addEdge("q1", 'a', "q2");
            aut2.addEdge("q2", 'a', "q3");
            aut2.addEdge("q3", 'a', "q3");
            aut2.addFinalState("q3");

            FSA automaton = aut1.cartesian(aut2, FSA.CartesianType.DIFF);

            assertTrue(automaton.accepts("a"));
            assertTrue(automaton.accepts("aa"));
            assertTrue(automaton.accepts(""));

            assertFalse(automaton.accepts("aaa"));
            assertFalse(automaton.accepts("aaaa"));
            assertFalse(automaton.accepts("aaaaa"));
            assertFalse(automaton.accepts("aaaaaa"));

        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestCartesianDifferenceWithSelf() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>());
            aut1.addEdge("q0", 'e', "q1");
            aut1.addEdge("q1", 'f', "q2");
            aut1.addEdge("q2", 'a', "q3");
            aut1.addEdge("q3", 'c', "q4");
            aut1.addEdge("q4", 'l', "q5");
            aut1.addFinalState("q2");

            FSA automaton = aut1.cartesian(aut1, FSA.CartesianType.DIFF);

            assertTrue(automaton.doesNotAcceptAnything());
        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void TestCartesianXOR() {
        try {
            FSA aut1 = new FSA("aut1", "q0", new LinkedHashSet<String>());
            aut1.addEdge("q0", 'a', "q0");
            aut1.addEdge("q0", 'c', "q0");
            aut1.addFinalState("q0");

            FSA aut2 = new FSA("aut1", "q0", new LinkedHashSet<String>());
            aut2.addEdge("q0", 'b', "q0");
            aut2.addEdge("q0", 'c', "q0");
            aut2.addFinalState("q0");

            FSA automaton = aut1.cartesian(aut2, FSA.CartesianType.XOR);
            assertTrue(automaton.accepts("a"));
            assertTrue(automaton.accepts("aa"));
            assertTrue(automaton.accepts("aaa"));
            assertTrue(automaton.accepts("ac"));
            assertTrue(automaton.accepts("acacca"));
            assertTrue(automaton.accepts("ccaacaca"));
            assertTrue(automaton.accepts("b"));
            assertTrue(automaton.accepts("bb"));
            assertTrue(automaton.accepts("bbb"));
            assertTrue(automaton.accepts("bc"));
            assertTrue(automaton.accepts("bcbccb"));
            assertTrue(automaton.accepts("ccbbcbcb"));

            assertFalse(automaton.accepts(""));
            assertFalse(automaton.accepts("c"));
            assertFalse(automaton.accepts("cc"));
            assertFalse(automaton.accepts("ccc"));
            assertFalse(automaton.accepts("ab"));
            assertFalse(automaton.accepts("abcacbca"));
            assertFalse(automaton.accepts("sdjgdfjd"));

        } catch (FSAException e) {
            e.printStackTrace();
            fail();
        }
    }
}


text:
package trafo

import (
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/101loops/hrd/entity"
	"github.com/101loops/hrd/internal/types"
	"github.com/101loops/iszero"

	ae "appengine"
	ds "appengine/datastore"
)

var (
	nowFunc = func() time.Time {
		return time.Now()
	}
)

// Save saves the entity to datastore properties.
func (doc *Doc) Save(ctx ae.Context) (props []*ds.Property, err error) {
	src := doc.get()

	// event hook: before save
	if hook, ok := src.(entity.BeforeSaver); ok {
		if err = hook.BeforeSave(); err != nil {
			return
		}
	}

	// timestamp
	now := nowFunc()
	if ts, ok := src.(entity.CreateTimestamper); ok {
		ts.SetCreatedAt(now)
	}
	if ts, ok := src.(entity.UpdateTimestamper); ok {
		ts.SetUpdatedAt(now)
	}

	// export properties
	props, err = doc.toProperties(ctx, "", []string{""}, false)
	if err != nil {
		return
	}

	// event hook: after save
	if hook, ok := src.(entity.AfterSaver); ok {
		if err = hook.AfterSave(); err != nil {
			return
		}
	}

	return
}

func (doc *Doc) toProperties(ctx ae.Context, prefix string, tags []string, multi bool) (res []*ds.Property, err error) {
	var props []*ds.Property
	res = make([]*ds.Property, 0)

	srcVal := doc.val()
	for _, fCodec := range doc.codec.Fields {
		fVal := srcVal.Field(fCodec.Index)
		if !fVal.IsValid() || !fVal.CanSet() {
			continue
		}

		name := fCodec.Attrs["label"].(string)
		if name == "-" {
			continue
		}
		aggrTags := append(tags, fCodec.Tag.Modifiers()...)

		// for slice fields (that aren't []byte), save each element
		if fVal.Kind() == reflect.Slice && fVal.Type() != typeOfByteSlice {
			for i := 0; i < fVal.Len(); i++ {
				props, err = fieldToProps(ctx, prefix, name, aggrTags, true, fVal.Index(i))
				if err != nil {
					return
				}
				res = append(res, props...)
			}
			continue
		}

		props, err = fieldToProps(ctx, prefix, name, aggrTags, multi, fVal)
		if err != nil {
			return
		}
		res = append(res, props...)
	}

	return
}

func fieldToProps(ctx ae.Context, prefix, name string, tags []string, multi bool, v reflect.Value) (props []*ds.Property, err error) {

	// process tags
	indexed := false
	for _, tag := range tags {
		tag = strings.ToLower(tag)
		if tag == "omitempty" {
			if iszero.Value(v) {
				return // ignore complete field if empty
			}
		} else if strings.HasPrefix(tag, "index") {
			indexed = true
			if strings.HasSuffix(tag, ":omitempty") && iszero.Value(v) {
				indexed = false // ignore index if empty
			}
		} else if tag != "" {
			err = fmt.Errorf("unknown tag %q", tag)
			return
		}
	}

	p := &ds.Property{Name: name, NoIndex: !indexed, Multiple: multi}
	if prefix != "" {
		p.Name = prefix + propertySeparator + p.Name
	}
	props = []*ds.Property{p}

	// serialize
	switch x := v.Interface().(type) {
	case time.Time, ae.BlobKey, ae.GeoPoint, *ds.Key:
		p.Value = x
	case types.DSKeyConverter:
		p.Value = x.ToDSKey(ctx)
	case []byte:
		p.Value = x
		p.NoIndex = true
	default:
		switch v.Kind() {
		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
			p.Value = v.Int()
		case reflect.Bool:
			p.Value = v.Bool()
		case reflect.String:
			p.Value = v.String()
		case reflect.Float32, reflect.Float64:
			p.Value = v.Float()
		case reflect.Struct:
			if !v.CanAddr() {
				return nil, fmt.Errorf("unsupported property %q (unaddressable)", name)
			}

			sub, err := newDocFromInst(v.Addr().Interface())
			if err != nil {
				return nil, fmt.Errorf("unsupported property %q (%v)", name, err)
			}

			return sub.toProperties(ctx, name, tags, multi)
		}
	}

	if p.Value == nil {
		err = fmt.Errorf("unsupported struct field type %q", v.Type())
	}

	return
}


text:
define(() => {
	'use strict';

	const SCORING = [1, 0];

	const teamScoreSorter = (a, b) => {
		if(a.disqualified !== b.disqualified) {
			return a.disqualified ? 1 : -1;
		}
		return b.points - a.points;
	};

	const entryScoreSorter = (a, b) => {
		if(a.disqualified !== b.disqualified) {
			return a.disqualified ? 1 : -1;
		}
		return b.points - a.points;
	};

	return {
		score: (config, {teams}) => {
			const gameTeamScores = teams.map((team) => {
				let teamPoints = 0;
				let disqualified = true;
				const entries = [];
				team.entries.forEach((entry) => {
					if(!entry.disqualified) {
						disqualified = false;
						teamPoints += entry.points;
					}
					entries.push({
						id: entry.id,
						points: entry.points,
						disqualified: entry.disqualified,
					});
				});
				entries.sort(entryScoreSorter);
				return {
					id: team.id,
					points: teamPoints,
					disqualified,
					winner: false,
					score: 0,
					entries,
				};
			});
			gameTeamScores.sort(teamScoreSorter);

			let tiedPos = 0;
			let tiedPoints = 0;
			for(let i = 0; i < gameTeamScores.length; ++ i) {
				const place = gameTeamScores[i];
				if(place.points !== tiedPoints) {
					tiedPos = i;
					tiedPoints = place.points;
				}
				if(!place.disqualified && place.points > 0) {
					place.winner = (tiedPos === 0);
					place.score = SCORING[tiedPos];
				}
			}
			return {teams: gameTeamScores};
		},
	};
});