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

import {JsonMap} from '@iarna/toml';
import * as TOMLParser from '@iarna/toml/lib/toml-parser';

const taggedValueMarker = Symbol('__TAGGED_VALUE');

/**
 * The type for any value parsed by `TaggedTOMLParser`, including all kinds of
 * strings, numbers, dates, etc.
 */
interface TaggedValue {
  /** Type marker */
  [taggedValueMarker]: true;

  /** Byte offset of the start of the value */
  start: number;

  /** Byte offset of the end of the value */
  end: number;

  /** Current contents of the string. May be shorter than (end-start), if the string had escape sequences */
  value: unknown;
}

/**
 * A custom variant of `TOMLParser` that replaces all values with a tagged
 * variant that includes their start and end positions, allowing them to be
 * replaced.
 */
class TaggedTOMLParser extends TOMLParser {
  parseValue() {
    // Remember the start position of the value.
    //
    // Off-by-one correctness: by this point, `this.pos` points one character
    // *after* the first character of the value, which is in `this.char`
    this.state.__TAGGED_START = this.pos - 1;

    return super.parseValue();
  }

  next(fn: Function) {
    const prevState = this.state;
    super.next(fn); // `next` returns void

    // Carry over the start position. If it wasn't set, (say, if we were parsing
    // something other than a value), we're just assigning `undefined` here.
    this.state.__TAGGED_START = prevState.__TAGGED_START;
  }

  return(value: unknown) {
    const prevState = this.state;
    super.return(value); // `return` returns void

    if (prevState.__TAGGED_START && typeof this.state.returned !== 'object') {
      // If the parser we just returned from remembered a start position,
      // tag the returned value with "start" and "end".
      // Note that we don't tag objects to avoid encountering multiple tagged
      // values when replacing later on.
      const taggedValue: TaggedValue = {
        [taggedValueMarker]: true,
        start: prevState.__TAGGED_START,
        end: this.pos,
        value: this.state.returned,
      };

      this.state.returned = taggedValue;
    }
  }
}

/**
 * Parses input as TOML with the given parser
 * @param input A string
 * @param parserType The TOML parser to use (might be custom)
 */
function parseWith(input: string, parserType: typeof TOMLParser): JsonMap {
  const parser = new parserType();
  parser.parse(input);
  return parser.finish();
}

function isTaggedValue(x: unknown): x is TaggedValue {
  if (!x) {
    return false;
  }

  if (typeof x !== 'object') {
    return false;
  }

  const ts = x as TaggedValue;
  return ts[taggedValueMarker] === true;
}

/**
 * Given TOML input and a path to a value, attempt to replace
 * that value without modifying the formatting.
 * @param input A string that's valid TOML
 * @param path Path to a value to replace. When replacing 'deps.tokio.version', pass ['deps', 'tokio', 'version']. The value must already exist.
 * @param newValue The value to replace the value at `path` with. Is passed through `JSON.stringify()` when replacing: strings will end up being double-quoted strings, properly escaped. Numbers will be numbers.
 */
export function replaceTomlValue(
  input: string,
  path: string[],
  newValue: string
) {
  // our pointer into the object "tree", initially points to the root.
  let current = parseWith(input, TaggedTOMLParser) as Record<string, unknown>;

  // navigate down the object tree, following the path, expecting only objects.
  // Note that tagged strings (generated by `TaggedTOMLParser`) are also objects.
  for (let i = 0; i < path.length; i++) {
    const key = path[i];

    // // We may encounter tagged values when descending through the object tree
    // if (isTaggedValue(current)) {
    //   if (!current.value || typeof current.value !== 'object') {
    //     const msg = `partial path does not lead to table: ${path
    //       .slice(0, i)
    //       .join('.')}`;
    //     throw new Error(msg);
    //   }
    //   current = current.value as Record<string, unknown>;
    // }

    const next = current[key];

    if (typeof next !== 'object') {
      const msg = `path not found in object: ${path.slice(0, i + 1).join('.')}`;
      throw new Error(msg);
    }
    current = next as JsonMap;
  }

  if (!isTaggedValue(current)) {
    const msg = `value at path ${path.join('.')} is not tagged`;
    throw new Error(msg);
  }

  const before = input.slice(0, current.start);
  const after = input.slice(current.end);
  const output = before + JSON.stringify(newValue) + after;

  try {
    parseWith(output, TOMLParser);
  } catch (e) {
    throw new Error(`After replacing value, result is not valid TOML: ${e}`);
  }

  return output;
}


text:
package com.amazonaws.services.simplesystemsmanagement.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Information about comments added to a document review request.
 *

 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DocumentReviewCommentSource implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The type of information added to a review request. Currently, only the value Comment is supported.
     *

     */
    private String type;
    /**
     *

     * The content of a comment entered by a user who requests a review of a new document version, or who reviews the
     * new version.
     *

     */
    private String content;

    /**
     *

     * The type of information added to a review request. Currently, only the value Comment is supported.
     *

     *
     * @param type
     *        The type of information added to a review request. Currently, only the value Comment is
     *        supported.
     * @see DocumentReviewCommentType
     */

    public void setType(String type) {
        this.type = type;
    }

    /**
     *

     * The type of information added to a review request. Currently, only the value Comment is supported.
     *

     *
     * @return The type of information added to a review request. Currently, only the value Comment is
     *         supported.
     * @see DocumentReviewCommentType
     */

    public String getType() {
        return this.type;
    }

    /**
     *

     * The type of information added to a review request. Currently, only the value Comment is supported.
     *

     *
     * @param type
     *        The type of information added to a review request. Currently, only the value Comment is
     *        supported.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DocumentReviewCommentType
     */

    public DocumentReviewCommentSource withType(String type) {
        setType(type);
        return this;
    }

    /**
     *

     * The type of information added to a review request. Currently, only the value Comment is supported.
     *

     *
     * @param type
     *        The type of information added to a review request. Currently, only the value Comment is
     *        supported.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see DocumentReviewCommentType
     */

    public DocumentReviewCommentSource withType(DocumentReviewCommentType type) {
        this.type = type.toString();
        return this;
    }

    /**
     *

     * The content of a comment entered by a user who requests a review of a new document version, or who reviews the
     * new version.
     *

     *
     * @param content
     *        The content of a comment entered by a user who requests a review of a new document version, or who reviews
     *        the new version.
     */

    public void setContent(String content) {
        this.content = content;
    }

    /**
     *

     * The content of a comment entered by a user who requests a review of a new document version, or who reviews the
     * new version.
     *

     *
     * @return The content of a comment entered by a user who requests a review of a new document version, or who
     *         reviews the new version.
     */

    public String getContent() {
        return this.content;
    }

    /**
     *

     * The content of a comment entered by a user who requests a review of a new document version, or who reviews the
     * new version.
     *

     *
     * @param content
     *        The content of a comment entered by a user who requests a review of a new document version, or who reviews
     *        the new version.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DocumentReviewCommentSource withContent(String content) {
        setContent(content);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getType() != null)
            sb.append("Type: ").append(getType()).append(",");
        if (getContent() != null)
            sb.append("Content: ").append(getContent());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DocumentReviewCommentSource == false)
            return false;
        DocumentReviewCommentSource other = (DocumentReviewCommentSource) obj;
        if (other.getType() == null ^ this.getType() == null)
            return false;
        if (other.getType() != null && other.getType().equals(this.getType()) == false)
            return false;
        if (other.getContent() == null ^ this.getContent() == null)
            return false;
        if (other.getContent() != null && other.getContent().equals(this.getContent()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode());
        hashCode = prime * hashCode + ((getContent() == null) ? 0 : getContent().hashCode());
        return hashCode;
    }

    @Override
    public DocumentReviewCommentSource clone() {
        try {
            return (DocumentReviewCommentSource) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.simplesystemsmanagement.model.transform.DocumentReviewCommentSourceMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.catalina.connector;

import java.io.IOException;

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

import org.apache.catalina.Context;
import org.apache.catalina.startup.SimpleHttpClient;
import org.apache.catalina.startup.TomcatBaseTest;
import org.apache.catalina.startup.Tomcat;

public class TestKeepAliveCount extends TomcatBaseTest{

    public void testHttp10() throws Exception {
        TestKeepAliveClient client = new TestKeepAliveClient();
        client.doHttp10Request();
    }

    public void testHttp11() throws Exception {
        TestKeepAliveClient client = new TestKeepAliveClient();
        client.doHttp11Request();
    }

    private class TestKeepAliveClient extends SimpleHttpClient {

        private boolean init;

        private synchronized void init() {
            if (init) return;

            Tomcat tomcat = getTomcatInstance();
            Context root = tomcat.addContext("", TEMP_DIR);
            Tomcat.addServlet(root, "Simple", new SimpleServlet());
            root.addServletMapping("/test", "Simple");
            tomcat.getConnector().setProperty("maxKeepAliveRequests", "5");
            tomcat.getConnector().setProperty("soTimeout", "20000");
            tomcat.getConnector().setProperty("keepAliveTimeout", "50000");
            tomcat.getConnector().setProperty("port", "8080");
            init = true;
        }

        private void doHttp10Request() throws Exception {
            Tomcat tomcat = getTomcatInstance();
            init();
            tomcat.start();
            // Open connection
            connect();

            // Send request in two parts
            String[] request = new String[1];
            request[0] =
                "GET /test HTTP/1.0" + CRLF + CRLF;
            setRequest(request);
            processRequest(false); // blocks until response has been read
            boolean passed = (this.readLine()==null);
            // Close the connection
            disconnect();
            reset();
            tomcat.stop();
            assertTrue(passed);
        }

        private void doHttp11Request() throws Exception {
            Tomcat tomcat = getTomcatInstance();
            init();
            tomcat.start();
            // Open connection
            connect();

            // Send request in two parts
            String[] request = new String[1];
            request[0] =
                "GET /test HTTP/1.1" + CRLF +
                "Host: localhost" + CRLF +
                "Connection: Keep-Alive" + CRLF+
                "Keep-Alive: 300"+ CRLF+ CRLF;

            setRequest(request);

            for (int i=0; i<5; i++) {
                processRequest(false); // blocks until response has been read
                assertTrue(getResponseLine()!=null && getResponseLine().trim().startsWith("HTTP/1.1 200"));
            }
            boolean passed = (this.readLine()==null);
            // Close the connection
            disconnect();
            reset();
            tomcat.stop();
            assertTrue(passed);
        }

        @Override
        public boolean isResponseBodyOK() {
            return true;
        }

    }

    private static class SimpleServlet extends HttpServlet {

        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentLength(0);
            resp.flushBuffer();
        }

    }

}


text:
<?php

	# This is a little piece of syntactic sugar for logged-in users.
	# It is predicated on using OAuth2 which itself is mostly just a
	# lot of syntactic sugar around the same old api key + auth token
	# dance which is itself wrapped up in a big ol' blanket of HTTPS.
	#
	# So all this page does is mint a brand new key and access token
	# for a user in one go. It doesn't set a callback URL or do anything
	# fancy. It just gives them an access_token so they can start
	# using the API. (20121026/straup)

 	# sad face...
	# http://www.rfc-editor.org/rfc/rfc6749.txt

	include("include/init.php");

	features_ensure_enabled("api");
	features_ensure_enabled("api_delegated_auth");
	features_ensure_enabled("api_authenticate_self");

	login_ensure_loggedin();

	loadlib("api_keys");
	loadlib("api_oauth2_access_tokens");

	$crumb_key = 'access_token_authenticate_like_magic';
	$GLOBALS['smarty']->assign("crumb_key", $crumb_key);

	$perms_map = api_oauth2_access_tokens_permissions_map();
	$GLOBALS['smarty']->assign_by_ref("permissions", $perms_map);

	$ttl_map = api_oauth2_access_tokens_ttl_map();
	$GLOBALS['smarty']->assign_by_ref("ttl_map", $ttl_map);

	$step = 1;

	if ((post_isset("done")) && (crumb_check($crumb_key))){

		$ok = 1;

		$title = post_str("title");
		$perms = post_str("perms");
		$ttl = post_int32("ttl");
		$conf = post_str("confirm");

		if (($ok) && (! $title)){
			$GLOBALS['smarty']->assign("error", "no_title");
			$ok = 0;
		}

		if (($ok) && (! api_oauth2_access_tokens_is_valid_permission($perms))){
			$GLOBALS['smarty']->assign("error", "bad_perms");
			$ok = 0;
		}

		# We're not going to worry about descriptions

		if ($ok){
			$GLOBALS['smarty']->assign("title", $title);
			$GLOBALS['smarty']->assign("perms", $perms);
			$GLOBALS['smarty']->assign("ttl", $ttl);
			$step = 2;
		}

		if (($ok) && ($conf)){

			$key = null;
			$token = null;
			$step = 3;

			$description = "";

			$rsp = api_keys_create($GLOBALS['cfg']['user']['id'], $title, $description);
			$key = $rsp['key'];

			if (! $rsp['ok']){
				$ok = 0;
			}

			if ($ok){

				$rsp = api_oauth2_access_tokens_create($key, $GLOBALS['cfg']['user'], $perms, $ttl);
				$token = $rsp['token'];

				if (! $rsp['ok']){
					$ok = 0;
				}
			}

			$GLOBALS['smarty']->assign("try_update", 1);
			$GLOBALS['smarty']->assign("update_ok", $ok);
			$GLOBALS['smarty']->assign_by_ref("api_key", $key);
			$GLOBALS['smarty']->assign_by_ref("token", $token);
		}
	}

	$GLOBALS['smarty']->assign("step", $step);

	$GLOBALS['smarty']->display("page_api_oauth2_authenticate_like_magic.txt");
	exit();

?>


text:
// $Id: Malloc_Allocator.cpp 79134 2007-07-31 18:23:50Z johnnyw $

#include "ace/Malloc_Allocator.h"
#include "ace/Object_Manager.h"

#if !defined (__ACE_INLINE__)
#include "ace/Malloc_Allocator.inl"
#endif /* __ACE_INLINE__ */

#include "ace/Guard_T.h"
#include "ace/Recursive_Thread_Mutex.h"
#include "ace/Log_Msg.h"  // for ACE_ASSERT
#include "ace/OS_NS_string.h"

ACE_RCSID (ace, Malloc_Allocator, "$Id: Malloc_Allocator.cpp 79134 2007-07-31 18:23:50Z johnnyw $")

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

ACE_Allocator *
ACE_Allocator::instance (void)
{
  //  ACE_TRACE ("ACE_Allocator::instance");

  if (ACE_Allocator::allocator_ == 0)
    {
      // Perform Double-Checked Locking Optimization.
      ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
                                *ACE_Static_Object_Lock::instance (), 0));

      if (ACE_Allocator::allocator_ == 0)
        {
          // Have a seat.  We want to avoid ever having to delete the
          // ACE_Allocator instance, to avoid shutdown order
          // dependencies.  ACE_New_Allocator never needs to be
          // destroyed:  its destructor is empty and its instance
          // doesn't have any state.  Therefore, sizeof
          // ACE_New_Allocator is equal to sizeof void *.  It's
          // instance just contains a pointer to its virtual function
          // table.
          //
          // So, we allocate space for the ACE_New_Allocator instance
          // in the data segment.  Because its size is the same as
          // that of a pointer, we allocate it as a pointer so that it
          // doesn't get constructed statically.  We never bother to
          // destroy it.
          static void *allocator_instance = 0;

          // Check this critical assumption.  We put it in a variable
          // first to avoid stupid compiler warnings that the
          // condition may always be true/false.
#         if !defined (ACE_NDEBUG)
          int assertion = (sizeof allocator_instance ==
                           sizeof (ACE_New_Allocator));
          ACE_ASSERT (assertion);
#         endif /* !ACE_NDEBUG */

          // Initialize the allocator_instance by using a placement
          // new.
          ACE_Allocator::allocator_ =
            new (&allocator_instance) ACE_New_Allocator;
        }
    }

  return ACE_Allocator::allocator_;
}

ACE_Allocator *
ACE_Allocator::instance (ACE_Allocator *r)
{
  ACE_TRACE ("ACE_Allocator::instance");
  ACE_MT (ACE_GUARD_RETURN (ACE_Recursive_Thread_Mutex, ace_mon,
                            *ACE_Static_Object_Lock::instance (), 0));
  ACE_Allocator *t = ACE_Allocator::allocator_;

  // We can't safely delete it since we don't know who created it!
  ACE_Allocator::delete_allocator_ = 0;

  ACE_Allocator::allocator_ = r;
  return t;
}

void
ACE_Allocator::close_singleton (void)
{
  ACE_TRACE ("ACE_Allocator::close_singleton");

  ACE_MT (ACE_GUARD (ACE_Recursive_Thread_Mutex, ace_mon,
                     *ACE_Static_Object_Lock::instance ()));

  if (ACE_Allocator::delete_allocator_)
    {
      // This should never be executed....  See the
      // ACE_Allocator::instance (void) method for an explanation.
      delete ACE_Allocator::allocator_;
      ACE_Allocator::allocator_ = 0;
      ACE_Allocator::delete_allocator_ = 0;
    }
}

ACE_Allocator::~ACE_Allocator (void)
{
  ACE_TRACE ("ACE_Allocator::~ACE_Allocator");
}

ACE_Allocator::ACE_Allocator (void)
{
  ACE_TRACE ("ACE_Allocator::ACE_Allocator");
}

/******************************************************************************/

void *
ACE_New_Allocator::malloc (size_t nbytes)
{
  char *ptr = 0;

  if (nbytes > 0)
    ACE_NEW_RETURN (ptr, char[nbytes], 0);
  return (void *) ptr;
}

void *
ACE_New_Allocator::calloc (size_t nbytes,
                           char initial_value)
{
  char *ptr = 0;

  ACE_NEW_RETURN (ptr, char[nbytes], 0);

  ACE_OS::memset (ptr, initial_value, nbytes);
  return (void *) ptr;
}

void *
ACE_New_Allocator::calloc (size_t n_elem, size_t elem_size, char initial_value)
{
  return ACE_New_Allocator::calloc (n_elem * elem_size, initial_value);
}

void
ACE_New_Allocator::free (void *ptr)
{
  delete [] (char *) ptr;
}

int
ACE_New_Allocator::remove (void)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::bind (const char *, void *, int)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::trybind (const char *, void *&)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::find (const char *, void *&)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::find (const char *)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::unbind (const char *)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::unbind (const char *, void *&)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::sync (ssize_t, int)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::sync (void *, size_t, int)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::protect (ssize_t, int)
{
  ACE_NOTSUP_RETURN (-1);
}

int
ACE_New_Allocator::protect (void *, size_t, int)
{
  ACE_NOTSUP_RETURN (-1);
}

#if defined (ACE_HAS_MALLOC_STATS)
void
ACE_New_Allocator::print_stats (void) const
{
}
#endif /* ACE_HAS_MALLOC_STATS */

void
ACE_New_Allocator::dump (void) const
{
#if defined (ACE_HAS_DUMP)
#endif /* ACE_HAS_DUMP */
}

/******************************************************************************/

void *
ACE_Static_Allocator_Base::malloc (size_t nbytes)
{
  if (this->offset_ + nbytes > this->size_)
    {
      errno = ENOMEM;
      return 0;
    }
  else
    {
      // Record the current offset, increment the offset by the number
      // of bytes requested, and return the original offset.
      char *ptr = &this->buffer_[this->offset_];
      this->offset_ += nbytes;
      return (void *) ptr;
    }
}

void *
ACE_Static_Allocator_Base::calloc (size_t nbytes,
                                   char initial_value)
{
  void *ptr = this->malloc (nbytes);

  ACE_OS::memset (ptr, initial_value, nbytes);
  return (void *) ptr;
}

void *
ACE_Static_Allocator_Base::calloc (size_t n_elem,
                                   size_t elem_size,
                                   char initial_value)
{
  return this->calloc (n_elem * elem_size, initial_value);
}

void
ACE_Static_Allocator_Base::free (void *ptr)
{
  // Check to see if ptr is within our pool?!
  ACE_UNUSED_ARG (ptr);
  ACE_ASSERT (ptr >= this->buffer_ && ptr < this->buffer_ + this->size_);
}

int
ACE_Static_Allocator_Base::remove (void)
{
  return -1;
}

int
ACE_Static_Allocator_Base::bind (const char *, void *, int)
{
  return -1;
}

int
ACE_Static_Allocator_Base::trybind (const char *, void *&)
{
  return -1;
}

int
ACE_Static_Allocator_Base::find (const char *, void *&)
{
  return -1;
}

int
ACE_Static_Allocator_Base::find (const char *)
{
  return -1;
}

int
ACE_Static_Allocator_Base::unbind (const char *)
{
  return -1;
}

int
ACE_Static_Allocator_Base::unbind (const char *, void *&)
{
  return -1;
}

int
ACE_Static_Allocator_Base::sync (ssize_t, int)
{
  return -1;
}

int
ACE_Static_Allocator_Base::sync (void *, size_t, int)
{
  return -1;
}

int
ACE_Static_Allocator_Base::protect (ssize_t, int)
{
  return -1;
}

int
ACE_Static_Allocator_Base::protect (void *, size_t, int)
{
  return -1;
}

#if defined (ACE_HAS_MALLOC_STATS)
void
ACE_Static_Allocator_Base::print_stats (void) const
{
}
#endif /* ACE_HAS_MALLOC_STATS */

void
ACE_Static_Allocator_Base::dump (void) const
{
#if defined (ACE_HAS_DUMP)
  ACE_TRACE ("ACE_Static_Allocator_Base::dump");

  ACE_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\noffset_ = %d"), this->offset_));
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\nsize_ = %d\n"), this->size_));
  ACE_HEX_DUMP ((LM_DEBUG, this->buffer_, this->size_));
  ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n")));

  ACE_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}

ACE_END_VERSIONED_NAMESPACE_DECL


text:
package com.foc.web.modules.business;

import com.foc.desc.FocObject;
import com.foc.desc.dataModelTree.DataModelNodeDesc;
import com.foc.desc.dataModelTree.DataModelNodeList;
import com.foc.desc.dataModelTree.DataModelNodeTree;
import com.foc.formula.AbstractFormulaEnvironment;
import com.foc.formula.PropertyFormula;
import com.foc.formula.PropertyFormulaContext;
import com.foc.formula.PropertyFormulaDesc;
import com.foc.list.FocList;
import com.foc.property.FProperty;
import com.foc.shared.xmlView.XMLViewKey;
import com.foc.vaadin.FocWebApplication;
import com.foc.vaadin.ICentralPanel;
import com.foc.vaadin.gui.FVIconFactory;
import com.foc.vaadin.gui.components.FVButton;
import com.foc.vaadin.gui.components.FVLabel;
import com.foc.vaadin.gui.components.FVTextField;
import com.foc.vaadin.gui.components.ITableTree;
import com.foc.vaadin.gui.components.treeGrid.FVTreeGrid;
import com.foc.vaadin.gui.xmlForm.FocXMLLayout;
import com.foc.web.gui.INavigationWindow;
import com.foc.web.server.xmlViewDictionary.XMLViewDictionary;
import com.vaadin.event.FieldEvents.BlurEvent;
import com.vaadin.event.FieldEvents.BlurListener;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Table;
import com.vaadin.ui.themes.BaseTheme;

@SuppressWarnings("serial")
public class FocFormula_Form extends FocXMLLayout {

  private ITableTree tableTree = null;
  private FProperty selectedProperty = null;
  private FVTextField textField = null;
  private FVLabel expressionLabel = null;
  private FVButton appendButton = null;
  private AbstractFormulaEnvironment formulaEnvironment = null;

  private Object focObjectRowId = null;

  @Override
  public void dispose() {
    tableTree = null;
    selectedProperty = null;

    if (textField != null) {
      textField.dispose();
    }
    textField = null;

    if (expressionLabel != null) {
      expressionLabel.dispose();
    }
    expressionLabel = null;

    if (appendButton != null) {
      appendButton.dispose();
    }
    appendButton = null;
    super.dispose();
  }

  @Override
  protected void afterLayoutConstruction() {

    // The text field of the formula
    textField = (FVTextField) getComponentByName("TEXT_FIELD");
//    textField.setColumns(30);
//    setExpandRatio(textField, 1);

    // The label of the formula
    expressionLabel = (FVLabel) getComponentByName("LABEL");

    // The add button of the formula
    appendButton = (FVButton) getComponentByName("ADD");
    appendButton.setStyleName(BaseTheme.BUTTON_LINK);
    //appendButton.setIcon(FVIconFactory.getInstance().getFVIcon_Big(FVIconFactory.ICON_FORMULA));
    appendButton.setIcon(FVIconFactory.getInstance().getFVIcon_Small(FVIconFactory.ICON_EDIT));
    appendButton.addClickListener(new ClickListener() {

      @Override
      public void buttonClick(ClickEvent event) {
        String fieldPath = popupFieldSelection();
        if (fieldPath != null){
          textField.setValueString(textField.getValueString() + fieldPath);
        }
        textField.focus();
      }
    });
  }

  public FProperty getSelectedProperty() {
    return selectedProperty;
  }

  public ITableTree getTableOrTree() {
    return tableTree;
  }

  public void setTableOrTree(ITableTree tableTree) {
    this.tableTree = tableTree;
  }

  public Table getTable() {
    Table result = null;
    if (tableTree != null) {
      result = (Table) tableTree;
    }
    return result;
  }

  public AbstractFormulaEnvironment getFormulaEnvironment() {
    return formulaEnvironment;
  }

  public void setFormulaEnvironment(AbstractFormulaEnvironment fe) {
    this.formulaEnvironment = fe;
  }

  public FVTextField getTextField(){
    return textField;
  }

  public FVLabel getExpressionLabel(){
    return expressionLabel;
  }

  /**
   * This method needs to be called to initialize the table and the formula
   * environment
   *
   * @param table
   *          The ITableTree to apply formulas to.
   * @param forEnv
   *          The formula environment.
   */
  public void initialize(ITableTree table, AbstractFormulaEnvironment forEnv) {
    setTableOrTree(table);
    setFormulaEnvironment(forEnv);
    initializeTextFieldListener();
  }

  private void initializeTextFieldListener() {
    if (textField != null) {
      textField.addBlurListener(new BlurListener() {

        @Override
        public void blur(BlurEvent event) {
        	applyTextFieldFormulaInTheProperty();
        }
      });
    }
  }

	public void applyTextFieldFormulaInTheProperty(){
	  if (selectedProperty != null) {
	    if (!selectedProperty.isWithFormula() && !textField.getValueString().equals("")) {
	      formulaEnvironment.applyFormulaToProperty(selectedProperty, "");
	    }

	    PropertyFormulaContext propertyFormulaContext = selectedProperty.getPropertyFormulaContext();
	    if (propertyFormulaContext != null) {
	      PropertyFormula propertyFormula = propertyFormulaContext.getPropertyFormula();
	      if (propertyFormula != null) {
	        // A listener on the field expression will use the
	        // AbstractFormulaEnvironment to apply the formula
	        propertyFormula.setExpression(textField.getValueString());
	      }
	    }
      selectedProperty.notifyListeners();
	  }
	}

  public FocObject getSelectedFocObject() {
    FocObject result = null;
    ITableTree tempTableTree = getTableOrTree();

    if (tempTableTree != null) {
      FocList list = tempTableTree.getFocList();
      if(list != null){
        if(focObjectRowId != null){
          result = list.searchByReference((Long) focObjectRowId);
        }
      }
    }
    return result;
  }

  public String popupFieldSelection() {
    String str = null;
    FocObject fatherObj = getSelectedFocObject();
    if (fatherObj != null) {
      DataModelNodeList dataModelNodeList = new DataModelNodeList(fatherObj.getThisFocDesc(), 5, fatherObj);
      DataModelNodeTree dataModelNodeTree = new DataModelNodeTree(dataModelNodeList);

      XMLViewKey xmlViewKey = new XMLViewKey(DataModelNodeDesc.getInstance().getStorageName(), XMLViewKey.TYPE_TREE);
      ICentralPanel centralPanel = XMLViewDictionary.getInstance().newCentralPanel(getMainWindow(), xmlViewKey, dataModelNodeTree);

      FocDataModel_Tree treePanel = (FocDataModel_Tree) centralPanel;
      treePanel.setFormulaLayout(this);

      INavigationWindow navigationWindow = null;
      if(FocWebApplication.getInstanceForThread().getContent() instanceof INavigationWindow){
      	navigationWindow = (INavigationWindow) FocWebApplication.getInstanceForThread().getContent();
      }else{
      	navigationWindow = getMainWindow();
      }
      if(navigationWindow != null){
      	navigationWindow.changeCentralPanelContent(centralPanel, true);
      }
    }
    return str;
  }

  public void triggerFormulaChanges(FProperty selectedProperty, Object rowId, Object columnId){

  	focObjectRowId = rowId;
    boolean fStringEditable = true;

    if (selectedProperty != null) {
      FocFormula_Form.this.selectedProperty = selectedProperty;

      PropertyFormulaContext propertyFormulaContext = selectedProperty.getPropertyFormulaContext();
      if (propertyFormulaContext != null) {
        PropertyFormula propertyFormula = propertyFormulaContext.getPropertyFormula();
        if (propertyFormula != null) {
          FProperty pfProperty = propertyFormula.getFocProperty(PropertyFormulaDesc.FLD_EXPRESSION);
          textField.setValue((String) pfProperty.getObject());
        }
      } else {
        String expression = "";
        if (selectedProperty.getFocField() != null) {
          if (selectedProperty.getFocField().getFormulaString() != null && !selectedProperty.getFocField().getFormulaString().isEmpty()) {
            expression = selectedProperty.getFocField().getFormulaString();
            fStringEditable = false;
          } else {
            // if(outputFieldFormulaGetter != null){
            // expression =
            // outputFieldFormulaGetter.getOutputFieldFormulaExpression(selectionPanel,
            // selectedProperty, row, col);
            // if(expression != null && !expression.isEmpty()){
            // fStringEditable = false;
            // }
            // }
          }
        }
        textField.setValueString(expression);
      }

      textField.setEnabled(fStringEditable);
      appendButton.setEnabled(fStringEditable);
    }

//    String rowCode = getTable().getItem(rowId).getItemProperty("CODE").toString();
    String rowCode = null;
    if(getTableOrTree() instanceof FVTreeGrid){
    	FVTreeGrid treeGrid = (FVTreeGrid) getTableOrTree();
  		if(treeGrid.getSelectedObject() != null && treeGrid.getSelectedObject().getItemProperty("CODE") != null){
  			rowCode = treeGrid.getSelectedObject().getItemProperty("CODE").getValue().toString();
  		}
    }else{
    	rowCode = getTable().getItem(rowId).getItemProperty("CODE").toString();
    }

    expressionLabel.setValue(rowCode + " : " + columnId);

  }
}


text:
package change.me.ui.fragment;

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.evgeniysharafan.utils.ui.activity.DebugSettingsActivity;

import change.me.R;

public class SettingsFragment extends PreferenceFragment {

    public static SettingsFragment newInstance() {
        return new SettingsFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.preferences);
        DebugSettingsActivity.addDebugSettingsIfNeeded(getActivity(), getPreferenceScreen(), false,
                "evgeniysharafan@gmail.com");
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        prepareActionBar();
        return view;
    }

    private void prepareActionBar() {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.action_settings);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getActivity().onBackPressed();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
require 'spec_helper'

describe RType::Helper::RObjDelegatable do
  let(:klass) do
    Class.new(Delegator) do
      include RType::Helper::RObjDelegatable

      def initialize robj=nil, ruby_obj=nil
        if robj
          @robj = robj
        else
          @ruby_obj = ruby_obj
        end
      end
    end
  end
  let(:ruby_obj) { double("ruby_obj") }
  let(:robj)     { double("robj") }
  let(:r_stub)   { double("R") }

  before do
    robj.stub(:to_ruby).with(RSRuby::BASIC_CONVERSION).and_return ruby_obj
    robj.stub(:as_r).and_return robj
    ruby_obj.stub_chain(:as_r, :robj).and_return robj
  end

  context 'has R-obj' do
    subject { klass.new robj, nil }

    its(:ruby_obj) { should == ruby_obj }
    its(:robj)     { should == robj }
    its(:as_r)     { should == robj }
    its(:to_ruby)  { should == ruby_obj }
    its(:inspect)  { should =~ /RType::.*robj/ }

    it 'delegate a method to R' do
      R.stub(:[]).with('+') { r_stub }
      r_stub.stub(:call).with(subject, 100).and_return 150
      expect(subject + 100).to be_eql 150
    end

    it 'delegate a method to Ruby' do
      ruby_obj.should_receive(:hoge).and_return 'Hello world'
      expect(subject.hoge).to be_eql 'Hello world'
    end
  end

  context 'has Ruby-obj' do
    subject { klass.new nil, ruby_obj }

    its(:ruby_obj) { should == ruby_obj }
    its(:robj)     { should == robj }
    its(:as_r)     { should == robj }
    its(:to_ruby)  { should == ruby_obj }
    its(:inspect)  { should =~ /RType::.*ruby_obj/ }

    it 'delegate a method to R' do
      R.stub(:[]).with('+') { r_stub }
      r_stub.stub(:call).with(subject, 100).and_return 150
      expect(subject + 100).to be_eql 150
    end

    it 'delegate a method to Ruby' do
      ruby_obj.should_receive(:hoge).and_return 'Hello world'
      expect(subject.hoge).to be_eql 'Hello world'
    end
  end
end


text:
@interface NBTableViewController ()

- (void)adjustTableView;

@property(nonatomic, assign) AirTurnKeyboardManager *keyboardManager;

@end

@implementation NBTableViewController

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setup];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    self.keyboardManager = [AirTurnKeyboardManager sharedManager];

    [self adjustTableView];

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

    [nc addObserver:self selector:@selector(event) name:UIKeyboardDidShowNotification object:nil];
    [nc addObserver:self selector:@selector(event) name:UIKeyboardDidHideNotification object:nil];
    [nc addObserver:self selector:@selector(event) name:AirTurnVirtualKeyboardDidShowNotification object:nil];
    [nc addObserver:self selector:@selector(event) name:AirTurnVirtualKeyboardDidHideNotification object:nil];
}

- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)event {
    // perform after short timeout as insets do not appear to be set immediately by tableViewController
    [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(adjustTableView) userInfo:nil repeats:NO];
}

- (void)adjustTableView {
	UITableView *v = (UITableView *)self.view;
	UIEdgeInsets i = UIEdgeInsetsMake(0, 0, self.keyboardManager.isKeyboardVisible ? self.keyboardManager.keyboardFrameIncludingBar.size.height : 0, 0);
	v.contentInset = i;
	v.scrollIndicatorInsets = i;
}

@end


text:
Additional header content

Gets a specified condition by name

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
public override BaseConditionModel GetBy(
	string name
)
```

**VB**

``` VB
Public Overrides Function GetBy (
	name As String
) As BaseConditionModel
```

#### Parameters

name

Type: System.String
Name of condition

#### Return Value
Type: BaseConditionModel
The condition specified.

## Remarks
\[Missing <remarks> documentation for "M:iTin.Export.Model.ConditionsModel.GetBy(System.String)"\]

## See Also

#### Reference
ConditionsModel Class
iTin.Export.Model Namespace


text:
/*
 * CombineElement.cs
 */

using System.IO;

using Core.Library;

namespace Core.Library.RE {

    /**
     * A regular expression combination element. This element matches
     * two consecutive elements.
     *

     *
     */
    internal class CombineElement : Element {

        /**
         * The first element.
         */
        private Element elem1;

        /**
         * The second element.
         */
        private Element elem2;

        /**
         * Creates a new combine element.
         *
         * @param first          the first element
         * @param second         the second element
         */
        public CombineElement(Element first, Element second) {
            elem1 = first;
            elem2 = second;
        }

        /**
         * Creates a copy of this element. The copy will be an
         * instance of the same class matching the same strings.
         * Copies of elements are necessary to allow elements to cache
         * intermediate results while matching strings without
         * interfering with other threads.
         *
         * @return a copy of this element
         */
        public override object Clone() {
            return new CombineElement(elem1, elem2);
        }

        /**
         * Returns the length of a matching string starting at the
         * specified position. The number of matches to skip can also be
         * specified, but numbers higher than zero (0) cause a failed
         * match for any element that doesn't attempt to combine other
         * elements.
         *
         * @param m              the matcher being used
         * @param buffer         the input character buffer to match
         * @param start          the starting position
         * @param skip           the number of matches to skip
         *
         * @return the length of the longest matching string, or
         *         -1 if no match was found
         *
         * @throws IOException if an I/O error occurred
         */
        public override int Match(Matcher m,
                                  ReaderBuffer buffer,
                                  int start,
                                  int skip) {

            int  length1 = -1;
            int  length2 = 0;
            int  skip1 = 0;
            int  skip2 = 0;

            while (skip >= 0) {
                length1 = elem1.Match(m, buffer, start, skip1);
                if (length1 < 0) {
                    return -1;
                }
                length2 = elem2.Match(m, buffer, start + length1, skip2);
                if (length2 < 0) {
                    skip1++;
                    skip2 = 0;
                } else {
                    skip2++;
                    skip--;
                }
            }

            return length1 + length2;
        }

        /**
         * Prints this element to the specified output stream.
         *
         * @param output         the output stream to use
         * @param indent         the current indentation
         */
        public override void PrintTo(TextWriter output, string indent) {
            elem1.PrintTo(output, indent);
            elem2.PrintTo(output, indent);
        }
    }
}


text:
primes-test
===========
### Authors

* Qiaosong Dong <qdong@clemson.edu>
* Jared Klingenberger <klinge2@clemson.edu>

Project files for our team project of calculating primality of very large
numbers using distributed workload assignments in MPI.

This program was written for CpSc 3620 (Distributed Programming) at Clemson
University.


text:
ImageJ macro for quantification of polarized light images of picrosirius red stained tissues.

-----PS RED QUANTIFICATION-----/
Written 2017-03-08 by Josette Northcott for Weaver Lab use.
This is version 1.1 of this ImageJ macro (updated 2017-03-24 by J.Northcott).

-----VERSION NOTES-----/
Version 1.1 changes: Intensity measurements confined to user defined area (set by threshold).
Requires ImageJ version 1.50i.

-----INPUT DIRECTORY-----/
User input impage directory can contain:
- Only  polarized light images, OR
- Brightfield and polarized light images. In this case, the folder must contain the same number of brightfield and polarized light images
AND the order of the images must be either:
	- Alternating brightfield then polarized light for each image.
	- Alternating polarized light then brightfield for each image.
	- All brightfield and then all polarized light images.
	- All polarized light and then all brightfield images.

-----THRESHOLD-----/
The user defined threshold is set using the first image, and then applied to all subsequent images.

-----RESULTS-----/
The results window is selected and saved as a (tab delimited) text file.
The results are also copied to the clipboard for quick & easy pasting into excel.

-----SAMPLE DATA-----/
 	Label  				Area	Mean  	IntDen	%Area 	RawIntDen	MinThr	MaxThr
1	10070 pic 1 PS 			90655	42.551	3857487	6.262 	3857487		18    	255
2	10070 pic 1 PS:COL:Red		90655	57.421	5205521	100.000	5205521		0     	255
3	10070 pic 1 PS:COL:Green	90655	52.911	4796610	99.986	4796610		0     	255

-----QUANTIFICATION-----/
Amount of collagen per field = PS %Area
Ratio of collagen fiber types = (PS:COL:Red IntDen)/(PS:COL:Green IntDen)


text:
namespace OffByOne.Qls.Tests.Ast.Style.Properties
{
    using System;

    using OffByOne.Qls.Ast.Style.Literals;
    using OffByOne.Qls.Ast.Style.Properties;

    using Xunit;

    public class FontStylePropertyTests
    {
        [Fact]
        public void CreatingNewObject_ShouldHaveCorrectValueIfCorectDataGiven()
        {
            var actual = new FontStyleProperty(new StringLiteral("Fancy"));

            Assert.Equal("Fancy", actual.Value.Value);
        }

        [Fact]
        public void CreatingNewObject_ShouldThrowExceptionWhenIncorrectDataGiven()
        {
            Assert.Throws<ArgumentNullException>(() => new FontStyleProperty(null));
        }
    }
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm, reset } from 'redux-form';
import { validate } from './validationHelper';
import { renderInputField, renderTextAreaField, renderSelectField } from "../../utils/formHelper";
import './PostForm.css';

const FORM_NAME = 'post-form';

class PostForm extends Component {
  render() {
    const { handleSubmit, submitting, pristine, reset, onSubmit, categories, isEdit } = this.props;
    const options = categories ? categories.map(category => ({ label: category.name, value: category.path })) : [];
    return (
      <div className="PostForm-container">
        <form onSubmit={handleSubmit((values) => onSubmit(values))}>
          <Field
            name="title"
            type="text"
            component={renderInputField}
            label="Title *"
            placeholder="Enter the title here"
          />
          <Field
            name="body"
            type="text"
            component={renderTextAreaField}
            label="Body *"
            placeholder="Enter the body here"
            rows="5"
          />
          <Field
            name="author"
            type="text"
            component={renderInputField}
            label="Author *"
            placeholder="Enter your name here"
            disabled={isEdit}
          />
          <Field
            name="category"
            component={renderSelectField}
            label="Category *"
            options={options}
            disabled={isEdit}
          />
          <button className="btn btn-primary" type="submit" disabled={submitting}>
            Submit
          </button>
          <button className="btn btn-secondary" type="button" disabled={pristine || submitting} onClick={reset}>
            Reset
          </button>
        </form>
      </div>
    );
  }
}
PostForm.propTypes = {
  handleSubmit: PropTypes.func,
  submitting: PropTypes.bool,
  pristine: PropTypes.bool,
  reset: PropTypes.func,
  onSubmit: PropTypes.func,
  categories: PropTypes.array,
  isEdit: PropTypes.bool,
};
export default reduxForm({
  form: FORM_NAME,
  validate,
  enableReinitialize: true,
  onSubmitSuccess: (result, dispatch) => dispatch(reset(FORM_NAME)),
})(PostForm);


text:
int main(int argc, char * argv[]) {
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([ALRAppDelegate class]));
    }
}


text:
package org.hibernate.testing.cache;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.hibernate.cache.CacheException;
import org.hibernate.cache.spi.Region;

/**
 * @author Strong Liu
 */
class BaseRegion implements Region {
	protected final Map cache = new ConcurrentHashMap();
	private final String name;
	private static int timeout = Timestamper.ONE_MS * 60000;  //60s

	BaseRegion(String name) {
		this.name = name;
	}

	@Override
	public boolean contains(Object key) {
		return key != null ? cache.containsKey( key ) : false;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public void destroy() throws CacheException {
		cache.clear();
	}

	@Override
	public long getSizeInMemory() {
		return -1;
	}

	@Override
	public long getElementCountInMemory() {
		return cache.size();
	}

	@Override
	public long getElementCountOnDisk() {
		return 0;
	}

	@Override
	public Map toMap() {
		return Collections.unmodifiableMap( cache );
	}

	@Override
	public long nextTimestamp() {
		return Timestamper.next();
	}

	@Override
	public int getTimeout() {
		return timeout;
	}

}


text:
'use strict';

module.exports = {
  up: function (queryInterface, Sequelize) {

      return queryInterface.bulkInsert('Quizzes', [
         { question: 'Capital de Italia', answer: 'Roma',
           createdAt: new Date(), updatedAt: new Date() },
         { question: 'Capital de España', answer: 'Madrid',
           createdAt: new Date(), updatedAt: new Date() },
         { question: 'Mi Edad', answer: '20',
           createdAt: new Date(), updatedAt: new Date() }

        ]);
  },

  down: function (queryInterface, Sequelize) {
      return queryInterface.bulkDelete('Quizzes', null, {});
  }
};

/* NOTES:

id isnt required because it is autogenerated.

*/


text:
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------

using System.Runtime.InteropServices;

namespace Microsoft.WindowsAzure.MobileServices
{
    /// <summary>
    /// Implements the <see cref="IPlatform"/> interface for the Windows
    /// Phone platform.
    /// </summary>
    internal class PlatformInformation : IPlatformInformation
    {
        /// <summary>
        /// A singleton instance of the <see cref="ApplicationStorage"/>.
        /// </summary>
        public static IPlatformInformation Instance { get; } = new PlatformInformation();

        /// <summary>
        /// The architecture of the platform.
        /// </summary>
        public string OperatingSystemArchitecture => RuntimeInformation.OSArchitecture.ToString();

        /// <summary>
        /// The name of the operating system of the platform.
        /// </summary>
        public string OperatingSystemName => RuntimeInformation.OSDescription;

        /// <summary>
        /// The version of the operating system of the platform.
        /// </summary>
        public string OperatingSystemVersion => Platform.UnknownValueString;

        /// <summary>
        /// Indicated whether the device is an emulator or not
        /// </summary>
        public bool IsEmulator => false;

        public string Version => this.GetVersionFromAssemblyFileVersion();
    }
}


text:
namespace Microsoft.Azure.Management.HDInsight.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// This class represent a single filter object that defines a
    /// multidimensional set. The dimensions of this set are Regions,
    /// ClusterFlavors, NodeTypes and ClusterVersions. The constraint should be
    /// defined based on the following: FilterMode (Exclude vs Include),
    /// VMSizes (the vm sizes in affect of exclusion/inclusion) and the
    /// ordering of the Filters. Later filters override previous settings if
    /// conflicted.
    /// </summary>
    public partial class VmSizeCompatibilityFilterV2
    {
        /// <summary>
        /// Initializes a new instance of the VmSizeCompatibilityFilterV2
        /// class.
        /// </summary>
        public VmSizeCompatibilityFilterV2()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the VmSizeCompatibilityFilterV2
        /// class.
        /// </summary>
        /// <param name="filterMode">The filtering mode. Effectively this can
        /// enabling or disabling the VM sizes in a particular set. Possible
        /// values include: 'Exclude', 'Include'</param>
        /// <param name="regions">The list of regions under the effect of the
        /// filter.</param>
        /// <param name="clusterFlavors">The list of cluster flavors under the
        /// effect of the filter.</param>
        /// <param name="nodeTypes">The list of node types affected by the
        /// filter.</param>
        /// <param name="clusterVersions">The list of cluster versions affected
        /// in Major.Minor format.</param>
        /// <param name="osType">The OSType affected, Windows or Linux.</param>
        /// <param name="vmSizes">The list of virtual machine sizes to include
        /// or exclude.</param>
        public VmSizeCompatibilityFilterV2(string filterMode = default(string), IList<string> regions = default(IList<string>), IList<string> clusterFlavors = default(IList<string>), IList<string> nodeTypes = default(IList<string>), IList<string> clusterVersions = default(IList<string>), IList<OSType?> osType = default(IList<OSType?>), IList<string> vmSizes = default(IList<string>))
        {
            FilterMode = filterMode;
            Regions = regions;
            ClusterFlavors = clusterFlavors;
            NodeTypes = nodeTypes;
            ClusterVersions = clusterVersions;
            OsType = osType;
            VmSizes = vmSizes;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets the filtering mode. Effectively this can enabling or
        /// disabling the VM sizes in a particular set. Possible values
        /// include: 'Exclude', 'Include'
        /// </summary>
        [JsonProperty(PropertyName = "filterMode")]
        public string FilterMode { get; set; }

        /// <summary>
        /// Gets or sets the list of regions under the effect of the filter.
        /// </summary>
        [JsonProperty(PropertyName = "regions")]
        public IList<string> Regions { get; set; }

        /// <summary>
        /// Gets or sets the list of cluster flavors under the effect of the
        /// filter.
        /// </summary>
        [JsonProperty(PropertyName = "clusterFlavors")]
        public IList<string> ClusterFlavors { get; set; }

        /// <summary>
        /// Gets or sets the list of node types affected by the filter.
        /// </summary>
        [JsonProperty(PropertyName = "nodeTypes")]
        public IList<string> NodeTypes { get; set; }

        /// <summary>
        /// Gets or sets the list of cluster versions affected in Major.Minor
        /// format.
        /// </summary>
        [JsonProperty(PropertyName = "clusterVersions")]
        public IList<string> ClusterVersions { get; set; }

        /// <summary>
        /// Gets or sets the OSType affected, Windows or Linux.
        /// </summary>
        [JsonProperty(PropertyName = "osType")]
        public IList<OSType?> OsType { get; set; }

        /// <summary>
        /// Gets or sets the list of virtual machine sizes to include or
        /// exclude.
        /// </summary>
        [JsonProperty(PropertyName = "vmSizes")]
        public IList<string> VmSizes { get; set; }

    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
|	example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
|	https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
|	$route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
|	$route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
|	$route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples:	my-controller/index	-> my_controller/index
|		my-controller/my-method	-> my_controller/my_method
*/

/////PUBLIC ROUTE///////////

$route['index'] = 'Home_Controller/index';
$route['scholarship'] = 'Home_Controller/scholarship';
$route['contact'] = 'Home_Controller/contact';
$route['registration'] = 'Home_Controller/registration';
$route['registration/submit'] = 'Home_Controller/add_application';

///////Admin//////////
//user//

$route['login'] = 'Admin_Controller/login';

$route['dashboard/login'] = 'User_Controller/verify_login';

$route['logout'] = 'User_Controller/logout';

$route['dashboard/login'] = 'Admin_Controller/login';
$route['dashboard'] = 'Department_Controller';

$route['dashboard/logout'] = 'User_Controller/logout';
$route['dashboard/test'] = 'User_Controller/test';

/*Applications*/

$route['dashboard/applications'] = 'Admin_Controller/view_application';
$route['dashboard/applications/accept/(:num)'] = 'Admin_Controller/accept/$1';
$route['dashboard/applications/selected'] = 'Admin_Controller/view_selected';
$route['dashboard/applications/delete/(:num)'] = 'Admin_Controller/delete/$1';

$route['dashboard/applications/approve/(:num)'] = 'Admin_Controller/approve/$1';
$route['dashboard/applications/reject/(:num)'] = 'Admin_Controller/reject/$1';

$route['dashboard/applications/approved'] = 'Admin_Controller/view_approved';

/*department*/

$route['dashboard/department'] = 'Department_Controller';
$route['dashboard/department/view/(:num)'] = 'Department_Controller/view/$1';
$route['dashboard/department/delete/(:num)'] = 'Department_Controller/delete/$1';
$route['dashboard/department/add'] = 'Department_Controller/add';

/*course*/
$route['dashboard/department/view/(:num)/course/add'] = 'Course_Controller/add';
$route['dashboard/department/course/(:num)'] = 'Course_Controller/view/$1';
$route['dashboard/department/course/delete/(:num)'] = 'Course_Controller/delete/$1';

/*subject*/
$route['dashboard/department/course/subject/add'] = 'Semester_Subject_Controller/add';
$route['dashboard/department/course/semester/subject/delete/(:num)'] = 'Semester_Subject_Controller/delete/$1';

/*semester*/
$route['dashboard/semester'] = 'Admin_Controller/add_semester';
$route['dashboard/department/course/semester/add'] = 'Semester_Controller/add';
$route['dashboard/department/course/semester/delete/(:num)'] = 'Semester_Controller/delete/$1';
$route['dashboard/department/course/semester/view/(:num)'] = 'Semester_Controller/view/$1';

///////////////

/*staff*/
//$route['dashboard/view_staff/(:num)'] = 'Staff_Controller/view/$1';
$route['dashboard/add_staff']='Admin_Controller/add_staff';
$route['dashboard/staff']='Admin_Controller/view_staffs';
$route['dashboard/staff/add']='Staff_Controller/add';
$route['dashboard/staff/delete/(:num)']='Staff_Controller/delete/$1';

/*exam*/
$route['dashboard/exam'] = 'Admin_Controller/view_exam';
$route['dashboard/exam/add'] = 'Exam_controller/add';
$route['dashboard/exam/delete/(:num)'] = 'Exam_controller/delete/$1';

/*attendence*/
$route['dashboard/attendance'] = 'Admin_Controller/view_attendence';
$route['dashboard/attendance/add'] = 'Attendence_Controller/add_attendence';

/*subject*/
$route['dashboard/subjects'] = 'Admin_Controller/add_subject';
$route['dashboard/subjects/add'] = 'Subject_Controller/add';

/*payroll*/

$route['dashboard/payroll'] = 'Admin_Controller/view_payroll';
$route['dashboard/payroll/add'] = 'Payroll_Controller/add';

/*student_details*/
$route['dashboard/students'] = 'Student_Details_Controller';
$route['dashboard/students/view'] = 'Admin_Controller/view_student_details';
$route['dashboard/students/search'] = 'Student_Details_Controller/search';
$route['dashboard/students/add'] = 'Student_Details_Controller/add';
$route['dashboard/students/add/submit'] = 'Student_Details_Controller/submit';

$route['dashboard/students/add/(:num)'] = 'Student_Details_Controller/add_dir/$1';
//$route['dashboard/payroll'] = 'Payroll_Controller/view';

/*subjects*/
$route['dashboard/subjects'] = 'Admin_Controller/add_subject';

/*application routes*/
$route['default_controller'] = 'Home_Controller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;


text:
package io.iansoft.blockchain.service.impl;

import io.iansoft.blockchain.domain.Coin;
import io.iansoft.blockchain.domain.MarketCoin;
import io.iansoft.blockchain.domain.Ticker;
import io.iansoft.blockchain.repository.MarketCoinRepository;
import io.iansoft.blockchain.repository.TickerRepository;
import io.iansoft.blockchain.repository.search.MarketCoinSearchRepository;
import io.iansoft.blockchain.service.MarketCoinService;
import io.iansoft.blockchain.service.dto.CoinDTO;
import io.iansoft.blockchain.service.dto.MarketCoinDTO;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;

/**
 * Service Implementation for managing MarketCoin.
 */
@Service
@Transactional
public class MarketCoinServiceImpl implements MarketCoinService {

    private final Logger log = LoggerFactory.getLogger(MarketCoinServiceImpl.class);

    private final MarketCoinRepository marketCoinRepository;

    private final TickerRepository tickerRepository;

//    private final MarketMapper marketMapper;
    private final ModelMapper modelMapper;
    private final MarketCoinSearchRepository marketCoinSearchRepository;

    public MarketCoinServiceImpl(MarketCoinRepository marketCoinRepository, TickerRepository tickerRepository, ModelMapper modelMapper, MarketCoinSearchRepository marketCoinSearchRepository) {
        this.marketCoinRepository = marketCoinRepository;
        this.tickerRepository = tickerRepository;
        this.modelMapper = modelMapper;
        this.marketCoinSearchRepository = marketCoinSearchRepository;
    }

    /**
     * Save a market.
     *
     * @param marketCoinDTO the entity to save
     * @return the persisted entity
     */
    @Override
    public MarketCoinDTO save(MarketCoinDTO marketCoinDTO) {
        log.debug("Request to save MarketCoin : {}", marketCoinDTO);
        MarketCoin marketCoin = modelMapper.map(marketCoinDTO, MarketCoin.class);
        marketCoin = marketCoinRepository.save(marketCoin);
        MarketCoinDTO result = modelMapper.map(marketCoin, MarketCoinDTO.class);
        marketCoinSearchRepository.save(marketCoin);
        return result;
    }

    /**
     * Get all the marketCoins.
     *
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public List<MarketCoinDTO> findAll() {
        log.debug("Request to get all MarketCoins");
        return marketCoinRepository.findAll().stream()
            .map( x -> modelMapper.map(x,MarketCoinDTO.class))
            .collect(Collectors.toCollection(LinkedList::new));
    }

    /**
     * Get one marketCoin by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public MarketCoinDTO findOne(Long id) {
        log.debug("Request to get MarketCoin : {}", id);
        MarketCoin marketCoin = marketCoinRepository.findOne(id);
        return modelMapper.map(marketCoin, MarketCoinDTO.class);
    }

    /**
     * Delete the marketCoin by id.
     *
     * @param id the id of the entity
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete MarketCoin : {}", id);
        marketCoinRepository.delete(id);
        marketCoinSearchRepository.delete(id);
    }

    /**
     * Search for the marketCoin corresponding to the query.
     *
     * @param query the query of the search
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public List<MarketCoinDTO> search(String query) {
        log.debug("Request to search Markets for query {}", query);
        return StreamSupport
            .stream(marketCoinSearchRepository.search(queryStringQuery(query)).spliterator(), false)
            .map(x->modelMapper.map(x,MarketCoinDTO.class))
            .collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly = true)
    public List<MarketCoinDTO> findMarketCoinAll(long marketId, long userId) {
        List<MarketCoin> marketCoins = marketCoinRepository.findAllByMarketId(marketId);
        List<Ticker> tickers = tickerRepository.findAllByUserId(userId);
        marketCoins.removeIf(x-> tickers.stream().anyMatch(y->y.getMarketCoin().equals(x)));

        return marketCoins.stream().map(marketCoin -> modelMapper.map(marketCoin,MarketCoinDTO.class))
                             .collect(Collectors.toCollection(LinkedList::new));
    }
}


text:
package org.apache.camel.component.slack;

import org.apache.camel.Consumer;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePattern;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.slack.helper.SlackMessage;
import org.apache.camel.impl.DefaultEndpoint;
import org.apache.camel.impl.ScheduledPollEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.UriEndpoint;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriPath;
import org.apache.camel.util.ObjectHelper;
import org.json.simple.JSONObject;

/**
 * The slack component allows you to send messages to Slack.
 */
@UriEndpoint(firstVersion = "2.16.0", scheme = "slack", title = "Slack", syntax = "slack:channel", label = "social")
public class SlackEndpoint extends ScheduledPollEndpoint {

    @UriPath
    @Metadata(required = "true")
    private String channel;
    @UriParam(label = "producer")
    private String webhookUrl;
    @UriParam(label = "producer", secret = true)
    private String username;
    @UriParam(label = "producer")
    private String iconUrl;
    @UriParam(label = "producer")
    private String iconEmoji;
    @UriParam(label = "consumer", secret = true)
    private String token;
    @UriParam(label = "consumer", defaultValue = "10")
    private String maxResults = "10";

    /**
     * Constructor for SlackEndpoint
     *
     * @param uri the full component url
     * @param channelName the channel or username the message is directed at
     * @param component the component that was created
     */
    public SlackEndpoint(String uri, String channelName, SlackComponent component) {
        super(uri, component);
        this.webhookUrl = component.getWebhookUrl();
        this.channel = channelName;
    }

    @Override
    public Producer createProducer() throws Exception {
        SlackProducer producer = new SlackProducer(this);
        return producer;
    }

    @Override
    public Consumer createConsumer(Processor processor) throws Exception {
        if (ObjectHelper.isEmpty(token)) {
            throw new RuntimeCamelException("Missing required endpoint configuration: token must be defined for Slack consumer");
        }
        SlackConsumer consumer = new SlackConsumer(this, processor);
        configureConsumer(consumer);
        return consumer;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    /**
     * The incoming webhook URL
     */
    public void setWebhookUrl(String webhookUrl) {
        this.webhookUrl = webhookUrl;
    }

    public String getWebhookUrl() {
        return webhookUrl;
    }

    public String getChannel() {
        return channel;
    }

    /**
     * The channel name (syntax #name) or slackuser (syntax @userName) to send a
     * message directly to an user.
     */
    public void setChannel(String channel) {
        this.channel = channel;
    }

    public String getUsername() {
        return username;
    }

    /**
     * This is the username that the bot will have when sending messages to a
     * channel or user.
     */
    public void setUsername(String username) {
        this.username = username;
    }

    public String getIconUrl() {
        return iconUrl;
    }

    /**
     * The avatar that the component will use when sending message to a channel
     * or user.
     */
    public void setIconUrl(String iconUrl) {
        this.iconUrl = iconUrl;
    }

    public String getIconEmoji() {
        return iconEmoji;
    }

    /**
     * Use a Slack emoji as an avatar
     */
    public void setIconEmoji(String iconEmoji) {
        this.iconEmoji = iconEmoji;
    }

    public String getToken() {
        return token;
    }

    /**
     * The token to use
     */
    public void setToken(String token) {
        this.token = token;
    }

    public String getMaxResults() {
        return maxResults;
    }

    /**
     * The Max Result for the poll
     */
    public void setMaxResults(String maxResult) {
        this.maxResults = maxResult;
    }

    public Exchange createExchange(JSONObject object) {
        return createExchange(getExchangePattern(), object);
    }

    public Exchange createExchange(ExchangePattern pattern, JSONObject object) {
        Exchange exchange = super.createExchange(pattern);
        SlackMessage slackMessage = new SlackMessage();
        String text = (String)object.get("text");
        String username = (String)object.get("username");
        slackMessage.setText(text);
        slackMessage.setUsername(username);
        if (ObjectHelper.isNotEmpty((JSONObject)object.get("icons"))) {
            JSONObject icons = (JSONObject)object.get("icons");
            if (ObjectHelper.isNotEmpty((String)icons.get("emoji"))) {
                slackMessage.setIconEmoji((String)icons.get("emoji"));
            }
        }
        Message message = exchange.getIn();
        message.setBody(slackMessage);
        return exchange;
    }
}


text:
import os
import json

class File_Writer:

    def write_candidate_questions(self, content, file_name):
        '''
        @usage: write document length to local storage
        @arg content: content need to write
        '''
        with open(file_name, 'w') as c:
            json.dump(content, c)


text:
from django.conf.urls import patterns, include, url

urlpatterns = patterns('licenses.views',
    url(r'^$', 'index', name='index'),
    url(r'^available/(?P<key>.+)', 'available'),
    url(r'^available/(?P<key>.+)(?P<item_name>[^/]+)$', 'available'),
    url(r'^usage/$', 'usage'),
    url(r'^usage/(?P<item_name>[^/]+)$', 'usage'),
    #Edit License
    url(r'^edit/(?P<license_id>.+)/', 'edit_license', name='edit_license'),
    #Delete License
    url(r'^delete/(?P<license_id>.+)/', 'delete_license', name='delete_license'),
    # New License
    url(r'^new/', 'new_license', name='new_license'),
)


text:
<?php

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use common\models\Member;
use common\models\Notification;

/**
 * This is the model class for table "follow".
 *
 * @property integer $follow_id
 * @property integer $member_id_followed
 * @property integer $member_id_following
 * @property integer $delete_flag
 * @property string $updated_date
 * @property string $created_date
 */
class Follow extends \yii\db\ActiveRecord
{
    const FOLLOW_ACTIVE = 0;
    const FOLLOW_DELETED = 1;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'follow';
    }

    const SCENARIO_FOLLOW = 'follow';

    public function behaviors()
    {
        return [
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                          ActiveRecord::EVENT_BEFORE_INSERT => ['created_date'],
                          ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_date'],
                ],
                'value' => date('Y-m-d H:i:s'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['member_id_followed', 'member_id_following'], 'required'],
            [['member_id_following'], 'validateFollowing', 'on' => self::SCENARIO_FOLLOW],
            [['member_id_followed', 'member_id_following', 'delete_flag'], 'integer'],
            [['updated_date', 'created_date'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'follow_id' => 'Follow ID',
            'member_id_followed' => 'Member Id Followed',
            'member_id_following' => 'Member Id Following',
            'delete_flag' => 'Delete Flag',
            'updated_date' => 'Updated Date',
            'created_date' => 'Created Date',
        ];
    }

    public function validateFollowing($attribute)
    {
        $member = Member::findOne(['member_id' => $this->member_id_following]);
        $follow = Follow::findOne(['member_id_followed' => $this->member_id_followed, 'member_id_following' => $this->member_id_following, 'delete_flag' => 0]);
        if ($follow || !$member || ($this->member_id_following == $this->member_id_followed)) {
            $this->addError($attribute, \Yii::t('app', 'existing',['attribute' => $this->attributeLabels()[$attribute]]));
        }
    }

    /*
     * Get list follow
     *
     * Auth :
     * Create : 28-02-2017
     */

    public function getListFollow($memberId, $limit, $offset){
        $query = new \yii\db\Query();
        $query->select(['member.*'])
                ->from('follow');
        $query->join('INNER JOIN', 'member', 'follow.member_id_following = member.member_id');
        $query->where(['=', 'follow.delete_flag', 0]);
        $query->andWhere(['=', 'follow.member_id_followed', $memberId]);
        $query->offset($offset);
        $query->limit($limit);
        return $query->all();
    }

    /*
     * Get list Following
     *
     * Auth :
     * Create : 28-02-2017
     */

    public function getListFollowing($limit, $offset){
        $query = new \yii\db\Query();
        $query->select(['member.*'])
                ->from('follow');
        $query->join('INNER JOIN', 'member', 'follow.member_id_followed = member.member_id');
        $query->where(['=', 'follow.delete_flag', self::FOLLOW_ACTIVE]);
        $query->andWhere(['=', 'follow.member_id_following', Yii::$app->user->identity->member_id]);
        $query->offset($offset);
        $query->limit($limit);
        return $query->all();
    }

    /*
     * check follow
     *
     * Auth :
     * Created : 26-03-2017
     */
    public static function checkFollowing($memberId)
    {
        $idFollow  = Follow::findOne(['member_id_following' => $memberId, 'member_id_followed' => Yii::$app->user->identity->member_id, 'delete_flag' => self::FOLLOW_ACTIVE]);
        if (!$idFollow) {
            return false;
        }
        return true;
    }

    /*
     * Get total followed
     *
     * Auth :
     * Creat : 28-02-2017
     */

    public static function getTotalFollowedByMember($memberId)
    {
        return Follow::find()->where(['member_id_followed' => $memberId, 'delete_flag' => self::FOLLOW_ACTIVE])->count();
    }

    /*
     * Get total following
     *
     * Auth :
     * Creat : 28-02-2017
     */

    public static function getTotalFollowingByMember($memberId)
    {
        return Follow::find()->where(['member_id_following' => $memberId, 'delete_flag' => self::FOLLOW_ACTIVE])->count();
    }

    /*
     * save follow
     *
     * Auth :
     * Create : 20-03-2017
     */

    public function addFollow(){
        $transaction = \yii::$app->getDb()->beginTransaction();
        try {
            //save table reply
            $this->save();
            //save table notification
            $modelNotification = new Notification();
            $modelNotification->type = Notification::TYPE_FOLLOW;
            $modelNotification->related_id = $this->follow_id;
            $modelNotification->member_id = $this->member_id_following;
            $modelNotification->save();

            $transaction->commit();
            return TRUE;
        } catch (Exception $ex) {
            $transaction->rollBack();
            return FALSE;
        }
    }

    /*
     * Get info notification
     *
     * Auth :
     * Created : 06-04-2017
     */
    public static function getInforNotification($followId){
        $query = new \yii\db\Query();
        $query->select(['member.member_id','member.name', 'member_devices.device_token'])
                ->from('follow');
        $query->join('INNER JOIN', 'member', 'member.member_id = follow.member_id_followed');
        $query->join('LEFT JOIN', 'member_devices', 'member_devices.member_id = follow.member_id_followed');
        $query->where(['follow.follow_id' => $followId]);
        return $query->one();
    }
}


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : 05/07/2016, 09:48:50
    Author     : Igor
*/

.nav-bt {
    border-radius: 0px !important;
    border: 0px !important;
    border-bottom: 5px solid transparent !important;
}
.nav-bt:hover {
    background: #2d2d30 !important;
    border-color: #1e6be0 !important;
    color: #fff !important;
}
.nav-bt:focus {
    background: #1d1f22 !important;
    border-color: #003d99 !important;
    color: #fff;
}
.nav-tabs li a {
    color: #b3b3b3;
}
 /* Add a dark background color with a little bit see-through */
.navbar {
    background: #2d2d30 !important;
    font-size: 18px !important;
    text-align: justify !important;
    border: 0px !important;
    border-radius: 0px !important;
    letter-spacing: 6px;
    opacity: 0.9;
}

/*-------------------------------------*/
.search-bar {
    margin-top: 50px;
    width: 75%;
    margin-left: auto;
    margin-right: auto;
    box-shadow: 0 8px 16px -6px black;
}
/*=======================================*/
.person {
    border: 5px solid transparent;
    margin-bottom: 0px;
    /*width: 90%;
    height: 90%;*/
    opacity: 1;
}
.person:hover {
    border-color: #f1f1f1;
}
.teste {

}
@media screen and (max-device-width : 768px)
{
  .screen-text
  {
    text-align: right;
  }
}
@media screen and (min-device-width : 768px)
{
  .screen-text
  {
    text-align: center;
  }
}
/*========================================*/
.btn-group .btn {
    border-radius: 0;
    margin-left: -1px;
}
.btn-group .btn:last-child {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
}
.btn-group .form-horizontal .btn {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}
.form-horizontal .form-group {
    margin-left: 0;
    margin-right: 0;
}
.form-group .form-control:last-child {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
}

.grade {
    margin: 5px 10px 5px 10px;
}

.center-eff {
    line-height: 1.4em;
    margin-top:18px;
    text-align: center;
    -ms-text-justify: auto;
    text-justify: auto;
}


text:
using System.ComponentModel;

namespace DvachBrowser3.ViewModels
{
    /// <summary>
    /// Иконка.
    /// </summary>
    public interface IBoardInfoIcon : INotifyPropertyChanged
    {
        /// <summary>
        /// Имя.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Иконка.
        /// </summary>
        IImageSourceViewModel Icon { get; }
    }
}


text:
/*
 * hardsid.c - hardsid.c wrapper for the sdl ui.
 *
 * Written by
 *  Marco van den Heuvel <blackystardust68@yahoo.com>
 *
 * This file is part of VICE, modified from the sidplay2 sources.  It is
 * a one for all driver with real timing support via real time kernel
 * extensions or through the hardware buffering.  It supports the hardsid
 * isa/pci single/quattro and also the catweasel MK3/4.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 *  02111-1307  USA.
 *
 */

#include "vice.h"

#ifdef HAVE_HARDSID

#ifdef WINMIPS
#define UINT_PTR unsigned int
#endif

#ifdef UNIX_COMPILE
#include "../unix/hardsid.c"
#endif

#if defined(WIN32_COMPILE) && !defined(__XBOX__)
#include "../win32/hardsid.c"
#endif

#ifdef AMIGA_SUPPORT
#include "../amigaos/hardsid.c"
#endif

#endif


text:
class PermissionPromptChipModel {
 public:
  explicit PermissionPromptChipModel(
      permissions::PermissionPrompt::Delegate* delegate);
  ~PermissionPromptChipModel() = default;
  PermissionPromptChipModel(const PermissionPromptChipModel&) = delete;
  PermissionPromptChipModel& operator=(const PermissionPromptChipModel&) =
      delete;

  void ResetDelegate() { delegate_.reset(); }

  // The delegate representing the permission request
  absl::optional<permissions::PermissionPrompt::Delegate*> GetDelegate() {
    return delegate_;
  }

  const gfx::VectorIcon& GetIcon() {
    return should_display_blocked_icon_ ? *blocked_icon_ : *allowed_icon_;
  }

  std::u16string GetChipText() { return chip_text_; }
  std::u16string GetAccessibilityChipText() { return accessibility_chip_text_; }

  // Chip look
  PermissionPromptStyle GetPromptStyle() { return prompt_style_; }
  OmniboxChipTheme GetChipTheme() { return chip_theme_; }

  // Chip behaviour
  bool ShouldBubbleStartOpen() { return should_bubble_start_open_; }
  bool ShouldExpand() { return should_expand_; }

  // Permission state
  void SetShouldDismiss(bool flag) { should_dismiss_ = flag; }

  // Updates relevant properties of the model according to the chip's collapse
  // state if it's triggered automatically.
  void UpdateAutoCollapsePromptChipState(bool is_collapsed);

  bool ShouldDismiss() { return should_dismiss_; }

  bool IsExpandAnimationAllowed();

  bool CanDisplayConfirmation() { return chip_text_.length() > 0; }

  bool WasRequestAlreadyDisplayed() {
    DCHECK(delegate_.has_value());
    return delegate_.value()->WasCurrentRequestAlreadyDisplayed();
  }

  // Takes a user decision and updates relevant properties of the model
  void UpdateWithUserDecision(permissions::PermissionAction permission_action);

  permissions::PermissionAction GetUserDecision() { return user_decision_; }

 private:
  // Delegate holding the current request
  absl::optional<permissions::PermissionPrompt::Delegate*> delegate_;

  // Permission icons and text
  const raw_ref<const gfx::VectorIcon> allowed_icon_;
  const raw_ref<const gfx::VectorIcon> blocked_icon_;

  std::u16string chip_text_;
  std::u16string accessibility_chip_text_;

  // Chip look
  PermissionPromptStyle prompt_style_;
  OmniboxChipTheme chip_theme_;

  bool should_display_blocked_icon_ = false;

  // Chip behaviour
  bool should_bubble_start_open_ = false;
  bool should_expand_ = true;

  // Permission state
  bool should_dismiss_ = false;

  permissions::PermissionAction user_decision_ =
      permissions::PermissionAction::NUM;
};

#endif  // CHROME_BROWSER_UI_VIEWS_PERMISSIONS_PERMISSION_PROMPT_CHIP_MODEL_H_


text:
import { gql } from '@apollo/client'

import useQuery from '../../utils/useQuery'
import devicesField from '../../fragments/devicesField'
import enhanceDevices from '../../../enhancers/enhanceDevices'

const QUERY = gql`
	query fetchMergedDevices($sorting: Sorting!, $type: DeviceType!, $range: Range) {
		statistics {
			id
			...devicesField
		}
	}

	${ devicesField }
`

export default (filters) => {
	const selector = (data) => data?.statistics.devices
	const enhancer = enhanceDevices

	return useQuery(QUERY, selector, enhancer, {
		variables: filters,
	})
}


text:
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved

using System;
using System.Collections.Generic;
using System.Text;

namespace NotificationsExtensions
{
    /// <summary>
    /// Contains the base properties that an image needs.
    /// </summary>
    public interface IBaseImage
    {
        /// <summary>
        /// The URI of the image. Can be from your application package, application data, or the internet. Internet images must be less than 200 KB in size.
        /// </summary>
        string Source { get; set; }

        /// <summary>
        /// A description of the image, for users of assistive technologies.
        /// </summary>
        string AlternateText { get; set; }

        /// <summary>
        /// Set to true to allow Windows to append a query string to the image URI supplied in the tile notification. Use this attribute if your server hosts images and can handle query strings, either by retrieving an image variant based on the query strings or by ignoring the query string and returning the image as specified without the query string. This query string specifies scale, contrast setting, and language.
        /// </summary>
        bool? AddImageQuery { get; set; }
    }
}


text:
package io.motown.vas.viewmodel.persistence.entities;

import javax.persistence.*;
import java.util.UUID;

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"subscriberIdentity", "deliveryAddress"}))
public class Subscription {

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String subscriberIdentity;

    private String subscriptionId;

    private String deliveryAddress;

    private Subscription(){
        //Private no-arg constructor for Hibernate
    }

    public Subscription(String subscriberIdentity, String deliveryAddress) {
        this.subscriberIdentity = subscriberIdentity;
        this.subscriptionId = UUID.randomUUID().toString();
        this.deliveryAddress = deliveryAddress;
    }

    Long getId() {
        return id;
    }

    public String getSubscriberIdentity() {
        return subscriberIdentity;
    }

    public String getSubscriptionId() {
        return subscriptionId;
    }

    public String getDeliveryAddress() {
        return deliveryAddress;
    }

}


text:
@implementation NSBundle (AppIcon_yq)

- (NSString*)yq_appIconPath {
    NSString* iconFilename = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIconFile"] ;
    NSString* iconBasename = [iconFilename stringByDeletingPathExtension] ;
    NSString* iconExtension = [iconFilename pathExtension] ;
    return [[NSBundle mainBundle] pathForResource:iconBasename
                                           ofType:iconExtension] ;
}

- (UIImage*)yq_appIcon {
    UIImage*appIcon = [[UIImage alloc] initWithContentsOfFile:[self yq_appIconPath]] ;
    return appIcon;
}

@end


text:
const int MAX_RESOURCES = 16;

struct Resources {

	int _values[MAX_RESOURCES];
	int total;

	Resources() : total(MAX_RESOURCES) {
		for ( int i = 0; i < MAX_RESOURCES; ++i ) {
			_values[i] = 0;
		}
	}

	void add(const Resources& other) {
		for ( int i = 0; i < MAX_RESOURCES;++i ) {
			_values[i] += other._values[i];
		}
	}

	void add(int type,int value) {
		if ( type >= 0 && type < MAX_RESOURCES) {
			_values[type] += value;
		}
	}

	void sub(int type,int value) {
		if ( type >= 0 && type < MAX_RESOURCES) {
			_values[type] -= value;
			if ( _values[type] < 0 ) {
				_values[type] = 0;
			}
		}
	}

	const int get(int type) const {
		if ( type >= 0 && type < MAX_RESOURCES) {
			return _values[type];
		}
		return 0;
	}

	void set(int type,int value) {
		assert(type >= 0 && type < MAX_RESOURCES);
		_values[type] = value;
	}
};

class ResourceRegistry;

namespace res {

	void show_resources(const ResourceRegistry& reg,const Resources& res,bool complete);

	void log_resources(const ResourceRegistry& reg,const Resources& res,bool complete);

}


text:
var variantFrequencyConfiguration = {
    name: "Transition/Transversion Ratio",
    attributes: [{
            name: "Reference Allele",
            type: "string",
            variable: "reference"
        },
        {
            name: "Alternative Allele",
            type: "string",
            variable: "alternative"
        }],
    parameters: [{
            name: "Show Matrix",
            type: "boolean",
            variable: "showMatrix"
        }],
    render: function( elementId, selections, attributes, attributeMap, parameterMap ) {
        var data = [];

        var attributeReference = attributes[attributeMap.reference];
        var attributeAlternative = attributes[attributeMap.alternative];

        // create data structure: array of pair arrays for each selection
        for ( var s = 0; s < selections.getSize(); ++s ) {

            var max = 0;

            var values =
                [
                    [0,0,0,0], //A -> A, C, G, T
                    [0,0,0,0], //C -> A, C, G, T
                    [0,0,0,0], //G -> A, C, G, T
                    [0,0,0,0]  //T -> A, C, G, T
                ];

            var transitions = 0;
            var transversions = 0;

            var nucleotideIndexMap = { A: 0, C: 1, G: 2, T: 3 };

            var selection = selections.getSelection(s);

            for ( var i = 0; i < selection.items.length; ++i ) {
                var referenceIndex = nucleotideIndexMap[attributeReference.values[selection.items[i]]];
                var alternativeIndex = nucleotideIndexMap[attributeAlternative.values[selection.items[i]]];
                values[referenceIndex][alternativeIndex] += 1;

                if ( values[referenceIndex][alternativeIndex] > max ) {
                    max = values[referenceIndex][alternativeIndex];
                }

                var change = attributeReference.values[selection.items[i]] + attributeAlternative.values[selection.items[i]];

                if ( change === "AG" || change === "GA" || change === "CT" || change === "TC" ) {
                    transitions += 1;
                }
                else {
                    transversions += 1;
                }

            }

            values.color = selections.getColor( selection );
            values.transitions = transitions;
            values.transversions = transversions;
            values.max = max;

            data.push( values );
        }

        d3.select( elementId ).html( "" );
        var viewer = d3.select( elementId );

        viewer.selectAll( 'p' )
                .data( data )
            .enter()
                .append( 'p' )
                .html( function( d ) {  return ( 'ti/tv = ' + d3.round( d.transitions / d.transversions, 3 ) + ' (' + d.transitions + '/' + d.transversions + ')' ); } )
                .style( "color", function( d ) { return ( d.color ); } );

        if (!parameterMap.showMatrix) {
            return;
        }

        var margin = {top: 20, right: 20, bottom: 30, left: 40},
            width = 960 - margin.left - margin.right,
            height = 500 - margin.top - margin.bottom;

        var size = 20;

        for ( var s = 0; s < selections.getSize(); ++s ) {

            var x = d3.scale.ordinal()
                .domain(['A', 'C', 'G', 'T'])
                .rangePoints([0.5*size,3.5*size]);

            var y = d3.scale.ordinal()
                .domain(['A', 'C', 'G', 'T'])
                .rangePoints([0.5*size,3.5*size]);

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient("bottom");

            var yAxis = d3.svg.axis()
                .scale(y)
                .orient("left");

            var color = d3.scale.linear()
                .domain([0,data[s].max])
                .range(["#e8e8e8", "#080808"]);

            var svg = d3.select(elementId).append("svg")
                .attr("width", size * 5 + margin.left + margin.right)
                .attr("height", size * 5 + margin.top + margin.bottom)
              .append("g")
                .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

            svg.append("g")
                .attr("class", "x axis")
                .attr("transform", "translate(0," + size*4 + ")")
                .attr('stroke-width','0')
                .call(xAxis)
            .append("text")
              .attr("transform", "translate(0," + (size+10) + ")" )
              .style("text-anchor", "start")
              .text("Ref Allele");

            svg.append("g")
                .attr("class", "y axis")
                .attr('stroke-width','0')
                .call(yAxis)
            .append("text")
              .attr("transform", "rotate(-90)")
              .attr("y", -10-size)
              .attr("dy", ".71em")
              .style("text-anchor", "end")
              .text("Alt Allele");

            var hm = svg.append("svg:g");
            var hmrows = hm.selectAll("g")
                    .data(data)
                    .enter().append("svg:g")
                    .attr("transform", function(d, i) {
                            return "translate(0," + (size * i) + ")";
                        });

            var hmcells = hmrows.selectAll("g")
                    .data(function(d,i) { return d; })
                .enter().append("svg:g")
                    .attr("transform", function(d, i) {
                            return "translate(" + (size * i) + ",0)";
                        });

            hmcells = hmcells.selectAll('rect')
                    .data(function(d,i) { return d; })
                .enter().append("svg:rect")
                    .attr("width", size)
                    .attr("height", size)
                    .attr("transform", function(d, i) {
                            return "translate(0," + (size * i) + ")";
                        })
                    .attr('fill', function(d,i) { return( color(d) ); })
                    .attr('stroke', 'white');
        }
    }
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.psalgs.string.misc;

import java.util.Stack;

/**
 *
 * @author djoshi
 *
 * http://www.geeksforgeeks.org/length-of-the-longest-valid-substring/
 *
 * Length of the longest valid substring
 *
 */
public class ValidSubstring {

    private static int findMaxLen(String str) {
        Stack<String> stack = new Stack<>();
        int count = 0;

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == '(') {
                stack.push("(");
            } else if (str.charAt(i) == ')') {
                String c = stack.pop();
                if (c.equals("(")) {
                    count += 2;
                }

                if (stack.isEmpty()) {
                    stack.push(")");
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        String str = "((()()";
        System.out.println(findMaxLen(str));

        str = "()(()))))";
        System.out.println(findMaxLen(str));

    }
}


text:
Introducing Functions
Functions are reusable pieces of code that you can use throughout an application, saving you lots of copying and pasting.

PHP has lots of built-in functions, and we'll learn some of them in these exercises. The first set of functions we'll learn about are string manipulation functions.

strlen() is one of the most common String functions in PHP. You pass it a string, or variable containing a string, and it returns the number of characters in that string. An example might be:

<?php
  // get the length of a string and
  // print it to the screen
  $length = strlen("david");
  print $length;
?>
Instructions
Use the index.php tab to write your own code.

Get the length of your own name, as I did for mine, and print it to the screen.

?
Stuck? Get a hint!