text:
<?php
// src/Acme/UserBundle/Entity/User.php

namespace Ei\einstitutBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="utilisateur")
 */
class User extends BaseUser
{

    /**
    * @ORM\OneToMany(targetEntity="CommentaireForum", mappedBy="comment_user")
    */
    protected $comentforum;

    public function setCommentaireForum(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $comentforum){
            $this->addCommentaireForum($comentforum);
        }
    }

    public function getCommentaireForum()
    {
        return $this->comentforum;
    }

     public function addCommentaireForum( $value)
    {
        $this->comentforum[] = $value;
    }

     public function removeCommentaireForum($value)
    {
        $this->comentforum->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Forum", mappedBy="forum_user")
    */
    protected $user_forum;

    public function setForum(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_forum){
            $this->addForum($user_forum);
        }
    }

    public function getForum()
    {
        return $this->user_forum;
    }

     public function addForum( $value)
    {
        $this->user_forum[] = $value;
    }

     public function removeForum($value)
    {
        $this->user_forum->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Contact", mappedBy="contact_user2")
    */
    protected $user_contact1;

     public function setContact1(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_contact1){
            $this->addContact1($user_contact1);
        }
    }

    public function getContact1()
    {
        return $this->user_contact1;
    }

     public function addContact1( $value)
    {
        $this->user_contact1[] = $value;
    }

     public function removeContact1($value)
    {
        $this->user_contact1->removeElement($value);
    }

     /**
    * @ORM\OneToMany(targetEntity="Contact", mappedBy="contact_user1")
    */
    protected $user_contact;

    public function setContacts(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_contact){
            $this->addContact($user_contact);
        }
    }

    public function getContacts()
    {
        return $this->user_contact;
    }

     public function addContact( $value)
    {
        $this->user_contact[] = $value;
    }

     public function removeContact($value)
    {
        $this->user_contact->removeElement($value);
    }

     /**
    * @ORM\OneToMany(targetEntity="Actualites", mappedBy="user")
    */
    protected $actualites;

    public function setActualites(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $actualite){
            $this->addActualite($actualite);
        }
    }

    public function getActualites()
    {
        return $this->actualites;
    }

     public function addActualite( $value)
    {
        $this->actualites[] = $value;
    }

     public function removeActualite($value)
    {
        $this->actualites->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Messages", mappedBy="messages_user")
    */
    protected $user_messages;

    public function setMessage(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_messages){
            $this->addMessage($user_messages);
        }
    }

    public function getMessage()
    {
        return $this->user_messages;
    }

     public function addMessage( $value)
    {
        $this->user_messages[] = $value;
    }

     public function removeMessage($value)
    {
        $this->user_messages->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Eticket", mappedBy="eticket_user")
    */
    protected $user_eticket;

    public function setEtickets(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_eticket){
            $this->addEticket($user_eticket);
        }
    }

    public function getEtickets()
    {
        return $this->user_eticket;
    }

     public function addEticket( $value)
    {
        $this->user_eticket[] = $value;
    }

     public function removeEticket($value)
    {
        $this->user_eticket->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Cercles", mappedBy="cercles_user")
    */
    protected $user_cercles;

     public function setCercles(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_cercles){
            $this->addCercles($user_cercles);
        }
    }

    public function getCercles()
    {
        return $this->user_cercles;
    }

     public function addCercles( $value)
    {
        $this->user_cercles[] = $value;
    }

     public function removeCercles($value)
    {
        $this->user_cercles->removeElement($value);
    }

    /**
    * @ORM\ManyToMany(targetEntity="Cercles", inversedBy="users")
    * @ORM\JoinTable(name="Partage_Utilisateurs_Cercles")
    */

    protected $cercle;

    public function setCercle(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $cercle){
            $this->addCercle($cercle);
        }
    }

    public function getCercle()
    {
        return $this->cercle;
    }

     public function addCercle($value)
    {
        $this->cercle[] = $value;
    }

     public function removeCercle($value)
    {
        $this->cercle->removeElement($value);
    }

    /**
    * @ORM\ManyToMany(targetEntity="Messages", inversedBy="users")
    * @ORM\JoinTable(name="To_Users")
    */

    protected $message;

    public function setMessages(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $message){
            $this->addMessages($message);
        }
    }

    public function getMessages()
    {
        return $this->message;
    }

     public function addMessages( $value)
    {
        $this->message[] = $value;
    }

     public function removeMessages($value)
    {
        $this->message->removeElement($value);
    }

    /**
    * @ORM\ManyToMany(targetEntity="Evenements", inversedBy="users")
    * @ORM\JoinTable(name="Partage_evenements_Utilisateurs")
    */

    protected $evenements;

    public function setEvenements(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $evenements){
            $this->addEvenement($evenements);
        }
    }

    public function getEvenements()
    {
        return $this->evenements;
    }

     public function addEvenement( $value)
    {
        $this->evenements[] = $value;
    }

     public function removeEvenements($value)
    {
        $this->evenements->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Evenements", mappedBy="user")
    */
    private $evenements_user;

    public function setEvenementsUser(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $evenements_user){
            $this->addEvenementsUser($evenements_user);
        }
    }

    public function getEvenementsUser()
    {
        return $this->evenements_user;
    }

     public function addEvenementsUser($value)
    {
        $this->evenements_user[] = $value;
    }

     public function removeEvenementsUser($value)
    {
        $this->evenements_user->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="TutorielsEnLigne", mappedBy="user_tuto")
    */
    protected $user_tuto_en_ligne;

    public function setTutorielsEnLigne(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $user_tuto_en_ligne){
            $this->addEvenementsUser($user_tuto_en_ligne);
        }
    }

    public function getTutorielsEnLigne()
    {
        return $this->user_tuto_en_ligne;
    }

     public function addTutorielsEnLigne($value)
    {
        $this->user_tuto_en_ligne[] = $value;
    }

     public function removeTutorielsEnLigne($value)
    {
        $this->user_tuto_en_ligne->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Preconisation", mappedBy="user_preconisation")
    */
    protected $preconisation;

    /**
    * @ORM\ManyToMany(targetEntity="Fiche", inversedBy="users")
    * @ORM\JoinTable(name="Favoris")
    */

    protected $fiche;

    public function setFiche(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $fiche){
            $this->addFiche($fiche);
        }
    }

    public function getFiche()
    {
        return $this->fiche;
    }

     public function addFiche( $value)
    {
        $this->fiche[] = $value;
    }

     public function removeFiche($value)
    {
        $this->fiche->removeElement($value);
    }

    /**
    * @ORM\OneToMany(targetEntity="Fiche", mappedBy="user")
    */
    protected $fiches;

    public function setFiches(\Doctrine\Common\Collections\ArrayCollection $values)
    {
        foreach($values as $fiches){
            $this->addFiches($fiches);
        }
    }

    public function getFiches()
    {
        return $this->fiches;
    }

     public function addFiches( $value)
    {
        $this->fiches[] = $value;
    }

     public function removeFiches($value)
    {
        $this->fiches->removeElement($value);
    }

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

     /**
     * @var string
     *
     * @ORM\Column(name="Avatar", type="string", length=255, nullable=true)
     */
    private $avatar;

    /**
     * @var string
     *
     * @ORM\Column(name="Nom", type="string", length=255, nullable=true)
     */
    private $nom;

    /**
     * @var string
     *
     * @ORM\Column(name="Prenom", type="string", length=255, nullable=true)
     */
    private $prenom;

    /**
     * @var string
     *
     * @ORM\Column(name="Sexe", type="string", length=255, nullable=true)
     */
    private $sexe;

    /**
     * @var string
     *
     * @ORM\Column(name="Tel", type="string", length=255, nullable=true)
     */
    private $tel;

    /**
     * @var string
     *
     * @ORM\Column(name="Pays", type="string", length=255, nullable=true)
     */
    private $pays;

    /**
     * @var string
     *
     * @ORM\Column(name="Ville", type="string", length=255, nullable=true)
     */
    private $ville;

    /**
     * @var string
     *
     * @ORM\Column(name="Adresse", type="string", length=300 , nullable=true)
     */
    private $adresse;

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

    /**
     * Set avatar
     *
     * @param string $avatar
     * @return Ut
     */
    public function setAvatar($avatar)
    {
        $this->avatar = $avatar;

        return $this;
    }

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

    /**
     * Set nom
     *
     * @param string $nom
     * @return Ut
     */
    public function setNom($nom)
    {
        $this->nom = $nom;

        return $this;
    }

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

    /**
     * Set prenom
     *
     * @param string $prenom
     * @return Ut
     */
    public function setPrenom($prenom)
    {
        $this->prenom = $prenom;

        return $this;
    }

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

    /**
     * Set sexe
     *
     * @param string $sexe
     * @return Ut
     */
    public function setSexe($sexe)
    {
        $this->sexe = $sexe;

        return $this;
    }

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

    /**
     * Set tel
     *
     * @param string $tel
     * @return Ut
     */
    public function setTel($tel)
    {
        $this->tel = $tel;

        return $this;
    }

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

    /**
     * Set pays
     *
     * @param string $pays
     * @return Ut
     */
    public function setPays($pays)
    {
        $this->pays = $pays;

        return $this;
    }

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

    /**
     * Set ville
     *
     * @param string $ville
     * @return Ut
     */
    public function setVille($ville)
    {
        $this->ville = $ville;

        return $this;
    }

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

    /**
     * Set adresse
     *
     * @param string $adresse
     * @return Ut
     */
    public function setAdresse($adresse)
    {
        $this->adresse = $adresse;

        return $this;
    }

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

    public function __construct()
    {

        $this->evenements = new \Doctrine\Common\Collections\ArrayCollection();
        $this->message = new \Doctrine\Common\Collections\ArrayCollection();
        $this->cercle = new \Doctrine\Common\Collections\ArrayCollection();
        $this->fiche = new \Doctrine\Common\Collections\ArrayCollection();
        $this->comentforum = new \Doctrine\Common\Collections\ArrayCollection();
        $this->user_forum = new \Doctrine\Common\Collections\ArrayCollection();
        $this->user_contact1 = new \Doctrine\Common\Collections\ArrayCollection();
        $this->user_contact = new \Doctrine\Common\Collections\ArrayCollection();
        $this->actualites = new \Doctrine\Common\Collections\ArrayCollection();
        $this->user_messages = new \Doctrine\Common\Collections\ArrayCollection();
        $this->user_eticket = new \Doctrine\Common\Collections\ArrayCollection();
        $this->user_cercles = new \Doctrine\Common\Collections\ArrayCollection();

        parent::__construct();
        // your own logic
    }

}


text:
<?php
namespace frontend\models;

use yii\db\ActiveRecord;

class User_info extends ActiveRecord
{

	public function getUsers(){
    return $this->hasOne(Users::className(),['user_id'=>'user_id']);

	}

}
 ?>

redpajama_set_name: RedPajamaGithub


text:
namespace content {

enum class PermissionType;

// Implements the PermissionService Mojo interface.
// This service can be created from a RenderFrameHost or a RenderProcessHost.
// It is owned by a PermissionServiceContext.
// It receives at PermissionServiceContext instance when created which allows it
// to have some information about the current context. That enables the service
// to know whether it can show UI and have knowledge of the associated
// WebContents for example.
class PermissionServiceImpl : public blink::mojom::PermissionService {
 public:
  PermissionServiceImpl(
      PermissionServiceContext* context,
      mojo::InterfaceRequest<blink::mojom::PermissionService> request);
  ~PermissionServiceImpl() override;

  // Clear pending operations currently run by the service. This will be called
  // by PermissionServiceContext when it will need the service to clear its
  // state for example, if the frame changes.
  void CancelPendingOperations();

 private:
  using PermissionStatusCallback =
      base::Callback<void(blink::mojom::PermissionStatus)>;

  struct PendingRequest {
    PendingRequest(const RequestPermissionsCallback& callback,
                   int request_count);
    ~PendingRequest();

    // Request ID received from the PermissionManager.
    int id;
    RequestPermissionsCallback callback;
    int request_count;
  };
  using RequestsMap = IDMap<std::unique_ptr<PendingRequest>>;

  // blink::mojom::PermissionService.
  void HasPermission(blink::mojom::PermissionDescriptorPtr permission,
                     const url::Origin& origin,
                     const PermissionStatusCallback& callback) override;
  void RequestPermission(blink::mojom::PermissionDescriptorPtr permission,
                         const url::Origin& origin,
                         bool user_gesture,
                         const PermissionStatusCallback& callback) override;
  void RequestPermissions(
      std::vector<blink::mojom::PermissionDescriptorPtr> permissions,
      const url::Origin& origin,
      bool user_gesture,
      const RequestPermissionsCallback& callback) override;
  void RevokePermission(blink::mojom::PermissionDescriptorPtr permission,
                        const url::Origin& origin,
                        const PermissionStatusCallback& callback) override;
  void AddPermissionObserver(
      blink::mojom::PermissionDescriptorPtr permission,
      const url::Origin& origin,
      blink::mojom::PermissionStatus last_known_status,
      blink::mojom::PermissionObserverPtr observer) override;

  void OnConnectionError();

  void OnRequestPermissionResponse(int pending_request_id,
                                   blink::mojom::PermissionStatus status);
  void OnRequestPermissionsResponse(
      int pending_request_id,
      const std::vector<blink::mojom::PermissionStatus>& result);

  blink::mojom::PermissionStatus GetPermissionStatus(
      const blink::mojom::PermissionDescriptorPtr& permission,
      const url::Origin& origin);
  blink::mojom::PermissionStatus GetPermissionStatusFromType(
      PermissionType type,
      const url::Origin& origin);
  void ResetPermissionStatus(PermissionType type, const url::Origin& origin);

  RequestsMap pending_requests_;
  // context_ owns |this|.
  PermissionServiceContext* context_;
  mojo::Binding<blink::mojom::PermissionService> binding_;
  base::WeakPtrFactory<PermissionServiceImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(PermissionServiceImpl);
};

}  // namespace content

#endif  // CONTENT_BROWSER_PERMISSIONS_PERMISSION_SERVICE_IMPL_H_


text:
import * as path from 'vs/base/common/path';
import * as platform from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { Schemas } from 'vs/base/common/network';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';

const REMOTE_PATH_SERVICE_ID = 'remotePath';
export const IRemotePathService = createDecorator<IRemotePathService>(REMOTE_PATH_SERVICE_ID);

export interface IRemotePathService {
	_serviceBrand: undefined;

	readonly path: Promise<path.IPath>;
	fileURI(path: string): Promise<URI>;

	readonly userHome: Promise<URI>;
}

/**
 * Provides the correct IPath implementation for dealing with paths that refer to locations in the extension host
 */
export class RemotePathService implements IRemotePathService {
	_serviceBrand: undefined;

	private _extHostOS: Promise<platform.OperatingSystem>;

	constructor(
		@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
		@IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService
	) {
		this._extHostOS = remoteAgentService.getEnvironment().then(remoteEnvironment => {
			return remoteEnvironment ? remoteEnvironment.os : platform.OS;
		});
	}

	get path(): Promise<path.IPath> {
		return this._extHostOS.then(os => {
			return os === platform.OperatingSystem.Windows ?
				path.win32 :
				path.posix;
		});
	}

	async fileURI(_path: string): Promise<URI> {
		let authority = '';

		// normalize to fwd-slashes on windows,
		// on other systems bwd-slashes are valid
		// filename character, eg /f\oo/ba\r.txt
		if ((await this._extHostOS) === platform.OperatingSystem.Windows) {
			_path = _path.replace(/\\/g, '/');
		}

		// check for authority as used in UNC shares
		// or use the path as given
		if (_path[0] === '/' && _path[1] === '/') {
			const idx = _path.indexOf('/', 2);
			if (idx === -1) {
				authority = _path.substring(2);
				_path = '/';
			} else {
				authority = _path.substring(2, idx);
				_path = _path.substring(idx) || '/';
			}
		}

		// return new _URI('file', authority, path, '', '');
		return URI.from({
			scheme: 'file',
			authority,
			path: _path,
			query: '',
			fragment: ''
		});
	}

	get userHome(): Promise<URI> {
		return this.remoteAgentService.getEnvironment().then(env => {

			// remote: use remote environment userHome
			if (env) {
				return env.userHome;
			}

			// local: use the userHome from environment
			return URI.from({ scheme: Schemas.file, path: this.environmentService.userHome });
		});
	}
}

registerSingleton(IRemotePathService, RemotePathService, true);


text:
package io.grpc.testing.integration;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import io.grpc.ForwardingServerCall.SimpleForwardingServerCall;
import io.grpc.InsecureServerCredentials;
import io.grpc.Metadata;
import io.grpc.Server;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import io.grpc.health.v1.HealthCheckResponse.ServingStatus;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.protobuf.services.HealthStatusManager;
import io.grpc.protobuf.services.ProtoReflectionService;
import io.grpc.services.AdminInterface;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.integration.Messages.SimpleRequest;
import io.grpc.testing.integration.Messages.SimpleResponse;
import io.grpc.xds.XdsServerBuilder;
import io.grpc.xds.XdsServerCredentials;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/** Interop test server that implements the xDS testing service. */
public final class XdsTestServer {
  static final Metadata.Key<String> HOSTNAME_KEY =
      Metadata.Key.of("hostname", Metadata.ASCII_STRING_MARSHALLER);
  private static final Metadata.Key<String> CALL_BEHAVIOR_MD_KEY =
      Metadata.Key.of("rpc-behavior", Metadata.ASCII_STRING_MARSHALLER);
  private static final Metadata.Key<String> ATTEMPT_NUM =
      Metadata.Key.of("grpc-previous-rpc-attempts", Metadata.ASCII_STRING_MARSHALLER);
  private static final String CALL_BEHAVIOR_KEEP_OPEN_VALUE = "keep-open";
  private static final String CALL_BEHAVIOR_SLEEP_VALUE = "sleep-";
  private static final String CALL_BEHAVIOR_SUCCEED_ON_RETRY_ATTEMPT_VALUE =
      "succeed-on-retry-attempt-";
  private static final String CALL_BEHAVIOR_ERROR_CODE =
      "error-code-";
  private static final Splitter HEADER_VALUE_SPLITTER = Splitter.on(',')
      .trimResults()
      .omitEmptyStrings();

  private static Logger logger = Logger.getLogger(XdsTestServer.class.getName());

  private int port = 8080;
  private int maintenancePort = 8080;
  private boolean secureMode = false;
  private String serverId = "java_server";
  private HealthStatusManager health;
  private Server server;
  private Server maintenanceServer;
  private String host;

  /**
   * The main application allowing this client to be launched from the command line.
   */
  public static void main(String[] args) throws Exception {
    final XdsTestServer server = new XdsTestServer();
    server.parseArgs(args);
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              @SuppressWarnings("CatchAndPrintStackTrace")
              public void run() {
                try {
                  System.out.println("Shutting down");
                  server.stop();
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            });
    server.start();
    System.out.println("Server started on port " + server.port);
    server.blockUntilShutdown();
  }

  private void parseArgs(String[] args) {
    boolean usage = false;
    for (String arg : args) {
      if (!arg.startsWith("--")) {
        System.err.println("All arguments must start with '--': " + arg);
        usage = true;
        break;
      }
      String[] parts = arg.substring(2).split("=", 2);
      String key = parts[0];
      if ("help".equals(key)) {
        usage = true;
        break;
      }
      if (parts.length != 2) {
        System.err.println("All arguments must be of the form --arg=value");
        usage = true;
        break;
      }
      String value = parts[1];
      if ("port".equals(key)) {
        port = Integer.valueOf(value);
      } else if ("maintenance_port".equals(key)) {
        maintenancePort = Integer.valueOf(value);
      } else if ("secure_mode".equals(key)) {
        secureMode = Boolean.parseBoolean(value);
      } else if ("server_id".equals(key)) {
        serverId = value;
      } else {
        System.err.println("Unknown argument: " + key);
        usage = true;
        break;
      }
    }

    if (secureMode && (port == maintenancePort)) {
      System.err.println(
          "port and maintenance_port should be different for secure mode: port="
              + port
              + ", maintenance_port="
              + maintenancePort);
      usage = true;
    }

    if (usage) {
      XdsTestServer s = new XdsTestServer();
      System.err.println(
          "Usage: [ARGS...]"
              + "\n"
              + "\n  --port=INT          listening port for test server."
              + "\n                      Default: "
              + s.port
              + "\n  --maintenance_port=INT      listening port for other servers."
              + "\n                      Default: "
              + s.maintenancePort
              + "\n  --secure_mode=BOOLEAN Use true to enable XdsCredentials."
              + " port and maintenance_port should be different for secure mode."
              + "\n                      Default: "
              + s.secureMode
              + "\n  --server_id=STRING  server ID for response."
              + "\n                      Default: "
              + s.serverId);
      System.exit(1);
    }
  }

  private void start() throws Exception {
    try {
      host = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
      logger.log(Level.SEVERE, "Failed to get host", e);
      throw new RuntimeException(e);
    }
    health = new HealthStatusManager();
    if (secureMode) {
      server =
          XdsServerBuilder.forPort(
                  port, XdsServerCredentials.create(InsecureServerCredentials.create()))
              .addService(
                  ServerInterceptors.intercept(
                      new TestServiceImpl(serverId, host), new TestInfoInterceptor(host)))
              .build();
      server.start();
      maintenanceServer =
          NettyServerBuilder.forPort(maintenancePort)
              .addService(new XdsUpdateHealthServiceImpl(health))
              .addService(health.getHealthService())
              .addService(ProtoReflectionService.newInstance())
              .addServices(AdminInterface.getStandardServices())
              .build();
      maintenanceServer.start();
    } else {
      server =
          NettyServerBuilder.forPort(port)
              .addService(
                  ServerInterceptors.intercept(
                      new TestServiceImpl(serverId, host), new TestInfoInterceptor(host)))
              .addService(new XdsUpdateHealthServiceImpl(health))
              .addService(health.getHealthService())
              .addService(ProtoReflectionService.newInstance())
              .addServices(AdminInterface.getStandardServices())
              .build();
      server.start();
      maintenanceServer = null;
    }
    health.setStatus("", ServingStatus.SERVING);
  }

  private void stop() throws Exception {
    server.shutdownNow();
    if (maintenanceServer != null) {
      maintenanceServer.shutdownNow();
    }
    if (!server.awaitTermination(5, TimeUnit.SECONDS)) {
      System.err.println("Timed out waiting for server shutdown");
    }
    if (maintenanceServer != null && !maintenanceServer.awaitTermination(5, TimeUnit.SECONDS)) {
      System.err.println("Timed out waiting for maintenanceServer shutdown");
    }
  }

  private void blockUntilShutdown() throws InterruptedException {
    if (server != null) {
      server.awaitTermination();
    }
    if (maintenanceServer != null) {
      maintenanceServer.awaitTermination();
    }
  }

  private static class TestServiceImpl extends TestServiceGrpc.TestServiceImplBase {
    private final String serverId;
    private final String host;

    private TestServiceImpl(String serverId, String host) {
      this.serverId = serverId;
      this.host = host;
    }

    @Override
    public void emptyCall(
        EmptyProtos.Empty req, StreamObserver<EmptyProtos.Empty> responseObserver) {
      responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
      responseObserver.onCompleted();
    }

    @Override
    public void unaryCall(SimpleRequest req, StreamObserver<SimpleResponse> responseObserver) {
      responseObserver.onNext(
          SimpleResponse.newBuilder().setServerId(serverId).setHostname(host).build());
      responseObserver.onCompleted();
    }
  }

  private static class XdsUpdateHealthServiceImpl
      extends XdsUpdateHealthServiceGrpc.XdsUpdateHealthServiceImplBase {
    private HealthStatusManager health;

    private XdsUpdateHealthServiceImpl(HealthStatusManager health) {
      this.health = health;
    }

    @Override
    public void setServing(
        EmptyProtos.Empty req, StreamObserver<EmptyProtos.Empty> responseObserver) {
      health.setStatus("", ServingStatus.SERVING);
      responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
      responseObserver.onCompleted();
    }

    @Override
    public void setNotServing(
        EmptyProtos.Empty req, StreamObserver<EmptyProtos.Empty> responseObserver) {
      health.setStatus("", ServingStatus.NOT_SERVING);
      responseObserver.onNext(EmptyProtos.Empty.getDefaultInstance());
      responseObserver.onCompleted();
    }
  }

  private static class TestInfoInterceptor implements ServerInterceptor {
    private final String host;

    private TestInfoInterceptor(String host) {
      this.host = host;
    }

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
        ServerCall<ReqT, RespT> call,
        final Metadata requestHeaders,
        ServerCallHandler<ReqT, RespT> next) {
      List<String> callBehaviors = getCallBehaviors(requestHeaders);
      ServerCall<ReqT, RespT> newCall = new SimpleForwardingServerCall<ReqT, RespT>(call) {
        @Override
        public void sendHeaders(Metadata responseHeaders) {
          responseHeaders.put(HOSTNAME_KEY, host);
          super.sendHeaders(responseHeaders);
        }
      };
      ServerCall.Listener<ReqT> noopListener = new ServerCall.Listener<ReqT>() {};

      // sleep if instructed by rpc-behavior
      for (String callBehavior : callBehaviors) {
        if (callBehavior.startsWith(CALL_BEHAVIOR_SLEEP_VALUE)) {
          try {
            int timeout = Integer.parseInt(
                callBehavior.substring(CALL_BEHAVIOR_SLEEP_VALUE.length()));
            Thread.sleep(timeout * 1000);
          } catch (NumberFormatException e) {
            newCall.close(
                Status.INVALID_ARGUMENT.withDescription(
                    String.format("Invalid format for rpc-behavior header (%s)", callBehavior)),
                new Metadata());
            return noopListener;
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            newCall.close(
                Status.ABORTED.withDescription("execution of server interrupted"),
                new Metadata());
            return noopListener;
          }
        }
      }

      // succeed the retry attempt if instructed by rpc-behavior
      int succeedOnAttemptNum = Integer.MAX_VALUE;
      for (String callBehavior : callBehaviors) {
        if (callBehavior.startsWith(CALL_BEHAVIOR_SUCCEED_ON_RETRY_ATTEMPT_VALUE)) {
          try {
            succeedOnAttemptNum = Integer.parseInt(
                callBehavior.substring(CALL_BEHAVIOR_SUCCEED_ON_RETRY_ATTEMPT_VALUE.length()));
          } catch (NumberFormatException e) {
            newCall.close(
                Status.INVALID_ARGUMENT.withDescription(
                    String.format("Invalid format for rpc-behavior header (%s)", callBehavior)),
                new Metadata());
            return noopListener;
          }
          break;
        }
      }
      int attemptNum = 0;
      String attemptNumHeader = requestHeaders.get(ATTEMPT_NUM);
      if (attemptNumHeader != null) {
        try {
          attemptNum = Integer.valueOf(attemptNumHeader);
        } catch (NumberFormatException e) {
          newCall.close(
              Status.INVALID_ARGUMENT.withDescription(
                  String.format(
                      "Invalid format for grpc-previous-rpc-attempts header (%s)",
                      attemptNumHeader)),
              new Metadata());
          return noopListener;
        }
      }
      if (attemptNum == succeedOnAttemptNum) {
        return next.startCall(newCall, requestHeaders);
      }

      // hang if instructed by rpc-behavior
      if (callBehaviors.contains(CALL_BEHAVIOR_KEEP_OPEN_VALUE)) {
        return noopListener;
      }

      // fail if instructed by rpc-behavior
      for (String callBehavior : callBehaviors) {
        if (callBehavior.startsWith(CALL_BEHAVIOR_ERROR_CODE)) {
          try {
            int codeValue = Integer.valueOf(
                callBehavior.substring(CALL_BEHAVIOR_ERROR_CODE.length()));
            newCall.close(
                Status.fromCodeValue(codeValue).withDescription(
                    "Rpc failed as per the rpc-behavior header value:" + callBehaviors),
                new Metadata());
            return noopListener;
          } catch (NumberFormatException e) {
            newCall.close(
                Status.INVALID_ARGUMENT.withDescription(
                    String.format("Invalid format for rpc-behavior header (%s)", callBehavior)),
                new Metadata());
            return noopListener;
          }
        }
      }

      return next.startCall(newCall, requestHeaders);
    }
  }

  private static List<String> getCallBehaviors(Metadata requestHeaders) {
    List<String> callBehaviors = new ArrayList<>();
    Iterable<String> values = requestHeaders.getAll(CALL_BEHAVIOR_MD_KEY);
    if (values == null) {
      return callBehaviors;
    }
    for (String value : values) {
      Iterables.addAll(callBehaviors, HEADER_VALUE_SPLITTER.split(value));
    }
    return callBehaviors;
  }
}


text:
require "test_helper"

class BranchTestCase < Test::Unit::TestCase

  def setup
    LLVM.init_x86
  end

  def test_branching
    assert_equal 0, run_default_function(direct_jump_function).to_i
    assert_equal 0, run_default_function(conditional_jump_function).to_i
    assert_equal 0, run_default_function(switched_jump_function).to_i
  end

  def direct_jump_function
    function [], :int do |f|
      f.entry { f.branch(:branch_2) }
      f.block(:branch_1) { f.returns int(1) }
      f.block(:branch_2) { f.returns int(0) }
    end
  end

  def conditional_jump_function
    function [], :int do |f|
      f.entry { f.condition(f.icmp(:eq, int(1), int(2)), :branch_1, :branch_2) }
      f.block(:branch_1) { f.returns int(1) }
      f.block(:branch_2) { f.returns int(0) }
    end
  end

  def switched_jump_function
    function [], :int do |f|
      f.entry {
        f.switch int(1), :branch_1,
          { :on => int(2), :go_to => :branch_2 },
          { :on => int(3), :go_to => :branch_3 }
      }
      f.block(:branch_1) { f.returns int(0) }
      f.block(:branch_2) { f.returns int(1) }
      f.block(:branch_3) { f.returns int(2) }
    end
  end

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface com.fasterxml.jackson.databind.util.Converter (jackson-databind 2.2.0 API)</title>
<meta name="date" content="2013-04-22">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.fasterxml.jackson.databind.util.Converter

Packages that use Converter

Package
Description

com.fasterxml.jackson.databind

Contains basic mapper (conversion) functionality that
allows for converting between regular streaming json content and
Java objects (beans or Tree Model: support for both is via
ObjectMapper class, as well
as convenience methods included in
JsonParser

com.fasterxml.jackson.databind.cfg

Package that contains most of configuration-related classes;
exception being couple of most-commonly used configuration
things (like Feature enumerations) that are at the
main level (com.fasterxml.jackson.databind).

com.fasterxml.jackson.databind.deser

Contains implementation classes of deserialization part of
 data binding.

com.fasterxml.jackson.databind.deser.std

Contains public standard implementations of abstraction that
 Jackson uses.

com.fasterxml.jackson.databind.introspect

Functionality needed for Bean introspection, required for detecting
 accessors and mutators for Beans, as well as locating and handling
 method annotations.

com.fasterxml.jackson.databind.ser

Contains implementation classes of serialization part of
 data binding.

com.fasterxml.jackson.databind.ser.std

com.fasterxml.jackson.databind.util

Utility classes for Mapper package.

Uses of Converter in com.fasterxml.jackson.databind

Methods in com.fasterxml.jackson.databind that return Converter

Modifier and Type
Method and Description

Converter<Object,Object>
DatabindContext.converterInstance(Annotated annotated,
                 Object converterDef)

Helper method to use to construct a Converter, given a definition
 that may be either actual converter instance, or Class for instantiating one.

abstract Converter<Object,Object>
BeanDescription.findDeserializationConverter()

Method for finding Converter used for serializing instances
 of this class.

abstract Converter<Object,Object>
BeanDescription.findSerializationConverter()

Method for finding Converter used for serializing instances
 of this class.

Uses of Converter in com.fasterxml.jackson.databind.cfg

Methods in com.fasterxml.jackson.databind.cfg that return Converter

Modifier and Type
Method and Description

Converter<?,?>
HandlerInstantiator.converterInstance(MapperConfig<?> config,
                 Annotated annotated,
                 Class<?> implClass)

Method called to construct a Converter instance used for specified class.

Uses of Converter in com.fasterxml.jackson.databind.deser

Methods in com.fasterxml.jackson.databind.deser that return Converter

Modifier and Type
Method and Description

protected Converter<Object,Object>
DeserializerCache.findConverter(DeserializationContext ctxt,
             Annotated a)

Uses of Converter in com.fasterxml.jackson.databind.deser.std

Fields in com.fasterxml.jackson.databind.deser.std declared as Converter

Modifier and Type
Field and Description

protected Converter<Object,T>
StdDelegatingDeserializer._converter

Methods in com.fasterxml.jackson.databind.deser.std with parameters of type Converter

Modifier and Type
Method and Description

protected StdDelegatingDeserializer<T>
StdDelegatingDeserializer.withDelegate(Converter<Object,T> converter,
            JavaType delegateType,
            JsonDeserializer<?> delegateDeserializer)

Method used for creating resolved contextual instances.

Constructors in com.fasterxml.jackson.databind.deser.std with parameters of type Converter

Constructor and Description

StdDelegatingDeserializer(Converter<?,T> converter)

StdDelegatingDeserializer(Converter<Object,T> converter,
                         JavaType delegateType,
                         JsonDeserializer<?> delegateDeserializer)

Uses of Converter in com.fasterxml.jackson.databind.introspect

Methods in com.fasterxml.jackson.databind.introspect that return Converter

Modifier and Type
Method and Description

Converter<Object,Object>
BasicBeanDescription._createConverter(Object converterDef)

Converter<Object,Object>
BasicBeanDescription.findDeserializationConverter()

Converter<Object,Object>
BasicBeanDescription.findSerializationConverter()

Uses of Converter in com.fasterxml.jackson.databind.ser

Methods in com.fasterxml.jackson.databind.ser that return Converter

Modifier and Type
Method and Description

protected Converter<Object,Object>
BasicSerializerFactory.findConverter(SerializerProvider prov,
             Annotated a)

Uses of Converter in com.fasterxml.jackson.databind.ser.std

Fields in com.fasterxml.jackson.databind.ser.std declared as Converter

Modifier and Type
Field and Description

protected Converter<Object,?>
StdDelegatingSerializer._converter

Methods in com.fasterxml.jackson.databind.ser.std that return Converter

Modifier and Type
Method and Description

protected Converter<Object,?>
StdDelegatingSerializer.getConverter()

Methods in com.fasterxml.jackson.databind.ser.std with parameters of type Converter

Modifier and Type
Method and Description

protected StdDelegatingSerializer
StdDelegatingSerializer.withDelegate(Converter<Object,?> converter,
            JavaType delegateType,
            JsonSerializer<?> delegateSerializer)

Method used for creating resolved contextual instances.

Constructors in com.fasterxml.jackson.databind.ser.std with parameters of type Converter

Constructor and Description

StdDelegatingSerializer(Class<T> cls,
                       Converter<T,?> converter)

StdDelegatingSerializer(Converter<?,?> converter)

StdDelegatingSerializer(Converter<Object,?> converter,
                       JavaType delegateType,
                       JsonSerializer<?> delegateSerializer)

Uses of Converter in com.fasterxml.jackson.databind.util

Classes in com.fasterxml.jackson.databind.util that implement Converter

Modifier and Type
Class and Description

static class
Converter.None

This marker class is only to be used with annotations, to
 indicate that no converter is to be used.

class
StdConverter<IN,OUT>

Standard implementation of Converter that supports explicit
 type access, instead of relying type detection of generic type
 parameters.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012-2013 FasterXML. All Rights Reserved.


text:
require 'spec_helper'

module Sparrowhawk

  describe BundlerGemFinder do
    let(:finder) do
      definition = BundlerDefinition.new 'Gemfile', 'Gemfile.lock'
      BundlerGemFinder.new definition
    end

    before do
      FileUtils.rm_rf current_dir
      write_file "Gemfile.lock", <<-LOCK
GEM
  remote: http://rubygems.org/
  specs:
    activerecord-jdbc-adapter (1.1.0)
    pg (0.9.0)
    nokogiri (1.4.3.1)
    nokogiri (1.4.3.1-java)
      weakling (>= 0.0.3)

PLATFORMS
  java
  ruby

DEPENDENCIES
  activerecord-jdbc-adapter
  pg
  nokogiri
       LOCK

      write_file "Gemfile", <<-GEMFILE
       source :gemcutter
       platform :jruby do
         gem 'activerecord-jdbc-adapter'
       end
       platform :ruby_18, :ruby_19 do
         gem 'pg'
       end
       gem 'logging', :group => :production
       gem 'rspec', :groups => [:test, :development]
       gem 'nokogiri'
       GEMFILE

      in_current_dir do
        FileUtils.mkdir_p 'vendor/cache'
        FileUtils.cp Dir.glob('../../spec/fixtures/*.gem'), 'vendor/cache'
      end
    end

    it "returns default gems from vendor cache that are appropriate for the java platform" do
      in_current_dir do
        finder.map(&:gem_path).should include(ENV['GEM_HOME'] + "/cache/bundler-1.0.10.gem")
        finder.map(&:gem_path).should include('vendor/cache/weakling-0.0.4-java.gem')
        finder.map(&:gem_path).should include('vendor/cache/nokogiri-1.4.3.1-java.gem')
      end
    end

    context "when gem home is not set" do
      before do
        @old_gem_home = ENV['GEM_HOME']
        ENV['GEM_HOME'] = nil
      end

      after do
        ENV['GEM_HOME'] = @old_gem_home
      end

      it "returns bundler gem from the bundle path, if gem home is not set" do
        in_current_dir do
          finder.map(&:gem_path).should include(Bundler.bundle_path.to_s + "/cache/bundler-1.0.10.gem")
        end
      end
    end

    it "returns only runtime dependencies" do
      in_current_dir do
        finder.map(&:gem_path).should_not include('vendor/cache/hoe-2.8.0.gem')
      end
    end

    it "returns jruby platform gems" do
      in_current_dir do
        finder.map(&:gem_path).should include('vendor/cache/activerecord-jdbc-adapter-1.1.0.gem')
      end
    end

    it "does not return mri specific platform gems" do
      in_current_dir do
        finder.map(&:gem_path).should_not include('vendor/cache/pg-0.9.0.gem')
      end
    end

    it "returns gems from the :production group" do
      in_current_dir do
        finder.map(&:gem_path).should include('vendor/cache/logging-1.4.3.gem')
      end
    end

    it "exludes gems that aren't part of the :production or :default groups" do
      in_current_dir do
        finder.map(&:gem_path).should_not include('vendor/cache/rspec-2.2.0.gem')
      end
    end
  end

end


text:
package org.cyberjos.jaduni;

import java.io.Reader;
import java.io.Writer;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.Validate;

/**
 * {@code RenderEngine} is an interface which is responsible for converting the
 * given input source to another text with the specified format. The input
 * source can be a string, a {@link Renderable} object or a {@code Reader}
 * object. Whatever the input source is, it is supposed to be able to provide
 * text with the particular syntax which can be handled by this render engine. A
 * render engine parses the given input, converts it by following predefined
 * rules of conversion, and then output to the specified destination. The output
 * can be a string, or a {@code Writer} object for output.
 *

 * This interface contains a singleton enumeration and uses it to simply manage
 * all render engine. However, a developer only needs to deal with this
 * interface without accessing the enumeration directly:
 *
 *

 * // Retrieve the default render engine which is designed for Creole
 * RenderEngine defaultRenderEngine = RenderEngine.getDefault();
 *
 * // Add or retrieve a new render engine
 * RenderEngine.set("MyRenderEngine", new MyRenderEngine());
 * RenderEngine myRenderEngine = RenderEngine.get("MyRenderEngine");
 *
 * // Remove a render engine. It cannot remove the default render engine.
 * RenderEngine.set("MyRenderEngine", null);
 *

 *
 * @author Joseph S. Kuo
 * @since 0.0.1, 2014/4/30
 */
public interface RenderEngine {
    /**
     * The {@code RenderEngine} holder is a singleton enumeration for easily
     * managing all render engines in a JVM. It creates and registers the
     * default render engine by default during initialization. A user doesn't
     * need to use this enumeration to manage render engines. Instead, he should
     * use those static methods in {@link RenderEngine} to get or set a render
     * engine object associated with the specified name.
     *
     * @author Joseph S. Kuo
     * @since 0.0.1, 2014/5/2
     */
    public enum Holder {
        /**
         * Singleton instance.
         */
        INSTANCE;

        /**
         * Constant for default render engine.
         */
        private static final String DEFAULT_RENDER_ENGINE = "DefaultRenderEngine-RenderEngineImpl.class";

        /**
         * The map to store render engines.
         */
        private final Map<String, RenderEngine> renderEngineMapping = new ConcurrentHashMap<>();

        /**
         * Constructs without any arguments. It creates the default render
         * engine and put it into mapping while initialization.
         */
        private Holder() {
            this.renderEngineMapping.put(DEFAULT_RENDER_ENGINE, new RenderEngineImpl());
            // TODO: automatically initialize all custom render engines by following mechanism
            /*
             * Map<String, RenderEngine> customMapping = Loader.load(RenderEngine.class);
             * this.renderEngineMapping.putAll(customMapping);
             */
        }

        /**
         * Returns the render engine associated with the given name, or
         * {@code null} if not found.
         *
         * @param renderEngineName the name of the render engine
         * @return the render engine associated with the given name, or
         *         {@code null} if not found
         * @throws NullPointerException if the given name is {@code null}
         * @throws IllegalArgumentException if the given name is blank
         */
        RenderEngine get(final String renderEngineName) {
            Validate.notBlank(renderEngineName, "The given name must not be null.");
            return this.renderEngineMapping.get(renderEngineName);
        }

        /**
         * Sets the render engine into the mapping with the given name. The
         * passed render engine can be {@code null}.
         *
         * @param renderEngineName the name of render engine
         * @param renderEngine the render engine. It can be {@code null}
         * @throws NullPointerException if the given name is {@code null}
         * @throws IllegalArgumentException if the given name is blank
         */
        void set(final String renderEngineName, final RenderEngine renderEngine) {
            Validate.notBlank(renderEngineName, "The given name must not be null.");

            if (Holder.DEFAULT_RENDER_ENGINE.equals(renderEngineName)) {
                Objects.requireNonNull(renderEngine, "Cannot set the default render engine to a null object.");
            }

            this.renderEngineMapping.put(renderEngineName, renderEngine);
        }
    }

    /**
     * Returns the default render engine. It never returns a {@code null}
     * object.
     *
     * @return the default render engine which is never {@code null}
     */
    public static RenderEngine getDefault() {
        return get(Holder.DEFAULT_RENDER_ENGINE);
    }

    /**
     * Returns the render engine associated with the given name, or {@code null}
     * if not found.
     *
     * @param renderEngineName the name of the render engine
     * @return the render engine associated with the given name, or {@code null}
     *         if not found
     * @throws NullPointerException if the given name is {@code null}
     * @throws IllegalArgumentException if the given name is blank
     */
    public static RenderEngine get(final String renderEngineName) {
        return Holder.INSTANCE.get(renderEngineName);
    }

    /**
     * Sets the render engine into the mapping with the given name. The passed
     * render engine can be {@code null}.
     *
     * @param renderEngineName the name of render engine
     * @param renderEngine the render engine. It can be {@code null}
     * @throws NullPointerException if the given name is {@code null}
     * @throws IllegalArgumentException if the given name is blank
     */
    public static void set(final String renderEngineName, final RenderEngine renderEngine) {
        Holder.INSTANCE.set(renderEngineName, renderEngine);
    }

    /**
     * Parses the given source and then returns the converted string. The source
     * could be a string, or a location of data source which contains text. It
     * all depends on how this render engine implements this method and how it
     * treats the passed parameter. It throws a {@link RenderException} once if
     * it encounters errors during conversion.
     *
     * @param source the source to be parsed
     * @return the converted string
     * @throws RenderException if any exception occurs while a
     *         {@link RenderEngine} parses input, converts format and renders
     *         output
     */
    public String render(String source) throws RenderException;

    /**
     * Parses the given source and then writes the converted string to the
     * specified output. The source or destination could be a string, a local
     * file, or a resource via network. The reader should contain a string which
     * can be parsed. It throws a {@link RenderException} once if it encounters
     * errors during conversion.
     *
     * @param in the {@code Reader} which can provide string that can be parsed
     * @param out the {@code Writer} which receives the converted string
     * @throws RenderException if any exception occurs while a
     *         {@link RenderEngine} parses input, converts format and renders
     *         output
     */
    public void render(Reader in, Writer out) throws RenderException;
}


text:
import React from 'react'
import AxisLabels from './AxisLabels'

const YAxisLabels = props =>
  <AxisLabels
    axis="y"
    textAnchor="start"
    {...props}
  />

export default YAxisLabels


text:
<?php

/**
 * This is a model for a single order, stored in an XML document.
 *
 * @author jim
 */
class Course extends CI_Model {

    protected $xml = null;
    protected $id = '';
    protected $bookings = array();

    // Constructor
    public function __construct($filename = null) {
        parent::__construct();
        if ($filename == null)
            return;

        $this->xml = simplexml_load_file(DATAPATH . $filename . XMLSUFFIX);

        // extract basics
        $this->id = (string) $this->xml['id'];

        foreach ($this->xml->booking as $one) {
            $this->bookings[] = $this->makeBooking($one);
        }
    }

    // build a booking object from the simpleXML
    // use the DTD as a guide ... (patty, cheeses?, topping*, sauce*, instructions?, name?)
    function makeBooking($element) {
        $record = new stdClass();

        $record->type =  (string) $element['type'];
        $record->day = (string) $element['day'];
        $record->name = (string) $element->name;
        $record->instructor = (string) $element->instructor;
        $record->room = (string) $element->room;
        $record->start = (string) $element->period['start'];
        $record->end = (string) $element->period['end'];

        return $record;
    }

    // return the customer name
    function getId() {
        return $this->id;
    }

    // return the array of burgers in this order
    function getBookings() {
        return $this->bookings;
    }

}


text:
package edu.jhu.pacaya.gm.train;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

import edu.jhu.pacaya.autodiff.AbstractModuleTest;
import edu.jhu.pacaya.autodiff.AbstractModuleTest.OneToOneFactory;
import edu.jhu.pacaya.autodiff.Identity;
import edu.jhu.pacaya.autodiff.Module;
import edu.jhu.pacaya.autodiff.Tensor;
import edu.jhu.pacaya.gm.inf.Beliefs;
import edu.jhu.pacaya.gm.model.Var;
import edu.jhu.pacaya.gm.model.Var.VarType;
import edu.jhu.pacaya.gm.model.VarConfig;
import edu.jhu.pacaya.gm.model.VarSet;
import edu.jhu.pacaya.gm.model.VarTensor;
import edu.jhu.pacaya.util.collections.QLists;
import edu.jhu.pacaya.util.semiring.Algebra;
import edu.jhu.pacaya.util.semiring.RealAlgebra;

public class ExpectedRecallTest {

    private VarConfig goldConfig;
    private Identity<Beliefs> id1;
    private Algebra s = RealAlgebra.getInstance();

    @Before
    public void setUp() {
        Var t0 = new Var(VarType.PREDICTED, 2, "t0", QLists.getList("N", "V"));
        Var t1 = new Var(VarType.PREDICTED, 2, "t1", QLists.getList("N", "V"));
        t0.setId(0);
        t1.setId(1);

        goldConfig = new VarConfig();
        goldConfig.put(t1, 1);

        Beliefs b = new Beliefs(s);
        b.varBeliefs = new VarTensor[2];
        b.facBeliefs = new VarTensor[0];
        b.varBeliefs[0] = new VarTensor(s, new VarSet(t0), 0.5);
        b.varBeliefs[1] = new VarTensor(s, new VarSet(t1), 0.5);

        id1 = new Identity<Beliefs>(b);
    }

    @Test
    public void testSimple() {
        ExpectedRecall s = new ExpectedRecall(id1, goldConfig);

        Tensor out = s.forward();
        assertEquals(-0.5, out.getValue(0), 1e-13);

        s.getOutputAdj().setValue(0, 1);
        s.backward();
        Beliefs inAdj = id1.getOutputAdj();
        assertEquals(0, inAdj.varBeliefs[0].getValue(0), 1e-13);
        assertEquals(0, inAdj.varBeliefs[0].getValue(1), 1e-13);
        assertEquals(0, inAdj.varBeliefs[1].getValue(0), 1e-13);
        assertEquals(-1, inAdj.varBeliefs[1].getValue(1), 1e-13);
    }

    @Test
    public void testGradByFiniteDiffsAllSemirings() {
        OneToOneFactory<Beliefs,Tensor> fact = new OneToOneFactory<Beliefs,Tensor>() {
            public Module<Tensor> getModule(Module<Beliefs> m1) {
                return new ExpectedRecall(m1, goldConfig);
            }
        };
        AbstractModuleTest.evalOneToOneByFiniteDiffsAbs(fact, id1);
    }

}


text:
<!DOCTYPE html>

  <title>App Engine Endpoints with Google Cloud Messaging</title>

  <form action="javascript:void(0);">
    <input id="myMessage" type="text" name="message" />
    <input id="mySubmit" type="submit" value="Send Message" />
  </form>

  Your App Engine Admin Console provides some information about your App Engine app.

  Endpoints Api Explorer lets you access the endpoints API directly.

  Check out the documentation for more information on Google App Engine for Java.

  Check out the endpoints documentation for more information on Google Endpoints for Java.


text:
Install `gulp-pilot-merger-preprocess-topo` as a development dependency:

```shell
npm install --save-dev gulp-pilot-merger-preprocess-topo
```

# Usage

After you have installed this plugin you can utilize it in your .pilotrc.{js,json} assuming you use gulp-pilot and preprocess:

> .pilotrc.js

````javascript
module.exports = {
    init: {
        'preprocess': 'gulp-pilot-merger-preprocess-topo'
    },
    merger: {
        'preprocess': 'gulp-pilot-merger-preprocess-topo'
    }
};
````

Or as simple JSON:

> .pilotrc.json

````JSON
{
    "init": {
        "preprocess": "gulp-pilot-merger-preprocess-topo"
    },
    "merger": {
        "preprocess": "gulp-pilot-merger-preprocess-topo"
    }
}
````

# API Documentation

## Functions

preprocessTopoInitializor(config)

Initializes preprocess options and sorts dependencies.
This function adds a new property called preprocessFeatures holding an array of first level preprocess option keys.

Note: Dependencies are read from preprocessDependencies property.

preprocessTopoMerger(config, defaultConfig)

Merges preprocess options through complementing with a default config file and sorts dependencies.
This function adds a new property called preprocessFeatures holding an array of first level preprocess option keys.

Note: Dependencies are read from preprocessDependencies property.

hashToEdges(hash, preprocess) ⇒ Array

Turns a preprocessDependencies hash in an array of edges, consumable by toposort algorithm.

Note: This has also build in support for conditional dependencies.

## Typedefs

DependenciesHash : Object.<string, Array.<(string|{condition: string, value: string})>>

A hash containing features and their respective dependencies.

Note: This has also build in support for conditional dependencies.

## preprocessTopoInitializor(config)
Initializes preprocess options and sorts dependencies.
This function adds a new property called `preprocessFeatures` holding an array of first level preprocess option keys.

**Note:** Dependencies are read from `preprocessDependencies` property.

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| config | Object | The default or custom config to be initialized. |

## preprocessTopoMerger(config, defaultConfig)
Merges preprocess options through complementing with a default config file and sorts dependencies.
This function adds a new property called `preprocessFeatures` holding an array of first level preprocess option keys.

**Note:** Dependencies are read from `preprocessDependencies` property.

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| config | Object | The new config to be merged with defaultConfig. |
| defaultConfig | Object | The default config used to complement the new config. |

## hashToEdges(hash, preprocess) ⇒ Array
Turns a preprocessDependencies hash in an array of edges, consumable by toposort algorithm.

**Note:** This has also build in support for conditional dependencies.

**Kind**: global function

| Param | Type | Description |
| --- | --- | --- |
| hash | [DependenciesHash](#DependenciesHash) | The preprocessDependencies hash. |
| preprocess | Object | The preprocess config object. |

## DependenciesHash : Object.<string, Array.<(string\|{condition: string, value: string})>>
A hash containing features and their respective dependencies.

**Note:** This has also build in support for conditional dependencies.

**Kind**: global typedef

#License

The MIT License (MIT)

Copyright (c) 2016 Andreas Deuschlinger

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

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

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


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SimuRails.Models;

namespace SimuRails.Views.Components
{
    public partial class RenglonDeAgrupacionCoche : UserControl
    {
        public delegate void DelAgrupacion(AgrupacionCoche agrupacion);
        private DelAgrupacion handleRemove;

        public AgrupacionCoche Agrupacion{ get; set; }

        public RenglonDeAgrupacionCoche(AgrupacionCoche agrupacion, DelAgrupacion handleRemove)
        {
            InitializeComponent();
            this.Agrupacion = agrupacion;
            this.modeloLbl.Text = agrupacion.Coche.Modelo;
            this.cantidadLbl.Text = agrupacion.Cantidad.ToString();
            this.handleRemove = handleRemove;
        }

        private void materialFlatButton1_Click(object sender, EventArgs e)
        {
            if (this.handleRemove != null)
            {
                handleRemove(Agrupacion);
            }
        }

        private void materialDivider1_Click(object sender, EventArgs e)
        {

        }

        private void cantidadLbl_Click(object sender, EventArgs e)
        {

        }

        private void modeloLbl_Click(object sender, EventArgs e)
        {

        }
    }
}


text:
package com.aware;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import com.aware.providers.Proximity_Provider;
import com.aware.providers.Proximity_Provider.Proximity_Data;
import com.aware.providers.Proximity_Provider.Proximity_Sensor;
import com.aware.utils.Aware_Sensor;

/**
 * AWARE Proximity module
 * - Proximity raw data in centimeters / (binary far/near for some sensors)
 * - Proximity sensor information
 * @author df
 *
 */
public class Proximity extends Aware_Sensor implements SensorEventListener {

    /**
     * Sensor update frequency ( default = {@link SensorManager#SENSOR_DELAY_NORMAL})
     */
    private static int SENSOR_DELAY = 200000;

    private static SensorManager mSensorManager;
    private static Sensor mProximity;
    private static HandlerThread sensorThread = null;
    private static Handler sensorHandler = null;
    private static PowerManager powerManager = null;
    private static PowerManager.WakeLock wakeLock = null;

    /**
     * Broadcasted event: new sensor values
     * ContentProvider: ProximityProvider
     */
    public static final String ACTION_AWARE_PROXIMITY = "ACTION_AWARE_PROXIMITY";

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //We log current accuracy on the sensor changed event
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        ContentValues rowData = new ContentValues();
        rowData.put(Proximity_Data.DEVICE_ID, Aware.getSetting(getContentResolver(),"device_id"));
        rowData.put(Proximity_Data.TIMESTAMP, System.currentTimeMillis());
        rowData.put(Proximity_Data.PROXIMITY, event.values[0]);
        rowData.put(Proximity_Data.ACCURACY, event.accuracy);

        try {
            getContentResolver().insert(Proximity_Data.CONTENT_URI, rowData);

            Intent accelData = new Intent(ACTION_AWARE_PROXIMITY);
            sendBroadcast(accelData);

            if( Aware.DEBUG ) Log.d(TAG, "Proximity:"+ rowData.toString());
        }catch( SQLiteException e ) {
            if(Aware.DEBUG) Log.d(TAG,e.getMessage());
        }catch( SQLException e ) {
            if(Aware.DEBUG) Log.d(TAG,e.getMessage());
        }
    }

    private void saveSensorDevice(Sensor sensor) {
        Cursor sensorInfo = getContentResolver().query(Proximity_Sensor.CONTENT_URI, null, null, null, null);
        if( sensorInfo == null || ! sensorInfo.moveToFirst() ) {
            ContentValues rowData = new ContentValues();
            rowData.put(Proximity_Sensor.DEVICE_ID, Aware.getSetting(getContentResolver(),"device_id"));
            rowData.put(Proximity_Sensor.TIMESTAMP, System.currentTimeMillis());
            rowData.put(Proximity_Sensor.MAXIMUM_RANGE, sensor.getMaximumRange());
            rowData.put(Proximity_Sensor.MINIMUM_DELAY, sensor.getMinDelay());
            rowData.put(Proximity_Sensor.NAME, sensor.getName());
            rowData.put(Proximity_Sensor.POWER_MA, sensor.getPower());
            rowData.put(Proximity_Sensor.RESOLUTION, sensor.getResolution());
            rowData.put(Proximity_Sensor.TYPE, sensor.getType());
            rowData.put(Proximity_Sensor.VENDOR, sensor.getVendor());
            rowData.put(Proximity_Sensor.VERSION, sensor.getVersion());

            try {
                getContentResolver().insert(Proximity_Sensor.CONTENT_URI, rowData);
                if( Aware.DEBUG ) Log.d(TAG, "Proximity sensor: "+ rowData.toString());
            }catch( SQLiteException e ) {
                if(Aware.DEBUG) Log.d(TAG,e.getMessage());
            }catch( SQLException e ) {
                if(Aware.DEBUG) Log.d(TAG,e.getMessage());
            }
        }else sensorInfo.close();
    }

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

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);

        mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

        if(mProximity == null) {
            if(Aware.DEBUG) Log.w(TAG,"This device does not have a proximity sensor!");
            stopSelf();
        }

        TAG = Aware.getSetting(getContentResolver(),"debug_tag").length()>0?Aware.getSetting(getContentResolver(),"debug_tag"):"AWARE::Proximity";
        try {
            SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(),Aware_Preferences.FREQUENCY_PROXIMITY));
        } catch( NumberFormatException e ) {
            Aware.setSetting(getContentResolver(), Aware_Preferences.FREQUENCY_PROXIMITY, 200000);
            SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(),Aware_Preferences.FREQUENCY_PROXIMITY));
        }

        sensorThread = new HandlerThread(TAG);
        sensorThread.start();

        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();

        sensorHandler = new Handler(sensorThread.getLooper());
        mSensorManager.registerListener(this, mProximity, SENSOR_DELAY, sensorHandler);

        saveSensorDevice(mProximity);

        DATABASE_TABLES = Proximity_Provider.DATABASE_TABLES;
        TABLES_FIELDS = Proximity_Provider.TABLES_FIELDS;
        CONTEXT_URIS = new Uri[]{ Proximity_Sensor.CONTENT_URI, Proximity_Data.CONTENT_URI };

        if(Aware.DEBUG) Log.d(TAG,"Proximity service created!");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        sensorHandler.removeCallbacksAndMessages(null);
        mSensorManager.unregisterListener(this, mProximity);
        sensorThread.quit();

        wakeLock.release();

        if(Aware.DEBUG) Log.d(TAG,"Proximity service terminated...");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        TAG = Aware.getSetting(getContentResolver(),"debug_tag").length()>0?Aware.getSetting(getContentResolver(),"debug_tag"):"AWARE::Proximity";
        try {
            SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(),Aware_Preferences.FREQUENCY_PROXIMITY));
        } catch( NumberFormatException e ) {
            Aware.setSetting(getContentResolver(), Aware_Preferences.FREQUENCY_PROXIMITY, 200000);
            SENSOR_DELAY = Integer.parseInt(Aware.getSetting(getContentResolver(),Aware_Preferences.FREQUENCY_PROXIMITY));
        }

        if(intent.getBooleanExtra("refresh", false)) {
            sensorHandler.removeCallbacksAndMessages(null);
            mSensorManager.unregisterListener(this, mProximity);
            mSensorManager.registerListener(this, mProximity, SENSOR_DELAY, sensorHandler);
        }

        if(Aware.DEBUG) Log.d(TAG,"Proximity service active...");

        return START_STICKY;
    }

    //Singleton instance of this service
    private static Proximity proximitySrv = Proximity.getService();

    /**
     * Get singleton instance to service
     * @return Proximity obj
     */
    public static Proximity getService() {
        if( proximitySrv == null ) proximitySrv = new Proximity();
        return proximitySrv;
    }

    private final IBinder serviceBinder = new ServiceBinder();
    public class ServiceBinder extends Binder {
        Proximity getService() {
            return Proximity.getService();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return serviceBinder;
    }
}


text:
package com.pada.mongo.aop;

import java.lang.reflect.Field;
import java.util.Collection;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.mapping.model.MappingException;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import com.pada.mongo.annotation.CascadeSave;
import com.pada.mongo.domain.BaseDomain;
import com.pada.mongo.event.IdIncrementEvent;

@Aspect
@Component
public class MongoDBIdAOP {
    @Autowired
    private IdIncrementEvent incrementEvent;

    @Autowired
    private MongoOperations mongoOperations;

    @Pointcut("execution(* org.springframework.data.mongodb.repository.MongoRepository.save(..))")
    public void dBIdCutPoint() {
    }

    @Around(value = "dBIdCutPoint()")
    public Object pointCut(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object = joinPoint.getArgs()[0];
        if (object instanceof Collection) {
            Iterable<?> iterable = (Iterable<?>) object;
            for (Object _o : iterable) {
                if (_o instanceof BaseDomain) {
                    setId((BaseDomain) _o);
                    onBeforeSave(_o);  //在 Save 之前先检查该 Object 中是否需要级联存储
                }
            }
        } else {
            if (object instanceof BaseDomain) {
                setId((BaseDomain) object);
                onBeforeSave(object); //在 Save 之前先检查该 Object 中是否需要级联存储
            }

        }
        return joinPoint.proceed();
    }

    private synchronized void setId(BaseDomain baseDomain) {
        incrementEvent.incrementIdSetting(baseDomain);
    }

    private void onBeforeSave(final Object source) {

        // 遍历 source 中所有的 field, 如果 field 存在同时有 @DBRef 和 @CascadeSave
        // 则需要将该 field 设置 Id 并进行存储
        // 暂无考虑 field 为 Collection 的情况
        ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {

            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                ReflectionUtils.makeAccessible(field);

                if (field.isAnnotationPresent(DBRef.class) && field.isAnnotationPresent(CascadeSave.class)) {
                    final Object fieldValue = field.get(source);

                    DbRefFieldCallback callback = new DbRefFieldCallback();

                    ReflectionUtils.doWithFields(fieldValue.getClass(), callback);

                    if (!callback.isIdFound()) {
                        throw new MappingException("Cannot perform cascade save on child object without id set");
                    }
                    setId((BaseDomain) fieldValue);
                    mongoOperations.save(fieldValue);
                }
            }
        });
    }

    private static class DbRefFieldCallback implements ReflectionUtils.FieldCallback {
        private boolean idFound;

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            ReflectionUtils.makeAccessible(field);

            if (field.isAnnotationPresent(Id.class)) {
                idFound = true;
            }
        }

        public boolean isIdFound() {
            return idFound;
        }
    }

}


text:
package com.road7.blurswf.data.tags;

public class ExportAssetsTag extends Tag {

	public ExportAssetsTag() {
		// TODO Auto-generated constructor stub
	}

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.01.18 at 06:14:35 PM CST
//

package org.astm.ccr;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

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

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Practitioner" type="{urn:astm-org:CCR}ActorReferenceType" maxOccurs="unbounded"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "practitioner"
})
@XmlRootElement(name = "Practitioners")
public class Practitioners {

    @XmlElement(name = "Practitioner", required = true)
    protected List<ActorReferenceType> practitioner;

    /**
     * Gets the value of the practitioner property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the practitioner property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getPractitioner().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ActorReferenceType }
     *
     *
     */
    public List<ActorReferenceType> getPractitioner() {
        if (practitioner == null) {
            practitioner = new ArrayList<ActorReferenceType>();
        }
        return this.practitioner;
    }

}


text:
package org.jabref.logic.importer.fetcher;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import org.jabref.logic.cleanup.DoiCleanup;
import org.jabref.logic.cleanup.FieldFormatterCleanup;
import org.jabref.logic.cleanup.FieldFormatterCleanups;
import org.jabref.logic.formatter.bibtexfields.ClearFormatter;
import org.jabref.logic.help.HelpFile;
import org.jabref.logic.importer.FetcherException;
import org.jabref.logic.importer.ImportFormatPreferences;
import org.jabref.logic.importer.Parser;
import org.jabref.logic.importer.SearchBasedParserFetcher;
import org.jabref.logic.importer.fetcher.transformers.DBLPQueryTransformer;
import org.jabref.logic.importer.fileformat.BibtexParser;
import org.jabref.logic.layout.LayoutFormatterBasedFormatter;
import org.jabref.logic.layout.format.RemoveLatexCommandsFormatter;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.entry.field.StandardField;
import org.jabref.model.util.DummyFileUpdateMonitor;

import org.apache.http.client.utils.URIBuilder;
import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode;

/**
 * Fetches BibTeX data from DBLP (dblp.org)
 *
 * @see Basic API documentation
 */
public class DBLPFetcher implements SearchBasedParserFetcher {
    public static final String FETCHER_NAME = "DBLP";

    private static final String BASIC_SEARCH_URL = "https://dblp.org/search/publ/api";

    private final ImportFormatPreferences importFormatPreferences;

    public DBLPFetcher(ImportFormatPreferences importFormatPreferences) {
        Objects.requireNonNull(importFormatPreferences);
        this.importFormatPreferences = importFormatPreferences;
    }

    @Override
    public URL getURLForQuery(QueryNode luceneQuery) throws URISyntaxException, MalformedURLException, FetcherException {
        URIBuilder uriBuilder = new URIBuilder(BASIC_SEARCH_URL);
        uriBuilder.addParameter("q", new DBLPQueryTransformer().transformLuceneQuery(luceneQuery).orElse(""));
        uriBuilder.addParameter("h", String.valueOf(100)); // number of hits
        uriBuilder.addParameter("c", String.valueOf(0)); // no need for auto-completion
        uriBuilder.addParameter("f", String.valueOf(0)); // "from", index of first hit to download
        uriBuilder.addParameter("format", "bib1");

        return uriBuilder.build().toURL();
    }

    @Override
    public Parser getParser() {
        return new BibtexParser(importFormatPreferences, new DummyFileUpdateMonitor());
    }

    @Override
    public void doPostCleanup(BibEntry entry) {
        DoiCleanup doiCleaner = new DoiCleanup();
        doiCleaner.cleanup(entry);

        FieldFormatterCleanups cleanups = new FieldFormatterCleanups(true,
                List.of(
                        new FieldFormatterCleanup(StandardField.TIMESTAMP, new ClearFormatter()),
                        // unescape the the contents of the URL field, e.g., some\_url\_part becomes some_url_part
                        new FieldFormatterCleanup(StandardField.URL, new LayoutFormatterBasedFormatter(new RemoveLatexCommandsFormatter()))
                ));
        cleanups.applySaveActions(entry);
    }

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

    @Override
    public Optional<HelpFile> getHelpPage() {
        return Optional.of(HelpFile.FETCHER_DBLP);
    }
}


text:
Hapi Datadog Reporter
=====================

> [hapi-datadog][1] is a [hapi][2] plugin which reports metrics and events to [DataDog][3].

:warning: This plugin is built for Hapi 8 and doesn't currently support any older versions.

:construction: This plugin is still in it's initial stages of development and shouldn't be used in production.

Installation
------------

Firstly install the node module:

```sh
npm install --save hapi-datadog
```

Then add the plugin to your server:

```js
var Hapi = require('hapi');
var HapiDatadog = require('hapi-datadog');
var StatsD = require('node-dogstatsd').StatsD;

var server = new Hapi.Server();

server.register({
  plugin: HapiDatadog,
  options: {
    stats: new StatsD(),
  }
}, function (err) {
  if (err) {
    console.error(err);
    return;
  }
});
```

:grey_exclamation: Note that you will need to have the DataDog agent installed
on your server so that stats can be reported back.

Stats collected
---------------

### Metrics
- **http.response.count** as a counter for the number of requests
- **http.response.time** as the time taken to send a response to the request

### Tags
- request-host:*{request.info.host}*
- route-path:*{request.route.path}*
- route-method:*{request.route.method}*
- route-vhost:*{request.route.vhost}*
- response-status:*{request.response.statusCode}*

 [1]: https://github.com/Josiah/hapi-datadog
 [2]: http://hapijs.com "Hapi - Server Framework for Node.js"
 [3]: http://www.datadoghq.com "DataDog"


text:
angular.module('foodController', [])

	// inject the Todo service factory into our controller
	.controller('mainController', ['$scope', '$http', 'Foods', function ($scope, $http, Foods) {
		$scope.formData = {};
		$scope.loading = true;

		// GET =====================================================================
		// when landing on the page, get all foods and show them
		// use the service to get all the foods
        Foods.get()
            .success(function (data) {
                $scope.foods = data;
                $scope.loading = false;
            });

		// CREATE ==================================================================
		// when submitting the add form, send the text to the node API
		$scope.createFood = function () {

			// validate the formData to make sure that something is there
			// if form is empty, nothing will happen
			if ($scope.formData.food_name !== undefined || $scope.formData.price !== undefined) {
				$scope.loading = true;

				// call the create function from our service (returns a promise object)
				Foods.create($scope.formData)

					// if successful creation, call our get function to get all the new foods
					.success(function (data) {
						$scope.loading = false;
                        // $scope.food.food_name = $scope.formData.food_name; // assign our new list of todos
                        // $scope.food.price = $scope.formData.price; // assign our new list of todos
                        $scope.formData = {}; // clear the form so our user is ready to enter another
                        $scope.foods = data;
					});
			}
		};

		// DELETE ==================================================================
		// delete a food after checking it
		$scope.deleteFood = function (food_name) {
			$scope.loading = true;

			Foods.delete(food_name)
				// if successful creation, call our get function to get all the new foods
				.success(function (data) {
					$scope.loading = false;
					$scope.foods = data; // assign our new list of foods
				});
		};

        // TOTAL ==================================================================
		// get total of all the food items
		$scope.getTotal = function () {
			$scope.loading = true;

			Foods.total()
				// if successful call our get function to get total of all the food items
				.success(function (data) {
                    $scope.total = data;
                    $scope.loading = false;

				});
		};
	}]);


text:
package io.dropwizard.http2;

import io.dropwizard.Configuration;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.util.Optional;

import static io.dropwizard.testing.ConfigOverride.config;
import static io.dropwizard.testing.ResourceHelpers.resourceFilePath;

public class Http2WithCustomCipherTest extends AbstractHttp2Test {

    private static final String PREFIX = "tls_custom_http2";

    @Rule
    public final DropwizardAppRule<Configuration> appRule = new DropwizardAppRule<>(
        FakeApplication.class, resourceFilePath("test-http2-with-custom-cipher.yml"),
        Optional.of(PREFIX),
        config(PREFIX, "server.connector.keyStorePath", resourceFilePath("stores/http2_server.jks")),
        config(PREFIX, "server.connector.trustStorePath", resourceFilePath("stores/http2_client.jts"))
    );

    private final SslContextFactory sslContextFactory = new SslContextFactory();
    private HttpClient client;

    @Before
    public void setUp() throws Exception {
        sslContextFactory.setTrustStorePath(resourceFilePath("stores/http2_client.jts"));
        sslContextFactory.setTrustStorePassword("http2_client");
        sslContextFactory.start();

        client = new HttpClient(new HttpClientTransportOverHTTP2(new HTTP2Client()), sslContextFactory);
        client.start();
    }

    @After
    public void tearDown() throws Exception {
        client.stop();
    }

    @Test
    public void testHttp2WithCustomCipher() throws Exception {
        assertResponse(client.GET("https://localhost:" + appRule.getLocalPort() + "/api/test"));
    }

}


text:
title: Using different logs per environment in ASP.NET Core
description: Learn about how to log to individual elmah.io logs per ASP.NET Core environment. Let you set up notifications, apps and more for production only.
---

# Using different logs per environment in ASP.NET Core

We are often asked the question: Should I create a log per environment and how do I set it up with ASP.NET Core.

Creating a log per environment (staging, production, etc.) is a good idea since you probably want different notification rules and/or user access depending on the environment. We usually recommend a log per environment and disabling logging when running on localhost. There can be advantages in logging errors from developer machines, but every error counts against your monthly quota. This document provides a range of possibilities for setting up a log per environment.

## Using appsettings.{Environment}.json

All ASP.NET Core websites read an environment variable named `ASPNETCORE_ENVIRONMENT`. The value can be used to set config variables depending on the current environment. The feature works a bit like Web.config transformations that you may remember from the good old ASP.NET days. The value of `ASPNETCORE_ENVIRONMENT` can be tailored to your need but the following three values are provided out of the box: `Development`, `Staging`, and `Production`.

To only add elmah.io when on staging or production, you can add the following code when setting up the elmah.io middleware:

```csharp
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...
    if (env.IsProduction() || env.IsStaging())
    {
        app.UseElmahIo();
    }
    // ...
}
```

To create errors in different logs depending on the current environment, create two new files: `appsettings.staging.json` and `appsettings.production.json`. Add the `ElmahIo` config section to both files:

```json
{
  "ElmahIo": {
    "ApiKey": "API_KEY",
    "LogId": "LOG_ID"
  }
}
```

Inside each file, replace `API_KEY` with your API key and `LOG_ID` with the different log IDs.

The downside of this approach is that you have your production API key and log ID in source control.

## Using Azure Application settings

If you are hosting on Azure (other cloud hosting platforms have a similar feature), you can utilize the built-in Application settings feature to avoid adding API keys and log IDs to source control. Using application settings requires you to specify your elmah.io configuration in the `appsettings.json` file or one of the environment-specific files as shown above.

To replace the values inside the `ApiKey` and `LogId` properties, use the colon syntax as shown here:

![Azure Application settings](images/azure-application-settings.png)

(replace `API_KEY` and `LOG_ID` with your staging or production values depending on which environment you are configuring)


text:
package org.apache.dubbo.rpc.cluster.support;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.cluster.Directory;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * ForkingClusterInvokerTest
 */
@SuppressWarnings("unchecked")
public class ForkingClusterInvokerTest {

    private List<Invoker<ForkingClusterInvokerTest>> invokers = new ArrayList<Invoker<ForkingClusterInvokerTest>>();
    private URL url = URL.valueOf("test://test:11/test?forks=2");
    private Invoker<ForkingClusterInvokerTest> invoker1 = mock(Invoker.class);
    private Invoker<ForkingClusterInvokerTest> invoker2 = mock(Invoker.class);
    private Invoker<ForkingClusterInvokerTest> invoker3 = mock(Invoker.class);
    private RpcInvocation invocation = new RpcInvocation();
    private Directory<ForkingClusterInvokerTest> dic;
    private Result result = new AppResponse();

    @BeforeEach
    public void setUp() throws Exception {

        dic = mock(Directory.class);

        given(dic.getUrl()).willReturn(url);
        given(dic.list(invocation)).willReturn(invokers);
        given(dic.getInterface()).willReturn(ForkingClusterInvokerTest.class);

        invocation.setMethodName("method1");

        invokers.add(invoker1);
        invokers.add(invoker2);
        invokers.add(invoker3);

    }

    private void resetInvokerToException() {
        given(invoker1.invoke(invocation)).willThrow(new RuntimeException());
        given(invoker1.getUrl()).willReturn(url);
        given(invoker1.isAvailable()).willReturn(true);
        given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class);

        given(invoker2.invoke(invocation)).willThrow(new RuntimeException());
        given(invoker2.getUrl()).willReturn(url);
        given(invoker2.isAvailable()).willReturn(true);
        given(invoker2.getInterface()).willReturn(ForkingClusterInvokerTest.class);

        given(invoker3.invoke(invocation)).willThrow(new RuntimeException());
        given(invoker3.getUrl()).willReturn(url);
        given(invoker3.isAvailable()).willReturn(true);
        given(invoker3.getInterface()).willReturn(ForkingClusterInvokerTest.class);
    }

    private void resetInvokerToNoException() {
        given(invoker1.invoke(invocation)).willReturn(result);
        given(invoker1.getUrl()).willReturn(url);
        given(invoker1.isAvailable()).willReturn(true);
        given(invoker1.getInterface()).willReturn(ForkingClusterInvokerTest.class);

        given(invoker2.invoke(invocation)).willReturn(result);
        given(invoker2.getUrl()).willReturn(url);
        given(invoker2.isAvailable()).willReturn(true);
        given(invoker2.getInterface()).willReturn(ForkingClusterInvokerTest.class);

        given(invoker3.invoke(invocation)).willReturn(result);
        given(invoker3.getUrl()).willReturn(url);
        given(invoker3.isAvailable()).willReturn(true);
        given(invoker3.getInterface()).willReturn(ForkingClusterInvokerTest.class);
    }

    @Test
    public void testInvokeException() {
        resetInvokerToException();
        ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<ForkingClusterInvokerTest>(
                dic);

        try {
            invoker.invoke(invocation);
            Assertions.fail();
        } catch (RpcException expected) {
            Assertions.assertTrue(expected.getMessage().contains("Failed to forking invoke provider"));
            assertFalse(expected.getCause() instanceof RpcException);
        }
    }

    @Test
    public void testClearRpcContext() {
        resetInvokerToException();
        ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<ForkingClusterInvokerTest>(
                dic);

        String attachKey = "attach";
        String attachValue = "value";

        RpcContext.getContext().setAttachment(attachKey, attachValue);

        Map<String, Object> attachments = RpcContext.getContext().getAttachments();
        Assertions.assertTrue(attachments != null && attachments.size() == 1, "set attachment failed!");
        try {
            invoker.invoke(invocation);
            Assertions.fail();
        } catch (RpcException expected) {
            Assertions.assertTrue(expected.getMessage().contains("Failed to forking invoke provider"), "Succeeded to forking invoke provider !");
            assertFalse(expected.getCause() instanceof RpcException);
        }
        Map<String, Object> afterInvoke = RpcContext.getContext().getAttachments();
        Assertions.assertTrue(afterInvoke != null && afterInvoke.size() == 0, "clear attachment failed!");
    }

    @Test()
    public void testInvokeNoException() {

        resetInvokerToNoException();

        ForkingClusterInvoker<ForkingClusterInvokerTest> invoker = new ForkingClusterInvoker<ForkingClusterInvokerTest>(
                dic);
        Result ret = invoker.invoke(invocation);
        Assertions.assertSame(result, ret);
    }

}


text:
package org.springframework.social.strava.api;

import java.io.Serializable;

public class StravaAthleteProfile implements Serializable {
    private long id;
    private String firstName;
    private String lastName;
    private String email;
    private String avatarMedium;
    private String avatarLarge;

    public StravaAthleteProfile(long id, String firstName, String lastName, String email, String avatarMedium, String avatarLarge) {
        this.id = id;
        this.email = email;
        this.avatarMedium = avatarMedium;
        this.avatarLarge = avatarLarge;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return firstName + " " + lastName;
    }

    public String getEmail() {
        return email;
    }

    public String getAvatarMedium() {
        return avatarMedium;
    }

    public String getAvatarLarge() {
        return avatarLarge;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


text:
module Skynet::ObjectExtensions

  def send_later(method, *arguments, &block)

    raise ArgumentError("send_later can not serialize blocks.") if block_given?

    if is_a?(Class) or is_a?(Module)
      data = {
        :class_name => name,
        :method     => method,
        :arguments  => arguments
      }.to_yaml
    else
      data = {
        :object    => self,
        :method    => method,
        :arguments => arguments
      }.to_yaml
    end

    jobopts = {
      :single                => true,
      :mappers               => 1,
      :map_data              => [data],
      :name                  => "send_later #{data[:class_name] ? "#{self}.#{method}" : "#{self.class}##{method}"}",
      :map_name              => "",
      :map_timeout           => 2.minutes,
      :reduce_timeout        => 2.minutes,
      :master_timeout        => 2.minutes,
      :master_result_timeout => 2.minutes,
      :map_reduce_class      => Skynet::ObjectAsync,
      :master_retry          => 0,
      :map_retry             => 0
    }
    job = Skynet::AsyncJob.new(jobopts)
    job.run

  end

  private

  def method_missing(method_id, *arguments, &block)
    return super unless method_id.to_s =~ /^(.*)_later$/
    send_later($1, *arguments)
  end

end

Object.send :include, Skynet::ObjectExtensions

class Skynet::ObjectAsync
  include SkynetDebugger

  class << self
    def map(datas)
      begin
        datas.each do |yaml|
          data = YAML.load(yaml)
          data[:object] = data[:class_name].constantize if data[:class_name]
          data[:object].send(data[:method], *data[:arguments])
        end
      rescue Exception => e
        error "Error in #{self} #{e.inspect} with data #{datas.inspect}"
      end
      return
    end
  end
end