text:
/* collect.c - Demonstration of overlay code */
/* $OpenLDAP: pkg/ldap/servers/slapd/overlays/collect.c,v 1.5.2.15 2011/01/28 18:53:37 quanah Exp $ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
 * Copyright 2003-2011 The OpenLDAP Foundation.
 * Portions Copyright 2003 Howard Chu.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
/* ACKNOWLEDGEMENTS:
 * This work was initially developed by the Howard Chu for inclusion
 * in OpenLDAP Software.
 */

#include "portable.h"

#ifdef SLAPD_OVER_COLLECT

#include <stdio.h>

#include <ac/string.h>
#include <ac/socket.h>

#include "slap.h"
#include "config.h"

#include "lutil.h"

/* This is a cheap hack to implement a collective attribute.
 *
 * This demonstration overlay looks for a specified attribute in an
 * ancestor of a given entry and adds that attribute to the given
 * entry when it is returned in a search response. It takes no effect
 * for any other operations. If the ancestor does not exist, there
 * is no effect. If no attribute was configured, there is no effect.
 */

typedef struct collect_info {
	struct collect_info *ci_next;
	struct berval ci_dn;
	int ci_ad_num;
	AttributeDescription *ci_ad[1];
} collect_info;

static int collect_cf( ConfigArgs *c );

static ConfigTable collectcfg[] = {
	{ "collectinfo", "dn> <attribute", 3, 3, 0,
	  ARG_MAGIC, collect_cf,
	  "( OLcfgOvAt:19.1 NAME 'olcCollectInfo' "
	  "DESC 'DN of entry and attribute to distribute' "
	  "EQUALITY caseIgnoreMatch "
	  "SYNTAX OMsDirectoryString )", NULL, NULL },
	{ NULL, NULL, 0, 0, 0, ARG_IGNORED }
};

static ConfigOCs collectocs[] = {
	{ "( OLcfgOvOc:19.1 "
	  "NAME 'olcCollectConfig' "
	  "DESC 'Collective Attribute configuration' "
	  "SUP olcOverlayConfig "
	  "MAY olcCollectInfo )",
	  Cft_Overlay, collectcfg },
	{ NULL, 0, NULL }
};

/*
 * inserts a collect_info into on->on_bi.bi_private taking into account
 * order. this means longer dn's (i.e. more specific dn's) will be found
 * first when searching, allowing some limited overlap of dn's
 */
static void
insert_ordered( slap_overinst *on, collect_info *ci ) {
	collect_info *find = on->on_bi.bi_private;
	collect_info *prev = NULL;
	int found = 0;

	while (!found) {
		if (find == NULL) {
			if (prev == NULL) {
				/* base case - empty list */
				on->on_bi.bi_private = ci;
				ci->ci_next = NULL;
			} else {
				/* final case - end of list */
				prev->ci_next = ci;
				ci->ci_next = NULL;
			}
			found = 1;
		} else if (find->ci_dn.bv_len < ci->ci_dn.bv_len) {
			/* insert into list here */
			if (prev == NULL) {
				/* entry is head of list */
				ci->ci_next = on->on_bi.bi_private;
				on->on_bi.bi_private = ci;
			} else {
				/* entry is not head of list */
				prev->ci_next = ci;
				ci->ci_next = find;
			}
			found = 1;
		} else {
			/* keep looking */
			prev = find;
			find = find->ci_next;
		}
	}
}

static int
collect_cf( ConfigArgs *c )
{
	slap_overinst *on = (slap_overinst *)c->bi;
	int rc = 1, idx;

	switch( c->op ) {
	case SLAP_CONFIG_EMIT:
		{
		collect_info *ci;
		for ( ci = on->on_bi.bi_private; ci; ci = ci->ci_next ) {
			struct berval bv;
			char *ptr;
			int len;

			/* calculate the length & malloc memory */
			bv.bv_len = ci->ci_dn.bv_len + STRLENOF("\"\" ");
			for (idx=0; idx<ci->ci_ad_num; idx++) {
				bv.bv_len += ci->ci_ad[idx]->ad_cname.bv_len;
				if (idx<(ci->ci_ad_num-1)) {
					bv.bv_len++;
				}
			}
			bv.bv_val = ch_malloc( bv.bv_len + 1 );

			/* copy the value and update len */
			len = snprintf( bv.bv_val, bv.bv_len + 1, "\"%s\" ",
				ci->ci_dn.bv_val);
			ptr = bv.bv_val + len;
			for (idx=0; idx<ci->ci_ad_num; idx++) {
				ptr = lutil_strncopy( ptr,
					ci->ci_ad[idx]->ad_cname.bv_val,
					ci->ci_ad[idx]->ad_cname.bv_len);
				if (idx<(ci->ci_ad_num-1)) {
					*ptr++ = ',';
				}
			}
			*ptr = '\0';
			bv.bv_len = ptr - bv.bv_val;

			ber_bvarray_add( &c->rvalue_vals, &bv );
			rc = 0;
		}
		}
		break;
	case LDAP_MOD_DELETE:
		if ( c->valx == -1 ) {
		/* Delete entire attribute */
			collect_info *ci;
			while (( ci = on->on_bi.bi_private )) {
				on->on_bi.bi_private = ci->ci_next;
				ch_free( ci->ci_dn.bv_val );
				ch_free( ci );
			}
		} else {
		/* Delete just one value */
			collect_info **cip, *ci;
			int i;
			cip = (collect_info **)&on->on_bi.bi_private;
			ci = *cip;
			for ( i=0; i < c->valx; i++ ) {
				cip = &ci->ci_next;
				ci = *cip;
			}
			*cip = ci->ci_next;
			ch_free( ci->ci_dn.bv_val );
			ch_free( ci );
		}
		rc = 0;
		break;
	case SLAP_CONFIG_ADD:
	case LDAP_MOD_ADD:
		{
		collect_info *ci;
		struct berval bv, dn;
		const char *text;
		int idx, count=0;
		char *arg;

		/* count delimiters in attribute argument */
		arg = strtok(c->argv[2], ",");
		while (arg!=NULL) {
			count++;
			arg = strtok(NULL, ",");
		}

		/* validate and normalize dn */
		ber_str2bv( c->argv[1], 0, 0, &bv );
		if ( dnNormalize( 0, NULL, NULL, &bv, &dn, NULL ) ) {
			snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s invalid DN: \"%s\"",
				c->argv[0], c->argv[1] );
			Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
				"%s: %s\n", c->log, c->cr_msg, 0 );
			return ARG_BAD_CONF;
		}

		/* check for duplicate DNs */
		for ( ci = (collect_info *)on->on_bi.bi_private; ci;
			ci = ci->ci_next ) {
			/* If new DN is longest, there are no possible matches */
			if ( dn.bv_len > ci->ci_dn.bv_len ) {
				ci = NULL;
				break;
			}
			if ( bvmatch( &dn, &ci->ci_dn )) {
				break;
			}
		}
		if ( ci ) {
			snprintf( c->cr_msg, sizeof( c->cr_msg ), "%s DN already configured: \"%s\"",
				c->argv[0], c->argv[1] );
			Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
				"%s: %s\n", c->log, c->cr_msg, 0 );
			return ARG_BAD_CONF;
		}

		/* allocate config info with room for attribute array */
		ci = ch_malloc( sizeof( collect_info ) +
			sizeof( AttributeDescription * ) * count );

		/* load attribute description for attribute list */
		arg = c->argv[2];
		for( idx=0; idx<count; idx++) {
			ci->ci_ad[idx] = NULL;

			if ( slap_str2ad( arg, &ci->ci_ad[idx], &text ) ) {
				snprintf( c->cr_msg, sizeof( c->cr_msg ),
					"%s attribute description unknown: \"%s\"",
					c->argv[0], arg);
				Debug( LDAP_DEBUG_CONFIG|LDAP_DEBUG_NONE,
					"%s: %s\n", c->log, c->cr_msg, 0 );
				ch_free( ci );
				return ARG_BAD_CONF;
			}
			while(*arg!='\0') {
				arg++; /* skip to end of argument */
			}
			if (idx<count-1) {
				arg++; /* skip inner delimiters */
			}
		}

		/* The on->on_bi.bi_private pointer can be used for
		 * anything this instance of the overlay needs.
		 */
		ci->ci_ad[count] = NULL;
		ci->ci_ad_num = count;
		ci->ci_dn = dn;

		/* creates list of ci's ordered by dn length */
		insert_ordered ( on, ci );

		/* New ci wasn't simply appended to end, adjust its
		 * position in the config entry's a_vals
		 */
		if ( c->ca_entry && ci->ci_next ) {
			Attribute *a = attr_find( c->ca_entry->e_attrs,
				collectcfg[0].ad );
			if ( a ) {
				struct berval bv, nbv;
				collect_info *c2 = (collect_info *)on->on_bi.bi_private;
				int i, j;
				for ( i=0; c2 != ci; i++, c2 = c2->ci_next );
				bv = a->a_vals[a->a_numvals-1];
				nbv = a->a_nvals[a->a_numvals-1];
				for ( j=a->a_numvals-1; j>i; j-- ) {
					a->a_vals[j] = a->a_vals[j-1];
					a->a_nvals[j] = a->a_nvals[j-1];
				}
				a->a_vals[j] = bv;
				a->a_nvals[j] = nbv;
			}
		}

		rc = 0;
		}
	}
	return rc;
}

static int
collect_destroy(
	BackendDB *be,
	ConfigReply *cr
)
{
	slap_overinst *on = (slap_overinst *)be->bd_info;
	collect_info *ci;

	while (( ci = on->on_bi.bi_private )) {
		on->on_bi.bi_private = ci->ci_next;
		ch_free( ci->ci_dn.bv_val );
		ch_free( ci );
	}
	return 0;
}

static int
collect_modify( Operation *op, SlapReply *rs)
{
	slap_overinst *on = (slap_overinst *) op->o_bd->bd_info;
	collect_info *ci = on->on_bi.bi_private;
	Modifications *ml;
	char errMsg[100];
	int idx;

	for ( ml = op->orm_modlist; ml != NULL; ml = ml->sml_next) {
		for (; ci; ci=ci->ci_next ) {
			/* Is this entry an ancestor of this collectinfo ? */
			if (!dnIsSuffix(&op->o_req_ndn, &ci->ci_dn)) {
				/* this collectinfo does not match */
				continue;
			}

			/* Is this entry the same as the template DN ? */
			if ( dn_match(&op->o_req_ndn, &ci->ci_dn)) {
				/* all changes in this ci are allowed */
				continue;
			}

			/* check for collect attributes - disallow modify if present */
			for(idx=0; idx<ci->ci_ad_num; idx++) {
				if (ml->sml_desc == ci->ci_ad[idx]) {
					rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
					snprintf( errMsg, sizeof( errMsg ),
						"cannot change virtual attribute '%s'",
						ci->ci_ad[idx]->ad_cname.bv_val);
					rs->sr_text = errMsg;
					send_ldap_result( op, rs );
					return rs->sr_err;
				}
			}
		}

	}

	return SLAP_CB_CONTINUE;
}

static int
collect_response( Operation *op, SlapReply *rs )
{
	slap_overinst *on = (slap_overinst *) op->o_bd->bd_info;
	collect_info *ci = on->on_bi.bi_private;

	/* If we've been configured and the current response is
	 * a search entry
	 */
	if ( ci && rs->sr_type == REP_SEARCH ) {
		int rc;

		op->o_bd->bd_info = (BackendInfo *)on->on_info;

		for (; ci; ci=ci->ci_next ) {
			int idx=0;

			/* Is this entry an ancestor of this collectinfo ? */
			if (!dnIsSuffix(&rs->sr_entry->e_nname, &ci->ci_dn)) {
				/* collectinfo does not match */
				continue;
			}

			/* Is this entry the same as the template DN ? */
			if ( dn_match(&rs->sr_entry->e_nname, &ci->ci_dn)) {
				/* dont apply change to parent */
				continue;
			}

			/* The current entry may live in a cache, so
			* don't modify it directly. Make a copy and
			* work with that instead.
			*/
			rs_entry2modifiable( op, rs, on );

			/* Loop for each attribute in this collectinfo */
			for(idx=0; idx<ci->ci_ad_num; idx++) {
				BerVarray vals = NULL;

				/* Extract the values of the desired attribute from
			 	 * the ancestor entry */
				rc = backend_attribute( op, NULL, &ci->ci_dn,
					ci->ci_ad[idx], &vals, ACL_READ );

				/* If there are any values, merge them into the
			 	 * current search result
			 	 */
				if ( vals ) {
					attr_merge( rs->sr_entry, ci->ci_ad[idx],
						vals, NULL );
					ber_bvarray_free_x( vals, op->o_tmpmemctx );
				}
			}
		}
	}

	/* Default is to just fall through to the normal processing */
	return SLAP_CB_CONTINUE;
}

static slap_overinst collect;

int collect_initialize() {
	int code;

	collect.on_bi.bi_type = "collect";
	collect.on_bi.bi_db_destroy = collect_destroy;
	collect.on_bi.bi_op_modify = collect_modify;
	collect.on_response = collect_response;

	collect.on_bi.bi_cf_ocs = collectocs;
	code = config_register_schema( collectcfg, collectocs );
	if ( code ) return code;

	return overlay_register( &collect );
}

#if SLAPD_OVER_COLLECT == SLAPD_MOD_DYNAMIC
int init_module(int argc, char *argv[]) {
	return collect_initialize();
}
#endif

#endif /* SLAPD_OVER_COLLECT */


text:
<?php

namespace Joli\Jane\Guesser\JsonSchema;

use Joli\Jane\Guesser\ChainGuesserAwareInterface;
use Joli\Jane\Guesser\ChainGuesserAwareTrait;
use Joli\Jane\Guesser\ClassGuesserInterface;
use Joli\Jane\Guesser\Guess\MapType;
use Joli\Jane\Guesser\Guess\Type;
use Joli\Jane\Guesser\GuesserInterface;
use Joli\Jane\Guesser\TypeGuesserInterface;
use Joli\Jane\Model\JsonSchema;
use Joli\Jane\Registry;

class AdditionalPropertiesGuesser implements GuesserInterface, TypeGuesserInterface, ChainGuesserAwareInterface, ClassGuesserInterface
{
    use ChainGuesserAwareTrait;

    /**
     * {@inheritDoc}
     */
    public function guessClass($object, $name, $reference, Registry $registry)
    {
        if (is_a($object->getAdditionalProperties(), $this->getSchemaClass())) {
            $this->chainGuesser->guessClass($object->getAdditionalProperties(), $name . 'Item', $reference . '/additionalProperties', $registry);
        }
    }

    /**
     * {@inheritDoc}
     */
    public function supportObject($object)
    {
        if (!($object instanceof JsonSchema)) {
            return false;
        }

        if ($object->getType() !== 'object') {
            return false;
        }

        if ($object->getAdditionalProperties() !== true && !is_object($object->getAdditionalProperties())) {
            return false;
        }

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function guessType($object, $name, $reference, Registry $registry)
    {
        if ($object->getAdditionalProperties() === true) {
            return new MapType($object, new Type($object, 'mixed'));
        }

        return new MapType($object, $this->chainGuesser->guessType($object->getAdditionalProperties(), $name . 'Item', $reference . '/additionalProperties', $registry));
    }

    /**
     * @return string
     */
    protected function getSchemaClass()
    {
        return JsonSchema::class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

const cli = require("@absolunet/cli");
const Task = require("../classes/task");
const util = require("../helpers/util");

class RunTask extends Task {
	constructor() {
		super();
		this.filename = __filename;
	}

	cli(meowCli) {
		util.checkInstalledWorkflow();
		cli.refuseFlags(meowCli);

		if (meowCli.input.length <= 3) {
			const [, task, bundle] = meowCli.input;

			if (task) {
				util.runWorkflowTask(task, { bundle });
			} else {
				cli.showTaskUsage(meowCli);
			}
		} else {
			cli.showTaskUsage(meowCli);
		}
	}
}

module.exports = new RunTask();


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { StaticQuery, graphql } from 'gatsby';

import '../assets/sass/main.scss';
import Footer from './Footer';
import SideBar from './Sidebar';

class Layout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isPreloaded: true,
    };
  }

  componentDidMount() {
    this.timeoutId = setTimeout(() => {
      this.setState({ isPreloaded: false });
    }, 100);
  }

  componentWillUnmount() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
  }

  render() {
    const { children, fullMenu } = this.props;
    const { isPreloaded } = this.state;
    return (
      <StaticQuery
        query={graphql`
          query SiteTitleQuery {
            site {
              siteMetadata {
                title
              }
            }
          }
        `}
        render={data => (
          <>
            <Helmet
              title={data.site.siteMetadata.title}
              meta={[
                {
                  name: 'description',
                  content: 'Complete Internet of Things solutions',
                },
                {
                  name: 'keywords',
                  content:
                    'iot, internet of things, react, react native, bluetooth, android, ios',
                },
              ]}
            >
              <html lang="en" />
            </Helmet>
            <div
              className={
                isPreloaded
                  ? 'landing main-body is-preload'
                  : 'landing main-body'
              }
            >
              <div id="page-wrapper">
                {/* <SideBar fullMenu={fullMenu} /> */}
                {children}
                <Footer />
              </div>
            </div>
          </>
        )}
      />
    );
  }
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
};

export default Layout;


text:
import * as chai from 'chai';
import {
	CompiledXPathFunction,
	compileXPathToJavaScript,
	executeJavaScriptCompiledXPath,
	IAstAccepted,
	Language,
	parseScript,
	ReturnType,
} from 'fontoxpath';
import escapeJavaScriptString from 'fontoxpath/jsCodegen/escapeJavaScriptString';
import * as slimdom from 'slimdom';
import jsonMlMapper from 'test-helpers/jsonMlMapper';
import evaluateXPathWithJsCodegen from '../../parsing/jsCodegen/evaluateXPathWithJsCodegen';

describe('string tests', () => {
	let documentNode: slimdom.Document;
	beforeEach(() => {
		documentNode = new slimdom.Document();
		jsonMlMapper.parse(['xml', 'Hello'], documentNode);
	});

	it('test simple string expression true', () => {
		chai.assert.equal(
			evaluateXPathWithJsCodegen('"hello"', documentNode, null, ReturnType.STRING, {}),
			'hello'
		);
	});

	it('test simple string expression false', () => {
		chai.assert.notEqual(
			evaluateXPathWithJsCodegen("'hello!'", documentNode, null, ReturnType.STRING, {}),
			'hello'
		);
	});

	it('test simple string expression with escaping', () => {
		chai.assert.equal(
			evaluateXPathWithJsCodegen("'he''llo'", documentNode, null, ReturnType.STRING, {}),
			"he'llo"
		);
	});

	it('test sanitize string', () => {
		chai.assert.equal(escapeJavaScriptString('hello\\'), '"hello\\\\"');
	});

	it('test sanitize string double quote', () => {
		chai.assert.equal(escapeJavaScriptString("''"), '"\'\'"');
	});

	it('test sanitize string triple quote', () => {
		chai.assert.equal(escapeJavaScriptString("'''"), "\"'''\"");
	});

	it('test sanitize string double backslash', () => {
		chai.assert.equal(escapeJavaScriptString('\\\\'), '"\\\\\\\\"');
	});

	it('test sanitize string triple backslash', () => {
		chai.assert.equal(escapeJavaScriptString('\\\\\\'), '"\\\\\\\\\\\\"');
	});

	it('test string expression malicous code', () => {
		chai.assert.equal(
			evaluateXPathWithJsCodegen(
				"''' || console.log(3); //'",
				documentNode,
				null,
				ReturnType.STRING,
				{}
			),
			"' || console.log(3); //"
		);
	});

	it('test xpath string escaping', () => {
		chai.assert.equal(
			evaluateXPathWithJsCodegen(
				"'child::element()'",
				documentNode,
				null,
				ReturnType.STRING,
				{}
			),
			'child::element()'
		);
	});

	it('test xpath string with character reference', () => {
		chai.assert.equal(
			evaluateXPathWithJsCodegen('"-"', documentNode, null, ReturnType.STRING, {
				language: Language.XQUERY_3_1_LANGUAGE,
			}),
			'-'
		);
	});

	it('test empty string codegen with xqueryx', () => {
		debugger;
		const xqueryx = parseScript('""', {}, documentNode);
		const script = compileXPathToJavaScript(xqueryx, ReturnType.STRING);
		chai.assert.isTrue(script.isAstAccepted);
		chai.assert.equal(
			executeJavaScriptCompiledXPath(
				new Function((script as IAstAccepted).code) as CompiledXPathFunction
			),
			''
		);
	});
});


text:
<?php

/**
 *   An object representing a single phone number. For more
 *   information, see the `IncomingPhoneNumber Instance Resource
 *   <http://www.twilio.com/docs/api/rest/incoming-phone-numbers#instance>`_
 *   documentation.
 *
 *   .. php:attr:: sid
 *
 *      A 34 character string that uniquely idetifies this resource.
 *
 *   .. php:attr:: date_created
 *
 *      The date that this resource was created, given as GMT RFC 2822 format.
 *
 *   .. php:attr:: date_updated
 *
 *      The date that this resource was last updated, given as GMT RFC 2822 format.
 *
 *   .. php:attr:: friendly_name
 *
 *      A human readable descriptive text for this resource, up to 64
 *      characters long. By default, the FriendlyName is a nicely formatted
 *      version of the phone number.
 *
 *   .. php:attr:: account_sid
 *
 *      The unique id of the Account responsible for this phone number.
 *
 *   .. php:attr:: phone_number
 *
 *      The incoming phone number. e.g., +16175551212 (E.164 format)
 *
 *   .. php:attr:: api_version
 *
 *      Calls to this phone number will start a new TwiML session with this
 *      API version.
 *
 *   .. php:attr:: voice_caller_id_lookup
 *
 *      Look up the caller's caller-ID name from the CNAM database (additional charges apply). Either true or false.
 *
 *   .. php:attr:: voice_url
 *
 *      The URL Twilio will request when this phone number receives a call.
 *
 *   .. php:attr:: voice_method
 *
 *      The HTTP method Twilio will use when requesting the above Url. Either GET or POST.
 *
 *   .. php:attr:: voice_fallback_url
 *
 *      The URL that Twilio will request if an error occurs retrieving or executing the TwiML requested by Url.
 *
 *   .. php:attr:: voice_fallback_method
 *
 *      The HTTP method Twilio will use when requesting the VoiceFallbackUrl. Either GET or POST.
 *
 *   .. php:attr:: status_callback
 *
 *      The URL that Twilio will request to pass status parameters (such as call ended) to your application.
 *
 *   .. php:attr:: status_callback_method
 *
 *      The HTTP method Twilio will use to make requests to the StatusCallback URL. Either GET or POST.
 *
 *   .. php:attr:: sms_url
 *
 *      The URL Twilio will request when receiving an incoming SMS message to this number.
 *
 *   .. php:attr:: sms_method
 *
 *      The HTTP method Twilio will use when making requests to the SmsUrl. Either GET or POST.
 *
 *   .. php:attr:: sms_fallback_url
 *
 *      The URL that Twilio will request if an error occurs retrieving or executing the TwiML from SmsUrl.
 *
 *   .. php:attr:: sms_fallback_method
 *
 *      The HTTP method Twilio will use when requesting the above URL. Either GET or POST.
 *
 *   .. php:attr:: beta
 *
 *      Whether this number is new to Twilio's inventory.
 *
 *   .. php:attr:: uri
 *
 *    The URI for this resource, relative to https://api.twilio.com.
 */
class Services_Twilio_Rest_IncomingPhoneNumber
    extends Services_Twilio_InstanceResource
{
}


text:
def good_guess?(num)
  return true if num == 42
  false
end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Mobile Clinic: TriagePatientViewController Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Mobile Clinic
    1.0

Senior Project

Main Page

Related Pages

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Structures

Data Structure Index

Class Hierarchy

Data Fields

 All Data Structures Functions Properties Pages

Public Member Functions |
Protected Attributes |
Properties

TriagePatientViewController Class Reference

Inheritance diagram for TriagePatientViewController:

<map name="_triage_patient_view_controller_inherit__map" id="_triage_patient_view_controller_inherit__map">
</map>
[legend]

Collaboration diagram for TriagePatientViewController:

<map name="_triage_patient_view_controller_coll__map" id="_triage_patient_view_controller_coll__map">
</map>
[legend]

Public Member Functions

(void) 	- setScreenHandler:

Protected Attributes

ScreenHandler 	handler

Properties

NSMutableDictionary * 	patientData

CurrentVisitViewController * 	control1

PreviousVisitsViewController * 	control2

IBOutlet UITextField * 	patientNameField

IBOutlet UITextField * 	familyNameField

IBOutlet UITextField * 	villageNameField

IBOutlet UITextField * 	patientAgeField

IBOutlet UITextField * 	patientSexField

IBOutlet UIImageView * 	patientPhoto

IBOutlet UILabel * 	patientWeightLabel

IBOutlet UILabel * 	patientBPLabel

IBOutlet UITableView * 	tableView

IBOutlet UIToolbar * 	toolBar

IBOutlet UISegmentedControl * 	segmentedControl

The documentation for this class was generated from the following files:

Mobile Clinic/TriagePatientViewController.h

Mobile Clinic/TriagePatientViewController.m

<address class="footer">
Generated on Sun Mar 3 2013 20:57:27 for Mobile Clinic by

 1.8.1.1
</address>


text:
//
//  HCPContentManifestStorage.h
//
//  InfinitusHotCodePush
//
//  Created by M on 16/8/30.
//

#import "HCPConfigStorageImpl.h"
#import "HCPFilesStructure.h"

/**
 *  保存和读取manifest文件的工具类
 *
 *  @see HCPContentManifest
 */
@interface HCPContentManifestStorage : HCPConfigStorageImpl

/**
 *  初始化
 *
 *  @param fileStructure fileStructure
 *
 *  @return 实例
 */
- (instancetype)initWithFileStructure:(HCPFilesStructure *)fileStructure;

@end


text:
var HamburgerButton = require('./HamburgerButton.react');
var DropdownMenu = require('./DropdownMenu.react');

/**
 * Creates a hamburger menu with a neat animation when clicked.
 *
 * Use the Openable.react.js component wrapper to get the fucntions for toggling
 * the open state of this component. They are not included in this component itself
 * so that the menu items are able to close the menu when they are clicked.
 *
 * @prop isOpen boolean if the hamburger menu is open
 * @prop toggleOpen the function to toggle the open state
 * @prop close the function to close the menu with
 * @prop label the aria label and the help text value
 * @prop helpPosition the position of the help text dropdown
 * @prop isLarge boolean if this is the large version of the hamburger menu
 * @prop menuClasses an array of additional css classes to apply to the dropdown menu
 * @prop onOpenFunc an optional function to call when opening the hamburger menu
 * @prop onCloseFunc an optional funciton to call when closing the hamburger menu
 */
var HamburgerMenu = React.createClass({
  propTypes: {
    isOpen: React.PropTypes.bool.isRequired,
    toggleOpen: React.PropTypes.func.isRequired,
    close: React.PropTypes.func.isRequired,
    label: React.PropTypes.string.isRequired,
    helpPosition: React.PropTypes.oneOf(['top', 'right', 'left', 'bottom']),
    isLarge: React.PropTypes.bool,
    menuClasses: React.PropTypes.arrayOf(React.PropTypes.string),
    onOpenFunc: React.PropTypes.func,
    onCloseFunc: React.PropTypes.func
  },

  getDefaultProps: function() {
    return {
      menuClasses: [],
      helpPosition: 'bottom',
      isLarge: false
    };
  },

  toggleMenu: function() {
    if(!this.props.isOpen && this.props.onOpenFunc) {
      this.props.onOpenFunc();
    } else if(this.props.isOpen && this.props.onCloseFunc) {
      this.props.onCloseFunc();
    }

    this.props.toggleOpen();
  },

  closeMenu: function() {
    if(this.props.onCloseFunc) {
      this.props.onCloseFunc();
    }

    this.props.close();
  },

  render: function() {
    var menuCss = ['dd-menu'].concat(this.props.menuClasses).join(' ');
    var itemClasses = ['dd-menu-items'];
    if(!this.props.isOpen) {
      itemClasses.push('items-hidden');
    }

    return (
      <DropdownMenu isOpen={this.props.isOpen} forceCloseFunction={this.closeMenu}
               menuItems={this.props.children} menuClasses={this.props.menuClasses}>
         <HamburgerButton isOpen={this.props.isOpen} onBtnClick={this.toggleMenu} label={this.props.label} helpPosition={this.props.helpPosition} />
      </DropdownMenu>
    );
  }
});

module.exports = HamburgerMenu;


text:
package org.omg.dds.core;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.omg.dds.type.Extensibility;
import org.omg.dds.type.Nested;

/**
 * A span of elapsed time expressed with nanosecond precision.
 *

 * Instances of this type are immutable.
 */
@Extensibility(Extensibility.Kind.FINAL_EXTENSIBILITY)
@Nested
public abstract class Duration
implements Comparable<Duration>, Serializable, DDSObject
{
    // -----------------------------------------------------------------------
    // Private Constants
    // -----------------------------------------------------------------------

    private static final long serialVersionUID = 6926514364942353575L;

    // -----------------------------------------------------------------------
    // Factory Methods
    // -----------------------------------------------------------------------

    /**
     * Construct a time duration of the given magnitude.
     *

     * A duration of magnitude {@link Long#MAX_VALUE} indicates an infinite
     * duration, regardless of the units specified.
     *
     * @param env       Identifies the Service instance to which the new
     *                  object will belong.
     *
     * @see     #isInfinite()
     * @see     #infiniteDuration(ServiceEnvironment)
     */
    public static Duration newDuration(
            long duration,
            TimeUnit unit,
            ServiceEnvironment env)
    {
        if (env == null) {
            throw new IllegalArgumentException(
                    "Invalid ServiceEnvironment (null) provided.");
        }
        return env.getSPI().newDuration(duration, unit);
    }

    /**
     * @param env       Identifies the Service instance to which the
     *                  object will belong.
     *
     * @return  An unmodifiable {@link org.omg.dds.core.Duration} of infinite length.
     */
    public static Duration infiniteDuration(ServiceEnvironment env)
    {
        if (env == null) {
            throw new IllegalArgumentException(
                    "Invalid ServiceEnvironment (null) provided.");
        }
        return env.getSPI().infiniteDuration();
    }

    /**
     * @param env       Identifies the Service instance to which the
     *                  object will belong.
     *
     * @return  A {@link org.omg.dds.core.Duration} of zero length.
     */
    public static Duration zeroDuration(ServiceEnvironment env)
    {
        if (env == null) {
            throw new IllegalArgumentException(
                    "Invalid ServiceEnvironment (null) provided.");
        }
        return env.getSPI().zeroDuration();
    }

    // -----------------------------------------------------------------------
    // Instance Methods
    // -----------------------------------------------------------------------

    // --- Data access: ------------------------------------------------------

    /**
     * Truncate this duration to a whole-number quantity of the given time
     * unit. For example, if this duration is equal to one second plus 100
     * nanoseconds, calling this method with an argument of
     * {@link TimeUnit#SECONDS} will result in the value 1.
     *

     * If this duration is infinite, this method shall return
     * {@link Long#MAX_VALUE}, regardless of the units given.
     *

     * If this duration cannot be expressed in the given units without
     * overflowing, this method shall return {@link Long#MAX_VALUE}. In such
     * a case, the caller may wish to use this method in combination with
     * {@link #getRemainder(TimeUnit, TimeUnit)} to obtain the full duration
     * without lack of precision.
     *
     * @param   inThisUnit  The time unit in which the return result will
     *                      be measured.
     *
     * @see     #getRemainder(TimeUnit, TimeUnit)
     * @see     Long#MAX_VALUE
     * @see     TimeUnit
     */
    public abstract long getDuration(TimeUnit inThisUnit);

    /**
     * If getting the magnitude of this duration in the given
     * primaryUnit would cause truncation with respect to the
     * given remainderUnit, return the magnitude of the
     * truncation in the latter (presumably finer-grained) unit. For example,
     * if this duration is equal to one second plus 100 nanoseconds, calling
     * this method with arguments of {@link TimeUnit#SECONDS} and
     * {@link TimeUnit#NANOSECONDS} respectively will result in the value
     * 100.
     *

     * This method is equivalent to the following pseudo-code:
     *

     *
     * (this - getDuration(primaryUnit)).getDuration(remainderUnit)
     *
     *

     * If remainderUnit is represents a coarser granularity than
     * primaryUnit (for example, the former is
     * {@link TimeUnit#MILLISECONDS} but the latter is {@link TimeUnit#SECONDS}),
     * this method shall return 0.
     *

     * If the resulting duration cannot be expressed in the given units
     * without overflowing, this method shall return {@link Long#MAX_VALUE}.
     *
     * @param   primaryUnit
     * @param   remainderUnit   The time unit in which the return result will
     *                          be measured.
     *
     * @see     #getDuration(TimeUnit)
     * @see     Long#MAX_VALUE
     * @see     TimeUnit
     */
    public abstract long getRemainder(
            TimeUnit primaryUnit, TimeUnit remainderUnit);

    // --- Query: ------------------------------------------------------------

    /**
     * Report whether this duration lasts no time at all. The result of this
     * method is equivalent to the following:
     *

     * this.getDuration(TimeUnit.NANOSECONDS) == 0;
     *
     * @see     #getDuration(TimeUnit)
     */
    public abstract boolean isZero();

    /**
     * Report whether this duration lasts forever.
     *

     * If this duration is infinite, the following relationship shall be
     * true:
     *

     * this.equals(infiniteDuration(this.getEnvironment()))
     *
     * @see     #infiniteDuration(ServiceEnvironment)
     */
    public abstract boolean isInfinite();

    // --- Manipulation: -----------------------------------------------------

    /**
     * @return  a new Duration that is the sum of this Duration and the
     *          given Duration.
     */
    public abstract Duration add(Duration duration);

    /**
     * @return  a new Duration that is the sum of this Duration and the
     *          given duration.
     */
    public abstract Duration add(long duration, TimeUnit unit);

    /**
     * @return  a new Duration that is the difference after subtracting the
     *          given Duration.
     */
    public abstract Duration subtract(Duration duration);

    /**
     * @return  a new Duration that is the difference after subtracting the
     *          given Duration.
     */
    public abstract Duration subtract(long duration, TimeUnit unit);
}


text:
// This module defines a way to access various metadata about an imageId.  This layer of abstraction exists
// So metadata can be provided in different ways (e.g. by parsing DICOM P10 or by a WADO-RS document)

const providers = [];

/**
 * @module Metadata
 */

/**
 * Adds a metadata provider with the specified priority
 * @param {Function} provider Metadata provider function
 * @param {Number} [priority=0] - 0 is default/normal, > 0 is high, < 0 is low
 *
 * @returns {void}
 * @memberof Metadata
 */
export function addProvider (provider, priority = 0) {
  let i;

  // Find the right spot to insert this provider based on priority
  for (i = 0; i < providers.length; i++) {
    if (providers[i].priority <= priority) {
      break;
    }
  }

  // Insert the decode task at position i
  providers.splice(i, 0, {
    priority,
    provider
  });
}

/**
 * Removes the specified provider
 *
 * @param {Function} provider Metadata provider function
 *
 * @returns {void}
 * @memberof Metadata
 */
export function removeProvider (provider) {
  for (let i = 0; i < providers.length; i++) {
    if (providers[i].provider === provider) {
      providers.splice(i, 1);

      break;
    }
  }
}

/**
 * Gets metadata from the registered metadata providers.  Will call each one from highest priority to lowest
 * until one responds
 *
 * @param {String} type The type of metadata requested from the metadata store
 * @param {String} imageId The Cornerstone Image Object's imageId
 *
 * @returns {*} The metadata retrieved from the metadata store
 * @memberof Metadata
 */
function getMetaData (type, imageId) {
  // Invoke each provider in priority order until one returns something
  for (let i = 0; i < providers.length; i++) {
    const result = providers[i].provider(type, imageId);

    if (result !== undefined) {
      return result;
    }
  }
}

export default {
  addProvider,
  removeProvider,
  get: getMetaData
};


text:
import kombu
import socket

from qpaca.helpers import logger

class RabbitMQHandler(object):
    def _create_producer(self):
        """Create a RabbitMQ producer"""

        return kombu.Producer(self.connection)

    def _create_exchange(self):
        """Create a RabbitMQ exchange"""

        logger.debug('Creating RabbitMQ Exchange')
        exchange = kombu.Exchange(
            **self.config.get('exchange'))(self.connection)
        exchange.declare()
        return exchange

    def _connect(self):
        """Create a RabbitMQ connection"""

        logger.debug('Connecting with RabbitMQ')
        connection = kombu.Connection(**self.config.get('connection'))
        connection.ensure_connection()
        return connection

    def _create_queue(self):
        """Create a RabbitMQ queue"""

        if not self.config.get('queue').get('name'):
            self.config['queue']['name'] = socket.gethostname()

        logger.debug('Creating RabbitMQ Queue')
        queue = kombu.Queue(exchange=self._exchange,
                            **self.config.get('queue'))(self.connection)
        queue.declare()
        return queue


text:
class UNIX_SystemConfigurationFixture :
	public CIMFixtureBase
{
public:
	UNIX_SystemConfigurationFixture();
	~UNIX_SystemConfigurationFixture();
	virtual void Run();

};


text:
@interface REFormattedNumberField : UITextField

@property (copy, readwrite, nonatomic) NSString *format;
@property (copy, readonly, nonatomic) NSString *unformattedText;

// Use NSString category NSString+RENumberFormat
// - (NSString *)re_stringWithNumberFormat:(NSString *)format;
//
- (NSString *)string:(NSString *)string withNumberFormat:(NSString *)format __attribute__ ((deprecated));

@end


text:
namespace ui_test_utils {

#if !defined(TOOLKIT_VIEWS)
namespace {

// Check if the focused widget for |root| is |target| or a child of |target|.
static bool IsWidgetInFocusChain(GtkWidget* root, GtkWidget* target) {
  GtkWidget* iter = root;

  while (iter) {
    if (iter == target)
      return true;

    if (!GTK_IS_CONTAINER(iter))
      return false;

    iter = GTK_CONTAINER(iter)->focus_child;
  }

  return false;
}

}  // namespace
#endif

bool IsViewFocused(const Browser* browser, ViewID vid) {
  BrowserWindow* browser_window = browser->window();
  DCHECK(browser_window);
#if defined(TOOLKIT_VIEWS)
  gfx::NativeWindow window = browser_window->GetNativeHandle();
  DCHECK(window);
  views::FocusManager* focus_manager =
      views::FocusManager::GetFocusManagerForNativeView(
          GTK_WIDGET(window));
  DCHECK(focus_manager);
  return focus_manager->GetFocusedView() &&
      focus_manager->GetFocusedView()->GetID() == vid;
#else
  gfx::NativeWindow window = browser_window->GetNativeHandle();
  DCHECK(window);
  GtkWidget* widget = ViewIDUtil::GetWidget(GTK_WIDGET(window), vid);
  DCHECK(widget);
  return IsWidgetInFocusChain(GTK_WIDGET(window), widget);
#endif
}

void ClickOnView(const Browser* browser, ViewID vid) {
  BrowserWindow* browser_window = browser->window();
  DCHECK(browser_window);
#if defined(TOOLKIT_VIEWS)
  views::View* view =
      reinterpret_cast<BrowserView*>(browser_window)->GetViewByID(vid);
#else
  gfx::NativeWindow window = browser_window->GetNativeHandle();
  DCHECK(window);
  GtkWidget* view = ViewIDUtil::GetWidget(GTK_WIDGET(window), vid);
#endif

  DCHECK(view);
  ui_controls::MoveMouseToCenterAndPress(
      view,
      ui_controls::LEFT,
      ui_controls::DOWN | ui_controls::UP,
      new MessageLoop::QuitTask());
  RunMessageLoop();
}

void HideNativeWindow(gfx::NativeWindow window) {
  gtk_widget_hide(GTK_WIDGET(window));
}

void ShowAndFocusNativeWindow(gfx::NativeWindow window) {
  if (gtk_window_has_toplevel_focus(GTK_WINDOW(window)))
    return;

  gtk_window_present(GTK_WINDOW(window));
}

}  // namespace ui_test_utils


text:
layout: post
title:  Double Render Errors
date:   2017-06-03 19:07:00 +0000
---

So I'm not a long form blogger. Hours of typing up clever posts substituted for hours of typing up actual code is not my idea of a well spent afternoon. With the exception of project posts, I'm starting a series of short segments each focusing on a particular code problem.

![Murder She Wrote - Typing](http://i.imgur.com/7fyj7Y1.gif)

The other reason for this change is that it hopefully motivates me to blog on a semi-regular basis. Fingers crossed. This week:
## Avoiding Double Render* (and redirect_to) Errors
RailsGuides are a lifesaver. Oftentimes, I've discovered the solution to a baffling Rails problems in them. However, there have been situations when I know nothing more about what I'm looking for, than just a vague error message and a few guesses as to what it might mean. This particular example will seem contrived. The only point of the application was to discover how Rails handles cookies through sessions and nothing more.

The sessions controller has three actions: `new`, `create`, and `destroy`. The `new` action leads to a login page. The `create` action instantiates a cookie in the sessions hash under `session[:name]`, and the `destroy` action deletes the cookie when the user logs out.

My double render error occured in the `create` action exclusively. Here's the code that created the error:

```
def create
    session[:name] = params[:name]

    if !session[:name] || session[:name].empty?
      redirect_to login_path
    end

	redirect_to root_path
end
```

You see, Rails reads this as having two redirect_to routes and spits out an error that says something like this: "Can only render or redirect once per action."

My first solution to the problem was in desperate need of refactoring. I'll reproduce it here:

```
def create
    if params[:name].present?
      session[:name] = params[:name]
      redirect_to root_path
    elsif !session[:name] || session[:name].empty?
      redirect_to login_path
    end
  end
```

Let me preface this by saying it works like this, but the code's a mess. Since Rubyists love simple, elegant code and since we programmers like to keep our controllers DRY, I sought out a better solution to my double render error and found one. This is it:

```
def create
    session[:name] = params[:name]
    if !session[:name] || session[:name].empty?
      redirect_to login_path and return
    end
    redirect_to root_path
  end
```

Notice I was close to the solution with the code that brought about the error. In fact, there are only two words difference between the two snippets. Did you spot it? That's right. The difference is `and return`. Looks simple, but what's happening?

Until the return is added to the action, Rails reads everything in the if statement and then continues beyond it, throwing the error message when it arrives at a second `redirect_to` path. But remember in Ruby, `return` acts like a `break` and exits the method before the entire block is executed, which means that if there is no `session[:name]` or it is empty, Rails will redirect to the login path and break out of the block.

Without breaking, the if statement tries executing both the if block and the line under it. In the Rails server, you will see that controller action works as expected, but it will not pass any tests instead spitting out a cryptic paragraph that had me scratching my head. I'd like to think the only reason it worked in the Rails server was dumb luck, but Rails likes to guess.

Needless to say, use return in your action whenever there are multiple redirects. You might even could write it like this:

```
return redirect_to login_path
```

Even less code! Adding a return statement protects you from Double Render Errors, and it makes your code readable to other developers. Cheers!

*If you want to read up on Double Render Errors in the RailsGuides, check it out here: [http://guides.rubyonrails.org/layouts_and_rendering.html#using-render](http://guides.rubyonrails.org/layouts_and_rendering.html#using-render), section 2.2.14.


text:
FROM golang:1.19-bullseye as builder

RUN apt-get update &&\
    apt-get install -y apt-utils make

# Install kubebuilder
WORKDIR /scratch
ENV version=2.3.1
ENV arch=amd64
RUN curl -L -O "https://github.com/kubernetes-sigs/kubebuilder/releases/download/v${version}/kubebuilder_${version}_linux_${arch}.tar.gz" &&\
    tar -zxvf kubebuilder_${version}_linux_${arch}.tar.gz &&\
    mv kubebuilder_${version}_linux_${arch} /usr/local/kubebuilder &&\
    rm kubebuilder_${version}_linux_${arch}.tar.gz
ENV PATH=$PATH:/usr/local/kubebuilder/bin:/usr/bin

# Install kustomize
ENV version=3.7.0
ENV arch=amd64
RUN curl -L -O "https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv${version}/kustomize_v${version}_linux_${arch}.tar.gz" &&\
    tar -zxvf kustomize_v${version}_linux_${arch}.tar.gz &&\
    chmod +x kustomize &&\
    mv kustomize /usr/local/bin

WORKDIR /app


text:
/*
 * Users Routers *
 * Users Data Access Object *
 * User Wallet *

 * Functionalities Index:
        ========================================================================================================================
        | S.No. |  Type  |         URL         |   Function Call   | Controller |                  Description                 |
        ========================================================================================================================
        |   1.  | Put    | /user/update/wallet | addCash           | usersCard  | Update wallet amount without payment gateway |     |
        ------------------------------------------------------------------------------------------------------------------------
		|   2.  | Post   | /user/update/wallet | addCash           | usersCard  | Update wallet amount with payment gateway    |
        ------------------------------------------------------------------------------------------------------------------------

*/

/* importing required files and packages */
const express = require('express');
const router = express.Router();
const xss = require('xss');
const data = require('../../../data');
const usersData = data.users;
const usersCardData = data.usersCard;
const usersWalletData = data.usersWallet;
const walletTransaction = data.transactionWallet;
const passport = require('../../../config/passport-users');

/* local scoped function */
//------ user authentication validation
function isLoggedIn(req, res, next) {
	if (req.isAuthenticated()) {
		return next();
	} else {
		res.render('alerts/error', {
			mainTitle: "Bad Request •",
			code: 400,
			message: "Unauthorized Request Attempt",
			url: req.originalUrl,
			user: req.user
		});
	}
}

/* global scoped function */
//------------------------ route to quickly update wallet amount by user id without payment gatewaty
router.put('/', isLoggedIn, (req, res) => {

	let email = xss(req.user._id);
	let amount = xss(req.body.amount);
	let cardUsed = xss(req.body.cardUsed);
	let status = xss(req.body.action);
	let remark = xss(req.body.description);

	if (Object.keys(amount).length === 0 || amount == undefined) {    // check for empty json passed
		res.render("users/gui/user-wallet", {
			mainTitle: "Bad Request •",
			code: 400,
			message: `No data has been provided for update.`,
			url: req.originalUrl
		});
	} else if (!amount) {
		res.status(400).json({ error: "No amount provided" });
	} else if (!cardUsed) {
		res.status(400).json({ error: "No card details provided" });
	} else if (!status || !remark) {
		res.status(400).json({ error: "Something went wrong. Please try again" });
	}

	// checking for user wallet updates
	usersCardData.getCardByIds(email, cardUsed).then((cardInfo) => {

		let cardData = {
			name: cardInfo.name,
			number: cardInfo._id,
			type: cardInfo.type,
			expiry: cardInfo.expiry,
			//issuer: cardInfo.issuer,
			cvv: cardInfo.cvv
		}

		usersWalletData.addCash(email, JSON.parse(amount)).then((walletInfo) => {
			if (walletInfo == false){
				res.json({ success: false, error: "Total wallet limit exceed. Maximum $10000 are allowed." })
			} else if (walletInfo) {
				walletTransaction.logTransaction(email, amount, cardData, status, remark).then((transactions) => {		// logging transaction

					req.user.wallet = walletInfo.wallet;
					let transactionsList = transactions.reverse();

					let data = {
						amount: walletInfo.wallet,
						success: true,
						transactions: transactionsList
					}

					res.json(data);
				});
			}
		});
	})
	.catch((error) => {     // rendering error page
		res.render('alerts/error', {
			mainTitle: "Server Error •",
			code: 500,
			message: error,
			url: req.originalUrl
		});
	});
});

//------------------------ route to quickly update wallet amount by user id with payment gatewaty
router.post('/', isLoggedIn, (req, res) => {

	let email = xss(req.user._id);
	let amount = xss(req.body.amount);
	let cardData = {
		name: xss(req.body.cardName),
		number: xss(req.body.cardNumber),
		type: xss(req.body.cardType),
		expiry: `${xss(req.body.cardMonth)}/${xss(req.body.cardYear)}`,
		//issuer: xss(req.body.cardBrand),
		cvv: xss(req.body.cardCVV)
	};
	let status = "Credit";
	let remark = "Added cash in wallet";

	if (Object.keys(amount).length === 0 || amount == undefined) {    // check for empty json passed
		res.status(400).json({ error: "No wallet details provided provided" });
	} else if (!amount) {
		res.status(400).json({ error: "No amount provided" });
	} else if (!cardData.name) {
		res.status(400).json({ error: "No card name provided" });
	} else if (!cardData.number) {
		res.status(400).json({ error: "No card number provided" });
	} else if (!cardData.type) {
		res.status(400).json({ error: "No card type provided" });
	} else if (!cardData.expiry) {
		res.status(400).json({ error: "No expiry provided" });
	}/* else if (!cardData.issuer) {
		res.status(400).json({ error: "No card issuer provided" });
	}*/ else if (!cardData.cvv) {
		res.status(400).json({ error: "No card CVV provided" });
	}

	// checking for user wallet updates
	usersWalletData.addCash(email, JSON.parse(amount)).then((walletInfo) => {

		if (walletInfo == false){
			res.render('alerts/error', {
				mainTitle: "Bad Request •",
				code: 400,
				message: "Total wallet limit exceed. Maximum $10000 are allowed.",
				url: req.originalUrl,
				user: req.user
			});
		} else if (walletInfo) {
			walletTransaction.logTransaction(email, amount, cardData, status, remark).then((transactions) => {		// logging transaction

				req.user.wallet = walletInfo.wallet;
				let transactionsList = transactions.reverse();
				let transId = transactionsList[0]._id;

				res.render('payment/payment-confirmation', {
					mainTitle: "Payment Successful •",
					user: req.user,
					redirectURL: "/user/dashboard/wallet",
					amount: amount,
					transactionId: transId
				});
			});
		}
	})
	.catch((error) => {     // rendering error page
		res.render('alerts/error', {
			mainTitle: "Server Error •",
			code: 500,
			message: error,
			url: req.originalUrl,
			user: req.user
		});
	});
});

// exporting routing apis
module.exports = router;


text:
/** ------------------------------------------------------------
 * PhotoDaoTests.java
 *
 * Big Cyber City
 *
 * @author wbruschi [ Dec 12, 2008 ]
 * ------------------------------------------------------------
 */
package com.bigcybercity.dao;

import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;

import com.bigcybercity.entity.Photo;

/**
 *
 */

public class PhotoDaoTests extends
		AbstractTransactionalDataSourceSpringContextTests {

	private PhotoDao photoDao;

	public void setPhotoDao(PhotoDao photoDao) {
		this.photoDao = photoDao;
	}

	@Override
	protected String[] getConfigLocations() {
		return new String[] {"classpath:test-context.xml"};
	}

	public void testGetPhoto() {
		Photo photo = photoDao.getPhoto(9);
		assertNotNull(photo);
		assertEquals(9, photo.getPhotoId());
		assertEquals(photo.getFileName(), "9.JPEG");
	}

}


text:
<?php namespace Fisharebest\Localization\Locale;

class LocaleFaIr extends LocaleFa {
}


text:
import { ShippingTestQueryRawResponse } from "v2/__generated__/ShippingTestQuery.graphql"
import { cloneDeep } from "lodash"

import { RadioGroup } from "@artsy/palette"
import {
  UntouchedBuyOrder,
  UntouchedOfferOrder,
} from "v2/Apps/__tests__/Fixtures/Order"
import {
  fillCountrySelect,
  fillIn,
  fillInPhoneNumber,
  validAddress,
} from "v2/Components/__tests__/Utils/addressForm"
import { Address } from "v2/Components/AddressForm"
import { CountrySelect } from "v2/Components/CountrySelect"
import Input from "v2/Components/Input"
import { createTestEnv } from "v2/DevTools/createTestEnv"
import { commitMutation as _commitMutation, graphql } from "react-relay"
import {
  settingOrderShipmentFailure,
  settingOrderShipmentMissingCountryFailure,
  settingOrderShipmentMissingRegionFailure,
  settingOrderShipmentSuccess,
} from "../__fixtures__/MutationResults"
import { ShippingFragmentContainer } from "../Shipping"
import { OrderAppTestPage } from "./Utils/OrderAppTestPage"

jest.unmock("react-relay")

const fillAddressForm = (component: any, address: Address) => {
  fillIn(component, { title: "Full name", value: address.name })
  fillIn(component, { title: "Address line 1", value: address.addressLine1 })
  fillIn(component, {
    title: "Address line 2 (optional)",
    value: address.addressLine2,
  })
  fillIn(component, { title: "City", value: address.city })
  fillIn(component, {
    title: "State, province, or region",
    value: address.region,
  })
  fillIn(component, { title: "Postal code", value: address.postalCode })
  fillInPhoneNumber(component, {
    value: address.phoneNumber,
  })
  fillCountrySelect(component, address.country)
}

const testOrder: ShippingTestQueryRawResponse["order"] = {
  ...UntouchedBuyOrder,
  internalID: "1234",
  id: "1234",
}

class ShippingTestPage extends OrderAppTestPage {
  async selectPickupOption() {
    this.find("Radio")
      .last()
      .simulate("click")
    await this.update()
  }
}

describe("Shipping", () => {
  const { mutations, buildPage, routes } = createTestEnv({
    Component: ShippingFragmentContainer,
    defaultData: { order: testOrder },
    defaultMutationResults: {
      ...settingOrderShipmentSuccess,
    },
    query: graphql`
      query ShippingTestQuery @raw_response_type {
        order: commerceOrder(id: "unused") {
          ...Shipping_order
        }
      }
    `,
    TestPage: ShippingTestPage,
  })

  it("removes radio group if pickup_available flag is false", async () => {
    const pickupAvailableOrder = cloneDeep(testOrder) as any
    pickupAvailableOrder.lineItems.edges[0].node.artwork.pickup_available = false
    const page = await buildPage({ mockData: { order: pickupAvailableOrder } })
    expect(page.find(RadioGroup).length).toEqual(0)
  })

  it("disables country select when onlyShipsDomestically is true and artwork is not in EU local zone", async () => {
    const domesticShippingOnlyOrder = cloneDeep(testOrder) as any
    domesticShippingOnlyOrder.lineItems.edges[0].node.artwork.onlyShipsDomestically = true
    domesticShippingOnlyOrder.lineItems.edges[0].node.artwork.euShippingOrigin = false
    const page = await buildPage({
      mockData: { order: domesticShippingOnlyOrder },
    })
    expect(page.find(CountrySelect).props().disabled).toBe(true)
  })

  it("does not disable select when onlyShipsDomestically is true but artwork is located in EU local zone", async () => {
    const domesticShippingEUOrder = cloneDeep(testOrder) as any
    domesticShippingEUOrder.lineItems.edges[0].node.artwork.onlyShipsDomestically = true
    domesticShippingEUOrder.lineItems.edges[0].node.artwork.euShippingOrigin = true
    const page = await buildPage({
      mockData: { order: domesticShippingEUOrder },
    })
    expect(page.find(CountrySelect).props().disabled).toBe(false)
  })

  it("commits the mutation with the orderId", async () => {
    const page = await buildPage()

    fillAddressForm(page.root, validAddress)

    expect(mutations.mockFetch).not.toHaveBeenCalled()
    await page.clickSubmit()

    expect(mutations.mockFetch).toHaveBeenCalledTimes(1)
    expect(mutations.lastFetchVariables).toMatchInlineSnapshot(`
      Object {
        "input": Object {
          "fulfillmentType": "SHIP",
          "id": "1234",
          "phoneNumber": "8475937743",
          "shipping": Object {
            "addressLine1": "14 Gower's Walk",
            "addressLine2": "Suite 2.5, The Loom",
            "city": "Whitechapel",
            "country": "UK",
            "name": "Artsy UK Ltd",
            "phoneNumber": "",
            "postalCode": "E1 8PY",
            "region": "London",
          },
        },
      }
    `)
  })

  it("commits the mutation with shipping option", async () => {
    const page = await buildPage()

    fillAddressForm(page.root, {
      ...validAddress,
      region: "New Brunswick",
      country: "US",
    })

    await page.clickSubmit()
    expect(mutations.lastFetchVariables.input.shipping.region).toBe(
      "New Brunswick"
    )
    expect(mutations.lastFetchVariables.input.shipping.country).toBe("US")
  })

  it("commits the mutation with pickup option", async () => {
    const page = await buildPage()
    console.log("")
    await page.selectPickupOption()
    fillInPhoneNumber(page.root, { isPickup: true, value: "2813308004" })
    expect(mutations.mockFetch).not.toHaveBeenCalled()
    await page.clickSubmit()
    expect(mutations.mockFetch).toHaveBeenCalledTimes(1)
    expect(mutations.lastFetchVariables.input.fulfillmentType).toBe("PICKUP")
  })

  describe("mutation", () => {
    let page: ShippingTestPage
    beforeEach(async () => {
      page = await buildPage()
    })

    it("routes to payment screen after mutation completes", async () => {
      fillAddressForm(page.root, validAddress)
      await page.clickSubmit()
      expect(routes.mockPushRoute).toHaveBeenCalledWith("/orders/1234/payment")
    })

    it("shows the button spinner while loading the mutation", async () => {
      fillAddressForm(page.root, validAddress)
      await page.expectButtonSpinnerWhenSubmitting()
    })

    it("shows an error modal when there is an error from the server", async () => {
      mutations.useResultsOnce(settingOrderShipmentFailure)
      fillAddressForm(page.root, validAddress)
      await page.clickSubmit()
      await page.expectAndDismissDefaultErrorDialog()
    })

    it("shows an error modal when there is a network error", async () => {
      fillAddressForm(page.root, validAddress)
      mutations.mockNetworkFailureOnce()
      await page.clickSubmit()
      await page.expectAndDismissDefaultErrorDialog()
    })

    it("shows a validation error modal when there is a missing_country error from the server", async () => {
      mutations.useResultsOnce(settingOrderShipmentMissingCountryFailure)
      fillAddressForm(page.root, validAddress)
      await page.clickSubmit()
      await page.expectAndDismissErrorDialogMatching(
        "Invalid address",
        "There was an error processing your address. Please review and try again."
      )
    })

    it("shows a validation error modal when there is a missing_region error from the server", async () => {
      mutations.useResultsOnce(settingOrderShipmentMissingRegionFailure)
      fillAddressForm(page.root, validAddress)
      await page.clickSubmit()
      await page.expectAndDismissErrorDialogMatching(
        "Invalid address",
        "There was an error processing your address. Please review and try again."
      )
    })
  })

  describe("with previously filled-in data", () => {
    let page: ShippingTestPage
    beforeEach(async () => {
      page = await buildPage({
        mockData: {
          order: {
            ...testOrder,
            requestedFulfillment: {
              ...validAddress,
              __typename: "CommerceShip",
              name: "Dr Collector",
            },
          },
        },
      })
    })

    it("includes already-filled-in data if available", () => {
      const input = page
        .find(Input)
        .filterWhere(wrapper => wrapper.props().title === "Full name")

      expect(input.props().value).toBe("Dr Collector")
    })

    it("includes already-filled-in data in mutation if re-sent", async () => {
      await page.clickSubmit()
      expect(mutations.lastFetchVariables.input).toMatchObject({
        shipping: {
          name: "Dr Collector",
        },
      })
    })
  })

  describe("Validations", () => {
    let page: ShippingTestPage
    beforeEach(async () => {
      page = await buildPage()
    })

    describe("for Ship orders", () => {
      it("does not submit an empty form for a SHIP order", async () => {
        await page.clickSubmit()
        expect(mutations.mockFetch).not.toBeCalled()
      })

      it("does not submit the mutation with an incomplete form for a SHIP order", async () => {
        fillIn(page.root, { title: "Full name", value: "Air Bud" })
        await page.clickSubmit()
        expect(mutations.mockFetch).not.toBeCalled()
      })

      it("does submit the mutation with a complete form for a SHIP order", async () => {
        fillAddressForm(page.root, validAddress)
        await page.clickSubmit()
        expect(mutations.mockFetch).toBeCalled()
      })

      it("says a required field is required for a SHIP order", async () => {
        await page.clickSubmit()
        const input = page
          .find(Input)
          .filterWhere(wrapper => wrapper.props().title === "Full name")
        expect(input.props().error).toEqual("This field is required")
      })

      it("allows a missing postal code if the selected country is not US or Canada", async () => {
        const address = {
          name: "Erik David",
          addressLine1: "401 Broadway",
          addressLine2: "",
          city: "New York",
          region: "NY",
          postalCode: "",
          phoneNumber: "5555937743",
          country: "AQ",
        }
        fillAddressForm(page.root, address)
        await page.clickSubmit()

        const input = page
          .find(Input)
          .filterWhere(wrapper => wrapper.props().title === "Postal code")
        expect(input.props().error).toBeFalsy()

        expect(mutations.mockFetch).toBeCalled()
      })

      it("before submit, only shows a validation error on inputs that have been touched", async () => {
        fillIn(page.root, { title: "Full name", value: "Erik David" })
        fillIn(page.root, { title: "Address line 1", value: "" })

        await page.update()

        const [addressInput, cityInput] = [
          "Address line 1",
          "City",
        ].map(label =>
          page
            .find(Input)
            .filterWhere(wrapper => wrapper.props().title === label)
        )

        expect(addressInput.props().error).toBeTruthy()
        expect(cityInput.props().error).toBeFalsy()
      })

      it("after submit, shows all validation errors on inputs that have been touched", async () => {
        fillIn(page.root, { title: "Full name", value: "Erik David" })

        await page.clickSubmit()

        const cityInput = page.root
          .find(Input)
          .filterWhere(wrapper => wrapper.props().title === "City")

        expect(cityInput.props().error).toBeTruthy()
      })

      it("does not submit the mutation without a phone number", async () => {
        const address = {
          name: "Erik David",
          addressLine1: "401 Broadway",
          addressLine2: "",
          city: "New York",
          region: "",
          postalCode: "7Z",
          phoneNumber: "",
          country: "AQ",
        }
        fillAddressForm(page.root, address)
        await page.clickSubmit()
        expect(mutations.mockFetch).not.toBeCalled()
      })

      it("allows a missing state/province if the selected country is not US or Canada", async () => {
        const address = {
          name: "Erik David",
          addressLine1: "401 Broadway",
          addressLine2: "",
          city: "New York",
          region: "",
          postalCode: "7Z",
          phoneNumber: "5555937743",
          country: "AQ",
        }
        fillAddressForm(page.root, address)
        await page.clickSubmit()
        expect(mutations.mockFetch).toBeCalled()
      })
    })

    it("does submit the mutation with a non-ship order", async () => {
      await page.selectPickupOption()
      fillInPhoneNumber(page.root, { isPickup: true, value: "2813308004" })
      await page.clickSubmit()
      expect(mutations.mockFetch).toBeCalled()
    })

    it("does not submit the mutation with an incomplete form for a PICKUP order", async () => {
      await page.selectPickupOption()
      await page.clickSubmit()
      expect(mutations.mockFetch).not.toBeCalled()
    })
  })

  describe("Offer-mode orders", () => {
    it("shows an active offer stepper if the order is an Offer Order", async () => {
      const page = await buildPage({
        mockData: {
          order: UntouchedOfferOrder,
        },
      })
      expect(page.orderStepper.text()).toMatchInlineSnapshot(
        `"CheckOffer Navigate rightShippingNavigate rightPaymentNavigate rightReview"`
      )
      expect(page.orderStepperCurrentStep).toBe("Shipping")
    })
  })
})


text:
class Activity
	include Auth::Concerns::ActivityConcern
end


text:
#import <objc/runtime.h>

#import "UIViewController+PETViewController.h"
#import "MBProgressHud.h"
#import "AppDelegate.h"

@implementation UIViewController (PETViewController)

@dynamic progressHud;

- (void)showErrorMessage:(NSString *)message
               withTitle:(NSString *)title {
    [self showMessage:message
            withTitle:title
               ofType:TSMessageNotificationTypeError];
}

- (void)showInfoMessage:(NSString *)message
              withTitle:(NSString *)title {
    [self showMessage:message
            withTitle:title
               ofType:TSMessageNotificationTypeMessage];
}

- (void)showMessage:(NSString *)message
          withTitle:(NSString *)title
             ofType:(TSMessageNotificationType)type {
    [TSMessage setDefaultViewController:self];
    [TSMessage showNotificationWithTitle:title
                                subtitle:message
                                    type:type];
}

- (void)showLoader:(NSString*)message {
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view
                                                  animated:YES];
        if (message != nil)
            hud.labelText = message;

        objc_setAssociatedObject(self, @selector(progressHud), hud, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    });
}

- (void)hideLoader {
    dispatch_async(dispatch_get_main_queue(), ^{
        MBProgressHUD *hud = (MBProgressHUD *)objc_getAssociatedObject(self, @selector(progressHud));
        [hud hide:YES];
    });
}

@end


text:
var toggle_dendro_view = require('../dendrogram/toggle_dendro_view');
var show_visible_area = require('../zoom/show_visible_area');
var ini_zoom_info = require('../zoom/ini_zoom_info');
var calc_downsampled_levels = require('../matrix/calc_downsampled_levels');
var two_translate_zoom = require('../zoom/two_translate_zoom');
var get_previous_zoom = require('../zoom/get_previous_zoom');
var underscore = require('underscore');

module.exports = function(cgm, inst_order, inst_rc) {

  var params = cgm.params;

  var prev_zoom = get_previous_zoom(params);

  var delay_reorder = 0;
  if (prev_zoom.zoom_y != 1 || prev_zoom.zoom_x !=1){
    // reset zoom before reordering
    two_translate_zoom(cgm, 0, 0, 1);
    delay_reorder = 1200;
  }

  // row/col names are swapped, will improve later
  var other_rc;
  if (inst_rc==='row'){
    other_rc = 'col';
  } else if (inst_rc === 'col'){
    other_rc = 'row';
  }

  params.viz.run_trans = true;

  // save order state
  if (other_rc === 'row'){
    params.viz.inst_order.row = inst_order;
  } else if (other_rc === 'col'){
    params.viz.inst_order.col = inst_order;
  }

  if (params.viz.show_dendrogram){
    toggle_dendro_view(cgm, inst_rc);
  }

  if (other_rc === 'row'){
    params.viz.x_scale
      .domain( params.matrix.orders[ params.viz.inst_order.row + '_row' ] );
  } else if (other_rc == 'col') {
    params.viz.y_scale
      .domain( params.matrix.orders[ params.viz.inst_order.col + '_col' ] );
  }

  // only animate transition if there are a small number of tiles
  var t;
  if (d3.selectAll(params.root+' .tile')[0].length < params.matrix.def_large_matrix){
    t = d3.select(params.root+' .viz_svg')
      .transition().duration(2500).delay(delay_reorder);
  } else {
    t = d3.select(params.root+' .viz_svg');
  }

  var row_nodes_names = params.network_data.row_nodes_names;
  var col_nodes_names = params.network_data.col_nodes_names;

  // only update matrix if not downsampled (otherwise rows are updated)
  if (params.viz.ds_level === -1){

    t.selectAll('.row')
      .attr('transform', function(d) {
        var inst_index = underscore.indexOf(row_nodes_names, d.name);
        return 'translate(0,' + params.viz.y_scale(inst_index) + ')';
        })
      .selectAll('.tile')
      .attr('transform', function(d) {
        return 'translate(' + params.viz.x_scale(d.pos_x) + ' , 0)';
      });

    t.selectAll('.tile_up')
      .attr('transform', function(d) {
        return 'translate(' + params.viz.x_scale(d.pos_x) + ' , 0)';
      });

    t.selectAll('.tile_dn')
      .attr('transform', function(d) {
        return 'translate(' + params.viz.x_scale(d.pos_x) + ' , 0)';
      });
  }

  // Move Row Labels
  t.select('.row_label_zoom_container')
    .selectAll('.row_label_group')
    .attr('transform', function(d) {
      var inst_index = underscore.indexOf(row_nodes_names, d.name);
      return 'translate(0,' + params.viz.y_scale(inst_index) + ')';
    });

  // Move Col Labels
  t.select('.col_zoom_container')
    .selectAll('.col_label_text')
    .attr('transform', function(d) {
      var inst_index = underscore.indexOf(col_nodes_names, d.name);
      return 'translate(' + params.viz.x_scale(inst_index) + ') rotate(-90)';
    });

  // reorder row categories
  t.selectAll('.row_cat_group')
    .attr('transform', function(d) {
      var inst_index = underscore.indexOf(row_nodes_names, d.name);
      return 'translate(0,' + params.viz.y_scale(inst_index) + ')';
    });

  // reorder col_class groups
  t.selectAll('.col_cat_group')
    .attr('transform', function(d) {
      var inst_index = underscore.indexOf(col_nodes_names, d.name);
      return 'translate(' + params.viz.x_scale(inst_index) + ',0)';
    });

  // redefine x and y positions
  params.network_data.links.forEach(function(d){
    d.x = params.viz.x_scale(d.target);
    d.y = params.viz.y_scale(d.source);
  });

  params.zoom_info = ini_zoom_info();

  // calculate downsmapling if necessary
  if (params.viz.ds_num_levels > 0 && params.viz.ds_level >=0){

    calc_downsampled_levels(params);
    var zooming_stopped = true;
    var zooming_out = true;
    var make_all_rows = true;

    // show_visible_area is also run with two_translate_zoom, but at that point
    // the parameters were not updated and two_translate_zoom if only run
    // if needed to reset zoom
    show_visible_area(cgm, zooming_stopped, zooming_out, make_all_rows);

  }

  setTimeout(function(){
    params.viz.run_trans = false;
  }, 2500);

};