text:
namespace BlitzML {

LIBRARY_API
Dataset* BlitzML_new_sparse_dataset_float(const index_t* indices,
                                          const size_t* indptr,
                                          const float* data,
                                          index_t height, index_t width,
                                          size_t nnz,
                                          const value_t *b, index_t length_b) {
  return new SparseDataset<float>(indices, indptr, data,
                                  height, width, nnz, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_sparse_dataset_double(const index_t* indices,
                                           const size_t* indptr,
                                           const double* data,
                                           index_t height, index_t width,
                                           size_t nnz,
                                           const value_t *b, index_t length_b) {
  return new SparseDataset<double>(indices, indptr, data,
                                   height, width, nnz, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_sparse_dataset_int(const index_t* indices,
                                        const size_t* indptr,
                                        const int* data,
                                        index_t height, index_t width,
                                        size_t nnz,
                                        const value_t *b, index_t length_b) {
  return new SparseDataset<int>(indices, indptr, data,
                                height, width, nnz, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_sparse_dataset_bool(const index_t* indices,
                                         const size_t* indptr,
                                         const bool* data,
                                         index_t height, index_t width,
                                         size_t nnz,
                                         const value_t *b, index_t length_b) {
  return new SparseDataset<bool>(indices, indptr, data,
                                 height, width, nnz, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_sparse_binary_dataset(const index_t* indices,
                                           const size_t* indptr,
                                           index_t height, index_t width,
                                           size_t nnz,
                                           const value_t *b, index_t length_b) {
  return new SparseBinaryDataset(indices, indptr,
                                 height, width, nnz, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_dense_dataset_float(const float *data,
                                         index_t height, index_t width,
                                         const value_t *b, index_t length_b) {
  return new DenseDataset<float>(data, height, width, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_dense_dataset_double(const double *values,
                                          index_t height, index_t width,
                                          const value_t *b, index_t length_b) {
  return new DenseDataset<double>(values, height, width, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_dense_dataset_int(const int *values,
                                       index_t height, index_t width,
                                       const value_t *b, index_t length_b) {
  return new DenseDataset<int>(values, height, width, b, length_b);
}

LIBRARY_API
Dataset* BlitzML_new_dense_dataset_bool(const bool *values,
                                        index_t height, index_t width,
                                        const value_t *b, index_t length_b) {
  return new DenseDataset<bool>(values, height, width, b, length_b);
}

LIBRARY_API
value_t BlitzML_column_norm(const Dataset* data, index_t i) {
  return data->column(i)->l2_norm();
}

LIBRARY_API
value_t BlitzML_b_value_j(const Dataset* data, index_t j) {
  return data->b_value(j);
}

LIBRARY_API
void BlitzML_delete_dataset(Dataset* data) {
  delete data;
}

} // namespace BlitzML


text:
import webapp2
from google.appengine.ext.webapp.util import run_wsgi_app
from tools.common import is_testenv

# Import our application settings/configuration
from settings import config

# And of course import our application routes
import routes

application = webapp2.WSGIApplication(routes.urls, config=config, debug=is_testenv())

redpajama_set_name: RedPajamaGithub


text:
from SDST.main import subparsers
from SDST.demultiplexer import demultiplex

def demultiplex_setup(opts):
    if(opts.readFile2):
        if(opts.indexFile2 is None):
            demultiplex(readfile = opts.readFile1,
                        readfile2 = opts.readFile2,
                        indexfile = opts.indexFile,
                        indexes = opts.index)
        else:
            demultiplex(readfile = opts.readFile1,
                        readfile2 = opts.readFile2,
                        indexfile = opts.indexFile,
                        indexfile2 = opts.indexFile2,
                        indexes = opts.index)
    else:
        demultiplex(readfile = opts.readFile1,
                    indexfile = opts.indexFile,
                    indexes = opts.index)

utils_parser = subparsers.add_parser('utils')
utils_subparsers = utils_parser.add_subparsers(help="General utilities")
demultiplex_parser = utils_subparsers.add_parser('demultiplex',
                                                 help="Demultiplex a set of fastq files")
demultiplex_parser.add_argument('-1','--readFile1',
                    help="read1 filename")
demultiplex_parser.add_argument('-2','--readFile2',
                    help="read2 filename")
demultiplex_parser.add_argument('-i','--indexFile',
                    help="index Filename")
demultiplex_parser.add_argument('-j','--indexFile2',
                    help="index Filename")
demultiplex_parser.add_argument('-x','--index',type=str,action='append',
                    help="The indexes, one per index or comma-separated pairs for dual-barcode indexing")

demultiplex_parser.set_defaults(func=demultiplex_setup)


text:
Our Manager is looking pretty good:

```javascript
@Manage('gold')
@Value(8000)
@Actions('earn', 'spend')
class GoldManager {}
```

But now that we've got action creation set up, we need to define reducers that respond to our dispatched actions and update the store's state. We've already got a reducer in the form of our Conflux:

```javascript
const goldReducer = getConflux(GoldManager)
```

But all this reducer knows how to do is initialize the default state of our Manager (`8000`). It won't actually handle any actions or return any new state after it's been initialized.

To accomplish this, we need to give it some sub-reducers. Confluxes are delegators. They use reducer composition to hand a given action off to all the sub-reducers who subscribe to that action type.

In Fluxuate, a sub-reducer is defined using the `@Reduce()` decorator:

```javascript
import { Actions, Manage, Reduce, Value, getConflux } from 'fluxuate'

@Manage('gold')
@Value(8000)
@Actions('earn', 'spend')
class GoldManager {

	@Reduce('earn')
	reduceEarn(state, payload) {
		return state + payload
	}

	@Reduce('spend')
	reduceSpend(state, payload) {
		return state - payload
	}
}

export default getConflux(GoldManager)
```

To create a sub-reducer, just decorate a Manager method with `@Reduce()`. As with most of Fluxuate's method decorators, `@Reduce()` takes one or more action paths as arguments. Here we've defined two sub-reducers that reduce the `gold/earn` and `gold/spend` actions, respectively.

### Notes

- The `state` variable that gets passed into a Fluxuate reducer will be bound to the context of its Manager. So the sub-reducers of our `gold` Manager will receive a number.

- Don't get reducers and sub-reducers confused! This can be especially difficult since sub-reducers are reducers by every technicality. This distinction will become important when we look at using Higher-Order Reducers to enhance our Confluxes.

### Next Step

Let's look at [Paths](/docs/tutorial/Paths.md).


text:
import React from 'react';
import { Col } from 'react-bootstrap';
import { Field } from 'redux-form';

import { AwesomeCheckbox } from '@waldur/core/AwesomeCheckbox';
import { FieldError } from '@waldur/form';
import { Section } from '@waldur/marketplace/types';

import { configAttrField } from './utils';

interface OfferingAttributesProps {
  sections: Section[];
  labelCols?: number;
  controlCols?: number;
}

export const OfferingAttributes: React.FC<OfferingAttributesProps> = (
  props,
) => (
  <>
    {props.sections.map((section, sectionIndex) => (

          <Col smOffset={props.labelCols} sm={props.controlCols}>

              {section.title}

          </Col>

        {section.attributes.map((attribute, attributeIndex) => {
          if (attribute.type === 'boolean') {
            return (

                <Col smOffset={props.labelCols} sm={props.controlCols}>
                  <Field
                    name={`attributes.${attribute.key}`}
                    component={(prop) => (
                      <AwesomeCheckbox
                        label={attribute.title}
                        {...prop.input}
                      />
                    )}
                  />
                </Col>

            );
          }
          const attr = configAttrField(attribute);
          return (

              <Col
                className="control-label"
                sm={props.labelCols}
                componentClass="label"
              >
                {attribute.title}
              </Col>
              <Col sm={props.controlCols}>
                <Field
                  key={attributeIndex}
                  name={`attributes.${attribute.key}`}
                  component="input"
                  className="form-control"
                  {...attr}
                />
                <Field
                  name={`attributes.${attribute.key}`}
                  {...attr}
                  component={(fieldProps) => (
                    <FieldError error={fieldProps.meta.error} />
                  )}
                />
              </Col>

          );
        })}

    ))}
  </>
);

OfferingAttributes.defaultProps = {
  labelCols: 3,
  controlCols: 5,
};


text:
using System;
using System.Linq;
using System.Numerics;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Testing;
using Xunit;

namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests;

public class AsciiDecodingTests
{
    [Fact]
    private void FullAsciiRangeSupported()
    {
        var byteRange = Enumerable.Range(1, 127).Select(x => (byte)x);

        var byteArray = byteRange
            .Concat(byteRange)
            .Concat(byteRange)
            .Concat(byteRange)
            .Concat(byteRange)
            .Concat(byteRange)
            .ToArray();

        var span = new Span<byte>(byteArray);

        for (var i = 0; i <= byteArray.Length; i++)
        {
            // Test all the lengths to hit all the different length paths e.g. Vector, long, short, char
            Test(span.Slice(i));
        }

        static void Test(Span<byte> asciiBytes)
        {
            var s = asciiBytes.GetAsciiStringNonNullCharacters();

            Assert.True(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, asciiBytes));
            Assert.Equal(s.Length, asciiBytes.Length);

            for (var i = 0; i < asciiBytes.Length; i++)
            {
                var sb = (byte)s[i];
                var b = asciiBytes[i];

                Assert.Equal(sb, b);
            }
        }
    }

    [Theory]
    [InlineData(0x00)]
    [InlineData(0x80)]
    private void ExceptionThrownForZeroOrNonAscii(byte b)
    {
        for (var length = 1; length < Vector<sbyte>.Count * 4; length++)
        {
            for (var position = 0; position < length; position++)
            {
                var byteRange = Enumerable.Range(1, length).Select(x => (byte)x).ToArray();
                byteRange[position] = b;

                Assert.Throws<InvalidOperationException>(() => new Span<byte>(byteRange).GetAsciiStringNonNullCharacters());
            }
        }
    }

    [Fact]
    private void LargeAllocationProducesCorrectResults()
    {
        var byteRange = Enumerable.Range(0, 16384 + 64).Select(x => (byte)((x & 0x7f) | 0x01)).ToArray();
        var expectedByteRange = byteRange.Concat(byteRange).ToArray();

        var span = new Span<byte>(expectedByteRange);
        var s = span.GetAsciiStringNonNullCharacters();

        Assert.Equal(expectedByteRange.Length, s.Length);

        for (var i = 0; i < expectedByteRange.Length; i++)
        {
            var sb = (byte)((s[i] & 0x7f) | 0x01);
            var b = expectedByteRange[i];
        }

        Assert.True(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, span));
    }

    [Fact]
    private void DifferentLengthsAreNotEqual()
    {
        var byteRange = Enumerable.Range(0, 4096).Select(x => (byte)((x & 0x7f) | 0x01)).ToArray();
        var expectedByteRange = byteRange.Concat(byteRange).ToArray();

        for (var i = 1; i < byteRange.Length; i++)
        {
            var span = new Span<byte>(expectedByteRange);
            var s = span.GetAsciiStringNonNullCharacters();

            Assert.True(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, span));

            // One off end
            Assert.False(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, span.Slice(0, span.Length - 1)));
            Assert.False(StringUtilities.BytesOrdinalEqualsStringAndAscii(s.Substring(0, s.Length - 1), span));

            // One off start
            Assert.False(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, span.Slice(1, span.Length - 1)));
            Assert.False(StringUtilities.BytesOrdinalEqualsStringAndAscii(s.Substring(1, s.Length - 1), span));
        }
    }

    [Fact]
    private void AsciiBytesEqualAsciiStrings()
    {
        var byteRange = Enumerable.Range(1, 127).Select(x => (byte)x);

        var byteArray = byteRange
            .Concat(byteRange)
            .Concat(byteRange)
            .Concat(byteRange)
            .Concat(byteRange)
            .Concat(byteRange)
            .ToArray();

        var span = new Span<byte>(byteArray);

        for (var i = 0; i <= byteArray.Length; i++)
        {
            // Test all the lengths to hit all the different length paths e.g. Vector, long, short, char
            Test(span.Slice(i));
        }

        static void Test(Span<byte> asciiBytes)
        {
            var s = asciiBytes.GetAsciiStringNonNullCharacters();

            // Should start as equal
            Assert.True(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, asciiBytes));

            for (var i = 0; i < asciiBytes.Length; i++)
            {
                var b = asciiBytes[i];

                // Change one byte, ensure is not equal
                asciiBytes[i] = (byte)(b + 1);
                Assert.False(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, asciiBytes));

                // Change byte back for next iteration, ensure is equal again
                asciiBytes[i] = b;
                Assert.True(StringUtilities.BytesOrdinalEqualsStringAndAscii(s, asciiBytes), s);
            }
        }
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
	function __construct(){
		parent::__construct();
		$this->load->model('general_model');
		$this->load->model('user_model');
	}

	function fb(){

		$fbid=$this->input->post('facebook_id');
		$name=$this->input->post('name');
		$email=$this->input->post('email');
		$data_facebook=$this->input->post('data_facebook');
		$token=$this->input->post('token');

		$newdate=date("Y-m-d H:i:s");
		$check=$this->user_model->check_fb_id($fbid);
		$imageURL = "http://graph.facebook.com/".$fbid."/picture?type=large";
		if($check){
			//update data
			$user_id=$check['id'];
			$table='user_tb';
			$where=array('id'=>$user_id);
			$data=array('fb_data'=>json_encode($data_facebook,TRUE));
			$this->general_model->update_data($table,$data,$where);

			$sess_user = array (
								   'user_logged_in' => true,
								   'user_id' => $check['id'],
								   'email' => $email,
								   'name' => $name,
								   'session_login'=>'facebook'
								);
			$this->session->set_userdata($sess_user);

			if($check['tanggal_lahir_sikecil']=='0000-00-00'){
				$tanggal = "01-01-2010";
			}else{
				$tanggal = date('d-m-Y',strtotime($check['tanggal_lahir_sikecil']));
			}

			echo json_encode(array('status'=>1,'message'=>'update','name'=>$check['name'],
				'email'=>$check['email'],'telp'=>$check['telp'],'tanggal'=>$tanggal,'produk_susu'=>$check['product_susu_yang_digunakan']));exit();
		}
		else{
			//insert new user
			if($this->session->userdata('vserv') != ''){
				$vserv = $this->session->userdata('vserv');
			} else {
				$vserv = '';
			}
			$table='user_tb';
			$data=array('fb_id'=>$fbid,'email'=>$email,'fb_data'=>json_encode($data_facebook,TRUE),'name'=>$name,
				'profile_picture'=>$imageURL,'created_date'=>$newdate,'vserv' => $vserv);
			$this->general_model->insert_data($table,$data);
			$user_id=$this->db->insert_id();

			$sess_user = array (
								   'user_logged_in' => true,
								   'user_id' => $user_id,
								   'email' => $email,
								   'name' => $name,
								   'session_login'=>'facebook'

								);
			$this->session->set_userdata($sess_user);

			echo json_encode(array('status'=>1,'message'=>'insert','name'=>$name,'email'=>$email));exit();
		}

		echo json_encode(array('status'=>0,'message'=>'error'));exit();
	}

}


text:
package snippets

// [START healthcare_create_hl7v2_store]
import (
	"context"
	"fmt"
	"io"

	healthcare "google.golang.org/api/healthcare/v1"
)

// createHL7V2Store creates an HL7V2 store.
func createHL7V2Store(w io.Writer, projectID, location, datasetID, hl7V2StoreID string) error {
	ctx := context.Background()

	healthcareService, err := healthcare.NewService(ctx)
	if err != nil {
		return fmt.Errorf("healthcare.NewService: %v", err)
	}

	storesService := healthcareService.Projects.Locations.Datasets.Hl7V2Stores

	store := &healthcare.Hl7V2Store{}
	parent := fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID)

	resp, err := storesService.Create(parent, store).Hl7V2StoreId(hl7V2StoreID).Do()
	if err != nil {
		return fmt.Errorf("Create: %v", err)
	}

	fmt.Fprintf(w, "Created HL7V2 store: %q\n", resp.Name)
	return nil
}

// [END healthcare_create_hl7v2_store]


text:
package com.cyb.tms.security.json;

import com.cyb.tms.security.model.ModelBase;

public class AuthenticationRequest extends ModelBase {

	private static final long serialVersionUID = -3440771457739026588L;
	private String username;
	private String password;

	public AuthenticationRequest() {
		super();
	}

	public AuthenticationRequest(String username, String password) {
		this.setUsername(username);
		this.setPassword(password);
	}

	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}


text:
/*
 * Low-level ethread support on PowerPC.
 * Author: Mikael Pettersson.
 */
#ifndef ETHREAD_PPC32_ETHREAD_H
#define ETHREAD_PPC32_ETHREAD_H

#include "atomic.h"
#include "spinlock.h"
#include "rwlock.h"

#define ETHR_HAVE_NATIVE_ATOMICS 1
#define ETHR_HAVE_NATIVE_LOCKS 1

#endif /* ETHREAD_PPC32_ETHREAD_H */


text:
 /**
 * <p>Description: </p>
 * @author Jeff Offutt and Yu-Seung Ma
 * @version 1.0
  */
package openjava.test;

import openjava.mop.OJSystem;
import openjava.ptree.CompilationUnit;
import openjava.tools.parser.ParseException;
import openjava.tools.parser.Parser;

public class ParserTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(System.getProperty("user.dir"));
		//String file = "src/openjava/test/Search.java";
		//String file = "src/openjava/test/Planet.java";
		//String file = "src/openjava/test/VendingMachine1.java";
		String file = "src/openjava/test/Flower.java";
		//String file = "e://muJavaJunit//src/junit/framework/TestSuite.java";
		//String file = "src/openjava/test/RequestForEnhancement.java";
		//String file = "src/openjava/test/stringPlay/StringTools.java";
//		String file = "src/openjava/test/Logic.java";
	      Parser parser = null;
	      try
	      {
	         parser = new Parser(new java.io.FileInputStream( file ) );
	      }
	      catch ( java.io.FileNotFoundException e )
	      {
	         System.err.println( "File " + file + " not found." );
	      }
	      catch (Exception e)
	      {
	    	  e.printStackTrace();
	      }

	      try
	      {
	    	 OJSystem.initConstants();
	         CompilationUnit result = parser.CompilationUnit( OJSystem.env );
	         //System.out.println("result: " + result);

	        // System.out.println("getComment: " + result.getComment());
	         /*
	         for(int i = 0; i < result.getDeclaredImports().length;i++)
	         {
	        	 System.out.println("getDeclaredImports: " + result.getDeclaredImports()[i]);
	         }
	         for(int i = 0; i < result.getContents().length;i++)
	         {
	        	 System.out.println("getContents: " + result.getContents()[i]);
	         }
	          */
	      }
	      catch (ParseException e)
	      {
	    	  e.printStackTrace();
	    	  System.out.println(" can't generate parse tree");
	      }
	      catch (Exception e)
	      {
	    	  System.out.println(e);
	    	  e.printStackTrace();
	      }

	}

}


text:
.PHONY: clean develop install-tests lint publish test

install-pip:
	pip install "pip==19.2.3"

develop: install-pip
	SENTRY_LIGHT_BUILD=1 pip install --no-use-pep517 -e "../sentry[dev]"
	pip install -e .[tests]

ci-install-tests-sentry-git: install-pip
	pip install --no-use-pep517 'git+https://github.com/getsentry/sentry.git#egg=sentry[dev]'
	pip install .[tests]

ci-install-tests-sentry-latest: install-pip
	# Note that requirements-test (setuptools tests_require) is in 9.1.2 but was removed in git.
	pip install --no-use-pep517 'sentry[dev,tests]'
	pip install .[tests]

lint:
	@echo "--> Linting python"
	flake8
	@echo ""

test:
	@echo "--> Running Python tests"
	py.test --cov . tests || exit 1
	@echo ""

publish:
	python setup.py sdist bdist_wheel upload

clean:
	rm -rf *.egg-info src/*.egg-info
	rm -rf dist build


text:
"""
Concatenates dumps from a LAMMPS script.

All dumps in the given LAMMPS script will be concatenated into single files
separately, which are to be written in the current working directory.
"""

import argparse
import re
import os.path
import glob

def main():
    """Drive the script."""

    parser = argparse.ArgumentParser(description=globals()['__doc__'])
    parser.add_argument(
        'input', type=argparse.FileType(mode='r'), metavar='INPUT',
        help='The LAMMPS input file whose dumps are to be concatenated.'
    )
    args = parser.parse_args()

    dump_cater = DumpCater(args.input)
    args.input.close()
    dump_cater.cat_dumps()

    return 0

class DumpCater(object):
    """Concatenator of LAMMPS dump files."""

    __slots__ = [
        'base_path',
        'vars',
        'dumps'
    ]

    def __init__(self, input_fp):
        """Initialize the concatenator from the input file object."""

        self.base_path = os.path.dirname(input_fp.name)
        self.vars = {}
        self.dumps = []

        for line in input_fp:
            fields = line.split()
            if len(fields) == 0:
                continue
            cmd = fields[0]

            if cmd == 'variable':
                self.vars[fields[1]] = fields[-1]
            elif cmd == 'dump':
                self.dumps.append(
                    self.subst_vars(fields[-1])
                )
            else:
                pass  # Skip all other lines.

        return

    def subst_vars(self, inp_str):
        """Substitute all variable references in the given string."""
        var_ref = re.compile(r'\$\{(?P<name>\w*)\}')

        # The string is going to be substituted for variable reference
        # repeatedly.
        curr = inp_str

        while True:
            match = var_ref.search(curr)
            if not match:
                break
            else:
                var_name = match.group('name')
                try:
                    curr = curr.replace(
                        ''.join(['${', var_name, '}']), self.vars[var_name]
                    )
                except KeyError:
                    print('Undefined variable {} in script!'.format(var_name))
                continue

        return curr

    def cat_dumps(self):
        """Concatenates all the dumps in the input script."""
        for dump in self.dumps:

            # Get all the file names and sort according to step number.
            file_names = sorted(glob.glob(
                os.path.join(self.base_path, dump)
            ), key=self.form_step_getter(dump))

            out_fn = re.sub(r'[-._]?\*', '', dump)
            with open(out_fn, 'w') as out_fp:
                for name in file_names:
                    with open(name, 'r') as inp_fp:
                        out_fp.write(inp_fp.read())
                    continue

            continue
        return

    @staticmethod
    def form_step_getter(dump):
        """Form the function to get the step number from a file name."""
        patt = re.compile(
            dump.replace('.', r'\.').replace('*', r'(?P<step>\d+)')
        )

        def get_step(name):
            """Get the step number from the file name."""
            match = patt.search(os.path.basename(name))
            return int(match.group('step'))

        return get_step

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Entity;

namespace AndroidSample.Utils
{
    class Constants
    {
            public const string Login_Type_UnviredID = "Unvired Id Login";

            public const string Login_Type_MicrosoftLogin = "Microsoft(R) ADS Login";

            public static CUSTOMERS_RESULTS_HEADER SelectedCustomer = null;

        	public const string APPLICATION_NAME = "UNVIRED_SAMPLE_SAP_ERP";

	        public const string GET_CUSTOMER_PROCESS_AGENT_FUNCTION_NAME = "UNVIRED_SAMPLE_SAP_ERP_PA_GET_CUSTOMERS";

	        public const string GET_MATERIAL_PROCESS_AGENT_FUNCTION_NAME = "UNVIRED_SAMPLE_SAP_ERP_PA_GET_MATERIALS";

	        public const string CURRENT_ACTIVITY = "CURRENT_ACTIVITY";

	        public const string SELECTED_CUSTOMER = "SELECTED_CUSTOMER";

	}
}


text:
package com.kenai.camera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.kenai.function.message.XLog;
import com.kenai.function.message.XToast;
import com.kenai.function.mzstore.XMZyanzheng;
import com.kenai.function.setting.XSetting;
import com.kenai.function.state.XState;
import com.kenai.function.tools.XYingjian;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.media.AudioManager;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;

public class CameraTake_pictureService extends Service {
	static Context context;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	private final boolean isSpecial() {
		ActivityManager mActivityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		String s = rti.get(0).topActivity.getPackageName();
		if (!s.equals("com.android.camera")) {
			// XToast.xToast(context, s);
			return false;
		} else
			return true;
	}

	private WakeLock xWakeLock;
	int started_volume;
	@Override
	public void onCreate() {
		super.onCreate();
		context = getBaseContext();
		final AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		started_volume=am.getStreamVolume(AudioManager.STREAM_SYSTEM);
		am.setStreamVolume(AudioManager.STREAM_SYSTEM,
				0,
				AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);

		if (XMZyanzheng.get_isLawful(context)) {

			if (Camera.getNumberOfCameras() >= 1) {
				if (!XState.get_isServiceRuning(
						"com.kenai.camera.KenaiService", context)
						&& !XState.get_isServiceRuning(
								"com.kenai.camera.CameraFaceService", context)) {
					if (!isSpecial()) {
						PowerManager xPowerManager = (PowerManager) context
								.getSystemService(Context.POWER_SERVICE);
						xWakeLock = xPowerManager.newWakeLock(
								PowerManager.ACQUIRE_CAUSES_WAKEUP
										| PowerManager.SCREEN_DIM_WAKE_LOCK,
								"PowerServiceDemo");
						xWakeLock.acquire();
						start(0);
						myhandler.sendEmptyMessageDelayed(1, 100);
					} else {
						stopSelf();
						XToast.xToast(context, "存在冲突程序");
					}

				} else {
					XToast.xToast(context, "存在冲突程序");
				}
			}

			myhandler.sendEmptyMessageDelayed(0, 5000);
		} else {
			stopSelf();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		final AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		am.setStreamVolume(AudioManager.STREAM_SYSTEM,
				started_volume,
				AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
		stop();
		if(xWakeLock!=null)
		xWakeLock.release();

	}

	private final Handler myhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				mCamera.autoFocus(new AutoFocusCallback() {
					public void onAutoFocus(boolean success, Camera camera) {
						mCamera.takePicture(null, null, mPicture);
					}
				});
				break;
			default:
				stopSelf();
				break;
			}

		}
	};

	public static boolean state_camera;
	private Camera mCamera;
	private CameraPreview cameraPreview;
	private WindowManager.LayoutParams wmParams_camera;

	private void prepareCamera(int i) {
		if (mCamera != null) {
			releaseCamera();
		}
		try {

			mCamera = Camera.open(i);

		} catch (Exception e) {
			mCamera = null;
			stopSelf();
		}
		load_view();
	}

	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.release();
			mCamera = null;
		}

	}

	private void load_view() {
		setPhotoView();
	}

	private void setPhotoView() {
		cameraPreview = new CameraPreview(context, mCamera){

//			@Override
			public void onPreviewCallback(Bitmap bmp) {
				// TODO 自动生成的方法存根

			}

		};
		cameraPreview.setOnTouchListener(new OnTouchListener() {
			private float mTouchStartX;
			private float mTouchStartY;
			private float x;
			private float y;

			public boolean onTouch(View v, MotionEvent event) {
				x = event.getRawX();
				y = event.getRawY();
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mTouchStartX = event.getX();
					mTouchStartY = event.getY();
					break;
				case MotionEvent.ACTION_MOVE:
					updateViewPosition();
					break;
				case MotionEvent.ACTION_UP:
					updateViewPosition();
					mTouchStartX = mTouchStartY = 0;
					break;
				}

				return true;

			}

			private void updateViewPosition() {
				int xx = (int) (x - mTouchStartX);
				int yy = (int) (y - mTouchStartY);
				XSetting.xset_string_int(context, "xx", "" + xx);
				XSetting.xset_string_int(context, "yy", "" + yy);
				wmParams_camera.x = xx;
				wmParams_camera.y = yy;
				WindowManager wm = (WindowManager) context
						.getSystemService("window");
				wm.updateViewLayout(cameraPreview, wmParams_camera); // 刷新显示
			}

		});
	}

	private PictureCallback mPicture = new PictureCallback() {
		public void onPictureTaken(final byte[] data, Camera camera) {
			if (XSetting.xget_boolean(context, "camera_vibrator")) {
				XYingjian.xvibrator(context, 100);
			}
			new Thread() {
				public void run() {
					File pictureFile = getOutputMediaFile();
					if (pictureFile == null) {
						Log.d("++ photo",
								"Error creating media file, check storage permissions: ");
						return;
					}
					try {
						FileOutputStream fos = new FileOutputStream(pictureFile);
						fos.write(data);
						fos.close();
					} catch (FileNotFoundException e) {
						Log.d("++wangjun", "File not found: " + e.getMessage());
					} catch (Exception e) {
						Log.d("++++wangjun",
								"Error accessing file: " + e.getMessage());
					}
				}
			}.start();
			// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			stop();
			stopSelf();

		}
	};

	private final static File getOutputMediaFile() {
		if (Environment.getExternalStorageState() == Environment.MEDIA_REMOVED) {
			XToast.xToast(context, "内存卡拔出");
		}

		File mediaStorageDir = CameraEnv.getOutputFile();
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("KenaiCamera", "failed to create directory");
				return null;
			} else {
			}
		}
		// 创建媒体文件名
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile; // 在静态方法里得用静态的变量,我把这个放在class开头,但是需要添加static

		mediaFile = new File(mediaStorageDir.getPath() + File.separator +

		"IMG_" + timeStamp + ".jpg");

		return mediaFile;

	}

	public void start(int i) {
		if (state_camera == false) {
			prepareCamera(i);
			WindowManager wm = (WindowManager) context.getApplicationContext()
					.getSystemService("window");
			wmParams_camera = new WindowManager.LayoutParams();
			wmParams_camera.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
			wmParams_camera.format = PixelFormat.RGBA_8888;
			wmParams_camera.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
					| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
			wmParams_camera.gravity = Gravity.LEFT | Gravity.TOP;
			int size = 1;
			wmParams_camera.width = wmParams_camera.height = size;
			wm.addView(cameraPreview, wmParams_camera);

			state_camera = true;
		}
	}

	public void stop() {
		if (state_camera) {
			releaseCamera();
			WindowManager wm = (WindowManager) context.getApplicationContext()
					.getSystemService("window");
			wm.removeView(cameraPreview);
			state_camera = false;
			XLog.xLog("恢复屏幕亮度");
		}
	}
}


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
package net.sourceforge.pmd.rules.strings;

import net.sourceforge.pmd.PropertyDescriptor;
import net.sourceforge.pmd.AbstractRule;
import net.sourceforge.pmd.ast.ASTAnnotation;
import net.sourceforge.pmd.ast.ASTCompilationUnit;
import net.sourceforge.pmd.ast.ASTLiteral;
import net.sourceforge.pmd.properties.BooleanProperty;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AvoidDuplicateLiteralsRule extends AbstractRule {

    private static final PropertyDescriptor SKIP_ANNOTATIONS = new BooleanProperty("skipAnnotations",
          "Skip literals within Annotations.", false, 1.0f);

    private static final Map<String, PropertyDescriptor> PROPERTY_DESCRIPTORS_BY_NAME = asFixedMap(new PropertyDescriptor[] { SKIP_ANNOTATIONS });

    public static class ExceptionParser {

        private static final char ESCAPE_CHAR = '\\';
        private char delimiter;

        public ExceptionParser(char delimiter) {
            this.delimiter = delimiter;
        }

        public Set<String> parse(String in) {
            Set<String> result = new HashSet<String>();
            StringBuffer currentToken = new StringBuffer();
            boolean inEscapeMode = false;
            for (int i = 0; i < in.length(); i++) {
                if (inEscapeMode) {
                    inEscapeMode = false;
                    currentToken.append(in.charAt(i));
                    continue;
                }
                if (in.charAt(i) == ESCAPE_CHAR) {
                    inEscapeMode = true;
                    continue;
                }
                if (in.charAt(i) == delimiter) {
                    result.add(currentToken.toString());
                    currentToken = new StringBuffer();
                } else {
                    currentToken.append(in.charAt(i));
                }
            }
            if (currentToken.length() > 0) {
                result.add(currentToken.toString());
            }
            return result;
        }
    }

    private static final char DEFAULT_SEPARATOR = ',';
    private static final String EXCEPTION_LIST_PROPERTY = "exceptionlist";
    private static final String SEPARATOR_PROPERTY = "separator";
    private static final String EXCEPTION_FILE_NAME_PROPERTY = "exceptionfile";

    private Map<String, List<ASTLiteral>> literals = new HashMap<String, List<ASTLiteral>>();
    private Set<String> exceptions = new HashSet<String>();

    public Object visit(ASTCompilationUnit node, Object data) {
        literals.clear();

        if (hasProperty(EXCEPTION_LIST_PROPERTY)) {
            ExceptionParser p;
            if (hasProperty(SEPARATOR_PROPERTY)) {
                p = new ExceptionParser(getStringProperty(SEPARATOR_PROPERTY).charAt(0));
            } else {
                p = new ExceptionParser(DEFAULT_SEPARATOR);
            }
            exceptions = p.parse(getStringProperty(EXCEPTION_LIST_PROPERTY));
        } else if (hasProperty(EXCEPTION_FILE_NAME_PROPERTY)) {
            exceptions = new HashSet<String>();
            LineNumberReader reader = null;
            try {
                reader = new LineNumberReader(new BufferedReader(new FileReader(new File(getStringProperty(EXCEPTION_FILE_NAME_PROPERTY)))));
                String line;
                while ((line = reader.readLine()) != null) {
                    exceptions.add(line);
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } finally {
                try {
                    if (reader != null)
                        reader.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

        super.visit(node, data);

        int threshold = getIntProperty("threshold");
        for (String key: literals.keySet()) {
            List<ASTLiteral> occurrences = literals.get(key);
            if (occurrences.size() >= threshold) {
                Object[] args = new Object[]{key, Integer.valueOf(occurrences.size()), Integer.valueOf(occurrences.get(0).getBeginLine())};
                addViolation(data, occurrences.get(0), args);
            }
        }
        return data;
    }

    public Object visit(ASTLiteral node, Object data) {
        // just catching strings of 5 chars or more (including the enclosing quotes) for now - no numbers
        if (node.getImage() == null || node.getImage().indexOf('\"') == -1 || node.getImage().length() < 5) {
            return data;
        }

        // skip any exceptions
        if (exceptions.contains(node.getImage().substring(1, node.getImage().length() - 1))) {
            return data;
        }

        // Skip literals in annotations
        if (getBooleanProperty(SKIP_ANNOTATIONS) && node.getFirstParentOfType(ASTAnnotation.class) != null) {
            return data;
        }

        if (literals.containsKey(node.getImage())) {
            List<ASTLiteral> occurrences = literals.get(node.getImage());
            occurrences.add(node);
        } else {
            List<ASTLiteral> occurrences = new ArrayList<ASTLiteral>();
            occurrences.add(node);
            literals.put(node.getImage(), occurrences);
        }

        return data;
    }

    @Override
    protected Map<String, PropertyDescriptor> propertiesByName() {
	return PROPERTY_DESCRIPTORS_BY_NAME;
    }
}


text:
layout: default
title: CAS - Configuring Service Environments
category: Services
---

{% include variables.html %}

# Configure Service Environments

Each registered application in the registry may be assigned a set of environment names. The environment names act as a filter, allowing
CAS to only load and honor the registered service definition if the runtime environment does in fact match the registered service environment. This allows one to register multiple versions of the same application many times with CAS where each version may only be relevant in a particular runtime profile. Environments can be activated in CAS using the `spring.profiles.active` property specified as an environment variable or command-line flag, etc.

For example, the below service definition is only recognized and loaded by CAS if the runtime environment profile is one of `production` or `pre-production`:

```json
{
  "@class" : "org.apereo.cas.services.RegexRegisteredService",
  "serviceId" : "https://app.example.org/.+",
  "name" : "ExampleApp",
  "id" : 1,
  "environments" : [ "java.util.HashSet", [ "production", "pre-production" ] ]
}
```

Note that a registered service definition without an assigned environment will be loaded regardless of the runtime profile. Similarly, all
service definitions are considered eligible if CAS is set to run without an active profile.


text:
FASTLED_NAMESPACE_BEGIN

///@file noise.h
/// Noise functions provided by the library.

///@defgroup Noise Noise functions
///Simplex noise function definitions
///@{
/// @name scaled 16 bit noise functions
///@{
/// 16 bit, fixed point implementation of perlin's Simplex Noise.  Coordinates are
/// 16.16 fixed point values, 32 bit integers with integral coordinates in the high 16
/// bits and fractional in the low 16 bits, and the function takes 1d, 2d, and 3d coordinate
/// values.  These functions are scaled to return 0-65535

extern uint16_t inoise16(uint32_t x, uint32_t y, uint32_t z);
extern uint16_t inoise16(uint32_t x, uint32_t y);
extern uint16_t inoise16(uint32_t x);
///@}

/// @name raw 16 bit noise functions
//@{
/// 16 bit raw versions of the noise functions.  These values are not scaled/altered and have
/// output values roughly in the range (-18k,18k)
extern int16_t inoise16_raw(uint32_t x, uint32_t y, uint32_t z);
extern int16_t inoise16_raw(uint32_t x, uint32_t y);
extern int16_t inoise16_raw(uint32_t x);
///@}

/// @name 8 bit scaled noise functions
///@{
/// 8 bit, fixed point implementation of perlin's Simplex Noise.  Coordinates are
/// 8.8 fixed point values, 16 bit integers with integral coordinates in the high 8
/// bits and fractional in the low 8 bits, and the function takes 1d, 2d, and 3d coordinate
/// values.  These functions are scaled to return 0-255
extern uint8_t inoise8(uint16_t x, uint16_t y, uint16_t z);
extern uint8_t inoise8(uint16_t x, uint16_t y);
extern uint8_t inoise8(uint16_t x);
///@}

/// @name 8 bit raw noise functions
///@{
/// 8 bit raw versions of the noise functions.  These values are not scaled/altered and have
/// output values roughly in the range (-70,70)
extern int8_t inoise8_raw(uint16_t x, uint16_t y, uint16_t z);
extern int8_t inoise8_raw(uint16_t x, uint16_t y);
extern int8_t inoise8_raw(uint16_t x);
///@}

///@name raw fill functions
///@{
/// Raw noise fill functions - fill into a 1d or 2d array of 8-bit values using either 8-bit noise or 16-bit noise
/// functions.
///@param pData the array of data to write into
///@param num_points the number of points of noise to compute
///@param octaves the number of octaves to use for noise
///@param x the x position in the noise field
///@param y the y position in the noise field for 2d functions
///@param scalex the scale (distance) between x points when filling in noise
///@param scaley the scale (distance) between y points when filling in noise
///@param time the time position for the noise field
void fill_raw_noise8(uint8_t *pData, uint8_t num_points, uint8_t octaves, uint16_t x, int scalex, uint16_t time);
void fill_raw_noise16into8(uint8_t *pData, uint8_t num_points, uint8_t octaves, uint32_t x, int scalex, uint32_t time);
void fill_raw_2dnoise8(uint8_t *pData, int width, int height, uint8_t octaves, uint16_t x, int scalex, uint16_t y, int scaley, uint16_t time);
void fill_raw_2dnoise16into8(uint8_t *pData, int width, int height, uint8_t octaves, uint32_t x, int scalex, uint32_t y, int scaley, uint32_t time);

void fill_raw_2dnoise16(uint16_t *pData, int width, int height, uint8_t octaves, q88 freq88, fract16 amplitude, int skip, uint32_t x, int scalex, uint32_t y, int scaley, uint32_t time);
void fill_raw_2dnoise16into8(uint8_t *pData, int width, int height, uint8_t octaves, q44 freq44, fract8 amplitude, int skip, uint32_t x, int scalex, uint32_t y, int scaley, uint32_t time);
///@}

///@name fill functions
///@{
/// fill functions to fill leds with values based on noise functions.  These functions use the fill_raw_* functions as appropriate.
void fill_noise8(CRGB *leds, int num_leds,
            uint8_t octaves, uint16_t x, int scale,
            uint8_t hue_octaves, uint16_t hue_x, int hue_scale,
            uint16_t time);
void fill_noise16(CRGB *leds, int num_leds,
            uint8_t octaves, uint16_t x, int scale,
            uint8_t hue_octaves, uint16_t hue_x, int hue_scale,
            uint16_t time, uint8_t hue_shift=0);
void fill_2dnoise8(CRGB *leds, int width, int height, bool serpentine,
            uint8_t octaves, uint16_t x, int xscale, uint16_t y, int yscale, uint16_t time,
            uint8_t hue_octaves, uint16_t hue_x, int hue_xscale, uint16_t hue_y, uint16_t hue_yscale,uint16_t hue_time,bool blend);
void fill_2dnoise16(CRGB *leds, int width, int height, bool serpentine,
            uint8_t octaves, uint32_t x, int xscale, uint32_t y, int yscale, uint32_t time,
            uint8_t hue_octaves, uint16_t hue_x, int hue_xscale, uint16_t hue_y, uint16_t hue_yscale,uint16_t hue_time, bool blend, uint16_t hue_shift=0);

FASTLED_NAMESPACE_END
///@}

#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title> new document </title>
	<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
	<script type="text/javascript" src="../../require.js"></script>
	<script type="text/javascript" src="../../config.js"></script>
	<script type="text/javascript">
		//使用data-main时会自动设置baseUrl为main文件的路径
		require.config({
			baseUrl: '../../'
		});

		require(['sf/report', 'demo'], function(Report) {
			window.report = Report.init({
				url: 'data.php',
				colModel : [
					{width: 90},
					{width: 90},
					{width: 90},
					{width: 90},
					{width: 90},
					{width: 90},
					{width: 90},
					{width: 90},
					{width: 90}
				]
			});

			report.$div.appendTo('body');

			report.ajaxLoad();
		});
	</script>
</head>
<body>
</body>
</html>


text:
<?php

session_start();
if(isset($_POST['nome'])){
    //Destrói
    session_destroy();

        header("Location: index.php"); // Chamar um form de login por exemplo.
  }

 ?>

  <!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="shortcut icon" href="../../img/sad.png" type="image/x-icon" />
  <title>Cadastro - Receitas</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">

      <link rel="stylesheet" href="../../dist/css/skins/skin-blue.min.css">
      <link href="../../plugins/datatables/dataTables.bootstrap.css" rel="stylesheet">

        SAD

        SAD

          Toggle navigation

                   <?php echo $_SESSION['usuarioNome']; ?>

                   <?php echo $_SESSION['usuarioEmail'] ?>

                   <?php if ($_SESSION['usuarioNiveisAcessoId'] == "1") {
                    echo "Administrador";
                  }else{
                    echo "Usuário Padrão";
                  }
                  ?>

                      Editar

                      Sair

        <?php
        if ($_SESSION['usuarioNiveisAcessoId'] == "1"){
        ?>

Menu

 Usuários

             Receitas

 Visualizar

 Cadastrar

        <?php }else{ ?>

Menu

 Buscar Receita Possíveis

             Ingredientes

 Visualizar Todos

 Visualizar na validade

Visualizar fora da validade

     Receitas

 Visualizar

 Cadastrar

   Conversão de medidas

   Dicas

 Tempo no freezer

 Carrinho de compras

        <?php } ?>

    <?php
         include_once("conexao.php");

         $resultado= mysqli_query($conn, "SELECT id_ingrediente, nome FROM ingredientes order by nome");
         $linhas = mysqli_num_rows($resultado);
         ?>

Receita

            <form action="Cadreceitas2.php" method="post">

                  Nome
                  <input type="text" class="form-control" name="nome_receita">

                  N° de porções
                  <input type="number" step = "0.5" class="form-control" name="porcoes"  required="">

                  Categoria
                  <input type="text" class="form-control" name="categoria">

                  Tempo de preparo em Minutos
                  <input type="number" step = "0.5" class="form-control" name="tempo"  required="">

                Modo de preparo
                 <textarea class="form-control" rows="3" name="preparo"></textarea>

                  Link Imagem
                  <input type="text" class="form-control" name="imagem">

                  Número de ingredientes
                  <input type="number" step = "1" class="form-control" name="ingrediente"  required="">

              <button type="submit" class="btn btn-primary col-md-3 col-md-offset-4">Próximo</button>

          </form>


text:
@interface SampleAppViewController () {
    int yCoordinateControl;
}

@property (nonatomic, strong)RevMobFullscreen *fullscreen;
@property (nonatomic, strong)RevMobBannerView *banner;
@property (nonatomic, strong)RevMobBanner *bannerWindow;
@property (nonatomic, strong)RevMobAdLink *link;

@property (strong, nonatomic) UIScrollView *scroll;
@property (assign, nonatomic) CLLocationManager *locationManager;

- (UIImage *)imageWithColor:(UIColor *)color;
- (void)createButtonWithName:(NSString *)name andSelector:(SEL)selector;
- (void)addVerticalSpace;

@end

@implementation SampleAppViewController

- (id)init {
    self = [super init];
    if (self) {
        yCoordinateControl = 10;
        _scroll = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return self;
}

#pragma mark Layout methods

- (void)createButtonWithName:(NSString *)name andSelector:(SEL)selector {
    UIButton *button = [[[UIButton alloc] initWithFrame:CGRectMake(10, yCoordinateControl, 300, 40)] autorelease];
    [button setTitle:name forState:UIControlStateNormal];
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];

    UIImage *background1 = [self imageWithColor:[UIColor grayColor]];
    UIImage *background2 = [self imageWithColor:[UIColor lightGrayColor]];
    [button setBackgroundImage:background1 forState:UIControlStateNormal];
    [button setBackgroundImage:background2 forState:UIControlStateSelected];

    button.layer.cornerRadius = 5;
    button.clipsToBounds = YES;

    [self.scroll addSubview:button];
    yCoordinateControl += 50;
}

- (void)addVerticalSpace {
    yCoordinateControl += 20;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

#ifdef __IPHONE_7_0
    if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1) {
        CGRect statusBar, frame;
        CGRectDivide(self.view.bounds, &statusBar, &frame, 20, CGRectMinYEdge);
        self.scroll.frame = frame;
    } else {
        self.scroll.frame = self.view.bounds;
    }
#else
    self.scroll.frame = self.view.bounds;
#endif

    self.scroll.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.scroll];

    [self createButtonWithName:@"Start Session" andSelector:@selector(startSession)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Disable Testing mode" andSelector:@selector(disableTestMode)];
    [self createButtonWithName:@"Testing with Ads" andSelector:@selector(testingWithAds)];
    [self createButtonWithName:@"Testing without Ads" andSelector:@selector(testingWithoutAds)];
    [self createButtonWithName:@"Enable Parallax Effect" andSelector:@selector(enableParallaxEffect)];
    [self createButtonWithName:@"Disable Parallax Effect" andSelector:@selector(disableParallaxEffect)];
    [self createButtonWithName:@"Enable Parallax With Background" andSelector:@selector(enableParallaxWithBackgroundEffect)];
    [self createButtonWithName:@"Print Env Info" andSelector:@selector(printEnvironmentInformation)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Basic Usage: Fullscreen" andSelector:@selector(basicUsageShowFullscreen)];
    [self createButtonWithName:@"Basic Usage: Banner" andSelector:@selector(basicUsageShowBanner)];
    [self createButtonWithName:@"Basic Usage: Hide banner" andSelector:@selector(basicUsageHideBanner)];
    [self createButtonWithName:@"Basic Usage: Popup" andSelector:@selector(basicUsageShowPopup)];
    [self createButtonWithName:@"Basic Usage: Link" andSelector:@selector(basicUsageOpenAdLink)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Show Fullscreen with delegate" andSelector:@selector(showFullscreenWithDelegate)];
    [self createButtonWithName:@"Show Fullscreen for orientations" andSelector:@selector(showFullscreenWithSpecificOrientations)];
    [self createButtonWithName:@"Pre Load Fullscreen" andSelector:@selector(loadFullscreen)];
    [self createButtonWithName:@"Show pre-loaded fullscreen" andSelector:@selector(showPreLoadedFullscreen)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Show Banner with custom frame" andSelector:@selector(showBannerWithCustomFrame)];
    [self createButtonWithName:@"Hide Banner with custom frame" andSelector:@selector(hideBannerWithCustomFrame)];

    [self createButtonWithName:@"Show Banner Window" andSelector:@selector(showBannerWindow)];
    [self createButtonWithName:@"Banner Window for orientations" andSelector:@selector(showBannerWindowWithSpecificOrientations)];
    [self createButtonWithName:@"Hide Banner Window" andSelector:@selector(hideBannerWindow)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Load Ad Link" andSelector:@selector(loadAdLink)];
    [self createButtonWithName:@"Open Ad Link" andSelector:@selector(openAdLink)];
    [self createButtonWithName:@"Add Ad Button" andSelector:@selector(addAdButton)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Show Popup" andSelector:@selector(showPopup)];
    [self addVerticalSpace];

    [self createButtonWithName:@"Close Sample App" andSelector:@selector(closeSampleApp)];
    [self addVerticalSpace];

    [self.scroll setBackgroundColor:[UIColor whiteColor]];

    [self fillUserInfo];

    self.scroll.contentSize = CGSizeMake(320,yCoordinateControl);
}

- (void)fillUserInfo
{
    RevMobAds *revmob = [RevMobAds session];

    revmob.userGender = RevMobUserGenderFemale;
    revmob.userAgeRangeMin = 18;
    revmob.userAgeRangeMax = 21;
    revmob.userBirthday = [NSDate dateWithTimeIntervalSince1970:0];
    revmob.userPage = @"twitter.com/revmob";
    revmob.userInterests = @[@"mobile", @"iPhone", @"apps"];

}

- (void)setUserLocation
{
    RevMobAds *revmob = [RevMobAds session];

    BOOL locationAllowed = [CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied);

    if (locationAllowed){
        CLLocation *location = self.locationManager.location;

        [self.locationManager setDistanceFilter: kCLDistanceFilterNone];
        [self.locationManager setDesiredAccuracy: kCLLocationAccuracyHundredMeters];
        [self.locationManager startUpdatingLocation];

        [revmob setUserLatitude: location.coordinate.latitude
                  userLongitude: location.coordinate.longitude
         userAccuracy: location.horizontalAccuracy];
     }
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    [self setUserLocation];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    // Test with all orientations
    return YES;

    // Test only with Portrait mode
    //return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);

    // Test only with Landscape mode
    //return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

#pragma mark Methods to test RevMob Ads

- (void)startSession {
    [RevMobAds startSessionWithAppID:REVMOB_ID
     withSuccessHandler:^{
         NSLog(@"Session started with block");
     } andFailHandler:^(NSError *error) {
         NSLog(@"Session failed to start with block");
     }];
}

- (void)disableTestMode {
    [RevMobAds session].testingMode = RevMobAdsTestingModeOff;
}

- (void)testingWithAds {
    [RevMobAds session].testingMode = RevMobAdsTestingModeWithAds;
}

- (void)testingWithoutAds {
    [RevMobAds session].testingMode = RevMobAdsTestingModeWithoutAds;
}

- (void)disableParallaxEffect {
    [RevMobAds session].parallaxMode = RevMobParallaxModeOff;
}

- (void)enableParallaxEffect {
    [RevMobAds session].parallaxMode = RevMobParallaxModeDefault;
}

- (void)enableParallaxWithBackgroundEffect {
    [RevMobAds session].parallaxMode = RevMobParallaxModeWithBackground;
}

- (void)printEnvironmentInformation {
    [[RevMobAds session] printEnvironmentInformation];
}

#pragma mark - Basic Usage -

- (void)basicUsageShowFullscreen {
    [[RevMobAds session] showFullscreen];
}

- (void)basicUsageShowBanner {
    [[RevMobAds session] showBanner];
}

- (void)basicUsageHideBanner {
    [[RevMobAds session] hideBanner];
}

- (void)basicUsageShowPopup {
    [[RevMobAds session] showPopup];
}

- (void)basicUsageOpenAdLink {
    [[RevMobAds session] openAdLinkWithDelegate:self];
}

#pragma mark - Advanced mode -

#pragma mark Fullscreen

- (void)showFullscreenWithDelegate {
    RevMobFullscreen *fs = [[RevMobAds session] fullscreen];
    fs.delegate = self;
    [fs showAd];
}

- (void)showFullscreenWithSpecificOrientations {
    RevMobFullscreen *fs = [[RevMobAds session] fullscreen];
    fs.supportedInterfaceOrientations = @[@(UIInterfaceOrientationLandscapeRight), @(UIInterfaceOrientationLandscapeLeft)];

    [fs loadWithSuccessHandler:^(RevMobFullscreen *fs) {
        [fs showAd];
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobFullscreen *fs, NSError *error) {
        [self revmobAdDidFailWithError:error];
    } onClickHandler:^{
        [self revmobUserClickedInTheAd];
    } onCloseHandler:^{
        [self revmobUserClosedTheAd];
    }];
}

- (void)loadFullscreen {
    self.fullscreen = [[RevMobAds session] fullscreen];
    self.fullscreen.delegate = self;
    [self.fullscreen loadAd];
}

- (void)showPreLoadedFullscreen{
    if (self.fullscreen) [self.fullscreen showAd];
}

#pragma mark Banner

- (void)showBannerWithCustomFrame {
    self.banner = [[RevMobAds session] bannerView];

    [self.banner loadWithSuccessHandler:^(RevMobBannerView *banner) {
        [banner setFrame:CGRectMake(10, 692, 200, 40)];
        [self.scroll addSubview:banner];
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobBannerView *banner, NSError *error) {
        [self revmobAdDidFailWithError:error];
    } onClickHandler:^(RevMobBannerView *banner) {
        [self revmobUserClickedInTheAd];
    }];

}

- (void)hideBannerWithCustomFrame {
    [self.banner removeFromSuperview];
}

#pragma mark Banner Window

- (void)showBannerWindow {
    self.bannerWindow = [[RevMobAds session] banner];
    [self.bannerWindow loadWithSuccessHandler:^(RevMobBanner *banner) {
        [banner showAd];
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobBanner *banner, NSError *error) {
        [self revmobAdDidFailWithError:error];
    } onClickHandler:^(RevMobBanner *banner) {
        [self revmobUserClickedInTheAd];
    }];
}

- (void)showBannerWindowWithSpecificOrientations {
    self.bannerWindow = [[RevMobAds session] banner];
    self.bannerWindow.supportedInterfaceOrientations = @[@(UIInterfaceOrientationLandscapeRight), @(UIInterfaceOrientationLandscapeLeft)];
    [self.bannerWindow loadWithSuccessHandler:^(RevMobBanner *banner) {
        [banner showAd];
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobBanner *banner, NSError *error) {
        [self revmobAdDidFailWithError:error];
    } onClickHandler:^(RevMobBanner *banner) {
        [self revmobUserClickedInTheAd];
    }];

}

- (void)hideBannerWindow {
    [self.bannerWindow hideAd];
}

#pragma mark Link

- (void)loadAdLink {
    self.link = [[RevMobAds session] adLink];
    [self.link loadWithSuccessHandler:^(RevMobAdLink *link) {
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobAdLink *link, NSError *error) {
        [self revmobAdDidFailWithError:error];
    }];
}

- (void)openAdLink {
    if (self.link) [self.link openLink];
}

- (void)addAdButton {
    RevMobButton *button = [[RevMobAds session] buttonUnloaded];

    [button loadWithSuccessHandler:^(RevMobButton *button) {
        [button setFrame:CGRectMake(10, yCoordinateControl, 300, 40)];
        [self.scroll addSubview:button];
        [button setTitle:@"Free Games" forState:UIControlStateNormal];
        yCoordinateControl += 50;
        self.scroll.contentSize = CGSizeMake(320,yCoordinateControl);
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobButton *button, NSError *error) {
        [self revmobAdDidFailWithError:error];
    } onClickHandler:^(RevMobButton *button) {
        [self revmobUserClickedInTheAd];
    }];

}

#pragma mark Popup

- (void)showPopup {
    RevMobPopup *popup = [[RevMobAds session] popup];

    [popup loadWithSuccessHandler:^(RevMobPopup *popup) {
        [popup showAd];
        [self revmobAdDidReceive];
    } andLoadFailHandler:^(RevMobPopup *popup, NSError *error) {
        [self revmobAdDidFailWithError:error];
    } onClickHandler:^(RevMobPopup *popup) {
        [self revmobUserClickedInTheAd];
    }];
}

#pragma mark - RevMobAdsDelegate methods

- (void)revmobSessionIsStarted {
    NSLog(@"[RevMob Sample App] Session started again.");
}

- (void)revmobSessionNotStarted:(NSError *)error {
    NSLog(@"[RevMob Sample App] Session not started again: %@", error);
}

- (void)revmobAdDidReceive {
    NSLog(@"[RevMob Sample App] Ad loaded.");
}

- (void)revmobAdDidFailWithError:(NSError *)error {
    NSLog(@"[RevMob Sample App] Ad failed: %@", error);
}

- (void)revmobAdDisplayed {
    NSLog(@"[RevMob Sample App] Ad displayed.");
}

- (void)revmobUserClosedTheAd {
    NSLog(@"[RevMob Sample App] User clicked in the close button.");
}

- (void)revmobUserClickedInTheAd {
    NSLog(@"[RevMob Sample App] User clicked in the Ad.");
}

- (void)installDidReceive {
    NSLog(@"[RevMob Sample App] Install did receive.");
}

- (void)installDidFail {
    NSLog(@"[RevMob Sample App] Install did fail.");
}

#pragma mark - Others

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

- (void)dealloc {
    [_locationManager release], _locationManager = nil;
    [_scroll release], _scroll = nil;

    [super dealloc];
}

- (void)closeSampleApp {
    exit(0);
}

@end


text:
<link rel="import" href="../polymer/polymer.html">
<link rel="import" href="../../polymer-elements/paper-tab/core-selector.html">

<polymer-element name="core-pages" extends="core-selector" selected="0" notap noscript>
    <template>

        <link rel="stylesheet" href="core-pages.css">

        <shadow></shadow>

    </template>
</polymer-element>


text:
package org.apache.derby.impl.store.access.sort;

import org.apache.derby.shared.common.sanity.SanityManager;

import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.store.access.conglomerate.TransactionManager;

/**

  A sort scan that just reads rows out of a sorter.

**/

public class SortBufferScan extends SortScan
{
	/**
	The sorter we're returning rows from.
	**/
	protected SortBuffer sortBuffer;

	/*
	 * Constructors.
	 */

	SortBufferScan(
    MergeSort           sort,
    TransactionManager  tran,
    SortBuffer          sortBuffer,
    boolean             hold)
	{
		super(sort, tran, hold);

        if (SanityManager.DEBUG)
            SanityManager.ASSERT(sortBuffer != null);

		this.sortBuffer = sortBuffer;
	}

	/*
	 * Methods of MergeSortScan
	 */

    /**
    Move to the next position in the scan.
	@see org.apache.derby.iapi.store.access.ScanController#next
    **/
    public boolean next()
		throws StandardException
    {
        if (SanityManager.DEBUG)
        {
            SanityManager.ASSERT(
                sortBuffer != null,
                "next() called on scan after scan was closed.");
        }

        current = sortBuffer.removeFirst();
        return current != null;
    }

    /**
    Close the scan.
    **/
    public boolean closeForEndTransaction(boolean closeHeldScan)
    {
        if (closeHeldScan || !hold)
        {
            close();
            return(true);
        }
        else
        {
            return(false);
        }

    }

    /**
    Close the scan.
	@see org.apache.derby.iapi.store.access.ScanController#close
    **/
    public void close()
	{
		if (super.sort != null)
		{
			sort.doneScanning(this, sortBuffer);
			sortBuffer = null;
		}
		super.close();
	}

}


text:
namespace WPF.GettingStarted.ViewModels
{
    using System.Collections.ObjectModel;
    using Catel;
    using Catel.Data;
    using Catel.MVVM;
    using WPF.GettingStarted.Models;

    public class FamilyViewModel : ViewModelBase
    {
        public FamilyViewModel(Family family)
        {
            Argument.IsNotNull(() => family);

            Family = family;
        }

        /// <summary>
        /// Gets the family.
        /// </summary>
        [Model]
        public Family Family
        {
            get { return GetValue<Family>(FamilyProperty); }
            private set { SetValue(FamilyProperty, value); }
        }

        /// <summary>
        /// Register the Family property so it is known in the class.
        /// </summary>
        public static readonly PropertyData FamilyProperty = RegisterProperty("Family", typeof(Family), null);

        /// <summary>
        /// Gets the family members.
        /// </summary>
        [ViewModelToModel("Family")]
        public ObservableCollection<Person> Persons
        {
            get { return GetValue<ObservableCollection<Person>>(PersonsProperty); }
            private set { SetValue(PersonsProperty, value); }
        }

        /// <summary>
        /// Register the Persons property so it is known in the class.
        /// </summary>
        public static readonly PropertyData PersonsProperty = RegisterProperty("Persons", typeof(ObservableCollection<Person>), null);

        /// <summary>
        /// Gets or sets the family name.
        /// </summary>
        [ViewModelToModel("Family")]
        public string FamilyName
        {
            get { return GetValue<string>(FamilyNameProperty); }
            set { SetValue(FamilyNameProperty, value); }
        }

        /// <summary>
        /// Register the FamilyName property so it is known in the class.
        /// </summary>
        public static readonly PropertyData FamilyNameProperty = RegisterProperty("FamilyName", typeof(string));
    }
}


text:
#include <linear_locales.h>

#if _POSIX_VERSION >= 200809L

locale_handle set_c_locale()
{
	locale_handle c_locale = newlocale(LC_ALL_MASK, "C", 0);
	locale_handle old_locale = uselocale(c_locale);
	return old_locale;
}

void restore_locale(locale_handle locale)
{
	locale_handle c_locale = uselocale(locale);
	if (c_locale && c_locale != LC_GLOBAL_LOCALE) {
		freelocale(c_locale);
	}
}

#else

locale_handle set_c_locale()
{
	locale_handle old_locale = setlocale(LC_ALL, NULL);
	if (old_locale) {
		old_locale = strdup(old_locale);
	}
	setlocale(LC_ALL, "C");
	return old_locale;
}

void restore_locale(locale_handle locale)
{
	setlocale(LC_ALL, locale);
	free(locale);
}

#endif /* _POSIX_VERSION */


text:
public class TestReturnGradeMethod {
  public static void main(String[] args) {
    System.out.print("The grade is " + getGrade(78.5));
    System.out.print("\nThe grade is " + getGrade(59.5));
  }

  public static char getGrade(double score) {
    if (score >= 90.0)
      return 'A';
    else if (score >= 80.0)
      return 'B';
    else if (score >= 70.0)
      return 'C';
    else if (score >= 60.0)
      return 'D';
    else
      return 'F';
  }
}


text:
package com.redhat.demo.engine;

import io.vertx.core.json.JsonObject;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.shareddata.SharedData;
import io.vertx.ext.web.RoutingContext;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import io.vertx.core.shareddata.LocalMap;

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

import java.text.DecimalFormat;
public class TradeRecommendationsEngine {

   private Logger log = LoggerFactory.getLogger(TradeRecommendationsEngine.class);

   private SharedData engineData;

   private int aggressionFactor = 1;

   public TradeRecommendationsEngine(SharedData engineData) {
     this.engineData = engineData;
   }

   public void nextRecommendation(RoutingContext rc) {
        /* format of results
            {
                "order" : "BUY ACME",
                "detail":
                {
                    "targetPrice" : 10,
                    "numShares" : 1000
                },
                "context":
                {
                    "confidenceScore" : 10,
                    "tradeWindowStart" : "Wed Mar 29 20:21:29 EDT 2017",
                    "tradeWindowEnd" : "Thu Mar 30 01:21:29 EDT 2017"
                }
            }
        */

        JsonObject recommendation = new JsonObject();
        JsonObject detail = new JsonObject();
        JsonObject context = new JsonObject();

        String pick = determineStockPick();

        //populate JSON
        detail.put("targetPrice", determineTargetPrice(pick));
        detail.put("numShares", determineNumShares());

        context.put("confidenceScore",determineConfidenceScore());
        context.put("tradeWindowStart", determineTradeWindowStartDate().toString());
        //context.put("tradeWindowEnd", determineTradeWindowEndDate().toString());

        recommendation.put("order", "BUY " + pick);
        recommendation.put("detail",detail);
        recommendation.put("context",context);

        rc.response()
          .putHeader(HttpHeaders.CONTENT_TYPE,"application/json")
          .end(recommendation.encode());
        this.log.info("Created new trade recommendation: " + recommendation.encode());
    }

    private String determineStockPick() {
        // int index = new java.util.Random().nextInt();
        int min = 0;
        List<String> options = Arrays.asList(
            "BOBO",
            "BABO",
            "TODD",
            "FALK",
            "PAUL"
        );
        int index  = java.util.concurrent.ThreadLocalRandom.current().nextInt(min, options.size());
        System.out.println(index);
        System.out.println(options.get(index));
        return options.get(index);
    }
    private int determineNumShares() {
        int r = java.util.concurrent.ThreadLocalRandom.current().nextInt(50, 100);
        System.out.println(r);
        return this.aggressionFactor * r;
    }

//    private double determineTargetPrice() {
//        return 10.85;
//    }

    private double determineTargetPrice(String ticker) {
         LocalMap<String, Double> previousMap = engineData.getLocalMap("previousMap");
         Double oldPrice = previousMap.get(ticker);
         if (oldPrice == null) {
             // oldPrice = 10.85;
             double random = java.util.concurrent.ThreadLocalRandom.current().nextDouble(10.85,345.24);
             oldPrice = new Double(random);
         }
         DecimalFormat df2 = new DecimalFormat("###.##");
         double increment = java.util.concurrent.ThreadLocalRandom.current().nextDouble(10.85,24.12);
         Double newPrice = oldPrice + increment;
         Double twoDecimalPlaces = new Double(df2.format(newPrice));
         System.out.println("new price " + twoDecimalPlaces);

         previousMap.put(ticker, twoDecimalPlaces);

         return twoDecimalPlaces.doubleValue();
    }

   /* results in a runtime error
   Invalid type for shareddata data structure: java.math.BigDecimal

   private double determineTargetPrice(String ticker) {
       LocalMap<String, BigDecimal> previousMap = engineData.getLocalMap("previousMap");
       BigDecimal oldPrice = previousMap.get(ticker);
       if (oldPrice == null) {
           double random = java.util.concurrent.ThreadLocalRandom.current().nextDouble(10.85,345.24);
           oldPrice = BigDecimal.valueOf(random);
       }
       double increment = java.util.concurrent.ThreadLocalRandom.current().nextDouble(10.85,24.12);
       BigDecimal newPrice = oldPrice.add(BigDecimal.valueOf(increment));
       BigDecimal twoDecimalPrice = newPrice.setScale(2, RoundingMode.HALF_UP);
       System.out.println("newPrice: " + twoDecimalPrice);
       previousMap.put(ticker, twoDecimalPrice);
       return newPrice.doubleValue();
   }
*/

    private int determineConfidenceScore() {
        return java.util.concurrent.ThreadLocalRandom.current().nextInt(5, 10);
    }

   private Date determineTradeWindowStartDate(){
    LocalDateTime today = LocalDateTime.now();
    return Date.from(today.atZone(ZoneId.systemDefault()).toInstant());

   }
   private Date determineTradeWindowEndDate(){
    LocalDateTime tomorrow = LocalDateTime.now().plusHours(3);
    return Date.from(tomorrow.atZone(ZoneId.systemDefault()).toInstant());
   }
}


text:
require "google/cloud/speech/v1p1beta1/speech_client"
require "google/cloud/speech/v1p1beta1/helpers"

module Google
  module Cloud
    module Speech
      # rubocop:disable LineLength

      ##
      # # Ruby Client for Cloud Speech API ([Alpha](https://github.com/googleapis/google-cloud-ruby#versioning))
      #
      # [Cloud Speech API][Product Documentation]:
      # Converts audio to text by applying powerful neural network models.
      # - [Product Documentation][]
      #
      # ## Quick Start
      # In order to use this library, you first need to go through the following
      # steps:
      #
      # 1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project)
      # 2. [Enable billing for your project.](https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project)
      # 3. [Enable the Cloud Speech API.](https://console.cloud.google.com/apis/library/speech.googleapis.com)
      # 4. [Setup Authentication.](https://googleapis.github.io/google-cloud-ruby/#/docs/google-cloud/master/guides/authentication)
      #
      # ### Installation
      # ```
      # $ gem install google-cloud-speech
      # ```
      #
      # ### Preview
      # #### SpeechClient
      # ```rb
      # require "google/cloud/speech"
      #
      # speech_client = Google::Cloud::Speech.new(version: :v1p1beta1)
      # language_code = "en-US"
      # sample_rate_hertz = 44100
      # encoding = :FLAC
      # config = {
      #   language_code: language_code,
      #   sample_rate_hertz: sample_rate_hertz,
      #   encoding: encoding
      # }
      # uri = "gs://bucket-name/hello.flac"
      # audio = { uri: uri }
      # response = speech_client.recognize(config, audio)
      # ```
      #
      # ### Next Steps
      # - Read the [Cloud Speech API Product documentation][Product Documentation]
      #   to learn more about the product and see How-to Guides.
      # - View this [repository's main README](https://github.com/googleapis/google-cloud-ruby/blob/master/README.md)
      #   to see the full list of Cloud APIs that we cover.
      #
      # [Product Documentation]: https://cloud.google.com/speech
      #
      # ## Enabling Logging
      #
      # To enable logging for this library, set the logger for the underlying [gRPC](https://github.com/grpc/grpc/tree/master/src/ruby) library.
      # The logger that you set may be a Ruby stdlib [`Logger`](https://ruby-doc.org/stdlib-2.5.0/libdoc/logger/rdoc/Logger.html) as shown below,
      # or a [`Google::Cloud::Logging::Logger`](https://googleapis.github.io/google-cloud-ruby/#/docs/google-cloud-logging/latest/google/cloud/logging/logger)
      # that will write logs to [Stackdriver Logging](https://cloud.google.com/logging/). See [grpc/logconfig.rb](https://github.com/grpc/grpc/blob/master/src/ruby/lib/grpc/logconfig.rb)
      # and the gRPC [spec_helper.rb](https://github.com/grpc/grpc/blob/master/src/ruby/spec/spec_helper.rb) for additional information.
      #
      # Configuring a Ruby stdlib logger:
      #
      # ```ruby
      # require "logger"
      #
      # module MyLogger
      #   LOGGER = Logger.new $stderr, level: Logger::WARN
      #   def logger
      #     LOGGER
      #   end
      # end
      #
      # # Define a gRPC module-level logger method before grpc/logconfig.rb loads.
      # module GRPC
      #   extend MyLogger
      # end
      # ```
      #
      module V1p1beta1
        # rubocop:enable LineLength

        ##
        # Service that implements Google Cloud Speech API.
        #
        # @param credentials [Google::Auth::Credentials, String, Hash, GRPC::Core::Channel, GRPC::Core::ChannelCredentials, Proc]
        #   Provides the means for authenticating requests made by the client. This parameter can
        #   be many types.
        #   A `Google::Auth::Credentials` uses a the properties of its represented keyfile for
        #   authenticating requests made by this client.
        #   A `String` will be treated as the path to the keyfile to be used for the construction of
        #   credentials for this client.
        #   A `Hash` will be treated as the contents of a keyfile to be used for the construction of
        #   credentials for this client.
        #   A `GRPC::Core::Channel` will be used to make calls through.
        #   A `GRPC::Core::ChannelCredentials` for the setting up the RPC client. The channel credentials
        #   should already be composed with a `GRPC::Core::CallCredentials` object.
        #   A `Proc` will be used as an updater_proc for the Grpc channel. The proc transforms the
        #   metadata for requests, generally, to give OAuth credentials.
        # @param scopes [Array<String>]
        #   The OAuth scopes for this service. This parameter is ignored if
        #   an updater_proc is supplied.
        # @param client_config [Hash]
        #   A Hash for call options for each method. See
        #   Google::Gax#construct_settings for the structure of
        #   this data. Falls back to the default config if not specified
        #   or the specified config is missing data points.
        # @param timeout [Numeric]
        #   The default timeout, in seconds, for calls made through this client.
        # @param metadata [Hash]
        #   Default metadata to be sent with each request. This can be overridden on a per call basis.
        # @param exception_transformer [Proc]
        #   An optional proc that intercepts any exceptions raised during an API call to inject
        #   custom error handling.
        def self.new \
            credentials: nil,
            scopes: nil,
            client_config: nil,
            timeout: nil,
            metadata: nil,
            exception_transformer: nil,
            lib_name: nil,
            lib_version: nil
          kwargs = {
            credentials: credentials,
            scopes: scopes,
            client_config: client_config,
            timeout: timeout,
            metadata: metadata,
            exception_transformer: exception_transformer,
            lib_name: lib_name,
            lib_version: lib_version
          }.select { |_, v| v != nil }
          Google::Cloud::Speech::V1p1beta1::SpeechClient.new(**kwargs)
        end
      end
    end
  end
end


text:
package java.lang;

/**
 * Thrown when a method is invoked with an argument which it can not reasonably
 * deal with.
 */
public class IllegalArgumentException extends RuntimeException {
    /**
     * Constructs a new {@code IllegalArgumentException} that includes the
     * current stack trace.
     */
    public IllegalArgumentException() {
        super();
    }

    /**
     * Constructs a new {@code IllegalArgumentException} with the current stack
     * trace and the specified detail message.
     *
     * @param detailMessage
     *            the detail message for this exception.
     */
    public IllegalArgumentException(String detailMessage) {
        super(detailMessage);
    }

    /**
     * Constructs a new {@code IllegalArgumentException} with the current stack
     * trace, the specified detail message and the specified cause.
     *
     * @param message
     *            the detail message for this exception.
     * @param cause
     *            the cause of this exception, may be {@code null}.
     * @since 1.5
     */
    public IllegalArgumentException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new {@code IllegalArgumentException} with the current stack
     * trace and the specified cause.
     *
     * @param cause
     *            the cause of this exception, may be {@code null}.
     * @since 1.5
     */
    public IllegalArgumentException(Throwable cause) {
        super((cause == null ? null : cause.toString()), cause);
    }
}


text:
"use strict";

/*global app*/

(function(app){
  // Possible values : "1024x768" "1280x720" "1366x768" ("1920x1200")
  var resolutionHigh = "1920x1200";
  var resolution = "1366x768";
  var bingServiceUrl = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-ww";

  function init(){
    setImageFromCache();
    get(bingServiceUrl)
    .then(parseToJson)
    .then(checkIfImageIsAlreadyInCache)
    .then(getCopyright)
    .then(getBackground)
    .then(cacheImage)
    .then(setImage);
  }

  function checkIfImageIsAlreadyInCache(data){
    return new Promise(function(resolve) {
      var url = getResolutionHighRes("http://www.bing.com" + data.images[0].url);
      var cachedImageURL = localStorage.getItem("wallpaper_url");

      if (url !== cachedImageURL) {
        resolve(data);
      }
    });
  }

  function parseToJson(result) {
    return new Promise(function(resolve) {
      resolve(JSON.parse(result.responseText));
    });
  }

  function getCopyright(data) {
    return new Promise(function(resolve) {
      setCopyright(data.images[0].copyright);
      localStorage.setItem("wallpaper_caption", data.images[0].copyright);
      resolve(data);
    });
  }

  function setCopyright(captionText) {
    var caption = document.querySelector("div.caption") || document.createElement("div");
    caption.className = "caption";
    caption.appendChild(document.createTextNode(captionText));
    document.getElementsByTagName("body")[0].appendChild(caption);
  }

  function getBackground(data) {
    return getBackgroundHighRes(data).then(function(result) {
      return result;
    }, function() {
      return getBackgroundDefault(data);
    });
  }

  function getBackgroundDefault(data) {
    var url = "http://www.bing.com" + data.images[0].url;
    return get(url, "blob");
  }

  function getBackgroundHighRes(data) {
    var url = getResolutionHighRes("http://www.bing.com" + data.images[0].url);
    return get(url, "blob").then(function(result){
      localStorage.setItem("wallpaper_url", url);
      return result;
    }, function(result){
      return result;
    });
  }

  function getResolutionHighRes(url) {
    return url.replace(resolution, resolutionHigh);
  }

  function setImage(imageBase64) {
    document.getElementsByTagName("html")[0].style.backgroundImage = "url(" + imageBase64 + ")";
  }

  function cacheImage(result) {
    return new Promise(function(resolve, reject) {
      try {
        var fileReader = new FileReader();
        fileReader.onload = function (evt) {
            var result = evt.target.result;

            try {
                localStorage.setItem("wallpaper", result);
                resolve(result);
            }
            catch (e) {
                reject(result);
            }
        };
        fileReader.readAsDataURL(result.response);
      }
      catch (e) {
          reject(result);
      }
    });
  }

  function setImageFromCache(result) {
    var cachedImage = localStorage.getItem("wallpaper");
    var cachedCaption = localStorage.getItem("wallpaper_caption");

    if (cachedImage) {
      setImage(cachedImage);
    }

    if (cachedCaption) {
      setCopyright(cachedCaption);
    }
  }

  function get(url, responseType) {
    return new Promise(function(resolve, reject) {
      var req = new XMLHttpRequest();
      req.open("GET", url);

      if (responseType) {
        req.responseType = responseType;
      }

      req.onload = function() {
        if (req.status === 200) {
          resolve(req);
        }
        else {
          reject(Error(req.statusText));
        }
      };

      req.onerror = function() {
        reject(Error("Network Error"));
      };

      req.send();
    });
  }

  app.registerControl(init);
})(app);


text:
""" Memcached module.
"""
import os

def memcached(loader, project=None, variant=None, *args): #pylint:disable=keyword-arg-before-vararg
    project, variant = loader.setup_project_env(project, variant)
    loader.setup_shell_env()
    config = loader.get_project_config()

    binargs = [config.get('memcached.bin', '/usr/bin/memcached')] + list(args)
    os.execvp(binargs[0], binargs)

def memcached_run(loader, project=None, variant=None, *args): #pylint:disable=keyword-arg-before-vararg
    project, variant = loader.setup_project_env(project, variant)
    loader.setup_shell_env()
    config = loader.get_project_config()

    binargs = [
        config.get('memcached.bin', '/usr/bin/memcached'),
        '--listen=%s' % os.environ.get('MEMCACHED_LISTEN', '127.0.0.1'),
        '--port=%s' % os.environ.get('MEMCACHED_PORT', 11211),
    ]

    # in megabytes
    max_memory = config.get('memcached.max_memory')
    if max_memory:
        binargs.append('--memory-limit=%s' % max_memory)

    os.execvp(binargs[0], binargs + list(args))

commands = (memcached, memcached_run)


text:
import sinon from 'sinon';

export function createRunDetails(): jasmine.RunDetails {
  return {
    failedExpectations: [],
    order: {
      random: false,
      seed: '12foo',
      sort: (_) => _,
    } as jasmine.Order,
  };
}

export function createCustomReporterResult(overrides?: Partial<jasmine.CustomReporterResult>): jasmine.CustomReporterResult {
  return {
    description: 'should have bar',
    fullName: 'Foo should have bar',
    id: 'spec0',
    ...overrides,
  };
}

export function createEnvStub(): sinon.SinonStubbedInstance<jasmine.Env> {
  return {
    currentSpec: { id: 'spec1' } as jasmine.Spec,
    matchersClass: sinon.stub() as unknown as jasmine.Matchers<any>,
    version: sinon.stub(),
    versionString: sinon.stub(),
    nextSpecId: sinon.stub(),
    addReporter: sinon.stub(),
    execute: sinon.stub(),
    describe: sinon.stub(),
    beforeEach: sinon.stub(),
    beforeAll: sinon.stub(),
    currentRunner: sinon.stub(),
    afterEach: sinon.stub(),
    afterAll: sinon.stub(),
    xdescribe: sinon.stub(),
    it: sinon.stub(),
    xit: sinon.stub(),
    compareRegExps_: sinon.stub(),
    compareObjects_: sinon.stub(),
    equals_: sinon.stub(),
    contains_: sinon.stub(),
    addCustomEqualityTester: sinon.stub(),
    addMatchers: sinon.stub(),
    specFilter: sinon.stub(),
    throwOnExpectationFailure: sinon.stub(),
    stopOnSpecFailure: sinon.stub(),
    seed: sinon.stub(),
    provideFallbackReporter: sinon.stub(),
    throwingExpectationFailures: sinon.stub(),
    allowRespy: sinon.stub(),
    randomTests: sinon.stub(),
    randomizeTests: sinon.stub(),
    clearReporters: sinon.stub(),
    configure: sinon.stub(),
  };
}


text:
import { CachedReference } from '../utils/references';
import { CURRENT_TAG, CONSTANT_TAG, UpdatableTag, combine, isConst, referenceFromParts } from 'glimmer-reference';

/**
@module ember
@submodule ember-templates
*/

/**
  Dynamically look up a property on an object. The second argument to `{{get}}`
  should have a string value, although it can be bound.

  For example, these two usages are equivilent:

  ```handlebars
  {{person.height}}
  {{get person "height"}}
  ```

  If there were several facts about a person, the `{{get}}` helper can dynamically
  pick one:

  ```handlebars
  {{get person factName}}
  ```

  For a more complex example, this template would allow the user to switch
  between showing the user's height and weight with a click:

  ```handlebars
  {{get person factName}}
  <button {{action (mut factName) "height"}}>Show height</button>
  <button {{action (mut factName) "weight"}}>Show weight</button>
  ```

  The `{{get}}` helper can also respect mutable values itself. For example:

  ```handlebars
  {{input value=(mut (get person factName)) type="text"}}
  <button {{action (mut factName) "height"}}>Show height</button>
  <button {{action (mut factName) "weight"}}>Show weight</button>
  ```

  Would allow the user to swap what fact is being displayed, and also edit
  that fact via a two-way mutable binding.

  @public
  @method get
  @for Ember.Templates.helpers
  @since 2.1.0
 */

export default {
  isInternalHelper: true,

  toReference(args) {
    return GetHelperReference.create(args.positional.at(0), args.positional.at(1));
  }
};

class GetHelperReference extends CachedReference {
  static create(sourceReference, pathReference) {
    if (isConst(pathReference)) {
      let parts = pathReference.value().split('.');
      return referenceFromParts(sourceReference, parts);
    } else {
      return new GetHelperReference(sourceReference, pathReference);
    }
  }

  constructor(sourceReference, pathReference) {
    super();
    this.sourceReference = sourceReference;
    this.pathReference = pathReference;

    this.lastPath = null;
    this.innerReference = null;

    let innerTag = this.innerTag = new UpdatableTag(CURRENT_TAG);

    this.tag = combine([sourceReference.tag, pathReference.tag, innerTag]);
  }

  compute() {
    let { lastPath, innerReference, innerTag } = this;

    let path = this.lastPath = this.pathReference.value();

    if (path !== lastPath) {
      if (path) {
        let pathType = typeof path;

        if (pathType === 'string') {
          innerReference = this.innerReference = referenceFromParts(this.sourceReference, path.split('.'));
        } else if (pathType === 'number') {
          innerReference = this.innerReference = this.sourceReference.get(path);
        }

        innerTag.update(innerReference.tag);
      } else {
        innerReference = this.innerReference = null;
        innerTag.update(CONSTANT_TAG);
      }
    }

    return innerReference ? innerReference.value() : null;
  }
}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { ComponentBase } from '../../baseClasses/componentBase/component.base';

import { IVintageDateContainer } from '../../../fredapi/series/seriesVintageDates.interfaces';
import { IContainerExtensions } from '../../../fredapi/shared/shared.interfaces';

import { FormBuildAndValidationService } from '../../../shared/formBuildAndValidation/formBuildAndValidation.service';
import { FormsConfigurationService, IFormsConfiguration } from '../../shared/formsConfiguration/formsConfiguration.service';
import { RouteToFormBindingService, RouteToFormBinding } from '../../../shared/routeToFormBinding/routeToFormBinding.service';
import { SeriesService } from '../../../fredapi/series/series.service';

@Component({
  selector: 'seriesVintageDates',
  templateUrl: './seriesVintageDates.component.html'
})
export class SeriesVintageDatesComponent extends ComponentBase implements OnInit, OnDestroy {

  heading: string = "Series Vintage Dates";
  static queryParamsToFormBindingValues: RouteToFormBinding[] = [
    new RouteToFormBinding("realtime_start", "startDate"),
    new RouteToFormBinding("realtime_end", "endDate"),
    new RouteToFormBinding("limit"),
    new RouteToFormBinding("offset"),
    new RouteToFormBinding("sort_order", "sortOrder")
  ];

  // response
  response: IContainerExtensions;
  container: IVintageDateContainer;
  vintageDates: Date[];

  get dataName(): string {
    return "seriesVintageDates";
  }

  get formsConfigurations(): IFormsConfiguration[] {
    return [
      this.configurationService.getId("Series"),
      this.configurationService.dateRange,
      this.configurationService.getList()
    ];
  }

  get routeParamsToFormBindings(): RouteToFormBinding[] {
    return [
      new RouteToFormBinding("id")
    ];
  }

  get queryParamsToFormBindings(): RouteToFormBinding[] {
    return SeriesVintageDatesComponent.queryParamsToFormBindingValues;
  }

  get navigationRoute(): any[] {
    let seriesId = this.theForm.get("id").value;
    return ["/seriesVintageDates/", seriesId];
  }

  constructor(
    router: Router,
    route: ActivatedRoute,
    formBuilder: FormBuildAndValidationService,
    configurationService: FormsConfigurationService,
    bindingService: RouteToFormBindingService,
    private service: SeriesService) {

    super(router, route, formBuilder, configurationService, bindingService);
  }

  parseData(data) {
    console.log(data);
    this.response = data;
    this.container = data.container;
    this.vintageDates = data.container && data.container.vintage_dates;
  }

  callService(queryString: string): Observable<any> {
    let seriesId = this.theForm.get("id").value;
    return this.service.getVintageDates(seriesId, queryString);
  }

}


text:
package com.netflix.astyanax.retry;

import java.util.Random;

import com.netflix.astyanax.util.StringUtils;

/**
 * Unbounded exponential backoff will sleep a random number of intervals within an
 * exponentially increasing number of intervals.
 *
 * @author elandau
 *
 */
public class ExponentialBackoff extends SleepingRetryPolicy {

    private final Random random = new Random();
    private final int baseSleepTimeMs;

    public ExponentialBackoff(int baseSleepTimeMs, int maxAttempts) {
        super(maxAttempts);
        this.baseSleepTimeMs = baseSleepTimeMs;
    }

    @Override
    public long getSleepTimeMs() {
        return baseSleepTimeMs * Math.max(1, random.nextInt(1 << (this.getAttemptCount() + 1)));
    }

    public int getBaseSleepTimeMs() {
        return baseSleepTimeMs;
    }

    @Override
    public RetryPolicy duplicate() {
        return new ExponentialBackoff(baseSleepTimeMs, getMaxAttemptCount());
    }

    public String toString() {
        return StringUtils.joinClassAttributeValues(this, "ExponentialBackoff", ExponentialBackoff.class);
    }
}