text:
copyright:
  years: 2016
lastupdated:  "2016-09-12"

---

#	Professional 1 Application-Plan verwenden
{: #using_mobilefoundation_p2}

Mit dem Professional 1 Application-Plan können Benutzer 1 mobile Anwendung mit mehreren Betriebssystemen für mobile Geräte erstellen.
Nach der Erstellung der Serviceinstanz von {{site.data.keyword.mobilefoundation_short}}: Professional 1 Application lesen Sie die folgende Prozedur, um die Arbeit mit dem Service zu beginnen.

## Voraussetzungen
{: #prerequisites_p2}

Beachten Sie Folgendes, bevor Sie die Serviceinstanz von {{site.data.keyword.mobilefoundation_short}}: Professional 1 Application konfigurieren.
* {{site.data.keyword.mobilefoundation_short}}: Professional 1 Application wird  nur von {{site.data.keyword.dashdbshort_notm}}: Enterprise Transactional (Unterstützung für OLTP) {{site.data.keyword.Bluemix_notm}}-Plänen unterstützt.

* Sie benötigen Zugriff auf die Berechtigungsnachweise der {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz, bevor Sie die Einstellungen für die {{site.data.keyword.mobilefoundation_short}}-Serviceinstanz konfigurieren.

**Hinweis**: Die {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz kann sich in jedem `Bereich` in Ihrer {{site.data.keyword.Bluemix_notm}}-`Organisation` bzw. in jeder anderen `Organisation`, auf die Sie zugreifen können, befinden. Stellen Sie sicher, dass Sie über die Berechtigungen für den Zugriff auf den `Bereich` verfügen, in dem sich die {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz befindet.

## Datenbankverbindung hinzufügen
{: #configure_dashdb_p2}

###  Erste Schritte
{: #firststeps_p2}

Führen Sie nach der Erstellung der Serviceinstanz von {{site.data.keyword.mobilefoundation_short}}: Professional 1 Application die nachfolgend beschriebene Prozedur aus, um mit der Verwendung des Service zu beginnen.

### Stellen Sie eine Verbindung zur {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz her.
{: #connect_dashdb_p2}

Nachdem die Serviceinstanz {{site.data.keyword.mobilefoundation_short}}: Professional 1 Application erstellt wurde, sehen Sie die Seite *Übersicht*, auf der Sie die Verbindungsinformationen für die Serviceinstanz {{site.data.keyword.dashdbshort_notm}}: Enterprise Transactional angeben müssen.

1. Wählen Sie die {{site.data.keyword.Bluemix_notm}} `Organisation` aus, in der sich die {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz befindet.

+ Wählen Sie den {{site.data.keyword.Bluemix_notm}}-`Bereich`, in dem sich die {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz befindet, in der Liste der Bereiche aus, die in der ausgewählten `Organisation` verfügbar sind.

**Hinweis:** Wenn die `Organisation` und der `Bereich`, in denen sich Ihre {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz befindet, nicht aufgeführt sind, prüfen Sie, ob Sie ein Mitglied der betreffenden `Organisation` bzw. des betreffenden `Bereichs` sind.

+ Wählen Sie den `Servicenamen` und die `Berechtigungsnachweise` für {{site.data.keyword.dashdbshort_notm}} aus, um eine Verbindung zur vorhandenen {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz herzustellen.

+  Testen Sie die Verbindung zur angegebenen {{site.data.keyword.dashdbshort_notm}}: Enterprise Transactional-Serviceinstanz.

+  Klicken Sie auf **Weiter**. Mit dieser Aktion werden die erforderlichen Tabellen in der konfigurierten {{site.data.keyword.dashdbshort_notm}}-Datenbankserviceinstanz erstellt.

**Hinweis**: Sie können die {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz, die zur Verwendung durch die {{site.data.keyword.mobilefoundation_short}}-Serviceinstanz konfiguriert ist, nicht ändern. Sie können jedoch dieselbe {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz für mehrere {{site.data.keyword.mobilefoundation_short}}-Serviceinstanzen verwenden, da jede {{site.data.keyword.mobilefoundation_short}}-Serviceinstanz ein eigenes Schema in der ausgewählten {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz erstellt.

* Nach einigen Sekunden können Sie auf die Seite `Übersicht` zugreifen, auf der die Lernprogramme und Videos zur Verfügung stehen, die Sie beim Einstieg in die Verwendung des {{site.data.keyword.mobilefoundation_short}}-Service unterstützten.

## {{site.data.keyword.mobilefirst}}-Server starten
{: #start_mobilefoundation_p2}

* Um den {{site.data.keyword.mfserver_short_notm}} mit den Standardeinstellungen zu starten, klicken Sie auf **Basisserver starten**.

* Diese Auswahl stellt einen {{site.data.keyword.mfserver_long_notm}} mit den folgenden Einstellungen bereit:
    -  1 GB Hauptspeicher. Diese Größe ist für Entwicklungs- und kleinere Testaktivitäten sowie für kleinere Produktionsworkloads ausreichend.

    -	`Benutzername` und `Kennwort` werden automatisch
für Sie generiert. Sie können darauf zugreifen, wenn der Server betriebsbereit ist.

Der Prozess der Bereitstellung Ihres Servers wird gestartet. Dieser Prozess dauert ungefähr 10 Minuten;
in einem Nachrichtenfenster wird der Fortschritt dieser Operation angezeigt. Ist der Vorgang abgeschlossen, wird ein Dashboard mit folgenden
Informationen angezeigt:

  -	Status Ihres Servers, der ausgeführt wird (Zustand, Größe).

  -	Für Sie erstellte Serverroute. Verwenden Sie diese Route in Ihrer mobilen Anwendung, um eine Verbindung zum {{site.data.keyword.mfserver_short_notm}} herzustellen.

  -	Ihr persönlicher `Benutzername` und das `Kennwort` für den Zugriff auf die {{site.data.keyword.mfp_oc_short_notm}}. Das `Kennwort` wird ausgeblendet. Klicken Sie auf das Symbol **Kennwort anzeigen**, um es einzublenden.

*	Klicken Sie auf **Konsole starten**, um die {{site.data.keyword.mfp_oc_short_notm}} zu öffnen.

<!--This console runs inside the container.--> Mit der Konsole können Sie Ihre mobilen Apps, Adapter und Geräte verwalten, Ihren Server als mobiles Back-End verwenden, Push-Benachrichtigungen senden usw.

##  Mobile Analytics-Server hinzufügen
{: #adding_analytics_server_prof}

 Sie können Ihre mobile Anwendung nun auf dem {{site.data.keyword.mobilefirst}}-Server überwachen, indem Sie einen Mobile Analytics-Server zur Instanz des Service {{site.data.keyword.mobilefoundation_short}} hinzufügen.

 Durch den professionellen Plan wird der Mobile Analytics-Server in einer Containergruppe erstellt; der Benutzer kann die Konfiguration durch Auswahl der Anzahl von Containerknoten in der Containergruppe anpassen.

 Benutzer können auch Datenträger an die Container anhängen, um Daten dauerhaft zu speichern. Wird ein Datenträger einmal ausgewählt, kann er nicht mehr geändert werden. 20 GB Speicherplatz für die Dateifreigabe stehen dem Benutzer standardmäßig zur Verfügung. Benötigt der Benutzer zusätzlichen Speicherplatz, um die Analysedaten dauerhaft zu speichern, muss er weiteren Speicherplatz für die Dateifreigabe erwerben und mit dieser Dateifreigabe einen Datenträger erstellen. Anschließend kann er diesen neuen Datenträger auswählen und den Analyseserver bereitstellen.

 Weitere Informationen zum Hinzufügen von Datenträgern zu {{site.data.keyword.containerlong}} finden Sie im Abschnitt zum [Persistenten Speichern von Daten auf einem Datenträger über das {{site.data.keyword.Bluemix_notm}}-Dashboard](https://console.ng.bluemix.net/docs/containers/container_volumes_ui.html){: new_window}.

* Klicken Sie auf die Option zum Hinzufügen der Analyse, um den Mobile Analytics-Server zur Instanz des {{site.data.keyword.mobilefoundation_short}}-Service hinzuzufügen.

Der Prozess der Bereitstellung wird gestartet. Dieser Prozess dauert ungefähr 10 Minuten; in einem Nachrichtenfenster wird der Fortschritt dieser Operation angezeigt.

* Starten Sie die MobileFirst Analytics Console über die {{site.data.keyword.mfp_oc_short_notm}}.

* Für den {{site.data.keyword.mfserver_short_notm}} und den Mobile Analytics-Server ist Single Sign-on aktiviert. Der Mobile Analytics-Server ist mit denselben LTPA-Schlüsseln und denselben Benutzerberechtigungen konfiguriert wie der {{site.data.keyword.mfserver_short_notm}}-Server. Sie können für die Anmeldung an der Mobile Analytics Console den `Benutzernamen` und das `Kennwort` verwenden, die Sie auch für die Anmeldung bei der {{site.data.keyword.mfp_oc_short_notm}} verwendet haben.

Weitere Informationen zu MobileFirst Analytics finden Sie unter [MobileFirst Foundation Operational Analytics](https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/analytics/).

**Anmerkung:** Der Mobile Analytics-Server wird entfernt, wenn Sie die Instanz des Service {{site.data.keyword.mobilefoundation_short}} löschen oder wenn Sie versuchen, den {{site.data.keyword.mfserver_short_notm}} erneut zu erstellen.

## {{site.data.keyword.mobilefirst}} Server erneut erstellen
{: #recreate_mobilefoundation_p2}

*	Klicken Sie auf die Schaltfläche **Neu erstellen**, um den Server erneut zu erstellen.

* Diese Aktion stoppt Ihre vorhandenen Server und löscht die Daten. Eine neue Serverinstanz wird mit einer aktualisierten Version erstellt, falls verfügbar. Diese Aktion nimmt einige Minuten in Anspruch.

**Hinweis**: Alle Daten der vorherigen Serverinstanz, einschließlich Informationen zu den Apps und Adaptern, werden in der konfigurierten {{site.data.keyword.dashdbshort_notm}}-Serviceinstanz beibehalten; diese Daten werden zur erneuten Erstellung des Servers verwendet.

##	Erweiterte Konfiguration einrichten
{: #using_mfs_advanced_p2}

Mit der Option **Server mit erweiterter Konfiguration starten** auf der Seite `Übersicht` können Sie einen Server mit erweiterten oder benutzerdefinierten Einstellungen erstellen. Sie können die
Servereinstellungen auch aktualisieren, um Ihre Serverkonfiguration anzupassen; klicken Sie hierfür auf die
Registerkarte **Konfiguration**. {{site.data.keyword.mobilefoundation_short}} bietet Ihnen Zugriff auf einige erweiterte Einstellungen.

*	Auf der Registerkarte **Topologie** können Sie die Servergröße und die Anzahl der Serverinstanzen auswählen, die den jeweiligen Anforderungen entsprechen. Die Standardgröße von 1 GB für den Server ist für die Entwicklung und kleinere Tests ausreichend.
  - Wählen Sie in Abhängigkeit von Ihrem Bedarf die richtige Größe für Ihren Server aus.

  - **Knoten** zeigt die Anzahl der erstellten Knoten an.

      - Die {{site.data.keyword.mobilefirst}}-Server-Farm kann durch die Konfiguration der Anzahl der Knoten hier unterstützt werden.

Weitere Details finden Sie in der [{{site.data.keyword.mobilefoundation_long}}-Dokumentation](https://www.ibm.com/support/knowledgecenter/SSHS8R_8.0.0/wl_welcome.html){: new_window}.


text:
<?php

namespace App\Backend\Submodules\Task\Models;

class Log extends \App\Common\Models\Task\Log
{

    use \App\Backend\Models\Base;
}

redpajama_set_name: RedPajamaGithub


text:
Project Ideas:
1.Estimate the effects of genre of music interests on social behaviors and moods
I will design an algorithm to rate people's social behavior based on the genre of music that they are interested
in. I will use Twitter REST API to collect tweets from users who either play a musical instrument or show
interests in one. Moreover, I will rate the tweets based on their sentiments and languages using cloud based text
analysis APIs (such as Google and IBM's) to detect the mood of the user. The results can be evaluated by
comparing them with a control group.

2.Determine the effects of user attributes on how much they love Star Wars!
I will design an algorithm that finds the relation between users' attributes (such as gender, age) and their
interests in Star Wars the movie. I will use Twitter REST API to collect tweets from users who have tweets
related to Star Wars. I will then determine the users' attributes and report their relation with their interests
in Star Wars movie.

3.Estimate the effects of immigration on mental health
I will design an algorithm to predict how immigration may impact one's mental health and social behavior. I will
use Twitter REST API to collect tweets from those users who have immigrated from their home country. I will also
use cloud-based text analysis APIs to rate their tweets based on their sentiments and language to determine the
relation between their moods in tweets and the fact if they have immigrated or not.
(I am personally interested in this topic but worried if it is going to be too difficult to find immigrant users
in Twitter.)


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
module EDDA.Data.Cache (Cache,newCache,cachedIO,cachedForkIO) where

import Data.Maybe (isJust)
import Data.Int (Int64(..))
import Data.Time
import Data.Time.Clock.POSIX
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar

type Cache a = MVar (Int64, Maybe (a,Int64))

getCurrTime :: IO Int64
getCurrTime = round `fmap` getPOSIXTime

newCache :: Int64 -> IO (Cache a)
newCache t = newMVar (t, Nothing)

putValueInCache c t a = do !v' <- a
                           !currTime <- getCurrTime
                           putMVar c (t, Just (v',currTime))
                           return v'

cachedIO :: Cache a -> IO a -> IO a
cachedIO c a = do
                  (!t, !v) <- takeMVar c
                  if isJust v then do
                                   let Just (!c',!l) = v
                                   !currTime <- getCurrTime
                                   if (currTime - l) >= t then putValueInCache c t a
                                   else putMVar c (t, v) >> return c'
                  else putValueInCache c t a

cachedForkIO :: Cache a -> IO a -> IO a
cachedForkIO c a = do
                  (!t, !v) <- takeMVar c
                  if isJust v then do
                                   let Just (!c',!l) = v
                                   !currTime <- getCurrTime
                                   if (currTime - l) >= t then do !currTime <- getCurrTime
                                                                  putMVar c (t, Just (c',currTime))
                                                                  forkIO (do !v' <- a
                                                                             !currTime <- getCurrTime
                                                                             (!t, !v) <- takeMVar c
                                                                             putMVar c (t, Just (v',currTime)) )
                                                                  return c'
                                   else putMVar c (t, v) >> return c'
                  else putValueInCache c t a


text:
PImA
====
A Django app for managing course images


text:
package apple.webkit.enums;

import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.NUInt;

/**
 * [@enum] WKAudiovisualMediaTypes
 * <p>
 * The types of audiovisual media which will require a user gesture to begin playing.
 * [@constant] WKAudiovisualMediaTypeNone No audiovisual media will require a user gesture to begin playing.
 * [@constant] WKAudiovisualMediaTypeAudio Audiovisual media containing audio will require a user gesture to begin
 * playing.
 * [@constant] WKAudiovisualMediaTypeVideo Audiovisual media containing video will require a user gesture to begin
 * playing.
 * [@constant] WKAudiovisualMediaTypeAll All audiovisual media will require a user gesture to begin playing.
 */
@Generated
public final class WKAudiovisualMediaTypes {
    @Generated @NUInt public static final long None = 0x0000000000000000L;
    @Generated @NUInt public static final long Audio = 0x0000000000000001L;
    @Generated @NUInt public static final long Video = 0x0000000000000002L;
    @Generated @NUInt public static final long All = org.moe.natj.general.NatJ.is64Bit() ?
            0xFFFFFFFFFFFFFFFFL :
            0x00000000FFFFFFFFL;

    @Generated
    private WKAudiovisualMediaTypes() {
    }
}


text:
{% extends "index.html" %}
{% block title %}Category:{{ category }} - {{ SITENAME }}{% endblock %}
{% block metadesc %}{{ SITETAGALT }}Posts in category {{ category }}{% endblock %}

{% block    custom_header %}
{% if CUSTOM_HEADER_CATEGORY %}
{% include "includes/" + CUSTOM_HEADER_CATEGORY %}
{% endif %}
{% endblock custom_header%}

{% block    container_header %}
{% if CUSTOM_CONTAINER_TOP_CATEGORY %}
{% include "includes/" + CUSTOM_CONTAINER_TOP_CATEGORY %}
{% endif %}
{% endblock container_header %}

{% block    content_header %}
{% if CUSTOM_CONTENT_TOP_CATEGORY %}
{% include "includes/" + CUSTOM_CONTENT_TOP_CATEGORY %}
{% endif %}

{% if CATEGORIES_URL %}

Categories

{% else %}

Categories

{% endif %}

{{ category }}

{% endblock content_header %}

{% block article %}
{% include "includes/index_summaries.html" %}
{% endblock article %}

{% block    content_footer %}
{% if CUSTOM_CONTENT_BOTTOM_CATEGORY %}
{% include "includes/" + CUSTOM_CONTENT_BOTTOM_CATEGORY %}
{% endif %}
{% endblock content_footer %}

{% block    container_footer %}
{% if CUSTOM_CONTAINER_BOTTOM_CATEGORY %}
{% include "includes/" + CUSTOM_CONTAINER_BOTTOM_CATEGORY %}
{% endif %}
{% endblock container_footer %}


text:
// This pass converts each tfrt_dist.remote_execute_func op into a combination
// of tfrt_dist.register_tfrt_function op and tfrt_dist.remote_execute op. The
// function to be executed in the remote host will be serialized as a string
// attribute of the tfrt_dist.register_tfrt_function op.

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/SmallVector.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"  // from @llvm-project
#include "mlir/IR/Attributes.h"  // from @llvm-project
#include "mlir/IR/Builders.h"  // from @llvm-project
#include "mlir/IR/SymbolTable.h"  // from @llvm-project
#include "mlir/IR/Types.h"  // from @llvm-project
#include "mlir/IR/Visitors.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassManager.h"  // from @llvm-project
#include "mlir/Support/LLVM.h"  // from @llvm-project
#include "mlir/Transforms/Passes.h"  // from @llvm-project
#include "mlir/Transforms/RegionUtils.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/serialize_mlir_module_utils.h"
#include "tensorflow/core/util/device_name_utils.h"
#include "tfrt/basic_kernels/opdefs/types.h"  // from @tf_runtime
#include "tfrt/core_runtime/opdefs/types.h"  // from @tf_runtime
#include "tfrt/distributed_runtime/opdefs/kernels.h"  // from @tf_runtime
#include "tfrt/distributed_runtime/opdefs/types.h"  // from @tf_runtime
#include "tfrt/test_kernels/opdefs/test_kernels.h"  // from @tf_runtime

namespace tensorflow {

namespace {

constexpr const char* kHost = "host";
constexpr const char* kTFRTDevice = "tfrt.device";

struct DistRemoteRunEncapsulatePass
    : public PassWrapper<DistRemoteRunEncapsulatePass,
                         OperationPass<ModuleOp>> {
  llvm::StringRef getArgument() const final {
    return "tfrt-dist-remote-run-encapsulate";
  }
  llvm::StringRef getDescription() const final {
    return "This pass looks for a remote_run_func and serialize the callee to "
           "a string attribute attached to a remote_register operation, "
           "followed by a remote_execute invocation.";
  }
  void runOnOperation() override;

  void getDependentDialects(DialectRegistry& registry) const override {
    registry.insert<tfrt::dist::DistributedDialect>();
  }
};

LogicalResult EncapsulateFuncAndSerialize(FuncOp entry_func,
                                          std::string* serialized_func_module) {
  ModuleOp module = entry_func->getParentOfType<ModuleOp>();
  SymbolTable entry_module_table(module);
  SmallVector<FuncOp, 4> referenced({entry_func});

  // Create a new module to hold func and all referenced functions.
  OwningModuleRef module_for_func =
      ModuleOp::create(mlir::UnknownLoc::get(entry_func.getContext()));
  SymbolTable symbol_table(module_for_func.get());

  while (!referenced.empty()) {
    FuncOp func = referenced.pop_back_val();

    // Skip functions that have already been cloned into new module.
    if (symbol_table.lookup<FuncOp>(func.getName())) continue;

    // Find any SymbolRefAttr in func that maps to a FuncOp. We need to clone
    // all found FuncOps to new_module to make sure new_module is
    // self-contained.
    Optional<SymbolTable::UseRange> uses = SymbolTable::getSymbolUses(func);
    assert(uses && "expected to be able to collect symbol uses");
    for (SymbolTable::SymbolUse use : *uses) {
      FuncOp referenced_func = entry_module_table.lookup<FuncOp>(
          use.getSymbolRef().cast<FlatSymbolRefAttr>().getValue());

      // Skip Symbols that do not map to a function.
      if (!referenced_func) continue;

      referenced.emplace_back(referenced_func);
    }

    FuncOp clone = func.clone();
    if (clone.getName() == entry_func.getName()) {
      clone.setPublic();
    } else {
      clone.setPrivate();
    }
    symbol_table.insert(clone);
  }

  *serialized_func_module =
      tensorflow::SerializeMlirModule(module_for_func.get());
  return success();
}

void DistRemoteRunEncapsulatePass::runOnOperation() {
  mlir::TF::RuntimeDevices devices;
  ModuleOp module = getOperation();
  SymbolTable symtab(module);
  Type chain_type = tfrt::compiler::ChainType::get(&getContext());
  Type remote_object_id_ty = tfrt::dist::RemoteObjectIdType::get(&getContext());
  Type tensor_handle_ty = tfrt::corert::TensorHandleType::get(&getContext());
  module.walk([&](tfrt::dist::RemoteExecuteFuncOp remote_exec_op) {
    FlatSymbolRefAttr callee_sym = remote_exec_op.calleeAttr();
    FuncOp callee = symtab.lookup<FuncOp>(callee_sym.getValue());
    if (!callee) {
      remote_exec_op.emitOpError("callee function ")
          << callee_sym.getValue() << " is not found";
      signalPassFailure();
      return WalkResult::interrupt();
    }
    std::string txt_module;
    if (failed(EncapsulateFuncAndSerialize(callee, &txt_module))) {
      remote_exec_op.emitOpError("failed to serialize the callee function ")
          << callee.getName();
      signalPassFailure();
      return WalkResult::interrupt();
    }
    Location loc = remote_exec_op.getLoc();
    StringAttr callee_name =
        StringAttr::get(&getContext(), callee_sym.getValue());
    OpBuilder builder(remote_exec_op);
    auto register_op = builder.create<tfrt::dist::RegisterTFRTFunctionOp>(
        loc, chain_type, remote_exec_op.in_op_chain(), remote_exec_op.context(),
        remote_exec_op.remote_task(),
        StringAttr::get(&getContext(), txt_module), callee_name);

    // Build the device assignment for the results
    // TODO(tfrt-devs): Define properly MLIR types and operations
    SmallVector<Attribute, 8> result_devices;
    for (const auto& result : llvm::enumerate(remote_exec_op.results())) {
      StringAttr device =
          callee.getResultAttrOfType<StringAttr>(result.index(), kTFRTDevice);
      if (!device) {
        // The result might not have the device attribute if it is added by
        // the tf-to-tfrt pass. Use the first CPU on the remote host as the
        // device of this result.
        DeviceNameUtils::ParsedName parsed_name;
        if (StringAttr host_attr = callee->getAttrOfType<StringAttr>(kHost)) {
          auto host = host_attr.getValue();
          DeviceNameUtils::ParseFullName({host.data(), host.size()},
                                         &parsed_name);
        }
        parsed_name.has_type = true;
        parsed_name.type = "CPU";
        parsed_name.has_id = true;
        parsed_name.id = 0;
        device = StringAttr::get(
            &getContext(), DeviceNameUtils::ParsedNameToString(parsed_name));
      }
      result_devices.push_back(std::move(device));
    }
    // IDEA(donglin): Update the create_remote_execute_spec kernel to use Device
    // object instead of Device string.
    Type remote_spec_ty = tfrt::dist::RemoteExecuteSpecType::get(&getContext());
    auto result_devices_attr = ArrayAttr::get(&getContext(), result_devices);
    auto remote_spec = builder.create<tfrt::dist::CreateRemoteExecuteSpecOp>(
        loc, remote_spec_ty, remote_exec_op.context(), result_devices_attr);
    // If original argument is already tfrt_dist.remote_object_id, use it
    // directly. If it is TensorHandle, insert an op to extract the
    // tfrt_dist.remote_object_id from it. Otherwise, emit an error.
    SmallVector<Value, 4> arguments;
    for (Value value : remote_exec_op.callee_args()) {
      if (value.getType().isa<tfrt::dist::RemoteObjectIdType>()) {
        arguments.push_back(value);
      } else if (value.getType().isa<tfrt::corert::TensorHandleType>()) {
        auto new_op = builder.create<tfrt::dist::GetRemoteObjectIdFromTHOp>(
            loc, remote_object_id_ty, value);
        arguments.push_back(new_op.result());
      } else {
        remote_exec_op.emitOpError(
            "callee argument type should be either "
            "TensorHandle or RemoteObjectId");
        signalPassFailure();
        return WalkResult::interrupt();
      }
    }
    // Result types are 1 chain, followed by `num_th_results + 1`
    // tfrt_dist.remote_object_id results, followed by `num_th_results`
    // corert.tensorhandle results.
    int32_t num_th_results = remote_exec_op.results().size() - 1;
    SmallVector<Type, 8> result_types;
    result_types.push_back(chain_type);
    for (int count : llvm::seq<int>(0, num_th_results + 1)) {
      (void)count;
      result_types.push_back(remote_object_id_ty);
    }
    for (int count : llvm::seq<int>(0, num_th_results)) {
      (void)count;
      result_types.push_back(tensor_handle_ty);
    }
    auto new_remote_exec_th_op = builder.create<tfrt::dist::RemoteExecuteTHOp>(
        loc, result_types, register_op.out_op_chain(), remote_exec_op.context(),
        remote_exec_op.remote_task(), remote_spec, num_th_results,
        callee_name.getValue(), std::move(arguments));
    // The part of the new results to replace the original results are 2 chains,
    // followed `num_th_results` corert.tesnorhandle results from the callee
    // function.
    SmallVector<Value, 4> new_results;
    new_results.push_back(new_remote_exec_th_op.getResult(0));
    new_results.push_back(new_remote_exec_th_op.getResult(1));
    for (int i : llvm::seq<int>(0, num_th_results)) {
      new_results.push_back(
          new_remote_exec_th_op.getResult(i + 2 + num_th_results));
    }
    remote_exec_op.replaceAllUsesWith(new_results);
    remote_exec_op.erase();

    return WalkResult::advance();
  });
}

}  // namespace

std::unique_ptr<OperationPass<ModuleOp>> CreateDistRemoteRunEncapsulatePass() {
  return std::make_unique<DistRemoteRunEncapsulatePass>();
}

static PassRegistration<DistRemoteRunEncapsulatePass> pass;

}  // namespace tensorflow


text:
// PathVisio,
// a tool for data visualization and analysis using Biological Pathways
// Copyright 2006-2011 BiGCaT Bioinformatics
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package org.pathvisio.core.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bridgedb.DataSource;
import org.bridgedb.Xref;
import org.bridgedb.bio.BioDataSource;
import org.pathvisio.core.debug.Logger;

/**
 * Exports to pathway format understood by the EuGene
 * pathway statistics program.
 * This format is basically a list of genes in a flat text file
 * preceded by 3 header lines.
 *
 * EuGene supports several id systems but has its own naming
 * for them, this exporter also handles the translation.
 */
public class EUGeneExporter implements PathwayExporter
{
	public String[] getExtensions() {
		return new String[] { "pwf" };
	}

	public String getName() {
		return "Eu.Gene pathway";
	}

	public void doExport(File file, Pathway pathway) throws ConverterException {
		EUGenePathway eugPathway = new EUGenePathway(pathway);
		try {
			eugPathway.writeToEUGene(file);
		} catch(Exception e) {
			throw new ConverterException(e);
		}
	}

	private static class EUGenePathway {
		Logger log = Logger.log;
		Pathway pathway;

		DataSource system; //The annotation system

		List<Xref> refs;

		public EUGenePathway(Pathway p)  {
			pathway = p;
			read();
		}

		void writeToEUGene(File file) throws FileNotFoundException {
			String euGeneSystem = null;
			StringBuilder geneString = new StringBuilder();
			StringBuilder missedGenes = new StringBuilder();
			euGeneSystem = getEUGeneSystem();

			for(Xref ref : refs)
			{
				DataSource ds = ref.getDataSource();
				String id = ref.getId();
				if(ds == system)
				{ //Check if gene is of most occuring system
					geneString.append(id + "\n");
				}
				else
				{
					missedGenes.append(id + "|" + ds.getSystemCode() + "; ");
					log.error("id '" + id + "' differs from pathway annotation system");
				}
			}

			//Write the file
			PrintStream out = null;
			out = new PrintStream(file);

			//Print the data
			out.println("//PATHWAY_NAME = " + pathway.getMappInfo().getMapInfoName());
			out.println("//PATHWAY_SOURCE = GenMAPP");
			out.println("//PATHWAY_MARKER = " + euGeneSystem);
			if(missedGenes.length() > 0) out.println("//LOST_DURING_CONVERSION: " + missedGenes );
			out.print(geneString);

			out.close();
		}

		void read() {
			refs = new ArrayList<Xref>();
			Map<DataSource, Integer> codeCount = new HashMap<DataSource, Integer>();

			for(PathwayElement elm : pathway.getDataObjects()) {
				if(elm.getObjectType() != ObjectType.DATANODE) {
					continue; //Skip non-datanodes
				}
				Xref ref = elm.getXref();
				DataSource ds = ref.getDataSource();
				if(ref == null || ref.getId().equals("") || ref.getDataSource() == null)
				{
					continue; //Skip datanodes with incomplete annotation
				}
				refs.add (ref);

				//Increase code count for this code
				if(codeCount.containsKey(ref.getDataSource()))
					codeCount.put(ds, codeCount.get(ds) + 1);
				else codeCount.put(ds, 1);
			}

			//Get most occuring systemcode
			DataSource maxCode = null;
			for(DataSource ds : codeCount.keySet())
			{
				if(maxCode == null || codeCount.get(ds) > codeCount.get(maxCode))
				{
					maxCode = ds;
				}
			}
			system = maxCode;

			if(system == null) { //May occur when no identifiers available
				system = BioDataSource.ENSEMBL;
			}

			if(codeCount.keySet().size() > 1) {
				log.warn("\tThis pathway contains genes with different SystemCodes; '" +
						maxCode + "' has the highest occurence and is therefore chosen as PATHWAY_MARKER" +
						" for the EUGene file\n\t Other SystemCodes found and their occurences: "
						+ codeCount);
			}

		}

		String getEUGeneSystem() {
			if(systemMappings.containsKey(system))
			{
				return systemMappings.get(system);
			}
			else
			{
				return system.getFullName();
			}
		}
	}

	private static Map<DataSource, String> systemMappings;
	private static final String[] EU_GENE_SYSTEMS = new String[]
	                                           {
		"ENSEMBL_GENE_ID",
		"UNIPROT",
		"ENTREZ",
		"UNIGENE",
		"AFFYMETRIX",
		"AGILENT",
		"HGNC",
		"PDB_ID",
		"SGD_ID"
	                                           };
	private static final DataSource[] GENMAPP_SYSTEMS = new DataSource[]
	                                            {
		BioDataSource.ENSEMBL,
		BioDataSource.UNIPROT,
		BioDataSource.ENTREZ_GENE,
		BioDataSource.UNIGENE,
		BioDataSource.AFFY,
		BioDataSource.AGILENT,
		BioDataSource.HUGO,
		BioDataSource.PDB,
		BioDataSource.SGD
	                                            };

	static
	{
		systemMappings = new HashMap<DataSource, String>();
		for(int i = 0; i < EU_GENE_SYSTEMS.length; i++)
		{
			systemMappings.put(GENMAPP_SYSTEMS[i], EU_GENE_SYSTEMS[i]);
		}
	}

	@Override
	public List<String> getWarnings()
	{
		return Collections.emptyList();
	}
}


text:
namespace ofxLibwebsockets {

    struct ClientOptions {
        string  host;
        int     port;
        bool    bUseSSL;
        string  channel;
        string  protocol;
        int     version;

        // advanced: timeout options
        // names are from libwebsockets (ka == keep alive)
        int     ka_time;        // 0 == default, no timeout; nonzero == time to wait in seconds before testing conn
        int     ka_probes;      // # of times to test for connection; ignored if ka_time == 0
        int     ka_interval;    // how long to wait between probes, in seconds; ignored if ka_time == 0
    };

    // call this function to set up a vanilla client options object
    extern ClientOptions defaultClientOptions();

    class Client : public Reactor {
        friend class Protocol;
    public:

        Client();
        ~Client();

        // Note: the boolean returned here == libwebsockets setup success
        // You will receive an "onOpen" event on successful connect
        // and "onClose" on unsuccessful
        bool connect ( string _address, bool bUseSSL=false );
        bool connect ( string _address, int _port, bool bUseSSL=false );
        bool connect ( ClientOptions options );

        // force close this client
        void close();

        // check if connected
        bool isConnected();

        // most basic send function
        void send( string message );

        // send anything that has pixels
        template <class T>
        void sendBinary( T& image );

        // send any binary data
        void sendBinary( ofBuffer buffer );
        void sendBinary( unsigned char * data, int size );
        void sendBinary( char * data, int size );

        template<class T>
        void addListener(T * app){
            ofAddListener( clientProtocol.onconnectEvent, app, &T::onConnect);
            ofAddListener( clientProtocol.onopenEvent, app, &T::onOpen);
            ofAddListener( clientProtocol.oncloseEvent, app, &T::onClose);
            ofAddListener( clientProtocol.onidleEvent, app, &T::onIdle);
            ofAddListener( clientProtocol.onmessageEvent, app, &T::onMessage);
            ofAddListener( clientProtocol.onbroadcastEvent, app, &T::onBroadcast);
        }

        // get pointer to libwebsockets connection wrapper
        Connection * getConnection(){
            return connection;
        }

    protected:
        ClientOptions defaultOptions;
        void onClose( Event& args );

    private:

        Connection * connection;

        struct libwebsocket *  lwsconnection;
        void threadedFunction();

        //wrap protocol
        Protocol clientProtocol;

    };
};


text: The CSSian website


text: vim -u ~/.vimrc.bundles +PlugInstall +qall


text:
package ch.ethz.ssh2.packets;

/**
 * PacketSessionExecCommand.
 *
 * @author Christian Plattner, plattner@inf.ethz.ch
 * @version $Id: PacketSessionExecCommand.java,v 1.2 2005/08/24 17:54:09 cplattne Exp $
 */
public class PacketSessionExecCommand {
    public int recipientChannelID;
    public boolean wantReply;
    public String command;
    byte[] payload;

    public PacketSessionExecCommand(int recipientChannelID, boolean wantReply, String command) {
        this.recipientChannelID = recipientChannelID;
        this.wantReply = wantReply;
        this.command = command;
    }

    public byte[] getPayload() {
        if (payload == null) {
            TypesWriter tw = new TypesWriter();
            tw.writeByte(Packets.SSH_MSG_CHANNEL_REQUEST);
            tw.writeUINT32(recipientChannelID);
            tw.writeString("exec");
            tw.writeBoolean(wantReply);
            tw.writeString(command);
            payload = tw.getBytes();
        }
        return payload;
    }
}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_kbd.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/bus.h>

#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>

#include <sys/kbio.h>
#include <dev/kbd/kbdreg.h>
#include <dev/atkbdc/atkbdreg.h>
#include <dev/atkbdc/atkbdcreg.h>

typedef struct {
	struct resource	*intr;
	void		*ih;
} atkbd_softc_t;

static devclass_t	atkbd_devclass;

static void	atkbdidentify(driver_t *driver, device_t dev);
static int	atkbdprobe(device_t dev);
static int	atkbdattach(device_t dev);
static int	atkbdresume(device_t dev);
static void	atkbdintr(void *arg);

static device_method_t atkbd_methods[] = {
	DEVMETHOD(device_identify,	atkbdidentify),
	DEVMETHOD(device_probe,		atkbdprobe),
	DEVMETHOD(device_attach,	atkbdattach),
	DEVMETHOD(device_resume,	atkbdresume),
	{ 0, 0 }
};

static driver_t atkbd_driver = {
	ATKBD_DRIVER_NAME,
	atkbd_methods,
	sizeof(atkbd_softc_t),
};

static void
atkbdidentify(driver_t *driver, device_t parent)
{

	/* always add at least one child */
	BUS_ADD_CHILD(parent, KBDC_RID_KBD, driver->name, device_get_unit(parent));
}

static int
atkbdprobe(device_t dev)
{
	struct resource *res;
	u_long irq;
	int flags;
	int rid;

	device_set_desc(dev, "AT Keyboard");

	/* obtain parameters */
	flags = device_get_flags(dev);

	/* see if IRQ is available */
	rid = KBDC_RID_KBD;
	res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
	if (res == NULL) {
		if (bootverbose)
			device_printf(dev, "unable to allocate IRQ\n");
		return ENXIO;
	}
	irq = rman_get_start(res);
	bus_release_resource(dev, SYS_RES_IRQ, rid, res);

	/* probe the device */
	return atkbd_probe_unit(dev, irq, flags);
}

static int
atkbdattach(device_t dev)
{
	atkbd_softc_t *sc;
	keyboard_t *kbd;
	u_long irq;
	int flags;
	int rid;
	int error;

	sc = device_get_softc(dev);

	rid = KBDC_RID_KBD;
	irq = bus_get_resource_start(dev, SYS_RES_IRQ, rid);
	flags = device_get_flags(dev);
	error = atkbd_attach_unit(dev, &kbd, irq, flags);
	if (error)
		return error;

	/* declare our interrupt handler */
	sc->intr = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE);
	if (sc->intr == NULL)
		return ENXIO;
	error = bus_setup_intr(dev, sc->intr, INTR_TYPE_TTY, NULL, atkbdintr,
			       kbd, &sc->ih);
	if (error)
		bus_release_resource(dev, SYS_RES_IRQ, rid, sc->intr);

	return error;
}

static int
atkbdresume(device_t dev)
{
	atkbd_softc_t *sc;
	keyboard_t *kbd;
	int args[2];

	sc = device_get_softc(dev);
	kbd = kbd_get_keyboard(kbd_find_keyboard(ATKBD_DRIVER_NAME,
						 device_get_unit(dev)));
	if (kbd) {
		kbd->kb_flags &= ~KB_INITIALIZED;
		args[0] = device_get_unit(device_get_parent(dev));
		args[1] = rman_get_start(sc->intr);
		kbdd_init(kbd, device_get_unit(dev), &kbd, args,
		    device_get_flags(dev));
		kbdd_clear_state(kbd);
	}
	return 0;
}

static void
atkbdintr(void *arg)
{
	keyboard_t *kbd;

	kbd = (keyboard_t *)arg;
	kbdd_intr(kbd, NULL);
}

DRIVER_MODULE(atkbd, atkbdc, atkbd_driver, atkbd_devclass, 0, 0);


text:
import React from "react";
import { mount } from "enzyme";
import { TileReadPin } from "../tile_read_pin";
import { ReadPin } from "farmbot/dist";
import { StepParams } from "../../interfaces";
import { fakeStepParams } from "../../../__test_support__/fake_sequence_step_data";

describe("<TileReadPin />", () => {
  const fakeProps = (): StepParams<ReadPin> => ({
    ...fakeStepParams({
      kind: "read_pin",
      args: {
        pin_number: 3,
        label: "pinlabel",
        pin_mode: 1
      }
    }),
  });

  it("renders inputs", () => {
    const block = mount(<TileReadPin {...fakeProps()} />);
    const inputs = block.find("input");
    const labels = block.find("label");
    const buttons = block.find("button");
    expect(inputs.length).toEqual(2);
    expect(labels.length).toEqual(3);
    expect(buttons.length).toEqual(2);
    expect(inputs.first().props().placeholder).toEqual("Read Sensor");
    expect(labels.at(0).text()).toEqual("sensor or peripheral");
    expect(labels.at(1).text()).toEqual("Mode");
    expect(labels.at(2).text()).toEqual("Data Label");
    expect(inputs.at(1).props().value).toEqual("pinlabel");
    expect(buttons.at(0).text()).toEqual("Pin 3");
  });
});


text:
module PageObject
  module Member
    class Form < PageObject::Page

      set_url '/circles/{circle_id}/members/{id}/edit{?as}'

      element :first_name, '#user_first_name'
      element :last_name, '#user_last_name'
      element :profile_image, '#user_profile_image'
      element :remove_profile_image, '#user_remove_profile_image'

      include PageObject::IsForm

      private

      def next_page_object
        PageObject::Member::Page.new
      end

      def fill_form(attributes)
        first_name.set(attributes[:first_name]) if attributes[:first_name]
        last_name.set(attributes[:last_name]) if attributes[:last_name]
        profile_image.set(attributes[:profile_image]) if attributes[:profile_image]
        if attributes[:remove_profile_image]
          # the form is long, and we need to get at the checkbox after the fold
          page.current_window.resize_to(1024, 1024)
          remove_profile_image.set(attributes[:remove_profile_image])
        end
      end

      def submit_button
        find(".submit-row input[type=submit]")
      end

    end
  end
end


text:
package com.akoolla.cinema.seatbooking.core;

import org.joda.time.DateTime;

/**
 * IBooking.
 *
 * @author rich
 * @version $Id$
 */
public interface IBooking {

    int getNumberOfSeats();
    int getNumberOfWheelChairs();
    DateTime dateOfBooking();
    boolean isCancelled();
    ICustomer getCustomer();
    IBookingReference getBookingReference();
}


text:
#ifndef KYTHE_CXX_INDEXER_CXX_KYTHE_OUTPUT_STREAM_H_
#define KYTHE_CXX_INDEXER_CXX_KYTHE_OUTPUT_STREAM_H_

#include <memory>
#include <vector>

#include "google/protobuf/io/coded_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"

#include "gflags/gflags.h"
#include "kythe/proto/storage.pb.h"

DECLARE_bool(flush_after_each_entry);

namespace kythe {

// Interface for receiving Kythe `Entity` instances.
// TODO(jdennett): This interface should be recast in terms of emitting facts
//                 instead of directly constructing `Entity` protos.
//                 (Also see KytheGraphObserver.cc.)
class KytheOutputStream {
 public:
  virtual void Emit(const kythe::proto::Entry &entry) = 0;
};

// A `KytheOutputStream` that records `Entry` instances to a
// `FileOutputStream`.
class FileOutputStream : public KytheOutputStream {
 public:
  FileOutputStream(google::protobuf::io::FileOutputStream *stream)
      : stream_(stream) {}

  void Emit(const kythe::proto::Entry &entry) override {
    {
      google::protobuf::io::CodedOutputStream coded_stream(stream_);
      coded_stream.WriteVarint32(entry.ByteSize());
      entry.SerializeToCodedStream(&coded_stream);
    }
    if (FLAGS_flush_after_each_entry) {
      stream_->Flush();
    }
  }

 private:
  google::protobuf::io::FileOutputStream *stream_;
};

}  // namespace kythe

#endif  // KYTHE_CXX_INDEXER_CXX_KYTHE_OUTPUT_STREAM_H_


text:
package org.msgpack.template;

import java.io.IOException;
import org.msgpack.packer.Packer;
import org.msgpack.unpacker.Unpacker;
import org.msgpack.MessageTypeException;

public class ByteArrayTemplate extends AbstractTemplate<byte[]> {
    private ByteArrayTemplate() {
    }

    public void write(Packer pk, byte[] target, boolean required)
            throws IOException {
        if (target == null) {
            if (required) {
                throw new MessageTypeException("Attempted to write null");
            }
            pk.writeNil();
            return;
        }
        pk.write(target);
    }

    public byte[] read(Unpacker u, byte[] to, boolean required)
            throws IOException {
        if (!required && u.trySkipNil()) {
            return null;
        }
        return u.readByteArray(); // TODO read to 'to' obj
    }

    static public ByteArrayTemplate getInstance() {
        return instance;
    }

    static final ByteArrayTemplate instance = new ByteArrayTemplate();
}


text:
#Region "Microsoft.VisualBasic::84e0353f59931421888a125b92167a50, src\assembly\mz\TIC.vb"

' Author:
'
'       xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' 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.

' /********************************************************************************/

' Summaries:

' Module Program
'
'     Function: TIC, XIC, XICMgf
'
' /********************************************************************************/

#End Region

Imports System.ComponentModel
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.ASCII.MGF
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData
Imports BioNovoGene.Analytical.MassSpectrometry.Assembly.MarkupData.mzXML
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Chromatogram
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Ms1
Imports BioNovoGene.Analytical.MassSpectrometry.Math.Spectra
Imports Microsoft.VisualBasic.CommandLine
Imports Microsoft.VisualBasic.CommandLine.Reflection
Imports Microsoft.VisualBasic.Data.csv
Imports Microsoft.VisualBasic.Linq
Imports Microsoft.VisualBasic.Scripting.Runtime

Partial Module Program

    <ExportAPI("/mgf.XIC")>
    <Usage("/mgf.XIC /raw <data.mgf> [/out <XIC.png>]")>
    <Argument("/raw", False, CLITypes.File,
              Extensions:="*.mgf",
              Description:="This parameter could be file name list use comma symbol as delimiter.")>
    Public Function XICMgf(args As CommandLine) As Integer
        Dim raw$ = args <= "/raw"
        Dim files = CLITools.GetFileList(raw).ToArray
        Dim out$

        If files.Length = 1 Then
            out = args("/out") Or $"{raw.TrimSuffix}.plot.png"
        Else
            out = args("/out") Or $"{files.First.ParentPath}/{files.Select(Function(file) file.BaseName).JoinBy(",")}.plot.png"
        End If

        Dim ions = MgfReader.ReadIons(files) _
            .Select(Function(ion)
                        If ion.Meta.TryGetValue("activation", [default]:="") = "ms1" Then
                            Return ion.Peaks _
                                .Select(Function(peak)
                                            Return New TICPoint With {
                                                .intensity = peak.intensity,
                                                .mz = peak.mz,
                                                .time = ion.RtInSeconds
                                            }
                                        End Function)
                        Else
                            Return {
                                New TICPoint With {
                                    .intensity = ion.PepMass.text,
                                    .mz = ion.PepMass.name,
                                    .time = ion.RtInSeconds
                                }
                            }
                        End If
                    End Function) _
            .IteratesALL _
            .OrderBy(Function(p) p.time) _
            .ToArray

        Dim datafile = out.TrimSuffix & ".points.csv"
        Dim plot = CLI.mzplot.FromEnvironment(App.HOME)

        Call ions.SaveTo(datafile)

        Return plot.mzIntoXIC(datafile)
    End Function

    <ExportAPI("/TIC")>
    <Usage("/TIC /raw <data.mgf> [/mz /out <TIC.png>]")>
    <Argument("/raw", False, CLITypes.File,
              Extensions:="*.mgf",
              Description:="This parameter could be file name list use comma symbol as delimiter.")>
    <Argument("/mz", True, CLITypes.Boolean,
              AcceptTypes:={GetType(Boolean)},
              Description:="The m/z value as x axis.")>
    Public Function TIC(args As CommandLine) As Integer
        Dim raw$ = args <= "/raw"
        Dim files = CLITools.GetFileList(raw).ToArray
        Dim out$
        Dim ismzX As Boolean = args("/mz")

        If files.Length = 1 Then
            out = args("/out") Or $"{raw.TrimSuffix}.plot.png"
        Else
            out = args("/out") Or $"{files.First.ParentPath}/{files.Select(Function(file) file.BaseName).JoinBy(",")}.plot.png"
        End If

        Dim ions = MgfReader.ReadIons(files) _
            .Select(Function(ion)
                        Return New TICPoint With {
                            .intensity = ion.PepMass.text,
                            .mz = ion.PepMass.name,
                            .time = ion.RtInSeconds
                        }
                    End Function) _
            .OrderBy(Function(p) p.time) _
            .ToArray

        Dim datafile = out.TrimSuffix & ".points.csv"
        Dim plot = CLI.mzplot.FromEnvironment(App.HOME)

        Call ions.SaveTo(datafile)

        If ismzX Then
            Return plot.mzIntoXIC(datafile)
        Else
            Return plot.TICplot(datafile, rt:=NameOf(TICPoint.time), into:=NameOf(TICPoint.intensity), out:=out)
        End If
    End Function

    <ExportAPI("/XIC")>
    <Usage("/XIC /mz <mz.list> /raw <raw.mzXML> [/tolerance <default=ppm:20> /out <XIC.png>]")>
    <Description("Do TIC plot on a given list of selective parent ions.")>
    <Argument("/mz", False, CLITypes.File, PipelineTypes.std_in,
              AcceptTypes:={GetType(String)},
              Extensions:="*.txt, *.csv",
              Description:="A list file for specific the m/z values.")>
    <Argument("/out", True, CLITypes.File,
              Extensions:="*.png, *.svg",
              Description:="The output TIC plot image file path.")>
    Public Function XIC(args As CommandLine) As Integer
        Dim mz$ = args <= "/mz"
        Dim raw$ = args <= "/raw"
        Dim out$ = args("/out") Or $"{mz.TrimSuffix}-{raw.FileName}_XIC.png"
        Dim mzlist As Double() = mz.ReadAllLines.AsDouble

        Call "Load all ms1 scans".__DEBUG_ECHO
        Dim tolerance As Tolerance = Tolerance.ParseScript(args("/tolerance") Or "ppm:20")
        Dim chromatogram = mzXML.XML.LoadScans(raw) _
            .Where(Function(scan) scan.msLevel = "1") _
            .AsParallel _
            .Select(Function(scan)
                        Dim peaks = scan.ExtractMzI.peaks
                        Dim rt# = PeakMs2.RtInSecond(scan.retentionTime)

                        Return peaks _
                            .Where(Function(ion)
                                       Return mzlist.Any(Function(p) True = tolerance(p, ion.mz))
                                   End Function) _
                            .Select(Function(parent)
                                        Dim tick As New ChromatogramTick With {
                                            .Time = rt,
                                            .Intensity = parent.intensity
                                        }
                                        Dim parentIon = parent.mz

                                        Return (mz:=parentIon, tick:=tick)
                                    End Function)
                    End Function) _
            .IteratesALL _
            .Select(Function(parent)
                        Return New TICPoint With {
                            .mz = parent.mz,
                            .time = parent.tick.Time,
                            .intensity = parent.tick.Intensity
                        }
                    End Function) _
            .ToArray

        Dim datafile = out.TrimSuffix & ".points.csv"

        Call chromatogram.SaveTo(datafile)

        Return CLI.mzplot.FromEnvironment(App.HOME).TICplot(datafile, out:=out)
    End Function
End Module


text:
<?php

$languageStrings = array(
	'ERR_FAILED_TO_LOCK_MODULE'=> 'Falha ao bloquear o módulo para importação. Tente novamente mais tarde',
	'ERR_IMPORT_INTERRUPTED' => 'A importação atual foi interrompida. Por favor, tente novamente mais tarde',
	'ERR_UNIMPORTED_RECORDS_EXIST' => 'Não é possível importar mais dados neste lote. Por favor, comece uma nova importação.',
	'failed' => 'Registros Falhos',
	'LBL_AVAILABLE_FIELDS' => 'Campos Disponíveis' ,
	'LBL_CANCEL_IMPORT'=> 'Cancelar Importação' ,
	'LBL_CHARACTER_ENCODING' => 'Codificação Caracter',
	'LBL_CLEAR_DATA' => 'Limpar Dados',
	'LBL_CRM_FIELDS' => 'Campos CRM',
	'LBL_DEFAULT_VALUE'=> 'Valor Padrão' ,
	'LBL_DELIMITER'=> 'Delimitador:',
	'LBL_DETAILS' => 'Detalhes',
	'LBL_ERROR'=> 'Erro:' ,
	'LBL_FILE_COLUMN_HEADER' => 'Cabeçalho',
	'LBL_FILE_TYPE'=> 'Tipo Arquivo' ,
	'LBL_FILE_UPLOAD_FAILED' => 'Falha ao Atualizar Arquivo',
	'LBL_FINISH_BUTTON_LABEL'=> 'Final' ,
	'LBL_HAS_HEADER' => 'Tem Cabeçalho:' ,
	'LBL_IMPORT_BUTTON_LABEL'=> 'Importar',
	'LBL_IMPORT_CHANGE_UPLOAD_SIZE' => 'Alterar Tamanho Atualização Importação',
	'LBL_IMPORT_DIRECTORY_NOT_WRITABLE' => 'Diretório de Importação permissão escrita',
	'LBL_IMPORT_ERROR_LARGE_FILE' => 'Erro ao Importar Arquivo Grande',
	'LBL_IMPORT_FILE_COPY_FAILED' => 'Importação cópia Arquivo falhou',
	'LBL_IMPORT_MORE'=> 'Importar Mais' ,
	'LBL_IMPORT_SCHEDULED' => 'Importação Agendada',
	'LBL_IMPORT_STEP_1_DESCRIPTION' => 'Selecionar Arquivo' ,
	'LBL_IMPORT_STEP_1'=> 'Passo 1',
	'LBL_IMPORT_STEP_2_DESCRIPTION' => 'Especificar Formato',
	'LBL_IMPORT_STEP_2'=> 'Passo 2',
	'LBL_IMPORT_STEP_3_DESCRIPTION_DETAILED' => 'Selecionar esta opção para habilitar e configurar critérios para mesclar duplicados',
	'LBL_IMPORT_STEP_3_DESCRIPTION' => 'Manipular Registros Duplicados' ,
	'LBL_IMPORT_STEP_3'=> 'Passo 3',
	'LBL_IMPORT_STEP_4_DESCRIPTION' => 'Mapear as Colunas para o Campos do Módulo',
	'LBL_IMPORT_STEP_4'=> 'Passo 4',
	'LBL_IMPORT_SUPPORTED_FILE_TYPES' => 'Tipo(s) Arquivo(s) Suportado(a): .CSV, .VCF',
	'LBL_INVALID_FILE' => 'Arquivo Inválido',
	'LBL_NEXT_BUTTON_LABEL'=> 'Próximo',
	'LBL_NO_ROWS_FOUND' => 'Nenhuma linha foi encontrada',
	'LBL_NUMBER_OF_RECORDS_CREATED' => 'Registros criados' ,
	'LBL_NUMBER_OF_RECORDS_DELETED' => 'Número de registros apagados' ,
	'LBL_NUMBER_OF_RECORDS_MERGED' => 'Registros mesclados',
	'LBL_NUMBER_OF_RECORDS_SKIPPED' => 'Registros ignorados' ,
	'LBL_NUMBER_OF_RECORDS_UPDATED' => 'Registros sobrescritos' ,
	'LBL_OK_BUTTON_LABEL'=> 'Ok',
	'LBL_RESULT' => 'Resultado',
	'LBL_ROW_1' => 'Linha 1' ,
	'LBL_RUNNING'=> 'Executando',
	'LBL_SAVE_AS_CUSTOM_MAPPING' => 'Salvar como Mapeamento Customizado ' ,
	'LBL_SCHEDULED_IMPORT_DETAILS' => 'Sua importação está sendo agendada e iniciará dentro de 15 minutos. Você receberá um email assim que a importação estiver concluída.

 Por gentileza, certifique-se de que o Servidor de Envio de Mensagens e seu endereço de email estão devidamente configurados para receber a notificação.',
	'LBL_SELECTED_FIELDS'=> ' Campos para serem combinados',
	'LBL_SELECT_MERGE_FIELDS'=> 'Selecionar os campos correspondentes para localizar registros duplicados',
	'LBL_SELECT_SAVED_MAPPING' => 'Selecionar Mapeamento Salvo',
	'LBL_SPECIFY_MERGE_TYPE' => 'Definir como os registros duplicados devem ser manipulados',
	'LBL_TOTAL_RECORDS_FAILED' => 'Falha ao Importar Registros',
	'LBL_TOTAL_RECORDS_IMPORTED' => 'Registros importados com sucesso',
	'LBL_TOTAL_RECORDS'=> 'Número Total de Registros' ,
	'LBL_UNDO_LAST_IMPORT' => 'Desfazer Última Importação',
	'LBL_UNDO_RESULT'=> 'Desfazer Resultado Importação',
	'LBL_VIEW_LAST_IMPORTED_RECORDS' => 'Últimos Registros Importados' ,
	'skipped' => 'Registros Ignorados',
);


text:
Hi :)
This directory is for generating python 'wheels' for the TravisCI build.
It should be empty.


text:
// Template Source: BaseEntity.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.models;
import com.microsoft.graph.serializer.ISerializer;
import com.microsoft.graph.serializer.IJsonBackedObject;
import com.microsoft.graph.serializer.AdditionalDataManager;
import java.util.EnumSet;
import com.microsoft.graph.models.FileSystemInfo;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Drive Item Uploadable Properties.
 */
public class DriveItemUploadableProperties implements IJsonBackedObject {

    /** the OData type of the object as returned by the service */
    @SerializedName("@odata.type")
    @Expose
    @Nullable
    public String oDataType;

    private transient AdditionalDataManager additionalDataManager = new AdditionalDataManager(this);

    @Override
    @Nonnull
    public final AdditionalDataManager additionalDataManager() {
        return additionalDataManager;
    }

    /**
     * The Description.
     * Provides a user-visible description of the item. Read-write. Only on OneDrive Personal.
     */
    @SerializedName(value = "description", alternate = {"Description"})
    @Expose
	@Nullable
    public String description;

    /**
     * The File Size.
     * Provides an expected file size to perform a quota check prior to upload. Only on OneDrive Personal.
     */
    @SerializedName(value = "fileSize", alternate = {"FileSize"})
    @Expose
	@Nullable
    public Long fileSize;

    /**
     * The File System Info.
     * File system information on client. Read-write.
     */
    @SerializedName(value = "fileSystemInfo", alternate = {"FileSystemInfo"})
    @Expose
	@Nullable
    public FileSystemInfo fileSystemInfo;

    /**
     * The Name.
     * The name of the item (filename and extension). Read-write.
     */
    @SerializedName(value = "name", alternate = {"Name"})
    @Expose
	@Nullable
    public String name;

    /**
     * Sets the raw JSON object
     *
     * @param serializer the serializer
     * @param json the JSON object to set this object to
     */
    public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final JsonObject json) {

    }
}


text:
Quantum annealing for traveling salesman problem executed in R language.
It can be operated on the browser.

### Launch web application
You can install from R console.
Install related packages with the following command.

    install.packages("shiny")

If shiny is installed, it can be started from R console with the following command.

    shiny::runGitHub("qatsp", "ToshihiroIguchi", subdir = "shiny/")

### Host
Host the Shiny application from GitHub in a private network.
Enter the following command in R console.

    #Port specification
    port <- 1573

    #Acquire private address information
    ipconfig.dat <- system("ipconfig", intern = TRUE)
    ipv4.dat <- ipconfig.dat[grep("IPv4", ipconfig.dat)][1]
    ip <- gsub(".*? ([[:digit:]])", "\\1", ipv4.dat)

    #Host the Shiny application from GitHub
    shiny::runGitHub("qatsp", "ToshihiroIguchi", subdir = "shiny/", launch.browser = FALSE, port = port, host = ip)

If you are in the private network, you can also launch the Shiny application by entering the URL following `Listing on` to the browser.


text: "${PREFIX}/bin/python" -m nb_helloworld.setup remove --prefix "${PREFIX}"


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Remote.DebugUtil;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Diagnostics;
using System;
using Microsoft.CodeAnalysis.Execution;

namespace Microsoft.CodeAnalysis.Remote
{
    /// <summary>
    /// Create solution for given checksum from base solution
    /// </summary>
    internal class SolutionCreator
    {
        private readonly AssetService _assetService;
        private readonly Solution _baseSolution;
        private readonly CancellationToken _cancellationToken;

        public SolutionCreator(AssetService assetService, Solution baseSolution, CancellationToken cancellationToken)
        {
            Contract.ThrowIfNull(baseSolution);

            _assetService = assetService;
            _baseSolution = baseSolution;
            _cancellationToken = cancellationToken;
        }

        public async Task<bool> IsIncrementalUpdateAsync(Checksum newSolutionChecksum)
        {
            var newSolutionChecksums = await _assetService.GetAssetAsync<SolutionStateChecksums>(newSolutionChecksum, _cancellationToken).ConfigureAwait(false);
            var newSolutionInfo = await _assetService.GetAssetAsync<SolutionInfo.SolutionAttributes>(newSolutionChecksums.Info, _cancellationToken).ConfigureAwait(false);

            // if either solution id or file path changed, then we consider it as new solution
            return _baseSolution.Id == newSolutionInfo.Id && _baseSolution.FilePath == newSolutionInfo.FilePath;
        }

        public async Task<Solution> CreateSolutionAsync(Checksum newSolutionChecksum)
        {
            var solution = _baseSolution;

            var oldSolutionChecksums = await solution.State.GetStateChecksumsAsync(_cancellationToken).ConfigureAwait(false);
            var newSolutionChecksums = await _assetService.GetAssetAsync<SolutionStateChecksums>(newSolutionChecksum, _cancellationToken).ConfigureAwait(false);

            if (oldSolutionChecksums.Info != newSolutionChecksums.Info)
            {
                var newSolutionInfo = await _assetService.GetAssetAsync<SolutionInfo.SolutionAttributes>(newSolutionChecksums.Info, _cancellationToken).ConfigureAwait(false);

                // if either id or file path has changed, then this is not update
                Contract.ThrowIfFalse(solution.Id == newSolutionInfo.Id && solution.FilePath == newSolutionInfo.FilePath);
            }

            if (oldSolutionChecksums.Projects.Checksum != newSolutionChecksums.Projects.Checksum)
            {
                solution = await UpdateProjectsAsync(solution, oldSolutionChecksums.Projects, newSolutionChecksums.Projects).ConfigureAwait(false);
            }

            // make sure created solution has same checksum as given one
            await ValidateChecksumAsync(newSolutionChecksum, solution).ConfigureAwait(false);

            return solution;
        }

        private async Task<Solution> UpdateProjectsAsync(Solution solution, ChecksumCollection oldChecksums, ChecksumCollection newChecksums)
        {
            using var olds = SharedPools.Default<HashSet<Checksum>>().GetPooledObject();
            using var news = SharedPools.Default<HashSet<Checksum>>().GetPooledObject();

            olds.Object.UnionWith(oldChecksums);
            news.Object.UnionWith(newChecksums);

            // remove projects that exist in both side
            olds.Object.ExceptWith(newChecksums);
            news.Object.ExceptWith(oldChecksums);

            return await UpdateProjectsAsync(solution, olds.Object, news.Object).ConfigureAwait(false);
        }

        private async Task<Solution> UpdateProjectsAsync(Solution solution, HashSet<Checksum> oldChecksums, HashSet<Checksum> newChecksums)
        {
            var oldMap = await GetProjectMapAsync(solution, oldChecksums).ConfigureAwait(false);
            var newMap = await GetProjectMapAsync(_assetService, newChecksums).ConfigureAwait(false);

            // bulk sync assets
            await SynchronizeAssetsAsync(solution, oldMap, newMap).ConfigureAwait(false);

            // added project
            foreach (var kv in newMap)
            {
                if (!oldMap.ContainsKey(kv.Key))
                {
                    var projectInfo = await SolutionInfoCreator.CreateProjectInfoAsync(_assetService, kv.Value.Checksum, _cancellationToken).ConfigureAwait(false);
                    if (projectInfo == null)
                    {
                        // this project is not supported in OOP
                        continue;
                    }

                    // we have new project added
                    solution = solution.AddProject(projectInfo);
                }
            }

            // changed project
            foreach (var kv in newMap)
            {
                if (!oldMap.TryGetValue(kv.Key, out var oldProjectChecksums))
                {
                    continue;
                }

                var newProjectChecksums = kv.Value;
                Contract.ThrowIfTrue(oldProjectChecksums.Checksum == newProjectChecksums.Checksum);

                solution = await UpdateProjectAsync(solution.GetProject(kv.Key), oldProjectChecksums, newProjectChecksums).ConfigureAwait(false);
            }

            // removed project
            foreach (var kv in oldMap)
            {
                if (!newMap.ContainsKey(kv.Key))
                {
                    // we have a project removed
                    solution = solution.RemoveProject(kv.Key);
                }
            }

            return solution;
        }

        private async Task SynchronizeAssetsAsync(Solution solution, Dictionary<ProjectId, ProjectStateChecksums> oldMap, Dictionary<ProjectId, ProjectStateChecksums> newMap)
        {
            using var pooledObject = SharedPools.Default<HashSet<Checksum>>().GetPooledObject();

            // added project
            foreach (var kv in newMap)
            {
                if (oldMap.ContainsKey(kv.Key))
                {
                    continue;
                }

                pooledObject.Object.Add(kv.Value.Checksum);
            }

            await _assetService.SynchronizeProjectAssetsAsync(pooledObject.Object, _cancellationToken).ConfigureAwait(false);
        }

        private async Task<Solution> UpdateProjectAsync(Project project, ProjectStateChecksums oldProjectChecksums, ProjectStateChecksums newProjectChecksums)
        {
            // changed info
            if (oldProjectChecksums.Info != newProjectChecksums.Info)
            {
                project = await UpdateProjectInfoAsync(project, newProjectChecksums.Info).ConfigureAwait(false);
            }

            // changed compilation options
            if (oldProjectChecksums.CompilationOptions != newProjectChecksums.CompilationOptions)
            {
                project = project.WithCompilationOptions(
                    project.State.ProjectInfo.Attributes.FixUpCompilationOptions(
                        await _assetService.GetAssetAsync<CompilationOptions>(
                            newProjectChecksums.CompilationOptions, _cancellationToken).ConfigureAwait(false)));
            }

            // changed parse options
            if (oldProjectChecksums.ParseOptions != newProjectChecksums.ParseOptions)
            {
                project = project.WithParseOptions(await _assetService.GetAssetAsync<ParseOptions>(newProjectChecksums.ParseOptions, _cancellationToken).ConfigureAwait(false));
            }

            // changed project references
            if (oldProjectChecksums.ProjectReferences.Checksum != newProjectChecksums.ProjectReferences.Checksum)
            {
                project = project.WithProjectReferences(await _assetService.CreateCollectionAsync<ProjectReference>(
                    newProjectChecksums.ProjectReferences, _cancellationToken).ConfigureAwait(false));
            }

            // changed metadata references
            if (oldProjectChecksums.MetadataReferences.Checksum != newProjectChecksums.MetadataReferences.Checksum)
            {
                project = project.WithMetadataReferences(await _assetService.CreateCollectionAsync<MetadataReference>(
                    newProjectChecksums.MetadataReferences, _cancellationToken).ConfigureAwait(false));
            }

            // changed analyzer references
            if (oldProjectChecksums.AnalyzerReferences.Checksum != newProjectChecksums.AnalyzerReferences.Checksum)
            {
                project = project.WithAnalyzerReferences(await _assetService.CreateCollectionAsync<AnalyzerReference>(
                    newProjectChecksums.AnalyzerReferences, _cancellationToken).ConfigureAwait(false));
            }

            // changed analyzer references
            if (oldProjectChecksums.Documents.Checksum != newProjectChecksums.Documents.Checksum)
            {
                project = await UpdateDocumentsAsync(
                    project,
                    project.State.DocumentStates.Values,
                    oldProjectChecksums.Documents,
                    newProjectChecksums.Documents,
                    (solution, documents) => solution.AddDocuments(documents),
                    (solution, documentId) => solution.RemoveDocument(documentId)).ConfigureAwait(false);
            }

            // changed additional documents
            if (oldProjectChecksums.AdditionalDocuments.Checksum != newProjectChecksums.AdditionalDocuments.Checksum)
            {
                project = await UpdateDocumentsAsync(
                    project,
                    project.State.AdditionalDocumentStates.Values,
                    oldProjectChecksums.AdditionalDocuments,
                    newProjectChecksums.AdditionalDocuments,
                    (solution, documents) => solution.AddAdditionalDocuments(documents),
                    (solution, documentId) => solution.RemoveAdditionalDocument(documentId)).ConfigureAwait(false);
            }

            // changed analyzer config documents
            if (oldProjectChecksums.AnalyzerConfigDocuments.Checksum != newProjectChecksums.AnalyzerConfigDocuments.Checksum)
            {
                project = await UpdateDocumentsAsync(
                    project,
                    project.State.AnalyzerConfigDocumentStates.Values,
                    oldProjectChecksums.AnalyzerConfigDocuments,
                    newProjectChecksums.AnalyzerConfigDocuments,
                    (solution, documents) => solution.AddAnalyzerConfigDocuments(documents),
                    (solution, documentId) => solution.RemoveAnalyzerConfigDocument(documentId)).ConfigureAwait(false);
            }

            return project.Solution;
        }

        private async Task<Project> UpdateProjectInfoAsync(Project project, Checksum infoChecksum)
        {
            var newProjectInfo = await _assetService.GetAssetAsync<ProjectInfo.ProjectAttributes>(infoChecksum, _cancellationToken).ConfigureAwait(false);

            // there is no API to change these once project is created
            Contract.ThrowIfFalse(project.State.ProjectInfo.Attributes.Id == newProjectInfo.Id);
            Contract.ThrowIfFalse(project.State.ProjectInfo.Attributes.Language == newProjectInfo.Language);
            Contract.ThrowIfFalse(project.State.ProjectInfo.Attributes.IsSubmission == newProjectInfo.IsSubmission);

            if (project.State.ProjectInfo.Attributes.Name != newProjectInfo.Name)
            {
                project = project.Solution.WithProjectName(project.Id, newProjectInfo.Name).GetProject(project.Id);
            }

            if (project.State.ProjectInfo.Attributes.AssemblyName != newProjectInfo.AssemblyName)
            {
                project = project.Solution.WithProjectAssemblyName(project.Id, newProjectInfo.AssemblyName).GetProject(project.Id);
            }

            if (project.State.ProjectInfo.Attributes.FilePath != newProjectInfo.FilePath)
            {
                project = project.Solution.WithProjectFilePath(project.Id, newProjectInfo.FilePath).GetProject(project.Id);
            }

            if (project.State.ProjectInfo.Attributes.OutputFilePath != newProjectInfo.OutputFilePath)
            {
                project = project.Solution.WithProjectOutputFilePath(project.Id, newProjectInfo.OutputFilePath).GetProject(project.Id);
            }

            if (project.State.ProjectInfo.Attributes.OutputRefFilePath != newProjectInfo.OutputRefFilePath)
            {
                project = project.Solution.WithProjectOutputRefFilePath(project.Id, newProjectInfo.OutputRefFilePath).GetProject(project.Id);
            }

            if (project.State.ProjectInfo.Attributes.DefaultNamespace != newProjectInfo.DefaultNamespace)
            {
                project = project.Solution.WithProjectDefaultNamespace(project.Id, newProjectInfo.DefaultNamespace).GetProject(project.Id);
            }

            if (project.State.ProjectInfo.Attributes.HasAllInformation != newProjectInfo.HasAllInformation)
            {
                project = project.Solution.WithHasAllInformation(project.Id, newProjectInfo.HasAllInformation).GetProject(project.Id);
            }

            return project;
        }

        private async Task<Project> UpdateDocumentsAsync(
            Project project,
            IEnumerable<TextDocumentState> existingTextDocumentStates,
            ChecksumCollection oldChecksums,
            ChecksumCollection newChecksums,
            Func<Solution, ImmutableArray<DocumentInfo>, Solution> addDocuments,
            Func<Solution, DocumentId, Solution> removeDocument)
        {
            using var olds = SharedPools.Default<HashSet<Checksum>>().GetPooledObject();
            using var news = SharedPools.Default<HashSet<Checksum>>().GetPooledObject();

            olds.Object.UnionWith(oldChecksums);
            news.Object.UnionWith(newChecksums);

            // remove documents that exist in both side
            olds.Object.ExceptWith(newChecksums);
            news.Object.ExceptWith(oldChecksums);

            var oldMap = await GetDocumentMapAsync(existingTextDocumentStates, olds.Object).ConfigureAwait(false);
            var newMap = await GetDocumentMapAsync(_assetService, news.Object).ConfigureAwait(false);

            // added document
            ImmutableArray<DocumentInfo>.Builder documentsToAdd = null;
            foreach (var kv in newMap)
            {
                if (!oldMap.ContainsKey(kv.Key))
                {
                    documentsToAdd ??= ImmutableArray.CreateBuilder<DocumentInfo>();

                    // we have new document added
                    var documentInfo = await SolutionInfoCreator.CreateDocumentInfoAsync(_assetService, kv.Value.Checksum, _cancellationToken).ConfigureAwait(false);
                    documentsToAdd.Add(documentInfo);
                }
            }

            if (documentsToAdd != null)
            {
                project = addDocuments(project.Solution, documentsToAdd.ToImmutable()).GetProject(project.Id);
            }

            // changed document
            foreach (var kv in newMap)
            {
                if (!oldMap.TryGetValue(kv.Key, out var oldDocumentChecksums))
                {
                    continue;
                }

                var newDocumentChecksums = kv.Value;
                Contract.ThrowIfTrue(oldDocumentChecksums.Checksum == newDocumentChecksums.Checksum);

                var document = project.GetDocument(kv.Key) ?? project.GetAdditionalDocument(kv.Key) ?? project.GetAnalyzerConfigDocument(kv.Key);
                project = await UpdateDocumentAsync(document, oldDocumentChecksums, newDocumentChecksums).ConfigureAwait(false);
            }

            // removed document
            foreach (var kv in oldMap)
            {
                if (!newMap.ContainsKey(kv.Key))
                {
                    // we have a document removed
                    project = removeDocument(project.Solution, kv.Key).GetProject(project.Id);
                }
            }

            return project;
        }

        private async Task<Project> UpdateDocumentAsync(TextDocument document, DocumentStateChecksums oldDocumentChecksums, DocumentStateChecksums newDocumentChecksums)
        {
            // changed info
            if (oldDocumentChecksums.Info != newDocumentChecksums.Info)
            {
                document = await UpdateDocumentInfoAsync(document, newDocumentChecksums.Info).ConfigureAwait(false);
            }

            // changed text
            if (oldDocumentChecksums.Text != newDocumentChecksums.Text)
            {
                var sourceText = await _assetService.GetAssetAsync<SourceText>(newDocumentChecksums.Text, _cancellationToken).ConfigureAwait(false);

                document = document.Kind switch
                {
                    TextDocumentKind.Document => document.Project.Solution.WithDocumentText(document.Id, sourceText).GetDocument(document.Id),
                    TextDocumentKind.AnalyzerConfigDocument => document.Project.Solution.WithAnalyzerConfigDocumentText(document.Id, sourceText).GetAnalyzerConfigDocument(document.Id),
                    TextDocumentKind.AdditionalDocument => document.Project.Solution.WithAdditionalDocumentText(document.Id, sourceText).GetAdditionalDocument(document.Id),
                    _ => throw ExceptionUtilities.UnexpectedValue(document.Kind),
                };
            }

            return document.Project;
        }

        private async Task<TextDocument> UpdateDocumentInfoAsync(TextDocument document, Checksum infoChecksum)
        {
            var newDocumentInfo = await _assetService.GetAssetAsync<DocumentInfo.DocumentAttributes>(infoChecksum, _cancellationToken).ConfigureAwait(false);

            // there is no api to change these once document is created
            Contract.ThrowIfFalse(document.State.Attributes.Id == newDocumentInfo.Id);
            Contract.ThrowIfFalse(document.State.Attributes.Name == newDocumentInfo.Name);
            Contract.ThrowIfFalse(document.State.Attributes.FilePath == newDocumentInfo.FilePath);
            Contract.ThrowIfFalse(document.State.Attributes.IsGenerated == newDocumentInfo.IsGenerated);

            if (document.State.Attributes.Folders != newDocumentInfo.Folders)
            {
                // additional document can't change folder once created
                Contract.ThrowIfFalse(document is Document);
                document = document.Project.Solution.WithDocumentFolders(document.Id, newDocumentInfo.Folders).GetDocument(document.Id);
            }

            if (document.State.Attributes.SourceCodeKind != newDocumentInfo.SourceCodeKind)
            {
                // additional document can't change sourcecode kind once created
                Contract.ThrowIfFalse(document is Document);
                document = document.Project.Solution.WithDocumentSourceCodeKind(document.Id, newDocumentInfo.SourceCodeKind).GetDocument(document.Id);
            }

            return document;
        }

        private async Task<Dictionary<DocumentId, DocumentStateChecksums>> GetDocumentMapAsync(AssetService assetService, HashSet<Checksum> documents)
        {
            var map = new Dictionary<DocumentId, DocumentStateChecksums>();

            var documentChecksums = await assetService.GetAssetsAsync<DocumentStateChecksums>(documents, _cancellationToken).ConfigureAwait(false);
            var infos = await assetService.GetAssetsAsync<DocumentInfo.DocumentAttributes>(documentChecksums.Select(p => p.Item2.Info), _cancellationToken).ConfigureAwait(false);

            foreach (var kv in documentChecksums)
            {
                var info = await assetService.GetAssetAsync<DocumentInfo.DocumentAttributes>(kv.Item2.Info, _cancellationToken).ConfigureAwait(false);
                map.Add(info.Id, kv.Item2);
            }

            return map;
        }

        private async Task<Dictionary<DocumentId, DocumentStateChecksums>> GetDocumentMapAsync(IEnumerable<TextDocumentState> states, HashSet<Checksum> documents)
        {
            var map = new Dictionary<DocumentId, DocumentStateChecksums>();

            foreach (var state in states)
            {
                var documentChecksums = await state.GetStateChecksumsAsync(_cancellationToken).ConfigureAwait(false);
                if (documents.Contains(documentChecksums.Checksum))
                {
                    map.Add(state.Id, documentChecksums);
                }
            }

            return map;
        }

        private async Task<Dictionary<ProjectId, ProjectStateChecksums>> GetProjectMapAsync(AssetService assetService, HashSet<Checksum> projects)
        {
            var map = new Dictionary<ProjectId, ProjectStateChecksums>();

            var projectChecksums = await assetService.GetAssetsAsync<ProjectStateChecksums>(projects, _cancellationToken).ConfigureAwait(false);
            var infos = await assetService.GetAssetsAsync<ProjectInfo.ProjectAttributes>(projectChecksums.Select(p => p.Item2.Info), _cancellationToken).ConfigureAwait(false);

            foreach (var kv in projectChecksums)
            {
                var info = await assetService.GetAssetAsync<ProjectInfo.ProjectAttributes>(kv.Item2.Info, _cancellationToken).ConfigureAwait(false);
                map.Add(info.Id, kv.Item2);
            }

            return map;
        }

        private async Task<Dictionary<ProjectId, ProjectStateChecksums>> GetProjectMapAsync(Solution solution, HashSet<Checksum> projects)
        {
            var map = new Dictionary<ProjectId, ProjectStateChecksums>();

            foreach (var kv in solution.State.ProjectStates)
            {
                var projectChecksums = await kv.Value.GetStateChecksumsAsync(_cancellationToken).ConfigureAwait(false);
                if (projects.Contains(projectChecksums.Checksum))
                {
                    map.Add(kv.Key, projectChecksums);
                }
            }

            return map;
        }

        private Project AddDocument(Project project, DocumentInfo documentInfo, bool additionalText)
        {
            if (additionalText)
            {
                return project.Solution.AddAdditionalDocument(documentInfo).GetProject(project.Id);
            }

            return project.Solution.AddDocument(documentInfo).GetProject(project.Id);
        }

        private async Task ValidateChecksumAsync(Checksum checksumFromRequest, Solution incrementalSolutionBuilt)
        {
#if DEBUG
            var currentSolutionChecksum = await incrementalSolutionBuilt.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false);
            if (checksumFromRequest == currentSolutionChecksum)
            {
                return;
            }

            var solutionFromScratch = await CreateSolutionFromScratchAsync(checksumFromRequest).ConfigureAwait(false);

            await TestUtils.AssertChecksumsAsync(_assetService, checksumFromRequest, solutionFromScratch, incrementalSolutionBuilt).ConfigureAwait(false);

            async Task<Solution> CreateSolutionFromScratchAsync(Checksum checksum)
            {
                var solutionInfo = await SolutionInfoCreator.CreateSolutionInfoAsync(_assetService, checksum, _cancellationToken).ConfigureAwait(false);
                var workspace = new TemporaryWorkspace(solutionInfo);

                return workspace.CurrentSolution;
            }
#else

            // have this to avoid error on async
            await Task.CompletedTask.ConfigureAwait(false);
#endif
        }
    }
}


text:
using BEPUphysics.Entities;
using BEPUphysics.CollisionTests;
using BEPUphysics.Settings;
using BEPUutilities;
using System;
using BEPUutilities.DataStructures;

namespace BEPUphysics.Constraints.Collision
{
    ///
    /// Computes the forces necessary to keep two entities from going through each other at a contact point.
    ///
    public class ContactPenetrationConstraint : SolverUpdateable
    {
        internal Contact contact;

        ///
        /// Gets the contact associated with this penetration constraint.
        ///
        public Contact Contact { get { return contact; } }
        internal float accumulatedImpulse;
        //float linearBX, linearBY, linearBZ;
        internal float angularAX, angularAY, angularAZ;
        internal float angularBX, angularBY, angularBZ;

        private float softness;
        private float bias;
        private float linearAX, linearAY, linearAZ;
        private Entity entityA, entityB;
        private bool entityADynamic, entityBDynamic;
        //Inverse effective mass matrix
        internal float velocityToImpulse;
        private ContactManifoldConstraint contactManifoldConstraint;

        internal Vector3 ra, rb;

        ///
        /// Constructs a new penetration constraint.
        ///
        public ContactPenetrationConstraint()
        {
            isActive = false;
        }

        ///
        /// Configures the penetration constraint.
        ///
        ///<param name="contactManifoldConstraint">Owning manifold constraint.</param>
        ///<param name="contact">Contact associated with the penetration constraint.</param>
        public void Setup(ContactManifoldConstraint contactManifoldConstraint, Contact contact)
        {
            this.contactManifoldConstraint = contactManifoldConstraint;
            this.contact = contact;
            isActive = true;

            entityA = contactManifoldConstraint.EntityA;
            entityB = contactManifoldConstraint.EntityB;

        }

        ///
        /// Cleans up the constraint.
        ///
        public void CleanUp()
        {
            accumulatedImpulse = 0;
            contactManifoldConstraint = null;
            contact = null;
            entityA = null;
            entityB = null;
            isActive = false;

        }

        ///
        /// Gets the total normal impulse applied by this penetration constraint to maintain the separation of the involved entities.
        ///
        public float NormalImpulse
        {
            get { return accumulatedImpulse; }
        }

        ///
        /// Gets the relative velocity between the associated entities at the contact point along the contact normal.
        ///
        public float RelativeVelocity
        {
            get
            {
                float lambda = 0;
                if (entityA != null)
                {
                    lambda = entityA.linearVelocity.X * linearAX + entityA.linearVelocity.Y * linearAY + entityA.linearVelocity.Z * linearAZ +
                             entityA.angularVelocity.X * angularAX + entityA.angularVelocity.Y * angularAY + entityA.angularVelocity.Z * angularAZ;
                }
                if (entityB != null)
                {
                    lambda += -entityB.linearVelocity.X * linearAX - entityB.linearVelocity.Y * linearAY - entityB.linearVelocity.Z * linearAZ +
                              entityB.angularVelocity.X * angularBX + entityB.angularVelocity.Y * angularBY + entityB.angularVelocity.Z * angularBZ;
                }
                return lambda;
            }
        }

        ///
        /// Performs the frame's configuration step.
        ///
        ///<param name="dt">Timestep duration.</param>
        public override void Update(float dt)
        {

            entityADynamic = entityA != null && entityA.isDynamic;
            entityBDynamic = entityB != null && entityB.isDynamic;

            //Set up the jacobians.
            linearAX = -contact.Normal.X;
            linearAY = -contact.Normal.Y;
            linearAZ = -contact.Normal.Z;
            //linearBX = -linearAX;
            //linearBY = -linearAY;
            //linearBZ = -linearAZ;

            //angular A = Ra x N
            if (entityA != null)
            {
                Vector3.Subtract(ref contact.Position, ref entityA.position, out ra);
                angularAX = (ra.Y * linearAZ) - (ra.Z * linearAY);
                angularAY = (ra.Z * linearAX) - (ra.X * linearAZ);
                angularAZ = (ra.X * linearAY) - (ra.Y * linearAX);
            }

            //Angular B = N x Rb
            if (entityB != null)
            {
                Vector3.Subtract(ref contact.Position, ref entityB.position, out rb);
                angularBX = (linearAY * rb.Z) - (linearAZ * rb.Y);
                angularBY = (linearAZ * rb.X) - (linearAX * rb.Z);
                angularBZ = (linearAX * rb.Y) - (linearAY * rb.X);
            }

            //Compute inverse effective mass matrix
            float entryA, entryB;

            //these are the transformed coordinates
            float tX, tY, tZ;
            if (entityADynamic)
            {
                tX = angularAX * entityA.inertiaTensorInverse.M11 + angularAY * entityA.inertiaTensorInverse.M21 + angularAZ * entityA.inertiaTensorInverse.M31;
                tY = angularAX * entityA.inertiaTensorInverse.M12 + angularAY * entityA.inertiaTensorInverse.M22 + angularAZ * entityA.inertiaTensorInverse.M32;
                tZ = angularAX * entityA.inertiaTensorInverse.M13 + angularAY * entityA.inertiaTensorInverse.M23 + angularAZ * entityA.inertiaTensorInverse.M33;
                entryA = tX * angularAX + tY * angularAY + tZ * angularAZ + entityA.inverseMass;
            }
            else
                entryA = 0;

            if (entityBDynamic)
            {
                tX = angularBX * entityB.inertiaTensorInverse.M11 + angularBY * entityB.inertiaTensorInverse.M21 + angularBZ * entityB.inertiaTensorInverse.M31;
                tY = angularBX * entityB.inertiaTensorInverse.M12 + angularBY * entityB.inertiaTensorInverse.M22 + angularBZ * entityB.inertiaTensorInverse.M32;
                tZ = angularBX * entityB.inertiaTensorInverse.M13 + angularBY * entityB.inertiaTensorInverse.M23 + angularBZ * entityB.inertiaTensorInverse.M33;
                entryB = tX * angularBX + tY * angularBY + tZ * angularBZ + entityB.inverseMass;
            }
            else
                entryB = 0;

            //If we used a single fixed softness value, then heavier objects will tend to 'squish' more than light objects.
            //In the extreme case, very heavy objects could simply fall through the ground by force of gravity.
            //To see why this is the case, consider that a given dt, softness, and bias factor correspond to an equivalent spring's damping and stiffness coefficients.
            //Imagine trying to hang objects of different masses on the fixed-strength spring: obviously, heavier ones will pull it further down.

            //To counteract this, scale the softness value based on the effective mass felt by the constraint.
            //Larger effective masses should correspond to smaller softnesses so that the spring has the same positional behavior.
            //Fortunately, we're already computing the necessary values: the raw, unsoftened effective mass inverse shall be used to compute the softness.

            float effectiveMassInverse = entryA + entryB;
            float updateRate = 1 / dt;
            softness = CollisionResponseSettings.Softness * effectiveMassInverse * updateRate;
            velocityToImpulse = -1 / (softness + effectiveMassInverse);

            //Bounciness and bias (penetration correction)
            if (contact.PenetrationDepth >= 0)
            {
                bias = MathHelper.Min(
                    MathHelper.Max(0, contact.PenetrationDepth - CollisionDetectionSettings.AllowedPenetration) *
                    CollisionResponseSettings.PenetrationRecoveryStiffness * updateRate,
                    CollisionResponseSettings.MaximumPenetrationRecoverySpeed);

                if (contactManifoldConstraint.materialInteraction.Bounciness > 0)
                {
                    //Target a velocity which includes a portion of the incident velocity.
                    float bounceVelocity = -RelativeVelocity;
                    if (bounceVelocity > 0)
                    {
                        var lowThreshold = CollisionResponseSettings.BouncinessVelocityThreshold * 0.3f;
                        var velocityFraction = MathHelper.Clamp((bounceVelocity - lowThreshold) / (CollisionResponseSettings.BouncinessVelocityThreshold - lowThreshold + Toolbox.Epsilon), 0, 1);
                        var bouncinessVelocity = velocityFraction * bounceVelocity * contactManifoldConstraint.materialInteraction.Bounciness;
                        bias = MathHelper.Max(bouncinessVelocity, bias);
                    }
                }
            }
            else
            {
                //The contact is actually separated right now.  Allow the solver to target a position that is just barely in collision.
                //If the solver finds that an accumulated negative impulse is required to hit this target, then no work will be done.
                bias = contact.PenetrationDepth * updateRate;

                //This implementation is going to ignore bounciness for now.
                //Since it's not being used for CCD, these negative-depth contacts
                //only really occur in situations where no bounce should occur.

                //if (contactManifoldConstraint.materialInteraction.Bounciness > 0)
                //{
                //    //Target a velocity which includes a portion of the incident velocity.
                //    //The contact isn't colliding currently, but go ahead and target the post-bounce velocity.
                //    //The bias is added to the bounce velocity to simulate the object continuing to the surface and then bouncing off.
                //    float relativeVelocity = -RelativeVelocity;
                //    if (relativeVelocity > CollisionResponseSettings.BouncinessVelocityThreshold)
                //        bias = relativeVelocity * contactManifoldConstraint.materialInteraction.Bounciness + bias;
                //}
            }

        }

        ///
        /// Performs any pre-solve iteration work that needs exclusive
        /// access to the members of the solver updateable.
        /// Usually, this is used for applying warmstarting impulses.
        ///
        public override void ExclusiveUpdate()
        {
            //Warm starting
#if !WINDOWS
            Vector3 linear = new Vector3();
            Vector3 angular = new Vector3();
#else
            Vector3 linear, angular;
#endif
            linear.X = accumulatedImpulse * linearAX;
            linear.Y = accumulatedImpulse * linearAY;
            linear.Z = accumulatedImpulse * linearAZ;
            if (entityADynamic)
            {
                angular.X = accumulatedImpulse * angularAX;
                angular.Y = accumulatedImpulse * angularAY;
                angular.Z = accumulatedImpulse * angularAZ;
                entityA.ApplyLinearImpulse(ref linear);
                entityA.ApplyAngularImpulse(ref angular);
            }
            if (entityBDynamic)
            {
                linear.X = -linear.X;
                linear.Y = -linear.Y;
                linear.Z = -linear.Z;
                angular.X = accumulatedImpulse * angularBX;
                angular.Y = accumulatedImpulse * angularBY;
                angular.Z = accumulatedImpulse * angularBZ;
                entityB.ApplyLinearImpulse(ref linear);
                entityB.ApplyAngularImpulse(ref angular);
            }
        }

        ///
        /// Computes and applies an impulse to keep the colliders from penetrating.
        ///
        /// <returns>Impulse applied.</returns>
        public override float SolveIteration()
        {

            //Compute relative velocity
            float lambda = (RelativeVelocity - bias + softness * accumulatedImpulse) * velocityToImpulse;

            //Clamp accumulated impulse
            float previousAccumulatedImpulse = accumulatedImpulse;
            accumulatedImpulse = MathHelper.Max(0, accumulatedImpulse + lambda);
            lambda = accumulatedImpulse - previousAccumulatedImpulse;

            //Apply the impulse
#if !WINDOWS
            Vector3 linear = new Vector3();
            Vector3 angular = new Vector3();
#else
            Vector3 linear, angular;
#endif
            linear.X = lambda * linearAX;
            linear.Y = lambda * linearAY;
            linear.Z = lambda * linearAZ;
            if (entityADynamic)
            {
                angular.X = lambda * angularAX;
                angular.Y = lambda * angularAY;
                angular.Z = lambda * angularAZ;
                entityA.ApplyLinearImpulse(ref linear);
                entityA.ApplyAngularImpulse(ref angular);
            }
            if (entityBDynamic)
            {
                linear.X = -linear.X;
                linear.Y = -linear.Y;
                linear.Z = -linear.Z;
                angular.X = lambda * angularBX;
                angular.Y = lambda * angularBY;
                angular.Z = lambda * angularBZ;
                entityB.ApplyLinearImpulse(ref linear);
                entityB.ApplyAngularImpulse(ref angular);
            }

            return Math.Abs(lambda);
        }

        protected internal override void CollectInvolvedEntities(RawList<Entity> outputInvolvedEntities)
        {
            //This should never really have to be called.
            if (entityA != null)
                outputInvolvedEntities.Add(entityA);
            if (entityB != null)
                outputInvolvedEntities.Add(entityB);
        }

    }
}


text:
namespace quip {
  struct KeySequence;

  // A trie (or prefix tree) used to associate key sequences with mapped commands.
  struct MapTrie {
    MapTrie();

    void insert(const KeySequence& sequence, MapHandler handler);

    const MapTrieNode* find (const KeySequence& sequence) const;

  private:
    std::unique_ptr<MapTrieNode> m_root;
  };
}