text:
package client

import (
	"bytes"
	"io/ioutil"
	"os"
	"os/exec"
	"runtime"
	"text/template"

	"github.com/ninjasphere/go-ninja/config"
)

var src = `<?xml version="1.0" standalone="no"?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
	<name replace-wildcards="yes">{{.Serial}}</name>
	{{if .Paired}}
		{{if .Master}}
	<service>
		<type>_ninja-homecloud-rest._tcp</type>
		<port>{{.RestPort}}</port>
		<txt-record>ninja.sphere.user_id={{.User}}</txt-record>
		<txt-record>ninja.sphere.node_id={{.Serial}}</txt-record>
		<txt-record>ninja.sphere.site_id={{.Site}}</txt-record>
		<txt-record>ninja.sphere.site_updated={{.SiteUpdated}}</txt-record>
		<txt-record>ninja.sphere.master=true</txt-record>
	</service>
		{{end}}
	<service>
		<type>_ninja-homecloud-mqtt._tcp</type>
		<port>1883</port>
		<txt-record>ninja.sphere.user_id={{.User}}</txt-record>
		<txt-record>ninja.sphere.node_id={{.Serial}}</txt-record>
		<txt-record>ninja.sphere.master={{.Master}}</txt-record>
		<txt-record>ninja.sphere.master_node_id={{.MasterNode}}</txt-record>
		<txt-record>ninja.sphere.site_id={{.Site}}</txt-record>
		<txt-record>ninja.sphere.site_updated={{.SiteUpdated}}</txt-record>
	</service>
	{{else}}
	<service>
		<type>_ninja-setup-assistant-rest._tcp</type>
		<port>8888</port>
		<txt-record>ninja.sphere.node_id={{.Serial}}</txt-record>
	</service>
	{{end}}
</service-group>`

func UpdateSphereAvahiService(isPaired, isMaster bool) error {

	tmpl, err := template.New("avahi").Parse(src)

	if err != nil {
		return err
	}

	serviceDefinition := new(bytes.Buffer)

	err = tmpl.Execute(serviceDefinition, map[string]interface{}{
		"Serial":      config.Serial(),
		"Master":      isMaster,
		"Paired":      isPaired,
		"User":        config.String("", "userId"),
		"Site":        config.String("", "siteId"),
		"MasterNode":  config.String("", "masterNodeId"),
		"SiteUpdated": config.Int(0, "siteUpdated"),
		"RestPort":    config.MustInt("homecloud.rest.port"),
	})

	if err != nil {
		return err
	}

	log.Debugf("Saving service definition", serviceDefinition.String())

	if runtime.GOOS != "linux" {
		log.Warningf("Avahi service definition is not being saved, as platform != linux")
		return nil
	}

	if _, err := os.Stat("/data/etc/avahi/services"); err != nil {
		log.Warningf("Avahi service definition is not being saved, as /data/etc/avahi/services does not exist")
		return nil
	}

	err = ioutil.WriteFile("/data/etc/avahi/services/ninjasphere.service", []byte(serviceDefinition.String()), 0644)

	// HACK: Remove this if it doesn't fix Chris's problem
	exec.Command("service", "avahi-daemon", "restart").Output()

	return err
}


text:
package example;

import javax.enterprise.context.ApplicationScoped;

/**
 * Created by wlw on 14.09.16.
 */
public class Sample {

    public String saySomething() {
        return "something";
    }
}

redpajama_set_name: RedPajamaGithub


text:
{{ day }}

 0}"
      >

          {{ day.label }}

 0">

              {{event.name}}

 0">
            {{event.badge}}

              {{ event.title }}


text:
.argumentation-legend {
    display: flex;
    flex-direction: column;
}

.argumentation-title {
    margin-top: 16px;
}


text:
sap.ui.define(["exports", "sap/ui/webc/common/thirdparty/base/config/Theme", "./v5/line-chart-time-axis", "./v4/line-chart-time-axis"], function (_exports, _Theme, _lineChartTimeAxis, _lineChartTimeAxis2) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  Object.defineProperty(_exports, "accData", {
    enumerable: true,
    get: function () {
      return _lineChartTimeAxis.accData;
    }
  });
  _exports.default = void 0;
  Object.defineProperty(_exports, "ltr", {
    enumerable: true,
    get: function () {
      return _lineChartTimeAxis.ltr;
    }
  });
  _exports.pathData = void 0;
  const pathData = (0, _Theme.isThemeFamily)("sap_horizon") ? _lineChartTimeAxis.pathData : _lineChartTimeAxis2.pathData;
  _exports.pathData = pathData;
  var _default = "line-chart-time-axis";
  _exports.default = _default;
});


text:
namespace Messi.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class MessageTests
    {
        [TestMethod]
        public void GetBody()
        {
            Message message = new Message("Foo");

            Assert.AreEqual("Foo", message.Body);
        }

        [TestMethod]
        public void GetUnknownHeader()
        {
            Message message = new Message(null);

            Assert.IsNull(message.Headers["Foo"]);
        }

        [TestMethod]
        public void SetGetHeader()
        {
            Message message = new Message(null);

            message.Headers["Foo"] = "Bar";

            Assert.AreEqual("Bar", message.Headers["Foo"]);
        }

        [TestMethod]
        public void CloneHeaders()
        {
            Message message = new Message(null);
            message.Headers["Foo"] = "Bar";

            Message message2 = new Message(null, message.Headers);
            message2.Headers["Foo"] = "Baz";
            message2.Headers["Answer"] = 42;

            Assert.AreEqual("Bar", message.Headers["Foo"]);
            Assert.IsNull(message.Headers["Answer"]);
            Assert.AreEqual("Baz", message2.Headers["Foo"]);
            Assert.AreEqual(42, message2.Headers["Answer"]);
        }
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

#ifdef TINYTEST_LOCAL
#include "tinytest_local.h"
#endif

#ifdef WIN32
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif

#ifndef __GNUC__
#define __attribute__(x)
#endif

#include "tinytest.h"
#include "tinytest_macros.h"

#define LONGEST_TEST_NAME 16384

static int in_tinytest_main = 0; /**< true if we're in tinytest_main().*/
static int n_ok = 0; /**< Number of tests that have passed */
static int n_bad = 0; /**< Number of tests that have failed. */
static int n_skipped = 0; /**< Number of tests that have been skipped. */

static int opt_forked = 0; /**< True iff we're called from inside a win32 fork*/
static int opt_nofork = 0; /**< Suppress calls to fork() for debugging. */
static int opt_verbosity = 1; /**< -==quiet,0==terse,1==normal,2==verbose */
const char *verbosity_flag = "";

enum outcome { SKIP=2, OK=1, FAIL=0 };
static enum outcome cur_test_outcome = 0;
const char *cur_test_prefix = NULL; /**< prefix of the current test group */
/** Name of the current test, if we haven't logged is yet. Used for --quiet */
const char *cur_test_name = NULL;

#ifdef WIN32
/* Copy of argv[0] for win32. */
static char commandname[MAX_PATH+1];
#endif

static void usage(struct testgroup_t *groups, int list_groups)
  __attribute__((noreturn));

static enum outcome
_testcase_run_bare(const struct testcase_t *testcase)
{
	void *env = NULL;
	int outcome;
	if (testcase->setup) {
		env = testcase->setup->setup_fn(testcase);
		if (!env)
			return FAIL;
		else if (env == (void*)TT_SKIP)
			return SKIP;
	}

	cur_test_outcome = OK;
	testcase->fn(env);
	outcome = cur_test_outcome;

	if (testcase->setup) {
		if (testcase->setup->cleanup_fn(testcase, env) == 0)
			outcome = FAIL;
	}

	return outcome;
}

#define MAGIC_EXITCODE 42

static enum outcome
_testcase_run_forked(const struct testgroup_t *group,
		     const struct testcase_t *testcase)
{
#ifdef WIN32
	/* Fork? On Win32?  How primitive!  We'll do what the smart kids do:
	   we'll invoke our own exe (whose name we recall from the command
	   line) with a command line that tells it to run just the test we
	   want, and this time without forking.

	   (No, threads aren't an option.  The whole point of forking is to
	   share no state between tests.)
	 */
	int ok;
	char buffer[LONGEST_TEST_NAME+256];
	STARTUPINFOA si;
	PROCESS_INFORMATION info;
	DWORD exitcode;

	if (!in_tinytest_main) {
		printf("\nERROR.  On Windows, _testcase_run_forked must be"
		       " called from within tinytest_main.\n");
		abort();
	}
	if (opt_verbosity>0)
		printf("[forking] ");

	snprintf(buffer, sizeof(buffer), "%s --RUNNING-FORKED %s %s%s",
		 commandname, verbosity_flag, group->prefix, testcase->name);

	memset(&si, 0, sizeof(si));
	memset(&info, 0, sizeof(info));
	si.cb = sizeof(si);

	ok = CreateProcessA(commandname, buffer, NULL, NULL, 0,
			   0, NULL, NULL, &si, &info);
	if (!ok) {
		printf("CreateProcess failed!\n");
		return 0;
	}
	WaitForSingleObject(info.hProcess, INFINITE);
	GetExitCodeProcess(info.hProcess, &exitcode);
	CloseHandle(info.hProcess);
	CloseHandle(info.hThread);
	if (exitcode == 0)
		return OK;
	else if (exitcode == MAGIC_EXITCODE)
		return SKIP;
	else
		return FAIL;
#else
	int outcome_pipe[2];
	pid_t pid;
	(void)group;

	if (pipe(outcome_pipe))
		perror("opening pipe");

	if (opt_verbosity>0)
		printf("[forking] ");
	pid = fork();
	if (!pid) {
		/* child. */
		int test_r, write_r;
		char b[1];
		close(outcome_pipe[0]);
		test_r = _testcase_run_bare(testcase);
		assert(0<=(int)test_r && (int)test_r<=2);
		b[0] = "NYS"[test_r];
		write_r = (int)write(outcome_pipe[1], b, 1);
		if (write_r != 1) {
			perror("write outcome to pipe");
			exit(1);
		}
		exit(0);
		return FAIL; /* unreachable */
	} else {
		/* parent */
		int status, r;
		char b[1];
		/* Close this now, so that if the other side closes it,
		 * our read fails. */
		close(outcome_pipe[1]);
		r = (int)read(outcome_pipe[0], b, 1);
		if (r == 0) {
			printf("[Lost connection!] ");
			return 0;
		} else if (r != 1) {
			perror("read outcome from pipe");
		}
		waitpid(pid, &status, 0);
		close(outcome_pipe[0]);
		return b[0]=='Y' ? OK : (b[0]=='S' ? SKIP : FAIL);
	}
#endif
}

int
testcase_run_one(const struct testgroup_t *group,
		 const struct testcase_t *testcase)
{
	enum outcome outcome;

	if (testcase->flags & TT_SKIP) {
		if (opt_verbosity>0)
			printf("%s%s: SKIPPED\n",
			    group->prefix, testcase->name);
		++n_skipped;
		return SKIP;
	}

	if (opt_verbosity>0 && !opt_forked) {
		printf("%s%s: ", group->prefix, testcase->name);
	} else {
		if (opt_verbosity==0) printf(".");
		cur_test_prefix = group->prefix;
		cur_test_name = testcase->name;
	}

	if ((testcase->flags & TT_FORK) && !(opt_forked||opt_nofork)) {
		outcome = _testcase_run_forked(group, testcase);
	} else {
		outcome = _testcase_run_bare(testcase);
	}

	if (outcome == OK) {
		++n_ok;
		if (opt_verbosity>0 && !opt_forked)
			puts(opt_verbosity==1?"OK":"");
	} else if (outcome == SKIP) {
		++n_skipped;
		if (opt_verbosity>0 && !opt_forked)
			puts("SKIPPED");
	} else {
		++n_bad;
		if (!opt_forked)
			printf("\n  [%s FAILED]\n", testcase->name);
	}

	if (opt_forked) {
		exit(outcome==OK ? 0 : (outcome==SKIP?MAGIC_EXITCODE : 1));
		return 1; /* unreachable */
	} else {
		return (int)outcome;
	}
}

int
_tinytest_set_flag(struct testgroup_t *groups, const char *arg, unsigned long flag)
{
	int i, j;
	size_t length = LONGEST_TEST_NAME;
	char fullname[LONGEST_TEST_NAME];
	int found=0;
	if (strstr(arg, ".."))
		length = strstr(arg,"..")-arg;
	for (i=0; groups[i].prefix; ++i) {
		for (j=0; groups[i].cases[j].name; ++j) {
			snprintf(fullname, sizeof(fullname), "%s%s",
				 groups[i].prefix, groups[i].cases[j].name);
			if (!flag) /* Hack! */
				printf("    %s\n", fullname);
			if (!strncmp(fullname, arg, length)) {
				groups[i].cases[j].flags |= flag;
				++found;
			}
		}
	}
	return found;
}

static void
usage(struct testgroup_t *groups, int list_groups)
{
	puts("Options are: [--verbose|--quiet|--terse] [--no-fork]");
	puts("  Specify tests by name, or using a prefix ending with '..'");
	puts("  To skip a test, list give its name prefixed with a colon.");
	puts("  Use --list-tests for a list of tests.");
	if (list_groups) {
		puts("Known tests are:");
		_tinytest_set_flag(groups, "..", 0);
	}
	exit(0);
}

int
tinytest_main(int c, const char **v, struct testgroup_t *groups)
{
	int i, j, n=0;

#ifdef WIN32
	const char *sp = strrchr(v[0], '.');
	const char *extension = "";
	if (!sp || stricmp(sp, ".exe"))
		extension = ".exe"; /* Add an exe so CreateProcess will work */
	snprintf(commandname, sizeof(commandname), "%s%s", v[0], extension);
	commandname[MAX_PATH]='\0';
#endif
	for (i=1; i<c; ++i) {
		if (v[i][0] == '-') {
			if (!strcmp(v[i], "--RUNNING-FORKED")) {
				opt_forked = 1;
			} else if (!strcmp(v[i], "--no-fork")) {
				opt_nofork = 1;
			} else if (!strcmp(v[i], "--quiet")) {
				opt_verbosity = -1;
				verbosity_flag = "--quiet";
			} else if (!strcmp(v[i], "--verbose")) {
				opt_verbosity = 2;
				verbosity_flag = "--verbose";
			} else if (!strcmp(v[i], "--terse")) {
				opt_verbosity = 0;
				verbosity_flag = "--terse";
			} else if (!strcmp(v[i], "--help")) {
				usage(groups, 0);
			} else if (!strcmp(v[i], "--list-tests")) {
				usage(groups, 1);
			} else {
				printf("Unknown option %s.  Try --help\n",v[i]);
				return -1;
			}
		} else {
			const char *test = v[i];
			int flag = _TT_ENABLED;
			if (test[0] == ':') {
				++test;
				flag = TT_SKIP;
			} else {
				++n;
			}
			if (!_tinytest_set_flag(groups, test, flag)) {
				printf("No such test as %s!\n", v[i]);
				return -1;
			}
		}
	}
	if (!n)
		_tinytest_set_flag(groups, "..", _TT_ENABLED);

	setvbuf(stdout, NULL, _IONBF, 0);

	++in_tinytest_main;
	for (i=0; groups[i].prefix; ++i)
		for (j=0; groups[i].cases[j].name; ++j)
			if (groups[i].cases[j].flags & _TT_ENABLED)
				testcase_run_one(&groups[i],
						 &groups[i].cases[j]);

	--in_tinytest_main;

	if (opt_verbosity==0)
		puts("");

	if (n_bad)
		printf("%d/%d TESTS FAILED. (%d skipped)\n", n_bad,
		       n_bad+n_ok,n_skipped);
	else if (opt_verbosity >= 1)
		printf("%d tests ok.  (%d skipped)\n", n_ok, n_skipped);

	return (n_bad == 0) ? 0 : 1;
}

int
_tinytest_get_verbosity(void)
{
	return opt_verbosity;
}

void
_tinytest_set_test_failed(void)
{
	if (opt_verbosity <= 0 && cur_test_name) {
		if (opt_verbosity==0) puts("");
		printf("%s%s: ", cur_test_prefix, cur_test_name);
		cur_test_name = NULL;
	}
	cur_test_outcome = 0;
}

void
_tinytest_set_test_skipped(void)
{
	if (cur_test_outcome==OK)
		cur_test_outcome = SKIP;
}


text:
package br.edu.ufcg.web;

import br.edu.ufcg.domain.User;
import br.edu.ufcg.domain.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.net.URI;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
@RequestMapping(value="/user", produces="application/json")
public class UserController {

    @Autowired
    UserRepository userRepository;

    @RequestMapping(method=RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Page<User>> getUsers(Pageable pageable){

        Page<User> users = userRepository.findAll(pageable);

        for (User u: users) updateUserResourcesWithLinks(u, pageable);

        return new ResponseEntity<>(users, HttpStatus.OK);
    }

    @RequestMapping(value="/{userCode}", method=RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<User> getUser(@PathVariable long userCode){
        if(userRepository.exists(userCode)){
            User user = userRepository.findOne(userCode);
            updateUserResourcesWithLinks(user, null);
            return new ResponseEntity<>(user, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @RequestMapping(method=RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<User> createUser(@RequestBody User user){
        User u = userRepository.save(user);
        HttpHeaders responseHeaders = new HttpHeaders();
        URI newUserURI = ServletUriComponentsBuilder
                .fromCurrentRequest().path("/{id}")
                .buildAndExpand(user.getId())
                .toUri();
        responseHeaders.setLocation(newUserURI);
        return new ResponseEntity<>(u, responseHeaders, HttpStatus.CREATED);
    }

    @RequestMapping(value="/{userId}", method=RequestMethod.PUT)
    @ResponseBody
    public ResponseEntity<User> updateUser(@PathVariable long userId, @RequestBody User user){
        if(userRepository.exists(userId)){
            user.setUserId(userId);
            User u = userRepository.save(user);
            return new ResponseEntity<>(u, HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    @RequestMapping(value="/{userCode}", method=RequestMethod.DELETE)
    @ResponseBody
    public ResponseEntity<User> deleteUser(@PathVariable long userCode){
        if(userRepository.exists(userCode)){
            userRepository.delete(userCode);
            return new ResponseEntity<>(HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }

    private void updateUserResourcesWithLinks(User user, Pageable pageable){
        user.add(linkTo(methodOn(UserController.class).getUsers(pageable)).slash(user.getUserId()).withSelfRel());
        user.add(linkTo(methodOn(ProblemController.class).getProblems(user.getUserId(), null)).withRel("problems"));
        user.add(linkTo(methodOn(SolutionController.class).getSolutions(user.getUserId(), null, null)).withRel("solutions"));
    }
}


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerInParent="true"
        android:src="@mipmap/ic_launcher" />
</RelativeLayout>


text:
import cPickle as pickle
from math import isnan
import re
import gzip
import optlang
from pandas import read_table, notnull
from cameo.io import _apply_sanitize_rules, ID_SANITIZE_RULES_TAB_COMPLETION, ID_SANITIZE_RULES_SIMPHENY
from cameo import Reaction, Metabolite, Model
from cobra.io.json import save_json_model
from cobra.core.Formula import Formula

import logging

logger = logging.getLogger('parse_metanetx')
# logger.setLevel(logging.DEBUG)

def parse_reaction(formula, irrev_arrow='-->', rev_arrow='<=>'):
    def parse_rhs_side(string):
        return parse_one_side(string, factor=1.)

    def parse_lhs_side(string):
        return parse_one_side(string, factor=-1.)

    def parse_one_side(string, factor=1.):

        def parse_coeff_and_metabolites(term):
            try:
                coeff, metabolite_id = term.strip().split(' ')
            except:
                raise ValueError('Something is fishy with the provided term %s' % term)
            return Metabolite(metabolite_id), factor * float(coeff)

        terms = string.split('+')
        return dict([parse_coeff_and_metabolites(term) for term in terms])

    try:
        (lhs, rhs) = formula.split(irrev_arrow)
    except ValueError:
        try:
            (lhs, rhs) = formula.split(rev_arrow)
        except ValueError:
            raise ValueError('Something is wrong with the provided reaction formula %s' % formula)
    stoichiometry = parse_lhs_side(lhs)
    stoichiometry.update(parse_rhs_side(rhs))
    return stoichiometry

def construct_universal_model(list_of_db_prefixes):
    # Select which reactions to include in universal reaction database

    reaction_selection = reac_prop[[
        any([source.startswith(db_prefix) for db_prefix in list_of_db_prefixes]) and re.match('.*biomass.*', source,
                                                                                re.I) is None for source
        in reac_prop.Source]]
    reactions = list()
    for index, row in reaction_selection.iterrows():
        try:
            stoichiometry = parse_reaction(row.Equation, rev_arrow='=')
        except ValueError:
            continue
        else:
            for met, coeff in stoichiometry.iteritems():
                met.name = chem_prop.loc[met.id]['name']
                try:
                    met.formula = Formula(chem_prop.loc[met.id].formula)
                except:
                    logger.debug('Cannot parse formula %s. Skipping formula' % chem_prop.loc[met.id].formula)
                    continue
                # if met.formula.weight is None:
                #     logger.debug('Cannot calculate weight for formula %s. Skipping reaction %s' % (met.formula, row.Equation))
                #     # print('Cannot calculate weight for formula %s. Skipping reaction %s' % (met.formula, row.Equation))
                #     continue
                try:
                    met.charge = int(chem_prop.loc[met.id].charge)
                except (ValueError, TypeError):
                    logger.debug('Cannot parse charge %s. Skipping charge' % chem_prop.loc[met.id].charge)
                    pass
                rest = chem_prop.loc[met.id].to_dict()
                met.annotation = dict((key, rest[key]) for key in rest if key in ('mass', 'InChI', 'source'))
            mets = [met.id for met in stoichiometry.keys()]
            if len(mets) != len(set(mets)):
                continue
            reaction = Reaction(index)
            reaction.add_metabolites(stoichiometry)
            if reaction.check_mass_balance() != []:
                continue
            if row.Balance:
                reaction.lower_bound = -1 * reaction.upper_bound
            reaction.name = row['Source']
            rest = row.to_dict()
            reaction.annotation = dict((key, rest[key]) for key in rest if key in ('EC', 'Description'))
            reactions.append(reaction)

    model = Model('metanetx_universal_model_' + '_'.join(list_of_db_prefixes), solver_interface=optlang.interface)
    model.add_reactions(reactions)
    # Add sinks for all metabolites
    for metabolite in model.metabolites:
        model.add_demand(metabolite)
    return model

if __name__ == '__main__':

    import logging

    logging.basicConfig(level='INFO')

    # load metanetx data
    chem_xref = read_table('../data/metanetx/chem_xref.tsv.gz', skiprows=124, compression='gzip')
    chem_xref.columns = [name.replace('#', '') for name in chem_xref.columns]
    reac_xref = read_table('../data/metanetx/reac_xref.tsv.gz', skiprows=107, compression='gzip')
    reac_xref.columns = [name.replace('#', '') for name in reac_xref.columns]
    reac_prop = read_table('../data/metanetx/reac_prop.tsv.gz', skiprows=107, compression='gzip', index_col=0)
    reac_prop.columns = [name.replace('#', '') for name in reac_prop.columns]
    chem_prop = read_table('../data/metanetx/chem_prop.tsv.gz', skiprows=125, compression='gzip', index_col=0,
                           names=['name', 'formula', 'charge', 'mass', 'InChI', 'SMILES', 'source'])

    # replace NaN with None
    chem_prop = chem_prop.where((notnull(chem_prop)), None)

    REVERSE_ID_SANITIZE_RULES_SIMPHENY = [(value, key) for key, value in ID_SANITIZE_RULES_SIMPHENY]

    metanetx = dict()
    # Metabolites
    bigg_selection = chem_xref[['bigg' in blub for blub in chem_xref.XREF]]
    sanitized_XREF = [
        _apply_sanitize_rules(_apply_sanitize_rules(id.replace('bigg:', ''), REVERSE_ID_SANITIZE_RULES_SIMPHENY),
                              ID_SANITIZE_RULES_TAB_COMPLETION) for id in bigg_selection.XREF]
    bigg2mnx = dict(zip(sanitized_XREF, bigg_selection.MNX_ID))
    mnx2bigg = dict(zip(bigg_selection.MNX_ID, sanitized_XREF))

    # Reactions
    bigg_selection = reac_xref[['bigg' in blub for blub in reac_xref.XREF]]
    sanitized_XREF = [
        _apply_sanitize_rules(_apply_sanitize_rules(id.replace('bigg:', ''), REVERSE_ID_SANITIZE_RULES_SIMPHENY),
                              ID_SANITIZE_RULES_TAB_COMPLETION) for id in bigg_selection.XREF]
    bigg2mnx.update(dict(zip(sanitized_XREF, bigg_selection.MNX_ID)))
    mnx2bigg.update(dict(zip(bigg_selection.MNX_ID, sanitized_XREF)))

    # put into final result dict
    metanetx['bigg2mnx'] = bigg2mnx
    metanetx['mnx2bigg'] = mnx2bigg

    all2mnx = dict()
    for other_id, mnx_id in chem_xref[['XREF', 'MNX_ID']].values:
        cleaned_key = _apply_sanitize_rules(
            _apply_sanitize_rules(other_id.split(':')[1], REVERSE_ID_SANITIZE_RULES_SIMPHENY),
            ID_SANITIZE_RULES_TAB_COMPLETION)
        all2mnx[cleaned_key] = mnx_id
    for other_id, mnx_id in reac_xref[['XREF', 'MNX_ID']].values:
        cleaned_key = _apply_sanitize_rules(
            _apply_sanitize_rules(other_id.split(':')[1], REVERSE_ID_SANITIZE_RULES_SIMPHENY),
            ID_SANITIZE_RULES_TAB_COMPLETION)
        all2mnx[cleaned_key] = mnx_id

    metanetx['all2mnx'] = all2mnx
    with open('../cameo/data/metanetx.pickle', 'wb') as f:
        pickle.dump(metanetx, f)

    # generate universal reaction models
    db_combinations = [('bigg',), ('rhea',), ('bigg', 'rhea'), ('bigg', 'rhea', 'kegg'),
                       ('bigg', 'rhea', 'kegg', 'brenda')]
    for db_combination in db_combinations:
        universal_model = construct_universal_model(db_combination)
        # The following is a hack; uncomment the following
        import json
        from cobra.io.json import _to_dict, _DEFAULT_REACTION_ATTRIBUTES

        _DEFAULT_REACTION_ATTRIBUTES.add('annotation')
        d_model = _to_dict(universal_model)
        with open('../cameo/models/universal_models/{model_name}.json'.format(model_name=universal_model.id), 'w') as f:
            json.dump(d_model, f)
            # save_json_model(universal_model, '../cameo/models/universal_models/{model_name}.json'.format(model_name=universal_model.id))
    chem_prop_filtered = chem_prop[
        [any([source.startswith(db) for db in ('bigg', 'rhea', 'kegg', 'brenda', 'chebi')]) for source in
         chem_prop.source]]
    chem_prop_filtered = chem_prop_filtered.dropna(subset=['name'])
    with gzip.open('../cameo/data/metanetx_chem_prop.pklz', 'wb') as f:
        pickle.dump(chem_prop_filtered, f)


text:
import { SecurePayment_artwork } from "__generated__/SecurePayment_artwork.graphql"
import { renderRelayTree } from "DevTools"
import React from "react"
import { graphql } from "react-relay"
import { ExtractProps } from "Utils/ExtractProps"
import { SecurePaymentFragmentContainer } from "../SecurePayment"

jest.unmock("react-relay")

const render = (
  artwork: Omit<SecurePayment_artwork, " $refType">,
  extraProps?: Partial<ExtractProps<typeof SecurePaymentFragmentContainer>>
) =>
  renderRelayTree({
    Component: (props: any) => (
      <SecurePaymentFragmentContainer
        artwork={{
          ...artwork,
        }}
        {...props}
        {...extraProps}
      />
    ),
    mockData: {
      artwork,
    },
    query: graphql`
      query SecurePaymentTestQuery {
        artwork(id: "whatevs") {
          ...SecurePayment_artwork
        }
      }
    `,
  })

describe("SecurePayment", () => {
  it("Doesn't render when work is neither acquireable nor offerable", async () => {
    const component = await render({
      is_acquireable: false,
      is_offerable: false,
    })
    expect(component.find("TrustSignal").length).toBe(0)
  })

  it("Renders when the artwork is acquireable", async () => {
    const component = await render({
      is_acquireable: true,
      is_offerable: false,
    })
    expect(component.find("TrustSignal").length).toBe(1)
  })

  it("Renders when the artwork is offerable", async () => {
    const component = await render({
      is_acquireable: false,
      is_offerable: true,
    })
    expect(component.find("TrustSignal").length).toBe(1)
  })
})


text:
<?php
namespace PSFS\Services;

use Propel\Generator\Config\GeneratorConfig;
use Propel\Generator\Manager\AbstractManager;
use Propel\Generator\Manager\ModelManager;
use Propel\Generator\Manager\SqlManager;
use PSFS\base\Cache;
use PSFS\base\config\Config;
use PSFS\base\exception\ConfigException;
use PSFS\base\Logger;
use PSFS\base\Service;
use PSFS\base\types\helpers\GeneratorHelper;
use Symfony\Component\Filesystem\Filesystem;

class GeneratorService extends Service
{
    /**
     * @Injectable
     * @var \PSFS\base\config\Config Servicio de configuración
     */
    protected $config;
    /**
     * @Injectable
     * @var \PSFS\base\Security Servicio de autenticación
     */
    protected $security;
    /**
     * @Injectable
     * @var \PSFS\base\Template Servicio de gestión de plantillas
     */
    protected $tpl;

    /**
     * Método que revisa las traducciones directorio a directorio
     * @param $path
     * @param $locale
     * @return array
     */
    public static function findTranslations($path, $locale)
    {
        $localePath = realpath(BASE_DIR . DIRECTORY_SEPARATOR . 'locale');
        $localePath .= DIRECTORY_SEPARATOR . $locale . DIRECTORY_SEPARATOR . 'LC_MESSAGES' . DIRECTORY_SEPARATOR;

        $translations = array();
        if (file_exists($path)) {
            $d = dir($path);
            while (false !== ($dir = $d->read())) {
                GeneratorHelper::createDir($localePath);
                if (!file_exists($localePath . 'translations.po')) {
                    file_put_contents($localePath . 'translations.po', '');
                }
                $inspect_path = realpath($path . DIRECTORY_SEPARATOR . $dir);
                $cmd_php = "export PATH=\$PATH:/opt/local/bin; xgettext " .
                    $inspect_path . DIRECTORY_SEPARATOR .
                    "*.php --from-code=UTF-8 -j -L PHP --debug --force-po -o {$localePath}translations.po";
                if (is_dir($path . DIRECTORY_SEPARATOR . $dir) && preg_match('/^\./', $dir) == 0) {
                    $res = t('Revisando directorio: ') . $inspect_path;
                    $res .= t('Comando ejecutado: ') . $cmd_php;
                    $res .= shell_exec($cmd_php);
                    usleep(10);
                    $translations[] = $res;
                    $translations = array_merge($translations, self::findTranslations($inspect_path, $locale));
                }
            }
        }
        return $translations;
    }

    /**
     * Servicio que genera la estructura de un módulo o lo actualiza en caso de ser necesario
     * @param string $module
     * @param boolean $force
     * @param string $type
     * @param string $apiClass
     * @return mixed
     */
    public function createStructureModule($module, $force = false, $type = "", $apiClass = "")
    {
        $mod_path = CORE_DIR . DIRECTORY_SEPARATOR;
        $module = ucfirst($module);
        $this->createModulePath($module, $mod_path);
        $this->createModulePathTree($module, $mod_path);
        $this->createModuleBaseFiles($module, $mod_path, $force, $type);
        $this->createModuleModels($module, $mod_path);
        $this->generateBaseApiTemplate($module, $mod_path, $force, $apiClass);
        //Redireccionamos al home definido
        $this->log->addLog("Módulo generado correctamente");
    }

    /**
     * Service that creates the root paths for the modules
     * @param string $module
     * @param string $mod_path
     */
    private function createModulePath($module, $mod_path)
    {
        // Creates the src folder
        GeneratorHelper::createDir($mod_path);
        // Create module path
        GeneratorHelper::createDir($mod_path . $module);
    }

    /**
     * Servicio que genera la estructura base
     * @param string $module
     * @param boolean $mod_path
     * @return boolean
     */
    private function createModulePathTree($module, $mod_path)
    {
        //Creamos las carpetas CORE del módulo
        $this->log->addLog("Generamos la estructura");
        $paths = [
            "Api", "Api/base", "Config", "Controller", "Models", "Public", "Templates", "Services", "Test", "Doc",
            "Locale", "Locale/" . Config::getParam('default.locale', 'es_ES'), "Locale/" . Config::getParam('default.locale', 'es_ES') . "/LC_MESSAGES"
        ];
        $module_path = $mod_path . $module;
        foreach ($paths as $path) {
            GeneratorHelper::createDir($module_path . DIRECTORY_SEPARATOR . $path);
        }
        //Creamos las carpetas de los assets
        $htmlPaths = array("css", "js", "img", "media", "font");
        foreach ($htmlPaths as $path) {
            GeneratorHelper::createDir($module_path . DIRECTORY_SEPARATOR . "Public" . DIRECTORY_SEPARATOR . $path);
        }
    }

    /**
     * Servicio que genera las plantillas básicas de ficheros del módulo
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @param string $controllerType
     */
    private function createModuleBaseFiles($module, $mod_path, $force = false, $controllerType = '')
    {
        $module_path = $mod_path . $module;
        $this->generateControllerTemplate($module, $module_path, $force, $controllerType);
        $this->generateServiceTemplate($module, $module_path, $force);
        $this->genereateAutoloaderTemplate($module, $module_path, $force);
        $this->generateSchemaTemplate($module, $module_path, $force);
        $this->generatePropertiesTemplate($module, $module_path, $force);
        $this->generateConfigTemplate($module_path, $force);
        $this->generateIndexTemplate($module, $module_path, $force);
        $this->generatePublicTemplates($module_path, $force);
    }

    /**
     * Servicio que ejecuta Propel y genera el modelo de datos
     * @param string $module
     * @param string $path
     */
    private function createModuleModels($module, $path)
    {
        $module_path = $path . $module;
        $module_path = str_replace(CORE_DIR . DIRECTORY_SEPARATOR, '', $module_path);

        $configGenerator = $this->getConfigGenerator($module_path);

        $this->buildModels($configGenerator);
        $this->buildSql($configGenerator);

        $configTemplate = $this->tpl->dump("generator/config.propel.template.twig", array(
            "module" => $module,
        ));
        $this->writeTemplateToFile($configTemplate, CORE_DIR . DIRECTORY_SEPARATOR . $module_path . DIRECTORY_SEPARATOR . "Config" .
            DIRECTORY_SEPARATOR . "config.php", true);
        $this->log->addLog("Generado config genérico para propel");
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @param string $controllerType
     * @return boolean
     */
    private function generateControllerTemplate($module, $mod_path, $force = false, $controllerType = "")
    {
        //Generamos el controlador base
        $this->log->addLog("Generamos el controlador BASE");
        $class = preg_replace('/(\\\|\/)/', '', $module);
        $controllerBody = $this->tpl->dump("generator/controller.template.twig", array(
            "module" => $module,
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
            "class" => $class,
            "controllerType" => $class . "Base",
            "is_base" => false
        ));
        $controller = $this->writeTemplateToFile($controllerBody, $mod_path . DIRECTORY_SEPARATOR . "Controller" .
            DIRECTORY_SEPARATOR . "{$class}Controller.php", $force);

        $controllerBody = $this->tpl->dump("generator/controller.template.twig", array(
            "module" => $module,
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
            "class" => $class . "Base",
            "service" => $class,
            "controllerType" => $controllerType,
            "is_base" => true,
            "domain" => $class,
        ));
        $controllerBase = $this->writeTemplateToFile($controllerBody, $mod_path . DIRECTORY_SEPARATOR . "Controller" .
            DIRECTORY_SEPARATOR . "base" . DIRECTORY_SEPARATOR . "{$class}BaseController.php", true);

        $filename = $mod_path . DIRECTORY_SEPARATOR . "Test" . DIRECTORY_SEPARATOR . "{$class}Test.php";
        $test = true;
        if(!file_exists($filename)) {
            $testTemplate = $this->tpl->dump("generator/testCase.template.twig", array(
                "module" => $module,
                "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
                "class" => $class,
            ));
            $test = $this->writeTemplateToFile($testTemplate, $filename, true);
        }
        return ($controller && $controllerBase && $test);
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @param string $apiClass
     * @return boolean
     */
    private function generateBaseApiTemplate($module, $mod_path, $force = false, $apiClass = "")
    {
        $created = true;
        $modelPath = $mod_path . $module . DIRECTORY_SEPARATOR . 'Models';
        $api_path = $mod_path . $module . DIRECTORY_SEPARATOR . 'Api';
        if (file_exists($modelPath)) {
            $dir = dir($modelPath);
            while ($file = $dir->read()) {
                if (!in_array($file, array('.', '..'))
                    && !preg_match('/Query\.php$/i', $file)
                    && preg_match('/\.php$/i', $file)
                ) {
                    $filename = str_replace(".php", "", $file);
                    $this->log->addLog("Generamos Api BASES para {$filename}");
                    $this->createApiBaseFile($module, $api_path, $filename, $apiClass);
                    $this->createApi($module, $api_path, $force, $filename);
                }
            }
        }
        return $created;
    }

    /**
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function generateConfigTemplate($mod_path, $force = false)
    {
        //Generamos el fichero de configuración
        $this->log->addLog("Generamos fichero vacío de configuración");
        return $this->writeTemplateToFile("<?php\n\t",
            $mod_path . DIRECTORY_SEPARATOR . "Config" . DIRECTORY_SEPARATOR . "config.php",
            $force);
    }

    /**
     * @param string $mod_path
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function generatePublicTemplates($mod_path, $force = false)
    {
        //Generamos el fichero de configuración
        $this->log->addLog("Generamos ficheros para assets base");
        $css = $this->writeTemplateToFile("/* CSS3 STYLES */\n\n",
            $mod_path . DIRECTORY_SEPARATOR . "Public" . DIRECTORY_SEPARATOR . "css" . DIRECTORY_SEPARATOR . "styles.css",
            $force);
        $js = $this->writeTemplateToFile("/* APP MODULE JS */\n\n(function() {\n\t'use strict';\n})();",
            $mod_path . DIRECTORY_SEPARATOR . "Public" . DIRECTORY_SEPARATOR . "js" . DIRECTORY_SEPARATOR . "app.js",
            $force);
        return ($css && $js);
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function generateServiceTemplate($module, $mod_path, $force = false)
    {
        //Generamos el controlador base
        $this->log->addLog("Generamos el servicio BASE");
        $class = preg_replace('/(\\\|\/)/', '', $module);
        $controller = $this->tpl->dump("generator/service.template.twig", array(
            "module" => $module,
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
            "class" => $class,
        ));
        return $this->writeTemplateToFile($controller,
            $mod_path . DIRECTORY_SEPARATOR . "Services" . DIRECTORY_SEPARATOR . "{$class}Service.php",
            $force);
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function genereateAutoloaderTemplate($module, $mod_path, $force = false)
    {
        //Generamos el autoloader del módulo
        $this->log->addLog("Generamos el autoloader");
        $autoloader = $this->tpl->dump("generator/autoloader.template.twig", array(
            "module" => $module,
            "autoloader" => preg_replace('/(\\\|\/)/', '_', $module),
            "regex" => preg_replace('/(\\\|\/)/m', '\\\\\\\\\\\\', $module),
        ));
        $autoload = $this->writeTemplateToFile($autoloader, $mod_path . DIRECTORY_SEPARATOR . "autoload.php", $force);

        $this->log->addLog("Generamos el phpunit");
        $phpUnitTemplate = $this->tpl->dump("generator/phpunit.template.twig", array(
            "module" => $module,
        ));
        $phpunit = $this->writeTemplateToFile($phpUnitTemplate, $mod_path . DIRECTORY_SEPARATOR . "phpunit.xml.dist", $force);
        return $autoload && $phpunit;
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function generateSchemaTemplate($module, $mod_path, $force = false)
    {
        //Generamos el autoloader del módulo
        $this->log->addLog("Generamos el schema");
        $schema = $this->tpl->dump("generator/schema.propel.twig", array(
            "module" => $module,
            "namespace" => preg_replace('/(\\\|\/)/', '', $module),
            "prefix" => preg_replace('/(\\\|\/)/', '', $module),
            "db" => $this->config->get("db_name"),
        ));
        return $this->writeTemplateToFile($schema,
            $mod_path . DIRECTORY_SEPARATOR . "Config" . DIRECTORY_SEPARATOR . "schema.xml",
            $force);
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function generatePropertiesTemplate($module, $mod_path, $force = false)
    {
        $this->log->addLog("Generamos la configuración de Propel");
        $build_properties = $this->tpl->dump("generator/build.properties.twig", array(
            "module" => $module,
            "namespace" => preg_replace('/(\\\|\/)/', '', $module),
        ));
        return $this->writeTemplateToFile($build_properties,
            $mod_path . DIRECTORY_SEPARATOR . "Config" . DIRECTORY_SEPARATOR . "propel.yml",
            $force);
    }

    /**
     * @param string $module
     * @param string $mod_path
     * @param boolean $force
     * @return boolean
     */
    private function generateIndexTemplate($module, $mod_path, $force = false)
    {
        //Generamos la plantilla de index
        $this->log->addLog("Generamos una plantilla base por defecto");
        $index = $this->tpl->dump("generator/index.template.twig", array(
            "module" => $module,
        ));
        return $this->writeTemplateToFile($index,
            $mod_path . DIRECTORY_SEPARATOR . "Templates" . DIRECTORY_SEPARATOR . "index.html.twig",
            $force);
    }

    /**
     * Método que graba el contenido de una plantilla en un fichero
     * @param string $fileContent
     * @param string $filename
     * @param boolean $force
     * @return boolean
     */
    private function writeTemplateToFile($fileContent, $filename, $force = false)
    {
        $created = false;
        if ($force || !file_exists($filename)) {
            try {
                $this->cache->storeData($filename, $fileContent, Cache::TEXT, true);
                $created = true;
            } catch (\Exception $e) {
                Logger::log($e->getMessage(), LOG_ERR);
            }
        } else {
            Logger::log($filename . t(' not exists or cant write'), LOG_ERR);
        }
        return $created;
    }

    /**
     * Create ApiBase
     * @param string $module
     * @param string $mod_path
     * @param string $api
     * @param string $apiClass
     *
     * @return bool
     */
    private function createApiBaseFile($module, $mod_path, $api, $apiClass = '')
    {
        $class = preg_replace('/(\\\|\/)/', '', $module);
        $customClass = GeneratorHelper::extractClassFromNamespace($apiClass);
        $controller = $this->tpl->dump("generator/api.base.template.twig", array(
            "module" => $module,
            "api" => $api,
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
            "class" => $class,
            'customClass' => $customClass,
            'customNamespace' => $apiClass,
        ));

        return $this->writeTemplateToFile($controller,
            $mod_path . DIRECTORY_SEPARATOR . 'base' . DIRECTORY_SEPARATOR . "{$api}BaseApi.php", true);
    }

    /**
     * Create Api
     * @param string $module
     * @param string $mod_path
     * @param bool $force
     * @param string $api
     *
     * @return bool
     */
    private function createApi($module, $mod_path, $force, $api)
    {
        $class = preg_replace('/(\\\|\/)/', '', $module);
        $controller = $this->tpl->dump("generator/api.template.twig", array(
            "module" => $module,
            "api" => $api,
            "namespace" => preg_replace('/(\\\|\/)/', '\\', $module),
            "url" => preg_replace('/(\\\|\/)/', '/', $module),
            "class" => $class,
        ));

        return $this->writeTemplateToFile($controller, $mod_path . DIRECTORY_SEPARATOR . "{$api}.php", $force);
    }

    /**
     * Method that copy resources recursively
     * @param string $dest
     * @param boolean $force
     * @param $filename_path
     * @param boolean $debug
     */
    public static function copyResources($dest, $force, $filename_path, $debug)
    {
        if (file_exists($filename_path)) {
            $destfolder = basename($filename_path);
            if (!file_exists(WEB_DIR . $dest . DIRECTORY_SEPARATOR . $destfolder) || $debug || $force) {
                if (is_dir($filename_path)) {
                    self::copyr($filename_path, WEB_DIR . $dest . DIRECTORY_SEPARATOR . $destfolder);
                } else {
                    if (@copy($filename_path, WEB_DIR . $dest . DIRECTORY_SEPARATOR . $destfolder) === FALSE) {
                        throw new ConfigException("Can't copy " . $filename_path . " to " . WEB_DIR . $dest . DIRECTORY_SEPARATOR . $destfolder);
                    }
                }
            }
        }
    }

    /**
     * Method that copy a resource
     * @param string $src
     * @param string $dst
     * @throws ConfigException
     */
    public static function copyr($src, $dst)
    {
        $dir = opendir($src);
        GeneratorHelper::createDir($dst);
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($src . '/' . $file)) {
                    self::copyr($src . '/' . $file, $dst . '/' . $file);
                } elseif (@copy($src . '/' . $file, $dst . '/' . $file) === false) {
                    throw new ConfigException("Can't copy " . $src . " to " . $dst);
                }
            }
        }
        closedir($dir);
    }

    /**
     * @param $module_path
     * @return array
     */
    private function getPropelPaths($module_path)
    {
        $moduleDir = CORE_DIR . DIRECTORY_SEPARATOR . $module_path;
        GeneratorHelper::createDir($moduleDir);
        $moduleDir = realpath($moduleDir);
        $configDir = $moduleDir . DIRECTORY_SEPARATOR . 'Config';
        $sqlDir = $moduleDir . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . 'Sql';
        $migrationDir = $moduleDir . DIRECTORY_SEPARATOR . 'Config' . DIRECTORY_SEPARATOR . 'Migrations';
        $paths = [
            'projectDir' => $moduleDir,
            'outputDir' => $moduleDir,
            'phpDir' => $moduleDir,
            'phpConfDir' => $configDir,
            'sqlDir' => $sqlDir,
            'migrationDir' => $migrationDir,
            'schemaDir' => $configDir,
        ];
        return $paths;
    }

    /**
     * @param string $module_path
     * @return GeneratorConfig
     */
    private function getConfigGenerator($module_path)
    {
        // Generate the configurator
        $paths = $this->getPropelPaths($module_path);
        foreach ($paths as $path) {
            GeneratorHelper::createDir($path);
        }
        $configGenerator = new GeneratorConfig($paths['phpConfDir'], [
            'propel' => [
                'paths' => $paths,
            ]
        ]);
        return $configGenerator;
    }

    /**
     * @param GeneratorConfig $configGenerator
     */
    private function buildModels(GeneratorConfig $configGenerator)
    {
        $manager = new ModelManager();
        $manager->setFilesystem(new Filesystem());
        $this->setupManager($configGenerator, $manager);
        $manager->build();
    }

    /**
     * @param GeneratorConfig $configGenerator
     */
    private function buildSql(GeneratorConfig $configGenerator)
    {
        $manager = new SqlManager();
        $connections = $configGenerator->getBuildConnections();
        $manager->setConnections($connections);
        $manager->setValidate(true);
        $this->setupManager($configGenerator, $manager, $configGenerator->getSection('paths')['sqlDir']);

        $manager->buildSql();
    }

    /**
     * @param GeneratorConfig $configGenerator
     * @param AbstractManager $manager
     * @param string $workingDir
     */
    private function setupManager(GeneratorConfig $configGenerator, AbstractManager &$manager, $workingDir = CORE_DIR)
    {
        $manager->setGeneratorConfig($configGenerator);
        $schemaFile = new \SplFileInfo($configGenerator->getSection('paths')['schemaDir'] . DIRECTORY_SEPARATOR . 'schema.xml');
        $manager->setSchemas([$schemaFile]);
        $manager->setLoggerClosure(function ($message) {
            Logger::log($message, LOG_INFO);
        });
        $manager->setWorkingDirectory($workingDir);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.planner.optimizations;

import com.facebook.presto.Session;
import com.facebook.presto.SystemSessionProperties;
import com.facebook.presto.sql.planner.Plan;
import com.facebook.presto.sql.planner.assertions.ExpectedValueProvider;
import com.facebook.presto.sql.planner.assertions.PlanAssert;
import com.facebook.presto.sql.planner.assertions.PlanMatchPattern;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.testing.LocalQueryRunner;
import com.facebook.presto.tpch.TpchConnectorFactory;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.intellij.lang.annotations.Language;
import org.testng.annotations.Test;

import java.util.List;
import java.util.Map;
import java.util.Optional;

import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.aggregation;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.anySymbol;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.anyTree;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.functionCall;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.groupingSet;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.project;
import static com.facebook.presto.sql.planner.assertions.PlanMatchPattern.tableScan;
import static com.facebook.presto.testing.TestingSession.testSessionBuilder;
import static com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME;

public class TestMixedDistinctAggregationOptimizer
{
    private final LocalQueryRunner queryRunner;

    public TestMixedDistinctAggregationOptimizer()
    {
        Session defaultSession = testSessionBuilder()
                .setCatalog("local")
                .setSchema(TINY_SCHEMA_NAME)
                .setSystemProperty(SystemSessionProperties.OPTIMIZE_DISTINCT_AGGREGATIONS, "true")
                .build();

        this.queryRunner = new LocalQueryRunner(defaultSession);
        queryRunner.createCatalog(queryRunner.getDefaultSession().getCatalog().get(),
                new TpchConnectorFactory(1),
                ImmutableMap.of());
    }

    @Test
    public void testMixedDistinctAggregationOptimizer()
    {
        @Language("SQL") String sql = "SELECT custkey, max(totalprice) AS s, count(DISTINCT orderdate) AS d FROM orders GROUP BY custkey";

        String group = "GROUP";

        // Original keys
        String groupBy = "CUSTKEY";
        String aggregate = "TOTALPRICE";
        String distinctAggregation = "ORDERDATE";

        // Second Aggregation data
        List<String> groupByKeysSecond = ImmutableList.of(groupBy);
        Map<Optional<String>, ExpectedValueProvider<FunctionCall>> aggregationsSecond = ImmutableMap.of(
                Optional.of("arbitrary"), PlanMatchPattern.functionCall("arbitrary", false, ImmutableList.of(anySymbol())),
                Optional.of("count"), PlanMatchPattern.functionCall("count", false, ImmutableList.of(anySymbol())));

        // First Aggregation data
        List<String> groupByKeysFirst = ImmutableList.of(groupBy, distinctAggregation, group);
        Map<Optional<String>, ExpectedValueProvider<FunctionCall>> aggregationsFirst = ImmutableMap.of(
                Optional.of("MAX"), functionCall("max", ImmutableList.of("TOTALPRICE")));

        PlanMatchPattern tableScan = tableScan("orders", ImmutableMap.of("TOTALPRICE", "totalprice", "CUSTKEY", "custkey", "ORDERDATE", "orderdate"));

        // GroupingSet symbols
        ImmutableList.Builder<List<String>> groups = ImmutableList.builder();
        groups.add(ImmutableList.of(groupBy, aggregate));
        groups.add(ImmutableList.of(groupBy, distinctAggregation));
        PlanMatchPattern expectedPlanPattern = anyTree(
                aggregation(ImmutableList.of(groupByKeysSecond), aggregationsSecond, ImmutableMap.of(), Optional.empty(),
                        project(
                                aggregation(ImmutableList.of(groupByKeysFirst), aggregationsFirst, ImmutableMap.of(), Optional.empty(),
                                        groupingSet(groups.build(), group,
                                                anyTree(tableScan))))));

        List<PlanOptimizer> optimizerProvider = ImmutableList.of(
                new UnaliasSymbolReferences(),
                new PruneIdentityProjections(),
                new OptimizeMixedDistinctAggregations(queryRunner.getMetadata()),
                new PruneUnreferencedOutputs());

        queryRunner.inTransaction(transactionSession -> {
            Plan actualPlan = queryRunner.createPlan(transactionSession, sql, optimizerProvider);
            PlanAssert.assertPlan(transactionSession, queryRunner.getMetadata(), actualPlan, expectedPlanPattern);
            return null;
        });
    }
}


text:
const selectedOptions = (state = [], action) => {
  switch (action.type) {
    case 'TOGGLE_OPTION':
      let option = action.optionName
      if (state.includes(option)) {
        return removeItemFromArray(state, option)
      } else {
        return [...state, option]
      }
    default:
      return state
  }
}

export default selectedOptions

const removeItemFromArray = (theArray, theItem) => {
  let deleteIndex = theArray.indexOf(theItem)
  return [
    ...theArray.slice(0, deleteIndex),
    ...theArray.slice(deleteIndex + 1)
  ]
}


text:
FROM node:8
MAINTAINER Matt Malone <swapthatspoon@gmail.com>

RUN mkdir -p /app
WORKDIR /app

# yarn.lock & package.json are added separately from the app to speed up build time if those haven't changed.
RUN npm install yarn
COPY yarn.lock /app/
COPY package.json /app/
RUN yarn install

ARG GIT_SHA1
RUN echo "export GIT_SHA1=$GIT_SHA1" >> /root/.bashrc
COPY . /app/

ENTRYPOINT ["/app/container/docker-entrypoint.sh"]
CMD ["run"]
EXPOSE 3000


text:
<resources>
    <string name="app_name">FlashBusBenchmark</string>
</resources>


text:
/* Depandances PROVIDE :
 * =====================
 */
stage.provide("ui.layout.accordion");
/*
 * Depandances REQUIRE :
 * =====================
 */
stage.require("ui");
stage.require("ui.container");

stage.ui.registerLayout("Accordion", function(){

	var defaultSlotsSettingsAccordion = {
		ctype   : "panel",
		height	: 26,
		border	: "0",
		effect	: "sinusoidal"
	};

	var accordion = function( container, localSettings){
		if (! localSettings )
			localSettings = {};
		if ( ! localSettings.area )
			localSettings["area"] = "vertical";

		localSettings["align"] = "stretch";

		this.activedSlot = null;
		this.lastSlot = null;

		this.layout_mother = this.$super;
		this.layout_mother.constructor(container, localSettings);
		this.notificationsCenter = stage.createEventsManager();

	};

	accordion.prototype.addSlot = function(localSettings){

		localSettings.containerClass ?
			localSettings.containerClass += " stageui-accordion stageui-accordion-last-collapsed" :
			localSettings.containerClass = "stageui-accordion stageui-accordion-last-collapsed";

		if(this.nbslots === 0){
			localSettings.flex = 1;
			localSettings.border = "0 0 1 0";
		}else{
			stage.css.removeClass(this.slots[this.nbslots - 1].container, "stageui-accordion-last-collapsed");
		}

		var slot = this.layout_mother.addSlot(stage.extend(true, {}, defaultSlotsSettingsAccordion, localSettings ));

		if(this.nbslots === 1){
			this.activedSlot = slot;
			this.lastSlot = slot;
			stage.css.addClass(this.activedSlot.container, "stageui-accordion-active-panel");
		}

		stage.listen(slot.header, "click", stage.setContext(function(slot, event){
				this.handleActive(slot);
				this.notificationsCenter.fireEvent("enterSlot", slot , event);
		}, this, slot));
		return slot;
	};

	accordion.prototype.handleActive = function(slot){

		if (slot !== this.activedSlot){
			stage.css.removeClass(this.activedSlot.container, "stageui-accordion-active-panel");

			this.slotsSanitized[this.activedSlot.indexLayout].flex 	 = 0;
			this.slotsSanitized[this.activedSlot.indexLayout].height = 26;
			this.slotsSanitized[this.activedSlot.indexLayout].border = "0";

			// change the active class
			this.lastSlot = this.activedSlot;
			this.activedSlot = slot;
			stage.css.addClass(this.activedSlot.container, "stageui-accordion-active-panel");

			// change settings for the new active panel before doLayout
			this.slotsSanitized[slot.indexLayout].flex 	 = 1;
			this.slotsSanitized[slot.indexLayout].border = "0 0 1 0";

			if((this.nbslots - 1) == slot.indexLayout){
				stage.css.removeClass(slot.container, "stageui-accordion-last-collapsed");
				this.slots[slot.indexLayout].border = "0";
			}else{
				stage.css.addClass(this.slots[this.nbslots - 1].container, "stageui-accordion-last-collapsed");
			}

			this.render();
		}
	};

	return accordion;

});


text:
This event is fired whenever an entity is knocked back. The event is **cancelable** and doing so will prevent the entity from being knocked back. Alternately, the strength of the knockback in addition to the X and Z ratios can be adjusted.

## Event Class
You will need to cast the event in the function header as this class:
`crafttweaker.event.LivingKnockBackEvent`
You can, of course, also [import](/AdvancedFunctions/Import/) the class before and use that name then.

## Event interface extensions
LivingKnockBack Events implement the following interfaces and are able to call all of their methods/getters/setters as well:

- [IEventCancelable](/Vanilla/Events/Events/IEventCancelable/)
- [ILivingEvent](/Vanilla/Events/Events/ILivingEvent/)

## ZenGetters/ZenSetters
The following information can be retrieved/set during the event:

| ZenGetter          | ZenSetter  | Type                                  |
| ------------------ | ---------- | ------------------------------------- |
| `attacker`         | `attacker` | [IEntity](/Vanilla/Entities/IEntity/) |
| `originalAttacker` |            | [IEntity](/Vanilla/Entities/IEntity/) |
| `strength`         | `strength` | float                                 |
| `originalStrength` |            | float                                 |
| `ratioX`           | `ratioX`   | double                                |
| `ratioZ`           | `ratioZ`   | double                                |
| `originalRatioX`   |            | double                                |
| `originalRatioZ`   |            | double                                |

## Notes

When the event arrives, it's possible that the `attacker`, `strength`, or the various `ratio`s have already been modified. You can find these values in the `original*` variables.


text:
var arrayWithHoles = require("./arrayWithHoles");

var iterableToArray = require("./iterableToArray");

var unsupportedIterableToArray = require("./unsupportedIterableToArray");

var nonIterableRest = require("./nonIterableRest");

function _toArray(arr) {
  return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
}

module.exports = _toArray;


text:
<?php

require_once __DIR__.'/../Base.php';

use Core\Session;
use Model\UserSession;

class UserSessionTest extends Base
{
    public function testIsAdmin()
    {
        $s = new Session;
        $us = new UserSession($this->container);

        $this->assertFalse($us->isAdmin());

        $s['user'] = array();
        $this->assertFalse($us->isAdmin());

        $s['user'] = array('is_admin' => '1');
        $this->assertFalse($us->isAdmin());

        $s['user'] = array('is_admin' => false);
        $this->assertFalse($us->isAdmin());

        $s['user'] = array('is_admin' => '2');
        $this->assertFalse($us->isAdmin());

        $s['user'] = array('is_admin' => true);
        $this->assertTrue($us->isAdmin());
    }
}


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

#nullable enable

using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.UseCoalesceExpression;

namespace Microsoft.CodeAnalysis.CSharp.UseCoalesceExpression
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal class CSharpUseCoalesceExpressionDiagnosticAnalyzer :
        AbstractUseCoalesceExpressionDiagnosticAnalyzer<
            SyntaxKind,
            ExpressionSyntax,
            ConditionalExpressionSyntax,
            BinaryExpressionSyntax>
    {
        protected override ISyntaxFacts GetSyntaxFacts()
            => CSharpSyntaxFacts.Instance;
    }
}


text:
// -*- C++ -*-

/**
 *  @file   ECG_UDP_Receiver.h
 *
 *  $Id: ECG_UDP_Receiver.h 1861 2011-08-31 16:18:08Z mesnierp $
 *
 *  @author Carlos O'Ryan (coryan@cs.wustl.edu)
 *  @author Marina Spivak (marina@atdesk.com)
 *
 * Based on previous work by Tim Harrison (harrison@cs.wustl.edu) and
 * other members of the DOC group. More details can be found in:
 *
 * http://doc.ece.uci.edu/~coryan/EC/index.html
 *
 * Define helper classes to propagate events between ECs using
 * either UDP or multicast.
 * The architecture is a bit complicated and deserves some
 * explanation: sending the events over UDP (or mcast) is easy, a
 * Consumer (TAO_ECG_UDP_Sender) subscribes for a certain set of
 * events, its push() method marshalls the event set into a CDR
 * stream that is sent using an ACE_SOCK_Dgram. The subscription
 * set and IP address can be configured.
 * Another helper class (TAO_ECG_UDP_Receiver) acts as a supplier of
 * events; it receives a callback when an event is available on an
 * ACE_SOCK_Dgram, it demarshalls the event and pushes it to the
 * EC.  Two ACE_Event_Handler classes are provided that can forward
 * the events to this Supplier: TAO_ECG_Mcast_EH can receive events
 * from a multicast group; TAO_ECG_UDP_EH can receive events from a
 * regular UDP socket.
 *
 * @todo The class makes an extra copy of the events, we need to
 * investigate if closer collaboration with its collocated EC could
 * be used to remove that copy.
 */

#ifndef TAO_ECG_UDP_RECEIVER_H
#define TAO_ECG_UDP_RECEIVER_H
#include /**/ "ace/pre.h"

#include "orbsvcs/RtecUDPAdminS.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "orbsvcs/RtecEventChannelAdminS.h"
#include /**/ "orbsvcs/Event/event_serv_export.h"

#include "orbsvcs/Event/ECG_Adapters.h"
#include "orbsvcs/Event/EC_Lifetime_Utils.h"
#include "orbsvcs/Event/EC_Lifetime_Utils_T.h"
#include "orbsvcs/Event/ECG_CDR_Message_Receiver.h"

ACE_BEGIN_VERSIONED_NAMESPACE_DECL
class ACE_Reactor;
ACE_END_VERSIONED_NAMESPACE_DECL

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

class TAO_ECG_UDP_Out_Endpoint;

/**
 * @class TAO_ECG_UDP_Receiver_Disconnect_Command
 *
 * @brief Disconnects supplier represented by @a proxy from the Event Channel.
 *
 * Utility class for use as a template argument to TAO_EC_Auto_Command.
 * TAO_EC_Auto_Command<TAO_ECG_UDP_Receiver_Disconnect_Command> manages
 * supplier connection to the Event Channel, automatically disconnecting from
 * @a proxy in its destructor, if necessary.
 */
class TAO_RTEvent_Serv_Export TAO_ECG_UDP_Receiver_Disconnect_Command
{
public:
  TAO_ECG_UDP_Receiver_Disconnect_Command (void);
  TAO_ECG_UDP_Receiver_Disconnect_Command (
              RtecEventChannelAdmin::ProxyPushConsumer_ptr proxy);

  TAO_ECG_UDP_Receiver_Disconnect_Command (
              const TAO_ECG_UDP_Receiver_Disconnect_Command & rhs);

  TAO_ECG_UDP_Receiver_Disconnect_Command &
   operator= (const TAO_ECG_UDP_Receiver_Disconnect_Command & rhs);

  void execute (void);

private:

  RtecEventChannelAdmin::ProxyPushConsumer_var proxy_;
};

/**
 * @class TAO_ECG_UDP_Receiver
 *
 * @brief Receive events from UDP or Multicast and push them to a
 *        "local" EC.
 *        NOT THREAD-SAFE.
 *
 * This class connects as a supplier to an EventChannel, and supplies
 * to it all events it receives via UDP or Multicast.
 */
class TAO_RTEvent_Serv_Export TAO_ECG_UDP_Receiver :
  public virtual POA_RtecEventComm::PushSupplier
  , public virtual TAO_EC_Deactivated_Object
  , public virtual TAO_ECG_Dgram_Handler
{
public:

  /// Initialization and termination methods.
  //@{

  /// Create a new TAO_ECG_UDP_Receiver object.
  /// (Constructor access is restricted to insure that all
  /// TAO_ECG_UDP_Receiver objects are heap-allocated.)
  static PortableServer::Servant_var<TAO_ECG_UDP_Receiver> create (CORBA::Boolean perform_crc = 0);

  ~TAO_ECG_UDP_Receiver (void);

  /**
   * @param lcl_ec Event Channel to which we will act as a supplier of events.
   * @param ignore_from Endpoint used to remove events generated by
   *        the same process.
   * @param addr_server Address server used to obtain mapping of event type
   *        to multicast group.
   * To insure proper resource clean up, if init () is successful,
   * shutdown () must be called when the receiver is no longer needed.
   * This is done by disconnect_push_supplier() method.  If
   * disconnect_push_supplier() will not be called, it is the
   * responsibility of the user.
   * Furthermore, if shutdown() is not explicitly called by
   * either disconnect_push_supplier () or the user, the receiver
   * will clean up the resources in its destructor, however, certain
   * entities involved in cleanup must still exist at that point,
   * e.g., POA.
   */
  void init (RtecEventChannelAdmin::EventChannel_ptr lcl_ec,
             TAO_ECG_Refcounted_Endpoint ignore_from,
             RtecUDPAdmin::AddrServer_ptr addr_server);

  /// Connect or reconnect to the EC with the given publications.
  /**
   * @note If we are already connected to EC and a reconnection is
   * necessary, the EC must have reconnects enabled in order for this
   * method to succeed.
   */
  void connect (const RtecEventChannelAdmin::SupplierQOS& pub);

  /// Set the handler we must notify when shutdown occurs.  (This is
  /// the handler that alerts us when data is available on udp/mcast socket.)
  /// Shutdown notification gives the handler an opportunity to properly clean
  /// up resources.
  void set_handler_shutdown (TAO_ECG_Refcounted_Handler handler_shutdown_rptr);

  /// Deactivate from POA and disconnect from EC, if necessary.  Shut
  /// down all receiver components.
  /**
   * If this class is used with refcounting, calling this method may
   * result in decrementing of the reference count (due to
   * deactivation) and deletion of the object.
   */
  void shutdown (void);
  //@}

  /// Accessor.
  /// Call the RtecUDPAdmin::AddrServer::get_addr.  Throws exception
  /// if nil Address Server was specified in init ().
  void get_addr (const RtecEventComm::EventHeader& header,
                 RtecUDPAdmin::UDP_Addr_out addr);

  /// Call the RtecUDPAdmin::AddrServer::get_address.  Throws exception
  /// if nil Address Server was specified in init ().
  void get_address (const RtecEventComm::EventHeader& header,
                    RtecUDPAdmin::UDP_Address_out addr);

  /// The PushSupplier idl method.
  /// Invokes shutdown (), which may result in the object being deleted, if
  /// refcounting is used to manage its lifetime.
  virtual void disconnect_push_supplier (void);

  /// TAO_ECG_Dgram_Handler method.
  /**
   * UDP/Multicast Event_Handlers call this method when data is
   * available at the socket - the <dgram> is ready for reading.
   * Data is read from the socket, and, if complete message is
   * received, the event is pushed to the local Event Channel.
   */
  virtual int handle_input (ACE_SOCK_Dgram& dgram);

protected:

  /// Constructor (protected).  Clients can create new
  /// TAO_ECG_UDP_Receiver objects using the static create() method.
  TAO_ECG_UDP_Receiver (CORBA::Boolean perform_crc = false);

private:

  /// Helpers for the connect() method.
  //@{
  // Establishes connection to the Event Channel for the first time.
  void new_connect (const RtecEventChannelAdmin::SupplierQOS& pub);

  // Updates existing connection to the Event Channel.
  void reconnect (const RtecEventChannelAdmin::SupplierQOS& pub);
  //@}

  /// Event Channel to which we act as a supplier.
  RtecEventChannelAdmin::EventChannel_var lcl_ec_;

  /// The server used to map event types to multicast groups.
  RtecUDPAdmin::AddrServer_var addr_server_;

  /// Proxy used to supply events to the Event Channel.
  RtecEventChannelAdmin::ProxyPushConsumer_var consumer_proxy_;

  /// Helper for reading incoming UDP/Multicast messages.  It assembles
  /// message fragments and provides access to a cdr stream once the
  /// complete message has been received.
  TAO_ECG_CDR_Message_Receiver cdr_receiver_;

  /// Handler we must notify when shutdown occurs, so it has an
  /// opportunity to clean up resources.
  TAO_ECG_Refcounted_Handler handler_rptr_;

  typedef TAO_EC_Auto_Command<TAO_ECG_UDP_Receiver_Disconnect_Command>
  ECG_Receiver_Auto_Proxy_Disconnect;
  /// Manages our connection to Consumer Proxy.
  ECG_Receiver_Auto_Proxy_Disconnect auto_proxy_disconnect_;
};

TAO_END_VERSIONED_NAMESPACE_DECL

#if defined(__ACE_INLINE__)
#include "orbsvcs/Event/ECG_UDP_Receiver.inl"
#endif /* __ACE_INLINE__ */

#include /**/ "ace/post.h"
#endif /* TAO_ECG_UDP_RECEIVER_H */


text:
<?php include('header.php'); ?>

Bảng Giá tiền (Đơn vị $)

Loại vé

Giá vé thường

Giá vé early bird

Student | Vé sinh viên

                    <?php echo form_open('admin/editTicket'); ?>
                <?php foreach($student->result() as $sv){?>

<input id="p1" value="<?php echo $sv->price_en; ?>" name="se1" type="text" disabled="disabled" />Sửa

<input id="p2" value="<?php echo $sv->early_bird_en; ?>" name="se2" type="text" disabled="disabled" />Sửa

                    <?php };?>

Civilian | Vé Công nhân

                <?php foreach($civilian->result() as $cn){?>

<input id="p3" value="<?php echo $cn->price_en; ?>" name="ce1" type="text" disabled="disabled" />Sửa

<input id="p4" value="<?php echo $cn->early_bird_en; ?>" name="ce2" type="text" disabled="disabled" />Sửa

                    <?php };?>

Officer | Vé Công chức

                <?php foreach($officer->result() as $vp){?>

<input id="p5" value="<?php echo $vp->price_en; ?>" name="oe1" type="text" disabled="disabled" />Sửa

<input id="p6" value="<?php echo $vp->early_bird_en; ?>" name="oe2" type="text" disabled="disabled" />Sửa

                    <?php };?>

Bảng Giá tiền (Đơn vị VNĐ)

Loại vé

Giá vé thường

Giá vé early bird

Student | Vé sinh viên

                <?php foreach($student->result() as $sv){?>

<input id="p7" value="<?php echo $sv->price_vi; ?>" name="sv1" type="text" disabled="disabled" />Sửa

<input id="p8" value="<?php echo $sv->early_bird_vi; ?>" name="sv1" type="text" disabled="disabled" />Sửa

                    <?php };?>

Civilian | Vé Công nhân

                <?php foreach($civilian->result() as $cn){?>

<input id="p9" value="<?php echo $cn->price_vi; ?>" name="cv1" type="text" disabled="disabled" />Sửa

<input id="p10" value="<?php echo $cn->early_bird_vi; ?>" name="cv2" type="text" disabled="disabled" />Sửa

                    <?php };?>

Officer | Vé Công chức

                <?php foreach($officer->result() as $vp){?>

<input id="p11" value="<?php echo $vp->price_vi; ?>" name="ov1" type="text" disabled="disabled" />Sửa

<input id="p12" value="<?php echo $vp->early_bird_vi; ?>" name="ov1" type="text" disabled="disabled" />Sửa

                    <?php };?>

                	<input id="editprice" type="submit" name="submit" value="" />
                    <input id="cancel" class="cancel" type="button" value="" onclick="cancel(this)" />

         <?php echo form_close(); ?>

<?php include('footer.php') ?>


text:
import sys

from traitlets import default

from .baseapp import NbGrader, nbgrader_aliases, nbgrader_flags
from ..converters import BaseConverter, Autograde, NbGraderException
from traitlets.traitlets import MetaHasTraits
from traitlets.config.loader import Config
from typing import List

aliases = {
    'course': 'CourseDirectory.course_id'
}
aliases.update(nbgrader_aliases)
aliases.update({
})

flags = {}
flags.update(nbgrader_flags)
flags.update({
    'create': (
        {'Autograde': {'create_student': True}},
        "Deprecated: Create an entry for the student in the database, if one does not already exist. "
        "This is now the default."
    ),
    'no-execute': (
        {
            'Execute': {'enabled': False},
            'ClearOutput': {'enabled': False}
        },
        "Don't execute notebooks and clear output when autograding."
    ),
    'force': (
        {'BaseConverter': {'force': True}},
        "Overwrite an assignment/submission if it already exists."
    ),
    'f': (
        {'BaseConverter': {'force': True}},
        "Overwrite an assignment/submission if it already exists."
    ),
})

class AutogradeApp(NbGrader):

    name = u'nbgrader-autograde'
    description = u'Autograde a notebook by running it'

    aliases = aliases
    flags = flags

    examples = """
        Autograde submitted assignments. This takes one argument for the
        assignment id, and then (by default) autogrades assignments from the
        following directory structure:

            submitted/*/{assignment_id}/*.ipynb

        and saves the autograded files to the corresponding directory in:

            autograded/{student_id}/{assignment_id}/{notebook_id}.ipynb

        The student IDs will be created in the database if they don't already
        exist.

        Note that the assignment must also be present in the database. If it is
        not, you should first create it using `nbgrader generate_assignment`. Then, during
        autograding, the cells that contain tests for the students' answers will
        be overwritten with the master version of the tests that is saved in the
        database (this prevents students from modifying the tests in order to
        improve their score).

        To grade all submissions for "Problem Set 1":

            nbgrader autograde "Problem Set 1"

        To grade only the submission by student with ID 'Hacker':

            nbgrader autograde "Problem Set 1" --student Hacker

        To grade only the notebooks that start with '1':

            nbgrader autograde "Problem Set 1" --notebook "1*"

        By default, student submissions are re-executed and their output cleared.
        For long running notebooks, it can be useful to disable this with the
        '--no-execute' flag:

            nbgrader autograde "Problem Set 1" --no-execute

        Note, however, that doing so will not guarantee that students' solutions
        are correct. If you use this flag, you should make sure you manually
        check all solutions. For example, if a student saved their notebook with
        all outputs cleared, then using --no-execute would result in them
        receiving full credit on all autograded problems.
        """

    @default("classes")
    def _classes_default(self) -> List[MetaHasTraits]:
        classes = super(AutogradeApp, self)._classes_default()
        classes.extend([BaseConverter, Autograde])
        return classes

    def _load_config(self, cfg: Config, **kwargs: dict) -> None:
        if 'AutogradeApp' in cfg:
            self.log.warning(
                "Use Autograde in config, not AutogradeApp. Outdated config:\n%s",
                '\n'.join(
                    'AutogradeApp.{key} = {value!r}'.format(key=key, value=value)
                    for key, value in cfg.AutogradeApp.items()
                )
            )
            cfg.Autograde.merge(cfg.AutogradeApp)
            del cfg.AutogradeApp

        super(AutogradeApp, self)._load_config(cfg, **kwargs)

    def start(self) -> None:
        super().start()

        if len(self.extra_args) > 1:
            self.fail("Only one argument (the assignment id) may be specified")
        elif len(self.extra_args) == 1 and self.coursedir.assignment_id != "":
            self.fail("The assignment cannot both be specified in config and as an argument")
        elif len(self.extra_args) == 0 and self.coursedir.assignment_id == "":
            self.fail("An assignment id must be specified, either as an argument or with --assignment")
        elif len(self.extra_args) == 1:
            self.coursedir.assignment_id = self.extra_args[0]

        converter = Autograde(coursedir=self.coursedir, parent=self)
        try:
            converter.start()
        except NbGraderException:
            sys.exit(1)


text:
package com.whty.flow.statehandler;

import com.whty.flow.impl.context.FlowMapContext;
import com.whty.flow.impl.context.FlowStateHandler;

public class IsValidSdHandler extends FlowStateHandler{

	@Override
	public String handle(FlowMapContext context) {
		return "1";
	}
}


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="experiment_response")
 */
class Response
{
	/**
	 * @ORM\Column(type="integer")
	 * @ORM\Id
	 * @ORM\GeneratedValue(strategy="AUTO")
	 */
	protected $id;

	/**
	 * @ORM\Column(type="datetime")
	 */
	protected $timestamp;

	/**
	 * @ORM\ManyToOne(targetEntity="Player")
	 */
	protected $player;

	/**
	 * @ORM\Column(type="string", length=254)
	 */
	protected $field;

	/**
	 * @ORM\Column(type="string", length=254)
	 */
	protected $value;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set timestamp
     *
     * @param \DateTime $timestamp
     * @return Response
     */
    public function setTimestamp($timestamp)
    {
        $this->timestamp = $timestamp;

        return $this;
    }

    /**
     * Get timestamp
     *
     * @return \DateTime
     */
    public function getTimestamp()
    {
        return $this->timestamp;
    }

    /**
     * Set field
     *
     * @param string $field
     * @return Response
     */
    public function setField($field)
    {
        $this->field = $field;

        return $this;
    }

    /**
     * Get field
     *
     * @return string
     */
    public function getField()
    {
        return $this->field;
    }

    /**
     * Set value
     *
     * @param string $value
     * @return Response
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Set player
     *
     * @param \AppBundle\Entity\Player $player
     * @return Response
     */
    public function setPlayer(\AppBundle\Entity\Player $player = null)
    {
        $this->player = $player;

        return $this;
    }

    /**
     * Get player
     *
     * @return \AppBundle\Entity\Player
     */
    public function getPlayer()
    {
        return $this->player;
    }
}


text:
class InstanceMigration < Sequel::Migration

  def up
    create_table :instances do
      primary_key :id
    end
  end

  def down
    execute "DROP TABLE instances"
  end

end


text:
from django.db import models

class Author(models.Model):
    name = models.CharField('Name', max_length=255)

class Book(models.Model):
    author = models.ForeignKey('Author', related_name='books')
    title = models.CharField('Title', max_length=255)


text:
@interface TypesetTests : XCTestCase

@end

@implementation TypesetTests

- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
}

- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
}

- (void)testExample {
    // This is an example of a functional test case.
    XCTAssert(YES, @"Pass");
}

- (void)testSelfEqual {

    NSString *txt = @"Hello typeset";

    NSMutableAttributedString *attributedTxt1 = txt.typeset.matchAll(@"o").red.string;

    NSMutableAttributedString *attributedTxt2 = txt.typeset.matchAll(@"l").red.string;

    XCTAssertFalse([attributedTxt1 isEqualToAttributedString:attributedTxt2]);

    NSMutableAttributedString *attributedTxt3 = txt.typeset.matchAll(@"o").red.string;

    XCTAssertTrue([attributedTxt1 isEqualToAttributedString:attributedTxt3]);

}

- (void)testEqual {

    NSDictionary *obj1 = @{@"abc":@"Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset "};

    NSDictionary *tmpObj = @{@"def":@"Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset Hello typeset "};
    NSDictionary *obj2 = [[NSDictionary alloc] initWithDictionary:tmpObj];

    NSString *txt = obj1[@"abc"];
    NSString *txt2 = [obj2[@"def"] copy]; // no difference, just to demonstrate the optimization of NSString done by Apple

//    XCTAssertFalse([txt isEqual:txt2]);

    //attributedString from txt1
    NSMutableAttributedString *attributedTxt1 = txt.typeset.matchAll(@"o").red.string;

    //attributedString from txt2
    NSMutableAttributedString *attributedTxt2_1 = txt2.typeset.matchAll(@"o").red.string;
    XCTAssertTrue([attributedTxt1 isEqualToAttributedString:attributedTxt2_1]);

    NSMutableAttributedString *attributedTxt2_2 = txt2.typeset.matchAll(@"l").red.string;
    XCTAssertFalse([attributedTxt1 isEqualToAttributedString:attributedTxt2_2]);

    NSMutableAttributedString *attributedTxt2_3 = txt2.typeset.matchAll(@"o").red.string;
    XCTAssertTrue([attributedTxt1 isEqualToAttributedString:attributedTxt2_3]);

}

- (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
        // Put the code you want to measure the time of here.
    }];
}

@end


text:
#include "Search/Kino03/KinoSearch/Util/ToolSet.h"

#include "Search/Kino03/KinoSearch/Search/HitQueue.h"
#include "Search/Kino03/KinoSearch/FieldType.h"
#include "Search/Kino03/KinoSearch/Index/SegReader.h"
#include "Search/Kino03/KinoSearch/Index/SortCache.h"
#include "Search/Kino03/KinoSearch/Schema.h"
#include "Search/Kino03/KinoSearch/Search/MatchDoc.h"
#include "Search/Kino03/KinoSearch/Search/SortRule.h"
#include "Search/Kino03/KinoSearch/Search/SortSpec.h"
#include "Search/Kino03/KinoSearch/Util/IntArrays.h"

#define COMPARE_BY_SCORE      1
#define COMPARE_BY_SCORE_REV  2
#define COMPARE_BY_DOC_ID     3
#define COMPARE_BY_DOC_ID_REV 4
#define COMPARE_BY_VALUE      5
#define COMPARE_BY_VALUE_REV  6
#define ACTIONS_MASK          0xF

HitQueue*
HitQ_new(Schema *schema, SortSpec *sort_spec, u32_t wanted)
{
    HitQueue *self = (HitQueue*)VTable_Make_Obj(&HITQUEUE);
    return HitQ_init(self, schema, sort_spec, wanted);
}

HitQueue*
HitQ_init(HitQueue *self, Schema *schema, SortSpec *sort_spec, u32_t wanted)
{
    if (sort_spec) {
        u32_t i;
        VArray *rules      = SortSpec_Get_Rules(sort_spec);
        u32_t   num_rules  = VA_Get_Size(rules);
        u32_t   action_num = 0;

        if (!schema) {
            THROW("Can't supply sort_spec without schema");
        }

        self->need_values = false;
        self->num_actions = num_rules;
        self->actions     = MALLOCATE(num_rules, u8_t);
        self->field_types = CALLOCATE(num_rules, FieldType*);

        for (i = 0; i < num_rules; i++) {
            SortRule *rule      = (SortRule*)VA_Fetch(rules, i);
            i32_t     rule_type = SortRule_Get_Type(rule);
            bool_t    reverse   = SortRule_Get_Reverse(rule);

            if (rule_type == SortRule_SCORE) {
                self->actions[action_num++] = reverse
                                            ? COMPARE_BY_SCORE_REV
                                            : COMPARE_BY_SCORE;
            }
            else if (rule_type == SortRule_DOC_ID) {
                self->actions[action_num++] = reverse
                                            ? COMPARE_BY_DOC_ID_REV
                                            : COMPARE_BY_DOC_ID;
            }
            else if (rule_type == SortRule_FIELD) {
                CharBuf   *field = SortRule_Get_Field(rule);
                FieldType *type  = Schema_Fetch_Type(schema, field);
                if (type) {
                    self->field_types[action_num] = (FieldType*)INCREF(type);
                    self->actions[action_num++] = reverse
                                                ? COMPARE_BY_VALUE_REV
                                                : COMPARE_BY_VALUE;
                    self->need_values = true;
                }
                else {
                    /* Skip over fields we don't know how to sort on. */
                    continue;
                }
            }
            else {
                THROW("Unknown SortRule type: %i32", rule_type);
            }
        }
    }
    else {
        self->num_actions = 2;
        self->actions     = MALLOCATE(self->num_actions, u8_t);
        self->actions[0]  = COMPARE_BY_SCORE;
        self->actions[1]  = COMPARE_BY_DOC_ID;
    }

    return (HitQueue*)PriQ_init((PriorityQueue*)self, wanted);
}

void
HitQ_destroy(HitQueue *self)
{
    FieldType **types = self->field_types;
    FieldType **const limit = types + self->num_actions - 1;
    for ( ; types < limit; types++) {
        if (types) { DECREF(*types); }
    }
    MemMan_wrapped_free(self->actions);
    MemMan_wrapped_free(self->field_types);
    SUPER_DESTROY(self, HITQUEUE);
}

Obj*
HitQ_jostle(HitQueue *self, Obj *element)
{
    MatchDoc *match_doc = (MatchDoc*)ASSERT_IS_A(element, MATCHDOC);
    HitQ_jostle_t super_jostle
        = (HitQ_jostle_t)SUPER_METHOD(&HITQUEUE, HitQ, Jostle);
    if (self->need_values) {
        ASSERT_IS_A(match_doc->values, VARRAY);
    }
    return super_jostle(self, element);
}

static INLINE i32_t
SI_compare_by_value(HitQueue *self, u32_t tick, MatchDoc *a, MatchDoc *b)
{
    Obj *a_val = VA_Fetch(a->values, tick);
    Obj *b_val = VA_Fetch(b->values, tick);
    FieldType *field_type = self->field_types[tick];
    return FType_Compare_Values(field_type, a_val, b_val);
}

bool_t
HitQ_less_than(HitQueue *self, Obj *obj_a, Obj *obj_b)
{
    MatchDoc *const a = (MatchDoc*)obj_a;
    MatchDoc *const b = (MatchDoc*)obj_b;
    u32_t i = 0;
    u8_t *const actions = self->actions;

    do {
        switch (actions[i] & ACTIONS_MASK) {
            case COMPARE_BY_SCORE:
                /* Prefer high scores. */
                if      (a->score > b->score) { return false;   }
                else if (a->score < b->score) { return true;    }
                break;
            case COMPARE_BY_SCORE_REV:
                if      (a->score > b->score) { return true;    }
                else if (a->score < b->score) { return false;   }
                break;
            case COMPARE_BY_DOC_ID:
                /* Prefer low doc ids. */
                if      (a->doc_id > b->doc_id) { return true;    }
                else if (a->doc_id < b->doc_id) { return false;   }
                break;
            case COMPARE_BY_DOC_ID_REV:
                if      (a->doc_id > b->doc_id) { return false;    }
                else if (a->doc_id < b->doc_id) { return true;   }
                break;
            case COMPARE_BY_VALUE: {
                    i32_t comparison = SI_compare_by_value(self, i, a, b);
                    if      (comparison > 0) { return true; }
                    else if (comparison < 0) { return false; }
                }
                break;
            case COMPARE_BY_VALUE_REV: {
                    i32_t comparison = SI_compare_by_value(self, i, b, a);
                    if      (comparison > 0) { return true; }
                    else if (comparison < 0) { return false; }
                }
                break;
            default:
                THROW("Unexpected action %u8", actions[i]);
        }

    } while (++i < self->num_actions);

    return false;
}

/* Copyright 2006-2009 Marvin Humphrey
 *
 * This program is free software; you can redistribute it and/or modify
 * under the same terms as Perl itself.
 */


text:
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using ReMi.Common.Constants;
using ReMi.Common.Constants.ProductRequests;
using ReMi.Common.Utils.Enums;
using ReMi.DataEntities.ProductRequests;

namespace ReMi.DataAccess.AutoMapper
{
    public class TasksToProductRequestRegistrationStatusResolver : ValueResolver<IEnumerable<ProductRequestRegistrationTask>, string>
    {
        protected override string ResolveCore(IEnumerable<ProductRequestRegistrationTask> source)
        {
            if (source == null) return EnumDescriptionHelper.GetDescription(ProductRequestRegistrationStatus.New);

            var list = source.ToList();

            if (list.All(o => !o.IsCompleted)) return EnumDescriptionHelper.GetDescription(ProductRequestRegistrationStatus.New);

            if (list.All(o => o.IsCompleted)) return EnumDescriptionHelper.GetDescription(ProductRequestRegistrationStatus.Completed);

            return EnumDescriptionHelper.GetDescription(ProductRequestRegistrationStatus.InProgress);
        }
    }
}


text:
<?php

namespace Pronit\CoreBundle\Form\Type\Controlling\Documentos;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\EntityRepository;

class ItemEmisorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('clasificador', 'entity', array(
                'class' => 'PronitCoreBundle:Controlling\Documentos\ClasificadorItemImputacionSecundaria',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c')
                        ->where("c.nombre = 'Item emisor'");
                }
            ))
            ->add('gestionImputacion', 'entity', array(
                'class' => 'PronitCoreBundle:Controlling\GestionImputacion',
            ))
            ->add('importe')
            ->add('_type', 'hidden', array(
                'data'   => $this->getName(),
                'mapped' => false
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Pronit\CoreBundle\Entity\Controlling\Documentos\ItemEmisor',
        ));
    }

    public function getName() {
        return 'itememisortype';
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.Collections.Specialized;
using SendGrid;
using SendGrid.Helpers.Mail;
using Dsa.RapidResponse.Services;

namespace Dsa.RapidResponse.Implementations
{
    public class EmailService : IEmailService
    {
        async void IEmailService.Send(string to, string message)
        {
            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress("milwaukeedsa@gmail.com", "DSA Milwaukee"));

            var recipients = new List<EmailAddress>
            {
                new EmailAddress(to),
            };
            msg.AddTos(recipients);

            msg.SetSubject("Rapid Response Message");

            msg.AddContent(MimeType.Text, message);
            msg.AddContent(MimeType.Html, message);

            var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
            var client = new SendGridClient(apiKey);
            var response = await client.SendEmailAsync(msg);
        }
    }
}


text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Service/Nirvanix/Namespace/Imfs.php

Global

                      Classes

\Zend_Service_Nirvanix_Namespace_Imfs

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service

subpackage

Nirvanix

version

$Id: Imfs.php 23775 2011-03-01 17:25:24Z ralph $

\Zend_Service_Nirvanix_Namespace_Imfs
jump to top

Namespace proxy with additional convenience methods for the IMFS namespace.

Extends from

\Zend_Service_Nirvanix_Namespace_Base

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service

subpackage

Nirvanix

Methods

__call(
          string $methodName, array $args
          )

        :
          \Zend_Service_Nirvanix_Response

When a method call is made against this proxy, convert it to
an HTTP request to make against the Nirvanix REST service.

Inherited from:
                    \Zend_Service_Nirvanix_Namespace_Base::__call()

$imfs->DeleteFiles(array('filePath' => 'foo'));

Assuming this object was proxying the IMFS namespace, the
method call above would call the DeleteFiles command.  The
POST parameters would be filePath, merged with the
$this->_defaults (containing the sessionToken).

Parameters

Name
Type
Description

$methodName
string
Name of the command to call on this namespace.

$args
array
Only the first is used and it must be an array. It contains the POST params.

Returns

Type
Description

\Zend_Service_Nirvanix_Response

__construct(
          array $options
              =
              array
          )

        :
          void

Class constructor.

Inherited from:
                    \Zend_Service_Nirvanix_Namespace_Base::__construct()

Parameters

Name
Type
Description

$options
array
Options and dependency injection

_makeUri(
          string $methodName
          )

        :
          string

Make a complete URI from an RPC method name.  All Nirvanix REST
service URIs use the same format.

Inherited from:
                    \Zend_Service_Nirvanix_Namespace_Base::_makeUri()

Parameters

Name
Type
Description

$methodName
string
RPC method name

Returns

Type
Description

string

_wrapResponse(
          \Zend_Http_Response $httpResponse
          )

        :
          \Zend_Service_Nirvanix_Response

All Nirvanix REST service calls return an XML payload.  This method
makes a Zend_Service_Nirvanix_Response from that XML payload.

Inherited from:
                    \Zend_Service_Nirvanix_Namespace_Base::_wrapResponse()

Parameters

Name
Type
Description

$httpResponse
\Zend_Http_Response
Raw response from Nirvanix

Returns

Type
Description

\Zend_Service_Nirvanix_Response
Wrapped response

getContents(
          string $filePath, integer $expiration
              =
              3600
          )

        :
          string

Convenience function to get the contents of a file on
the Nirvanix IMFS.  Analog to PHP's file_get_contents().

Parameters

Name
Type
Description

$filePath
string
Remote path and filename

$expiration
integer
Number of seconds that Nirvanix make the file available for download.

Returns

Type
Description

string
Contents of file

getHttpClient(

          )

        :
          \Zend_Http_Client

Return the HTTP client used for this namespace.  This is useful
for inspecting the last request or directly interacting with the
HTTP client.

Inherited from:
                    \Zend_Service_Nirvanix_Namespace_Base::getHttpClient()

Returns

Type
Description

\Zend_Http_Client

putContents(
          string $filePath, integer $data, string $mimeType
              =
              null
          )

        :
          \Zend_Service_Nirvanix_Response

Convenience function to put the contents of a string into
the Nirvanix IMFS.  Analog to PHP's file_put_contents().

Parameters

Name
Type
Description

$filePath
string
Remote path and filename

$data
integer
Data to store in the file

$mimeType
string
Mime type of data

Returns

Type
Description

\Zend_Service_Nirvanix_Response

unlink(
          string $filePath
          )

        :
          \Zend_Service_Nirvanix_Response

Convenience function to remove a file from the Nirvanix IMFS.

Analog to PHP's unlink().

Parameters

Name
Type
Description

$filePath
string
Remove path and filename

Returns

Type
Description

\Zend_Service_Nirvanix_Response

Documentation was generated by DocBlox 0.13.3.