START SNIPPET: patientInstanceOperation
540543
@Operation(name="$everything", idempotent=true)
   public Bundle patientInstanceOperation(
      @IdParam IdDt thePatientId,
      @OperationParam(name="start") DateDt theStart,
      @OperationParam(name="end") DateDt theEnd) {
      
      Bundle retVal = new Bundle();
      // Populate bundle with matching resources
      return retVal;
   }
8671
def start(instance_id, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The stop action must be called with -a or --action.'
        )

    log.info('Starting instance %s', instance_id)

    params = {
        'action': 'StartInstances',
        'zone': _get_specified_zone(provider=get_configured_provider()),
        'instances.1': instance_id,
    }
    result = query(params)

    return result
109723
private Map<ServiceInstanceToken, InstanceHealthPair> getCacheServiceInstances() {
        if (instanceCache == null) {
            synchronized (this) {
                if (instanceCache == null) {
                    instanceCache = new ConcurrentHashMap<ServiceInstanceToken, InstanceHealthPair>();
                    initJobTasks();
                }
            }
        }
        return instanceCache;
    }
1054464
@Override
    public void start() throws Exception
    {
        try
        {
            reRegisterServices();
        }
        catch ( KeeperException e )
        {
            log.error("Could not register instances - will try again later", e);
        }
        client.getConnectionStateListenable().addListener(connectionStateListener);
    }
285801
private void processRunnableOperations(
            final Consumer<WorkflowSystem.OperationResult<DAT, RES, OP>> resultConsumer,
            final List<OP> shouldrun,
            final List<OP> shouldskip,
            final DAT inputData
    )
    {
        for (final OP operation : shouldrun) {
            if (shouldskip.contains(operation)) {
                continue;
            }
            pending.remove(operation);

            workflowEngine.event(
                    WorkflowSystemEventType.WillRunOperation,
                    String.format("operation starting: %s", operation),
                    operation
            );
            final ListenableFuture<RES> submit = executorService.submit(() -> operation.apply(inputData));
            inProcess.add(operation);
            futures.add(submit);
            FutureCallback<RES> callback = new FutureCallback<RES>() {
                @Override
                public void onSuccess(final RES successResult) {
                    workflowEngine.event(
                            WorkflowSystemEventType.OperationSuccess,
                            String.format("operation succeeded: %s", successResult),
                            successResult
                    );
                    assert successResult != null;
                    WorkflowSystem.OperationResult<DAT, RES, OP> result = result(successResult, operation);
                    resultConsumer.accept(result);
                    stateChangeQueue.add(successResult);
                    inProcess.remove(operation);
                }

                @Override
                public void onFailure(final Throwable t) {
                    workflowEngine.event(
                            WorkflowSystemEventType.OperationFailed,
                            String.format("operation failed: %s", t),
                            t
                    );
                    WorkflowSystem.OperationResult<DAT, RES, OP> result = result(t, operation);
                    resultConsumer.accept(result);
                    StateObj newFailureState = operation.getFailureState(t);
                    if (null != newFailureState && newFailureState.getState().size() > 0) {
                        WorkflowSystem.OperationCompleted<DAT> objectOperationCompleted = WorkflowEngine.dummyResult(
                                newFailureState);
                        stateChangeQueue.add(objectOperationCompleted);
                    }
                    inProcess.remove(operation);
                }
            };

            Futures.addCallback(submit, callback, manager);
        }
    }
163722
public void callProcedure(AuthUser user,
                              boolean isAdmin,
                              int timeout,
                              ProcedureCallback cb,
                              String procName,
                              Object[] args)
    {
        // since we know the caller, this is safe
        assert(cb != null);

        StoredProcedureInvocation task = new StoredProcedureInvocation();
        task.setProcName(procName);
        task.setParams(args);
        if (timeout != BatchTimeoutOverrideType.NO_TIMEOUT) {
            task.setBatchTimeout(timeout);
        }

        InternalAdapterTaskAttributes kattrs = new InternalAdapterTaskAttributes(
                DEFAULT_INTERNAL_ADAPTER_NAME, isAdmin, connectionId());

        assert(m_dispatcher != null);

        // JHH: I have no idea why we need to do this, but CL crashes if we don't. Sigh.
        try {
            task = MiscUtils.roundTripForCL(task);
        } catch (Exception e) {
            String msg = String.format("Cannot invoke procedure %s. failed to create task: %s",
                    procName, e.getMessage());
            m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.ERROR, null, msg);
            ClientResponseImpl cri = new ClientResponseImpl(ClientResponse.UNEXPECTED_FAILURE, new VoltTable[0], msg);
            try {
                cb.clientCallback(cri);
            } catch (Exception e1) {
                throw new IllegalStateException(e1);
            }
        }

        createTransaction(kattrs, cb, task, user);
    }
572269
def get_patient_pharmacies(self, patient_id,
                               patients_favorite_only='N'):
        
        magic = self._magic_json(
            action=TouchWorksMagicConstants.ACTION_GET_PATIENT_PHARAMCIES,
            patient_id=patient_id,
            parameter1=patients_favorite_only)
        response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic)
        result = self._get_results_or_raise_if_magic_invalid(
            magic,
            response,
            TouchWorksMagicConstants.RESULT_GET_PATIENT_PHARAMCIES)
        return result
1294734
public void loadClinicalAnnotation() {

        /**
         * Initialize VEP reader
         */
        logger.info("Initializing VEP reader...");
        VepFormatReader vepFormatReader = new VepFormatReader(clinicalAnnotationFilename.toString());
        vepFormatReader.open();
        vepFormatReader.pre();

        /**
         * Prepare clinical adaptor
         */
        logger.info("Initializing adaptor, connecting to the database...");
        logger.error("Implementation of this functionality  is outdated and must be re-written if needed");

        // TODO: this shall be done in a different way - old Java API was deprecated and removed

//        System.out.println("cellBaseConfiguration = " + configuration.getDatabase().getUser());
//        System.out.println("cellBaseConfiguration = " + configuration.getDatabase().getHost());
//        System.out.println("cellBaseConfiguration = " + configuration.getDatabase().getPassword());
//        DBAdaptorFactory dbAdaptorFactory = new MongoDBAdaptorFactory(configuration);
//        ClinicalDBAdaptor clinicalDBAdaptor = dbAdaptorFactory.getClinicalLegacyDBAdaptor("hsapiens", assembly);
//
//        /**
//         * Load annotations
//         */
//        logger.info("Reading/Loading variant annotations...");
//        int nVepAnnotatedVariants = 0;
//        List<VariantAnnotation> variantAnnotationList = vepFormatReader.read(CLINICAL_ANNOTATION_BATCH_SIZE);
//        while (!variantAnnotationList.isEmpty()) {
//            nVepAnnotatedVariants += variantAnnotationList.size();
//            clinicalDBAdaptor.updateAnnotations(variantAnnotationList, new QueryOptions());
//            logger.info(Integer.valueOf(nVepAnnotatedVariants) + " read variants with vep annotations");
//            variantAnnotationList = vepFormatReader.read(CLINICAL_ANNOTATION_BATCH_SIZE);
//        }

//
//        vepFormatReader.post();
//        vepFormatReader.close();
//        logger.info(nVepAnnotatedVariants + " VEP annotated variants were read from " + clinicalAnnotationFilename.toString());
//        logger.info("Finished");
    }
1263722
@Override
    protected void onStart() {
        super.onStart();
        mApiClient = new GoogleApiClient.Builder(this)
                .addApi(Wearable.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mApiClient.connect();
    }
4395
function CommonOperation(operationFunc, callback) {
  this.status = OperationState.Inited;
  this.operationId = -1;
  this._callbackArguments = null;
  var sliceStart = 2;
  if (azureutil.objectIsFunction(callback)) {
    this._userCallback = callback;
  } else {
    this._userCallback = null;
    sliceStart = 1;
  }
  var operationArguments = Array.prototype.slice.call(arguments).slice(sliceStart);
  this.run = function (cb) {
    if (!cb) cb = this._userCallback;
    operationArguments.push(cb);
    this.status = OperationState.RUNNING;
    operationFunc.apply(null, operationArguments);
    operationArguments = operationFunc = null;
  };
  
  this._fireUserCallback = function () {
    if (this._userCallback) {
      this._userCallback.apply(null, this._callbackArguments);
    }
    this._userCallback = this._callbackArguments = null;
  };
}
1043141
public static void initCustomerSession(@NonNull Context context,
                                           @NonNull EphemeralKeyProvider keyProvider) {
        setInstance(new CustomerSession(context, keyProvider));
    }
259885
private Object getJavaObjectInstance(Context c, Hashtable<?, ?> envmt, String className, String bindingName, ResourceInfo resourceRefInfo, IndirectReference ref) throws Exception {
        // Return null if we don't find a binding so that the caller can
        // use JNDI if enabled.
        Object resource = null;

        NamingConstants.JavaColonNamespace namespace = NamingConstants.JavaColonNamespace.match(bindingName);
        if (namespace != null) {
            ComponentMetaData cmd = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor().getComponentMetaData();
            if (cmd != null) {
                OSGiInjectionScopeData isd = injectionEngine.getInjectionScopeData(cmd, namespace);
                if (isd != null) {
                    String name = namespace.unprefix(bindingName);

                    InjectionBinding<?> binding = isd.getInjectionBinding(namespace, name);
                    if (binding == null && isd.processDeferredReferenceData()) {
                        // Try again after processing deferred reference data.
                        binding = isd.getInjectionBinding(namespace, name);
                    }

                    if (binding != null) {
                        resource = getBindingObjectInstance(c, envmt, className, resourceRefInfo, ref, binding);
                    }
                }
            }

            if (resource == null && namespace == NamingConstants.JavaColonNamespace.COMP) {
                resource = getDefaultJavaCompObjectInstance(namespace, bindingName, resourceRefInfo);
            }

            // If not found and the customer did not provide a binding, then try and
            // auto-link to a resource that matches on name in the service registry.
            if (resource == null && ref.defaultBinding && !ref.name.startsWith("java:")) {
                resource = createResource(ref.name, className, ref.name, resourceRefInfo);
            }
        }

        return resource;
    }
1048928
def get_task(self, patient_id, task_id):
        
        magic = self._magic_json(
            action=TouchWorksMagicConstants.ACTION_GET_TASK,
            patient_id=patient_id,
            parameter1=task_id)
        response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic)
        result = self._get_results_or_raise_if_magic_invalid(
            magic,
            response,
            TouchWorksMagicConstants.RESULT_GET_TASK)
        return result
967370
def execute(self):
        """"""
        self.provider.authenticate()
        identifier = self.config.resolve('lexicon:identifier')
        record_type = self.config.resolve('lexicon:type')
        name = self.config.resolve('lexicon:name')
        content = self.config.resolve('lexicon:content')

        if self.action == 'create':
            return self.provider.create_record(record_type, name, content)

        if self.action == 'list':
            return self.provider.list_records(record_type, name, content)

        if self.action == 'update':
            return self.provider.update_record(identifier, record_type, name, content)

        if self.action == 'delete':
            return self.provider.delete_record(identifier, record_type, name, content)

        raise ValueError('Invalid action statement: {0}'.format(self.action))
1068952
private void validateResource(Patient thePatient) {
		/*
		 * Our server will have a rule that patients must have a family name or we will reject them
		 */
		if (thePatient.getNameFirstRep().getFamilyFirstRep().isEmpty()) {
			OperationOutcome outcome = new OperationOutcome();
			outcome.addIssue().setSeverity(IssueSeverityEnum.FATAL).setDetails("No family name provided, Patient resources must have at least one family name.");
			throw new UnprocessableEntityException(outcome);
		}
	}
1214438
private void addNewVersion(Patient thePatient, Long theId) {
		InstantDt publishedDate;
		if (!myIdToPatientVersions.containsKey(theId)) {
			myIdToPatientVersions.put(theId, new LinkedList<Patient>());
			publishedDate = InstantDt.withCurrentTime();
		} else {
			Patient currentPatitne = myIdToPatientVersions.get(theId).getLast();
			Map<ResourceMetadataKeyEnum<?>, Object> resourceMetadata = currentPatitne.getResourceMetadata();
			publishedDate = (InstantDt) resourceMetadata.get(ResourceMetadataKeyEnum.PUBLISHED);
		}

		/*
		 * PUBLISHED time will always be set to the time that the first version was stored. UPDATED time is set to the time that the new version was stored.
		 */
		thePatient.getResourceMetadata().put(ResourceMetadataKeyEnum.PUBLISHED, publishedDate);
		thePatient.getResourceMetadata().put(ResourceMetadataKeyEnum.UPDATED, InstantDt.withCurrentTime());

		Deque<Patient> existingVersions = myIdToPatientVersions.get(theId);

		// We just use the current number of versions as the next version number
		String newVersion = Integer.toString(existingVersions.size());
		
		// Create an ID with the new version and assign it back to the resource
		IdDt newId = new IdDt("Patient", Long.toString(theId), newVersion);
		thePatient.setId(newId);
		
		existingVersions.add(thePatient);
	}
930375
def add_patient(patient)
      raise ArgumentError, "Invalid argument 'patient'. Expected Patient, got #{patient.class}." unless patient.is_a?(Patient)
      # Do not add it again if the patient already belongs to this instance:
      @patients << patient unless @associated_patients[patient.id]
      @associated_patients[patient.id] = patient
    end