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

---

{:new_window: target="\_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Edge analytics
{: #edge_analytics}

With edge analytics, you move the analytics rule-triggering process from the cloud to an edge analytics enabled gateway that might dramatically reduce the amount of device data traffic to the cloud by doing the analytics processing close to the device.
{:shortdesk}

Devices send their data to an edge analytics enabled gateway where edge analytics rules parse the data. Depending on your rule and its action, critical data and alerts might be sent to {{site.data.keyword.iot_full}}, trigger an alert on the gateway, or be written to a text file that is local to the gateway.

The following diagram illustrates the general architecture of an {{site.data.keyword.iot_full}} edge analytics environment.
![IBM Watson IoT Platform for edge analytics architecture](images/architecture_platform_edge.svg "IBM Watson IoT Platform withe edge analytics architecture")

## Before you begin
{: #byb}

Before you begin creating edge rules and actions:
- Make sure that your gateway is connected to {{site.data.keyword.iot_short}} and that device data is being transmitted. See [Connecting gateways](gateways/dashboard.html) for more information.
- Install the Edge Analytics Agent (EAA) on your gateway. For information, see [Installing the edge analytics agent](gateways/dashboard.html#edge).
 **Tip:** EAA-enabled gateways provide EAA diagnostic data in the form of gateway device messages. For information, see [Edge Analytics Agent diagnostic metrics](#eaa_metrics).
- Make sure that the device properties that you want to use as conditions in your rules are mapped to schemas. See [Connecting devices](iotplatform_task.html) and [Creating schemas](im_schemas.html) for more information.
- Review Edge Analytics recipes
In our Recipes portal, a couple of recipes describe the steps that are required to carry out IBM Edge Analytics. The recipes clearly describe about how to install and configure IBM Edge Analytics Agent on a device that is built on top of Apache Edgent to run analytics close to an IoT data source.
 - [Getting Started with Edge Analytics in IBM Watson IoT Platform](https://developer.ibm.com/recipes/tutorials/getting-started-with-edge-analytics-in-watson-iot-platform/) recipe is the beginning of this series. This recipe describes setting up Cisco DSA Platform on a Laptop System and Raspberry Pi 3 Device, installing and configuring IBM Edge Analytics Agent to connect to {{site.data.keyword.iot_short}}, installing System DS Link and configuring it to connect to Edge Gateway on {{site.data.keyword.iot_short}} as an attched device, defining and Activating the Edge Rule on the Edge Gateway, and the mangement of the Edge Rule from {{site.data.keyword.iot_short}}.
 - To illustrate an advanced usage of Edge Analytics, the [Handling Alerts and Device Actions with Edge Analytics in IBM Watson IoT Platform](https://developer.ibm.com/recipes/tutorials/handling-alerts-and-device-actions-with-edge-analytics-in-ibm-watson-iot-platform/) recipe show cases building our own DS Link to get data from an Arduino Uno as attached device to Raspberry Pi 3 Device. Then the recipe shows case data filtering and handling of local device actions as part of the Edge Rule alert in the recipe.

## Managing edge rules and actions
{: #managing_rules}

Edge rules are managed by using the following:
- The **Rules** dashboard is used to create and edit cloud and edge rules and actions for your devices and gateways.
- The **Edge Rules Gateways** board is used to activate, deactivate, update, and remove an edge rule on your gateways. To access the Edge Rules Gateways board, from the Rules dashboard click **Manage Rule** for the edge rule that you want to manage. For more information, see [ Activating, deactivating, and managing edge rules for your gateways](#manage).

To get an overview of edge rules and alerts that have been triggered for your gateway-connected devices, use the following boards:

|Board Name | Description |
 |:---|:---|
  |Rule-Centric Analytics | Shows the rules for your organization, including edge rules. Additional cards list forwarded edge alerts, associated devices, device properties, and forwarded edge alert information. |
 |Device-Centric Analytics | Shows the devices that are connected to your organization. Additional cards show forwarded alerts for a selected edge device, information for a selected device, device properties, and forwarded alert information. |

For more information about the default analytics boards, see [Visualizing real-time data by using boards and cards](data_visualization.html#default_boards).

## Creating edge rules
{: #rules}

Edge rules are condition-based decision points that match real-time device data with predefined threshold values or other property data to trigger an edge action if a condition is met.

**Important:** Before you can create rules for a device type, you must create a schema for the device type. For information, see [Create device type schemas](im_schemas.html).

To create a rule:
1. In the {{site.data.keyword.iot_short}} dashboard, go to **Rules**.
2. Click **Create Edge Rule**, give the rule a name, provide a description, select an edge device type that the rule applies to, and then click **Next**.
3. Set up the rule logic.
Add one or more IF conditions to use as triggers for the rule.
You can add conditions in parallel rows to apply them as OR conditions, or you can add conditions in sequential columns to apply them as AND conditions.
**Note:** To be able to select a device property as input for a rule, the property must be mapped to a schema. See [Creating schemas](im_schemas.html) for more information.

**Important:** To trigger a condition that compares two properties or to trigger two or more property conditions that are combined sequentially by using AND, the triggering data points must be included in the same device message. If the data is received in more than one message, the condition or sequential conditions do not trigger.

**Examples:**
A simple rule might trigger an alert if a parameter value is larger than a specified value:
`temp>80`
A more complex rule might trigger when a combination of thresholds is met:
`temp>60 AND capacity>50`

4. Configure conditional trigger requirements for your rule.
To control the number of alerts and actions that are triggered for a rule over a time period, you can configure conditional trigger requirements for your rule.
**Important:** The conditional triggering acts on any condition in the rule. For example, if a rule has five different parallel conditions set by using OR, each condition that is true counts towards the conditional trigger count.
To set conditional triggering for a rule:
 1. In the rule editor, click the default **Trigger each time conditions are met** link to open the set frequency requirement dialog box.
 2. Select and configure the conditional trigger that you want to use in the rule.

Trigger every time conditions are met

Trigger if conditions are met N times in M *Unit of time*

 For a more detailed description of the conditional triggers, see [Conditional rule triggering](cloud_analytics.html#conditional "Conditional triggering overview") in the cloud analytics section.
5. Create or select one or more actions that occur if the rule conditions are met.
For more information about edge actions, see [Creating edge actions](#edge_actions "Create edge actions").
 Example: An action can be to send device data to the cloud or write an alert to a local file.
3. **Optional:** Select an alert priority for the rule.
 The priority is used to classify the alerts that are displayed in the **Rule-Based Analytics** board. The default priority is Low.
6. When you are satisfied with your rule, click **Save**.

Your rule is created and is added to the browse dashboard. You can now [activate](#manage) the rule from the **Edge Rules Gateways** board that opens.

## Creating edge actions
{: #edge_actions}

You can create actions directly in the rule editor or create the actions in the Actions tab and then select the actions when you create your rules.

To create an action on the Actions tab:
1. In the {{site.data.keyword.iot_short}} dashboard, go to **Rules**.
2. In the Rules dashboard, select the **Actions** tab.
2. Click **Create An Action**, give the action a name and a description and select an action type, then click **Next**.
Edge analytics supports two action types:

Forward event to cloud

The device event is sent to {{site.data.keyword.iot_short}} where it can be used in boards and cards and with cloud analytics rules. For information, see [Integrating with cloud analytics](#integrate_with_cloud_analytics).
**Tip:** Use the forward event cloud action to reduce the amount of device data that is sent to the cloud by filtering out the less important data directly at the gateway device.

Alert

An alert is created on the gateway device.

3. Provide the required parameters for the type of action that you selected.

Forward event to cloud

Select the event data to forward to the cloud and provide the event name to use in the message.

**Tip:** You can use the event and properties when setting up boards and cards and when creating cloud analytics rules.

You can:

Include all device properties and virtual properties

Include only schema-defined properties and virtual properties

Alert

Specify an alert message and select at least one destination for the alert.

Forward to cloud
 The alert is forwarded to {{site.data.keyword.iot_short}} where it is displayed in the Rule-Centric Analytics and Device-Centric Analytics boards.

Publish to gateway broker
 The alert is published to the gateway broker. The broker configuration determines how the alert is surfaced to a user.

Save to a local text file
 The alert is appended to the local *IBMEdgeAnalyticsAlerts.csv* text file on the gateway server.

4. Click **OK** to create the new action.

The action is now available in the rule editor.

## Activating, deactivating, and managing edge rules for your gateways
{: #manage}

For a rule to trigger actions you must first activate it on one or more gateways. You use the **Edge Rules Gateways** board to activate, deactivate, update, and remove an edge rule on your gateways.

To activate an edge rule:
1. From the Rules dashboard, click the **Manage Rule** button for the edge rule that you want to manage.
In the **Edge Rules Gateways** board that opens you see a list of all connected EAA-enabled gateways. The rule status for gateways where the rule is not uploaded and activated is *None*.
2. Locate the gateway on which you want to activate the rule, and select **Activate** from the menu in the Select operation column.
The edge rule is uploaded to the gateway. When the upload is complete and the rule is active, the Rule status changes to **Active**.

The rule is now active on the gateway, and the configured actions will trigger when the rule conditions are met.

**Tip:** To manage rules on multiple gateways you can select the select-all box next to the Gateway column header. Clear any gateways that you do not want to include and then pick an operation from the **Select operation** menu at the top of the column with the same name.

In addition to activating a rule you can perform the following rule management operations on your gateways:

Operation | Description
--- | ---
Activate | Uploads and activates the rule on the selected gateways. The rule status is set to *Active*.
Deactivate | Deactivates the rule on the selected gateways. The rule remains on the gateway and can be reactivated if needed. The rule status is set to *Inactive*.
Update | Uploads an updated version of the rule to the selected gateways. Use this operation to bring a gateway up to date if the rule status for the gateway is *Active (Older)*. The rule status is set to *Active*.
Remove | Removes the rule from the selected gateways. The rule status for the gateway reverts to *None*.

## Integrating with cloud analytics
{: #integrate_with_cloud_analytics}

Use the edge rule triggered actions that are run on the EAA-enabled gateway to filter the data that flows to the cloud and forward gateway generated alerts to the cloud to use with {{site.data.keyword.iot_short}} boards and cards.

You can also use {{site.data.keyword.iot_short}} to do cloud analytics on device data that is sent to the cloud from the gateway. If you use the `Forward event to cloud` action in your edge rule, the created message can be used as input for a cloud analytics rule, just as if the device that provided the data that triggered the edge rule was connected directly to {{site.data.keyword.iot_short}}.

For more information on how to create cloud analytics rules and actions, see [Cloud Analytics](cloud_analytics.html).

## Edge Analytics Agent diagnostic metrics
{: #eaa_metrics}

A connected EAA-enabled gateway sends diagnostic information as device messages of the event type `gateway_xv-monitor-event`.
 **Tip:** You can use [cloud analytics](cloud_analytics.html) rules to configure alert actions such as email notifications based on the diagnostic values that are sent back by the EAA-enabled gateway. For example, you can create a rule to alert you if the `SystemLoad` exceeds a certain threshold.

To see information about the state of the gateway:
1. In the {{site.data.keyword.iot_short}} dashboard select **Devices** in the menu side bar.
2. Click your gateway device to open the device details page.
3. Access the gateway diagnostic information:
 - See the **Recent Events** section for a list of recent messages that were sent by the gateway.
 - See the **Diagnostic logs** section for any gateway warnings and other diagnostic messages.
 - See the **Sensor information** section for detailed diagnostic information from the gateway. The following table describes the different properties that might be included in the gateway device messages.

 Property | Description
 --- | ---
 `MsgInCount` |The number of messages that were sent to the Edge Analytics Agent (EAA).
 `MsgInRate` | The estimated number of messages per second that were sent to the EAA during the last time minute.
 `LastHeartBeat` | The millisecond timestamp when the last heart beat message was generated. A heart beat message is generated every 10 seconds at minimum.
 `CurrentTimestamp` | The milliseconds timestamp when the current monitoring message was generated.
 `IsAlive` | This property is 0 if the difference between `LastHeartBeat` and `CurrentTimestamp` is greater than 20 seconds.
 `BytesOutCount` | The number of message bytes that are sent by the EAA to {{site.data.keyword.iot_short}}.
 `BytesOutRate` | The estimated number of message bytes per second that were sent by the EAA to {{site.data.keyword.iot_short}} during the last minute.
 `BytesInCount` | The number of message bytes that were sent by {{site.data.keyword.iot_short}} to the EAA.
 `BytesInRate` | The estimated number of message bytes per second that that were sent by {{site.data.keyword.iot_short}} to the EAA in the last minute.
 `RuleBytesInCount` |The number of message bytes that were sent to the EAA rule engine core.
 **Note:** If no rule is set for a device type, messages for that device type are not sent to the rule engine core.
 `RuleBytesInRate` | The estimated number of message bytes per second that were sent to the EAA rule engine core during the last minute.
 `MsgOutCount` | The number of messages that were sent by the EAA to {{site.data.keyword.iot_short}}.
 `MsgOutRate` | The estimated number of messages bytes per second that are sent by the EAA to {{site.data.keyword.iot_short}} during the last minute.
 `MsgReducePercent` | The percentage difference between incoming and outgoing messages.
The following formula is used for the calculation: `(msgIn - msgOut) / msgIn`
 `BytesReducePercent` | The percentage difference between incoming and outgoing bytes.
The following formula is used for the calculation: `(bytesIn - bytesOut) / bytesIn`
 `MsgRateReduce` | The percentage difference between incoming and outgoing message rate.
The following formula is used for the calculation: `(msgInRate - msgOutRate) / msgInRate`
 `BytesRateReduce` | The percentage difference between incoming and outgoing messages bytes.
The following formula is used for the calculation: `(bytesInRate - bytesOutRate) / bytesInRate`
 `SystemLoad` | The current system load for the on the system where the EAA is running. **Note:** The CPU rate will be sent only if the `mpstat` command is available on the system where the EAA is running. Otherwise, the system load average for the last minute is sent.
"The system load average is the sum of the number of runnable entities queued to the available processors and the number of runnable entities running on the available processors averaged over a period of time. The way in which the load average is calculated is operating system specific but is typically a damped time-dependent average. If the load average is not available, a negative value is returned. " - javadoc for _ManagementFactory.getOperatingSystemMXBean_.
 `FreeMemory` | The number of bytes of free memory for the Java™ Virtual Machine (JVM) where EAA is running.
 `MemoryUsed` | The number of bytes of JVM memory that is used by EAA.
 `InQueueSize` | The number of messages that are queued for EAA processing.
 `RuleNumber` | The number of defined rules in the rule engine core.
 `ProcessorNumber` | For debug use. The number of defined processors in the rule engine core.
**Note:** A processor is the minimal execution unit in the rule engine core.
 `DataPointsInWindow` | The total number of data points that are buffered in the time window. The byte size of a data point differs depending on its data type. For example, a float/int data point size is 8 bytes whereas a string data point size differs depending on its length.  In most cases you can estimate the memory usage of the time window by using the following formula: `DataPointsInWindow * 8`.


text:
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'

import {
  customPropTypes,
  getElementType,
  getUnhandledProps,
  META,
  useKeyOnly,
} from '../../lib'

/**
 * A pushable sub-component for Sidebar.
 */
function SidebarPusher(props) {
  const { className, dimmed, children } = props

  const classes = cx(
    'pusher',
    useKeyOnly(dimmed, 'dimmed'),
    className,
  )
  const rest = getUnhandledProps(SidebarPusher, props)
  const ElementType = getElementType(SidebarPusher, props)

  return <ElementType {...rest} className={classes}>{children}</ElementType>
}

SidebarPusher._meta = {
  name: 'SidebarPusher',
  type: META.TYPES.MODULE,
  parent: 'Sidebar',
}

SidebarPusher.propTypes = {
  /** An element type to render as (string or function). */
  as: customPropTypes.as,

  /** Primary content. */
  children: PropTypes.node,

  /** Additional classes. */
  className: PropTypes.string,

  /** Controls whether or not the dim is displayed. */
  dimmed: PropTypes.bool,
}

export default SidebarPusher

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2017-2019 Hazuki
  ~
  ~ 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.
  -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:id="@+id/linear">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <com.turingtechnologies.materialscrollbar.TouchScrollBar
        android:id="@+id/touchScrollBar"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        app:msb_recyclerView="@+id/recyclerView"
        app:msb_lightOnTouch="true"/>

    <com.github.clans.fab.FloatingActionMenu
        android:id="@+id/fabMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="bottom|end"
        android:padding="@dimen/fab_margin"
        app:menu_colorNormal="@color/accent"
        app:menu_backgroundColor="#55000000"
        app:menu_closeOnTouchOutside="true"
        app:layout_behavior="jp.hazuki.yuzubrowser.legacy.utils.view.behavior.ScrollFaMenuBehavior">

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/addByEditFab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_edit_white_24dp"
            app:fab_size="mini"
            app:fab_colorNormal="@color/yuzu_orange"
            app:fab_label="@string/add_by_edit"/>

        <com.github.clans.fab.FloatingActionButton
            android:id="@+id/addFromFileFab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_file_white_24dp"
            app:fab_size="mini"
            app:fab_colorNormal="@color/yuzu_orange"
            app:fab_label="@string/add_from_file"/>

    </com.github.clans.fab.FloatingActionMenu>

</RelativeLayout>


text:
package co.com.codesoftware.server.nsigemco;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Clase Java para marcaEntity complex type.
 *
 *
El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
 *
 *

 * <complexType name="marcaEntity">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="descripcion" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="estado" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="nombre" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "marcaEntity", propOrder = {
    "descripcion",
    "estado",
    "id",
    "nombre"
})
public class MarcaEntity {

    protected String descripcion;
    protected String estado;
    protected Integer id;
    protected String nombre;

    /**
     * Obtiene el valor de la propiedad descripcion.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescripcion() {
        return descripcion;
    }

    /**
     * Define el valor de la propiedad descripcion.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescripcion(String value) {
        this.descripcion = value;
    }

    /**
     * Obtiene el valor de la propiedad estado.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getEstado() {
        return estado;
    }

    /**
     * Define el valor de la propiedad estado.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setEstado(String value) {
        this.estado = value;
    }

    /**
     * Obtiene el valor de la propiedad id.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    public Integer getId() {
        return id;
    }

    /**
     * Define el valor de la propiedad id.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setId(Integer value) {
        this.id = value;
    }

    /**
     * Obtiene el valor de la propiedad nombre.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNombre() {
        return nombre;
    }

    /**
     * Define el valor de la propiedad nombre.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNombre(String value) {
        this.nombre = value;
    }

}


text: Sources of objects, reported by Quilt are stored here


text:
import GfyCat from "./plugins/gfycat";
import ImageEmbed from "./plugins/image-embed";
import ImageLink from "./plugins/image-link";
import ImgurAlbum from "./plugins/imgur-album";
import ImgurGifv from "./plugins/imgur-gifv";
import StreamableLink from "./plugins/streamable-link";
import TumblrArchive from "./plugins/tumblr-archive";
import VimeoLink from "./plugins/vimeo-link";
import YouTubeLink from "./plugins/youtube-link";

export const enabledPlugins = [
    TumblrArchive,
    ImageEmbed,
    ImageLink,
    ImgurGifv,
    GfyCat,
    ImgurAlbum,
    YouTubeLink,
    VimeoLink,
    StreamableLink,
];


text:
#if !defined(MQTTREASONCODES_H)
#define MQTTREASONCODES_H

/** The MQTT V5 one byte reason code */
enum MQTTReasonCodes {
  MQTTREASONCODE_SUCCESS = 0,
  MQTTREASONCODE_NORMAL_DISCONNECTION = 0,
  MQTTREASONCODE_GRANTED_QOS_0 = 0,
  MQTTREASONCODE_GRANTED_QOS_1 = 1,
  MQTTREASONCODE_GRANTED_QOS_2 = 2,
  MQTTREASONCODE_DISCONNECT_WITH_WILL_MESSAGE = 4,
  MQTTREASONCODE_NO_MATCHING_SUBSCRIBERS = 16,
  MQTTREASONCODE_NO_SUBSCRIPTION_FOUND = 17,
  MQTTREASONCODE_CONTINUE_AUTHENTICATION = 24,
  MQTTREASONCODE_RE_AUTHENTICATE = 25,
  MQTTREASONCODE_UNSPECIFIED_ERROR = 128,
  MQTTREASONCODE_MALFORMED_PACKET = 129,
  MQTTREASONCODE_PROTOCOL_ERROR = 130,
  MQTTREASONCODE_IMPLEMENTATION_SPECIFIC_ERROR = 131,
  MQTTREASONCODE_UNSUPPORTED_PROTOCOL_VERSION = 132,
  MQTTREASONCODE_CLIENT_IDENTIFIER_NOT_VALID = 133,
  MQTTREASONCODE_BAD_USER_NAME_OR_PASSWORD = 134,
  MQTTREASONCODE_NOT_AUTHORIZED = 135,
  MQTTREASONCODE_SERVER_UNAVAILABLE = 136,
  MQTTREASONCODE_SERVER_BUSY = 137,
  MQTTREASONCODE_BANNED = 138,
  MQTTREASONCODE_SERVER_SHUTTING_DOWN = 139,
  MQTTREASONCODE_BAD_AUTHENTICATION_METHOD = 140,
  MQTTREASONCODE_KEEP_ALIVE_TIMEOUT = 141,
  MQTTREASONCODE_SESSION_TAKEN_OVER = 142,
  MQTTREASONCODE_TOPIC_FILTER_INVALID = 143,
  MQTTREASONCODE_TOPIC_NAME_INVALID = 144,
  MQTTREASONCODE_PACKET_IDENTIFIER_IN_USE = 145,
  MQTTREASONCODE_PACKET_IDENTIFIER_NOT_FOUND = 146,
  MQTTREASONCODE_RECEIVE_MAXIMUM_EXCEEDED = 147,
  MQTTREASONCODE_TOPIC_ALIAS_INVALID = 148,
  MQTTREASONCODE_PACKET_TOO_LARGE = 149,
  MQTTREASONCODE_MESSAGE_RATE_TOO_HIGH = 150,
  MQTTREASONCODE_QUOTA_EXCEEDED = 151,
  MQTTREASONCODE_ADMINISTRATIVE_ACTION = 152,
  MQTTREASONCODE_PAYLOAD_FORMAT_INVALID = 153,
  MQTTREASONCODE_RETAIN_NOT_SUPPORTED = 154,
  MQTTREASONCODE_QOS_NOT_SUPPORTED = 155,
  MQTTREASONCODE_USE_ANOTHER_SERVER = 156,
  MQTTREASONCODE_SERVER_MOVED = 157,
  MQTTREASONCODE_SHARED_SUBSCRIPTIONS_NOT_SUPPORTED = 158,
  MQTTREASONCODE_CONNECTION_RATE_EXCEEDED = 159,
  MQTTREASONCODE_MAXIMUM_CONNECT_TIME = 160,
  MQTTREASONCODE_SUBSCRIPTION_IDENTIFIERS_NOT_SUPPORTED = 161,
  MQTTREASONCODE_WILDCARD_SUBSCRIPTIONS_NOT_SUPPORTED = 162
};

#if defined(WIN32) || defined(WIN64)
  #define DLLImport __declspec(dllimport)
  #define DLLExport __declspec(dllexport)
#else
  #define DLLImport extern
  #define DLLExport __attribute__ ((visibility ("default")))
#endif

/**
 * Returns a printable string description of an MQTT V5 reason code.
 * @param value an MQTT V5 reason code.
 * @return the printable string description of the input reason code.
 * NULL if the code was not found.
 */
DLLExport const char* MQTTReasonCode_toString(enum MQTTReasonCodes value);

#endif


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

namespace Sitecore.NuGetCourier.Runner
{
    public static class Extensions
    {
        //If extensionless path add * to the end to work around bug in nuget pack with extensionless files
        public static string EnsureExtension(this string path)
        {
            if (Path.HasExtension(path))
                return path;

            return path + "*";

        }
        public static string GetTarget(this string filePath)
        {
            return filePath.Substring(0, filePath.LastIndexOf("\\", StringComparison.Ordinal));
        }

        public static string CreateReleaseNotesSection(this List<string> items, string heading)
        {
            if (items.Count > 0)
            {
                var sb = new StringBuilder();
                sb.AppendLine("
");
                sb.AppendLine(string.Format("{0} ({1})
", heading, items.Count));
                items.ForEach(item => sb.AppendLine(item + "
"));
                sb.AppendLine("
");
                return sb.ToString().Replace("_", "_"); //Fix problem with displaying underscores on std value items
            }
            return "";
        }
    }
}


text:
namespace media {

class AudioManagerWin;

// AudioOutputStream implementation using Windows Core Audio APIs.
class MEDIA_EXPORT WASAPIAudioOutputStream :
      public AudioOutputStream,
      public base::DelegateSimpleThread::Delegate {
 public:
  // The ctor takes all the usual parameters, plus |manager| which is the
  // the audio manager who is creating this object.
  WASAPIAudioOutputStream(AudioManagerWin* manager,
                          const AudioParameters& params,
                          ERole device_role);

  // The dtor is typically called by the AudioManager only and it is usually
  // triggered by calling AudioOutputStream::Close().
  virtual ~WASAPIAudioOutputStream();

  // Implementation of AudioOutputStream.
  virtual bool Open() OVERRIDE;
  virtual void Start(AudioSourceCallback* callback) OVERRIDE;
  virtual void Stop() OVERRIDE;
  virtual void Close() OVERRIDE;
  virtual void SetVolume(double volume) OVERRIDE;
  virtual void GetVolume(double* volume) OVERRIDE;

  // Retrieves the number of channels the audio engine uses for its internal
  // processing/mixing of shared-mode streams for the default endpoint device.
  static int HardwareChannelCount();

  // Retrieves the channel layout the audio engine uses for its internal
  // processing/mixing of shared-mode streams for the default endpoint device.
  // Note that we convert an internal channel layout mask (see ChannelMask())
  // into a Chrome-specific channel layout enumerator in this method, hence
  // the match might not be perfect.
  static ChannelLayout HardwareChannelLayout();

  // Retrieves the sample rate the audio engine uses for its internal
  // processing/mixing of shared-mode streams for the default endpoint device.
  static int HardwareSampleRate(ERole device_role);

  // Returns AUDCLNT_SHAREMODE_EXCLUSIVE if --enable-exclusive-mode is used
  // as command-line flag and AUDCLNT_SHAREMODE_SHARED otherwise (default).
  static AUDCLNT_SHAREMODE GetShareMode();

  bool started() const { return render_thread_.get() != NULL; }

  // Returns the number of channels the audio engine uses for its internal
  // processing/mixing of shared-mode streams for the default endpoint device.
  int GetEndpointChannelCountForTesting() { return format_.Format.nChannels; }

 private:
  // DelegateSimpleThread::Delegate implementation.
  virtual void Run() OVERRIDE;

  // Issues the OnError() callback to the |sink_|.
  void HandleError(HRESULT err);

  // The Open() method is divided into these sub methods.
  HRESULT SetRenderDevice();
  HRESULT ActivateRenderDevice();
  bool DesiredFormatIsSupported();
  HRESULT InitializeAudioEngine();

  // Called when the device will be opened in shared mode and use the
  // internal audio engine's mix format.
  HRESULT SharedModeInitialization();

  // Called when the device will be opened in exclusive mode and use the
  // application specified format.
  HRESULT ExclusiveModeInitialization();

  // Converts unique endpoint ID to user-friendly device name.
  std::string GetDeviceName(LPCWSTR device_id) const;

  // Contains the thread ID of the creating thread.
  base::PlatformThreadId creating_thread_id_;

  // Our creator, the audio manager needs to be notified when we close.
  AudioManagerWin* manager_;

  // Rendering is driven by this thread (which has no message loop).
  // All OnMoreData() callbacks will be called from this thread.
  scoped_ptr<base::DelegateSimpleThread> render_thread_;

  // Contains the desired audio format which is set up at construction.
  // Extended PCM waveform format structure based on WAVEFORMATEXTENSIBLE.
  // Use this for multiple channel and hi-resolution PCM data.
  WAVEFORMATPCMEX format_;

  // Copy of the audio format which we know the audio engine supports.
  // It is recommended to ensure that the sample rate in |format_| is identical
  // to the sample rate in |audio_engine_mix_format_|.
  base::win::ScopedCoMem<WAVEFORMATPCMEX> audio_engine_mix_format_;

  bool opened_;

  // Set to true as soon as a new default device is detected, and cleared when
  // the streaming has switched from using the old device to the new device.
  // All additional device detections during an active state are ignored to
  // ensure that the ongoing switch can finalize without disruptions.
  bool restart_rendering_mode_;

  // Volume level from 0 to 1.
  float volume_;

  // Size in bytes of each audio frame (4 bytes for 16-bit stereo PCM).
  size_t frame_size_;

  // Size in audio frames of each audio packet where an audio packet
  // is defined as the block of data which the source is expected to deliver
  // in each OnMoreData() callback.
  size_t packet_size_frames_;

  // Size in bytes of each audio packet.
  size_t packet_size_bytes_;

  // Size in milliseconds of each audio packet.
  float packet_size_ms_;

  // Length of the audio endpoint buffer.
  uint32 endpoint_buffer_size_frames_;

  // Defines the role that the system has assigned to an audio endpoint device.
  ERole device_role_;

  // The sharing mode for the connection.
  // Valid values are AUDCLNT_SHAREMODE_SHARED and AUDCLNT_SHAREMODE_EXCLUSIVE
  // where AUDCLNT_SHAREMODE_SHARED is the default.
  AUDCLNT_SHAREMODE share_mode_;

  // The channel count set by the client in |params| which is provided to the
  // constructor. The client must feed the AudioSourceCallback::OnMoreData()
  // callback with PCM-data that contains this number of channels.
  int client_channel_count_;

  // Counts the number of audio frames written to the endpoint buffer.
  UINT64 num_written_frames_;

  // Pointer to the client that will deliver audio samples to be played out.
  AudioSourceCallback* source_;

  // An IMMDeviceEnumerator interface which represents a device enumerator.
  base::win::ScopedComPtr<IMMDeviceEnumerator> device_enumerator_;

  // An IMMDevice interface which represents an audio endpoint device.
  base::win::ScopedComPtr<IMMDevice> endpoint_device_;

  // An IAudioClient interface which enables a client to create and initialize
  // an audio stream between an audio application and the audio engine.
  base::win::ScopedComPtr<IAudioClient> audio_client_;

  // The IAudioRenderClient interface enables a client to write output
  // data to a rendering endpoint buffer.
  base::win::ScopedComPtr<IAudioRenderClient> audio_render_client_;

  // The audio engine will signal this event each time a buffer becomes
  // ready to be filled by the client.
  base::win::ScopedHandle audio_samples_render_event_;

  // This event will be signaled when rendering shall stop.
  base::win::ScopedHandle stop_render_event_;

  // Container for retrieving data from AudioSourceCallback::OnMoreData().
  scoped_ptr<AudioBus> audio_bus_;

  DISALLOW_COPY_AND_ASSIGN(WASAPIAudioOutputStream);
};

}  // namespace media

#endif  // MEDIA_AUDIO_WIN_AUDIO_LOW_LATENCY_OUTPUT_WIN_H_


text:
package io.jenetics.util.performance;

import java.text.NumberFormat;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.random.RandomGenerator;

import io.jenetics.prngine.LCG64ShiftRandom;
//import io.jenetics.util.XORShiftRandom;

/**
 * @author Franz Wilhelmstötter
 */
public class RandomPerformanceTests {

	public static void main(final String[] args) {
		final int loops = Integer.MAX_VALUE;//1_000_000_000;

		test(new Random(), loops);
		test(ThreadLocalRandom.current(), loops);
		//test(new XORShiftRandom(), loops);
		test(new LCG64ShiftRandom(), loops);
	}

	private static void test(final RandomGenerator random, final int loops) {
		System.out.println(String.format(
			"%-20s %s; %s; %s; %s",
			random.getClass().getSimpleName() + ":",
			testNextInt(random, loops),
			testNextLong(random, loops),
			testNextFloat(random, loops),
			testNextDouble(random, loops)
		));
	}

	private static String testNextInt(final RandomGenerator random, final int loops) {
		long start = System.nanoTime();
		for (int i = loops; --i >= 0;) {
			random.nextInt();
		}
		long end = System.nanoTime();

		final NumberFormat format = NumberFormat.getIntegerInstance();
		return String.format("%11s i/sec", format.format(perSec(loops, start, end)));
	}

	private static String testNextLong(final RandomGenerator random, final int loops) {
		long start = System.nanoTime();
		for (int i = loops; --i >= 0;) {
			random.nextLong();
		}
		long end = System.nanoTime();

		final NumberFormat format = NumberFormat.getIntegerInstance();
		return String.format("%11s l/sec", format.format(perSec(loops, start, end)));
	}

	private static String testNextFloat(final RandomGenerator random, final int loops) {
		long start = System.nanoTime();
		for (int i = loops; --i >= 0;) {
			random.nextFloat();
		}
		long end = System.nanoTime();

		final NumberFormat format = NumberFormat.getIntegerInstance();
		return String.format("%11s f/sec", format.format(perSec(loops, start, end)));
	}

	private static String testNextDouble(final RandomGenerator random, final int loops) {
		long start = System.nanoTime();
		for (int i = loops; --i >= 0;) {
			random.nextDouble();
		}
		long end = System.nanoTime();

		final NumberFormat format = NumberFormat.getIntegerInstance();
		return String.format("%11s d/sec", format.format(perSec(loops, start, end)));
	}

	private static long perSec(final long loops, final long start, final long end) {
		final double seconds = (end - start)/1_000_000_000.0;
		return (long)(loops/seconds);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
  <Properties>
    <Property name="baseDir">target/rolling-direct-1906</Property>
  </Properties>
  <Appenders>
    <RollingFile name="RollingFile" filePattern="${baseDir}/rollingfile.%d{yyyy-MM-dd-HH-mm-ss}.log">
      <PatternLayout pattern="%d{yyyy-MM-dd-HH-mm-ss} [%level] [%c] %msg%n" />
      <Policies>
        <TimeBasedTriggeringPolicy />
      </Policies>
      <DirectWriteRolloverStrategy />
    </RollingFile>
  </Appenders>
  <Loggers>
    <Root level="trace">
      <AppenderRef ref="RollingFile" />
    </Root>
  </Loggers>
</Configuration>


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'about',
  templateUrl: 'about.component.html'
})
export class AboutComponent implements OnInit {
  constructor() { }

  ngOnInit() {

   }
}


text:
import os

class classFileWrite:
    fileobj = None
    directory = "./benchmark"
    fpath = directory + "/test.txt"

    def __init__(self):
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)
        self.openfile()

    def openfile(self):
        self.fileobj = open(self.fpath, "a")

    def writeline(self):
        line = "=" * 60
        line=line+"\n"
        self.fileobj.write(line)

    def writelog(self,logstr=""):
        self.fileobj.seek(0,0)
        logstr = logstr+"\n"
        self.fileobj.write(logstr)

    def closefile(self):
        self.fileobj.close()


text:
from __future__ import annotations

from unittest import mock

import pandas as pd
import pytest

from airflow.exceptions import AirflowException
from airflow.models import DAG, Connection
from airflow.providers.slack.transfers.sql_to_slack import (
    BaseSqlToSlackOperator,
    SqlToSlackApiFileOperator,
    SqlToSlackOperator,
)
from airflow.utils import timezone

TEST_DAG_ID = "sql_to_slack_unit_test"
TEST_TASK_ID = "sql_to_slack_unit_test_task"
DEFAULT_DATE = timezone.datetime(2017, 1, 1)

class TestBaseSqlToSlackOperator:
    def setup_method(self):
        self.default_op_kwargs = {
            "sql": "SELECT 1",
            "sql_conn_id": "test-sql-conn-id",
            "sql_hook_params": None,
            "parameters": None,
        }

    def test_execute_not_implemented(self):
        """Test that no base implementation for ``BaseSqlToSlackOperator.execute()``."""
        op = BaseSqlToSlackOperator(task_id="test_base_not_implements", **self.default_op_kwargs)
        with pytest.raises(NotImplementedError):
            op.execute(mock.MagicMock())

    @mock.patch("airflow.providers.common.sql.operators.sql.BaseHook.get_connection")
    @mock.patch("airflow.models.connection.Connection.get_hook")
    @pytest.mark.parametrize("conn_type", ["postgres", "snowflake"])
    @pytest.mark.parametrize("sql_hook_params", [None, {"foo": "bar"}])
    def test_get_hook(self, mock_get_hook, mock_get_conn, conn_type, sql_hook_params):
        class SomeDummyHook:
            """Hook which implements ``get_pandas_df`` method"""

            def get_pandas_df(self):
                pass

        expected_hook = SomeDummyHook()
        mock_get_conn.return_value = Connection(conn_id=f"test_connection_{conn_type}", conn_type=conn_type)
        mock_get_hook.return_value = expected_hook
        op_kwargs = {
            **self.default_op_kwargs,
            "sql_hook_params": sql_hook_params,
        }
        op = BaseSqlToSlackOperator(task_id="test_get_hook", **op_kwargs)
        hook = op._get_hook()
        mock_get_hook.assert_called_once_with(hook_params=sql_hook_params)
        assert hook == expected_hook

    @mock.patch("airflow.providers.common.sql.operators.sql.BaseHook.get_connection")
    @mock.patch("airflow.models.connection.Connection.get_hook")
    def test_get_not_supported_hook(self, mock_get_hook, mock_get_conn):
        class SomeDummyHook:
            """Hook which not implemented ``get_pandas_df`` method"""

        mock_get_conn.return_value = Connection(conn_id="test_connection", conn_type="test_connection")
        mock_get_hook.return_value = SomeDummyHook()
        op = BaseSqlToSlackOperator(task_id="test_get_not_supported_hook", **self.default_op_kwargs)
        error_message = r"This hook is not supported. The hook class must have get_pandas_df method\."
        with pytest.raises(AirflowException, match=error_message):
            op._get_hook()

    @mock.patch("airflow.providers.slack.transfers.sql_to_slack.BaseSqlToSlackOperator._get_hook")
    @pytest.mark.parametrize("sql", ["SELECT 42", "SELECT 1 FROM DUMMY WHERE col = ?"])
    @pytest.mark.parametrize("parameters", [None, {"col": "spam-egg"}])
    def test_get_query_results(self, mock_op_get_hook, sql, parameters):
        test_df = pd.DataFrame({"a": "1", "b": "2"}, index=[0, 1])
        mock_get_pandas_df = mock.MagicMock(return_value=test_df)
        mock_hook = mock.MagicMock()
        mock_hook.get_pandas_df = mock_get_pandas_df
        mock_op_get_hook.return_value = mock_hook
        op_kwargs = {
            **self.default_op_kwargs,
            "sql": sql,
            "parameters": parameters,
        }
        op = BaseSqlToSlackOperator(task_id="test_get_query_results", **op_kwargs)
        df = op._get_query_results()
        mock_get_pandas_df.assert_called_once_with(sql, parameters=parameters)
        assert df is test_df

class TestSqlToSlackOperator:
    def setup_method(self):
        self.example_dag = DAG(TEST_DAG_ID, start_date=DEFAULT_DATE)

    @staticmethod
    def _construct_operator(**kwargs):
        operator = SqlToSlackOperator(task_id=TEST_TASK_ID, **kwargs)
        return operator

    @mock.patch("airflow.providers.slack.transfers.sql_to_slack.SlackWebhookHook")
    def test_rendering_and_message_execution(self, mock_slack_hook_class):
        mock_dbapi_hook = mock.Mock()

        test_df = pd.DataFrame({"a": "1", "b": "2"}, index=[0, 1])
        get_pandas_df_mock = mock_dbapi_hook.return_value.get_pandas_df
        get_pandas_df_mock.return_value = test_df

        operator_args = {
            "sql_conn_id": "snowflake_connection",
            "slack_conn_id": "slack_connection",
            "slack_message": "message: {{ ds }}, {{ results_df }}",
            "slack_channel": "#test",
            "sql": "sql {{ ds }}",
            "dag": self.example_dag,
        }
        sql_to_slack_operator = self._construct_operator(**operator_args)

        slack_webhook_hook = mock_slack_hook_class.return_value
        sql_to_slack_operator._get_hook = mock_dbapi_hook
        sql_to_slack_operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)

        # Test that the Slack hook is instantiated with the right parameters
        mock_slack_hook_class.assert_called_once_with(
            slack_webhook_conn_id="slack_connection",
            webhook_token=None,
        )

        # Test that the `SlackWebhookHook.send` method gets run once
        slack_webhook_hook.send.assert_called_once_with(
            text=f"message: 2017-01-01, {test_df}",
            channel="#test",
        )

    @mock.patch("airflow.providers.slack.transfers.sql_to_slack.SlackWebhookHook")
    def test_rendering_and_message_execution_with_slack_hook(self, mock_slack_hook_class):
        mock_dbapi_hook = mock.Mock()

        test_df = pd.DataFrame({"a": "1", "b": "2"}, index=[0, 1])
        get_pandas_df_mock = mock_dbapi_hook.return_value.get_pandas_df
        get_pandas_df_mock.return_value = test_df

        operator_args = {
            "sql_conn_id": "snowflake_connection",
            "slack_conn_id": "slack_connection",
            "slack_webhook_token": "test_token",
            "slack_message": "message: {{ ds }}, {{ results_df }}",
            "slack_channel": "#test",
            "sql": "sql {{ ds }}",
            "dag": self.example_dag,
        }
        sql_to_slack_operator = self._construct_operator(**operator_args)

        slack_webhook_hook = mock_slack_hook_class.return_value
        sql_to_slack_operator._get_hook = mock_dbapi_hook
        sql_to_slack_operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)

        # Test that the Slack hook is instantiated with the right parameters
        mock_slack_hook_class.assert_called_once_with(
            slack_webhook_conn_id="slack_connection",
            webhook_token="test_token",
        )

        # Test that the `SlackWebhookHook.send` method gets run once
        slack_webhook_hook.send.assert_called_once_with(
            text=f"message: 2017-01-01, {test_df}",
            channel="#test",
        )

    def test_non_existing_slack_parameters_provided_exception_thrown(self):
        operator_args = {
            "sql_conn_id": "snowflake_connection",
            "slack_message": "message: {{ ds }}, {{ xxxx }}",
            "sql": "sql {{ ds }}",
        }
        with pytest.raises(AirflowException):
            self._construct_operator(**operator_args)

    @mock.patch("airflow.providers.slack.transfers.sql_to_slack.SlackWebhookHook")
    def test_rendering_custom_df_name_message_execution(self, mock_slack_hook_class):
        mock_dbapi_hook = mock.Mock()

        test_df = pd.DataFrame({"a": "1", "b": "2"}, index=[0, 1])
        get_pandas_df_mock = mock_dbapi_hook.return_value.get_pandas_df
        get_pandas_df_mock.return_value = test_df

        operator_args = {
            "sql_conn_id": "snowflake_connection",
            "slack_conn_id": "slack_connection",
            "slack_message": "message: {{ ds }}, {{ testing }}",
            "slack_channel": "#test",
            "sql": "sql {{ ds }}",
            "results_df_name": "testing",
            "dag": self.example_dag,
        }
        sql_to_slack_operator = self._construct_operator(**operator_args)

        slack_webhook_hook = mock_slack_hook_class.return_value
        sql_to_slack_operator._get_hook = mock_dbapi_hook
        sql_to_slack_operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)

        # Test that the Slack hook is instantiated with the right parameters
        mock_slack_hook_class.assert_called_once_with(
            slack_webhook_conn_id="slack_connection",
            webhook_token=None,
        )

        # Test that the `SlackWebhookHook.send` method gets run once
        slack_webhook_hook.send.assert_called_once_with(
            text=f"message: 2017-01-01, {test_df}",
            channel="#test",
        )

    @mock.patch("airflow.providers.common.sql.operators.sql.BaseHook.get_connection")
    def test_hook_params_building(self, mock_get_conn):
        mock_get_conn.return_value = Connection(conn_id="snowflake_connection", conn_type="snowflake")
        hook_params = {
            "schema": "test_schema",
            "role": "test_role",
            "database": "test_database",
            "warehouse": "test_warehouse",
        }
        operator_args = {
            "sql_conn_id": "dummy_connection",
            "sql": "sql {{ ds }}",
            "results_df_name": "xxxx",
            "sql_hook_params": hook_params,
            "parameters": ["1", "2", "3"],
            "slack_message": "message: {{ ds }}, {{ xxxx }}",
            "slack_webhook_token": "test_token",
            "dag": self.example_dag,
        }
        sql_to_slack_operator = SqlToSlackOperator(task_id=TEST_TASK_ID, **operator_args)

        assert sql_to_slack_operator.sql_hook_params == hook_params

    @mock.patch("airflow.providers.common.sql.operators.sql.BaseHook.get_connection")
    def test_hook_params(self, mock_get_conn):
        mock_get_conn.return_value = Connection(conn_id="postgres_test", conn_type="postgres")
        op = SqlToSlackOperator(
            task_id="sql_hook_params",
            sql_conn_id="postgres_test",
            slack_webhook_token="slack_token",
            sql="SELECT 1",
            slack_message="message: {{ ds }}, {{ xxxx }}",
            sql_hook_params={
                "log_sql": False,
            },
        )
        hook = op._get_hook()
        assert hook.log_sql == op.sql_hook_params["log_sql"]

    @mock.patch("airflow.providers.common.sql.operators.sql.BaseHook.get_connection")
    def test_hook_params_snowflake(self, mock_get_conn):
        mock_get_conn.return_value = Connection(conn_id="snowflake_default", conn_type="snowflake")
        op = SqlToSlackOperator(
            task_id="snowflake_hook_params",
            sql_conn_id="snowflake_default",
            slack_conn_id="slack_default",
            results_df_name="xxxx",
            sql="SELECT 1",
            slack_message="message: {{ ds }}, {{ xxxx }}",
            sql_hook_params={
                "warehouse": "warehouse",
                "database": "database",
                "role": "role",
                "schema": "schema",
            },
        )
        hook = op._get_hook()

        assert hook.warehouse == "warehouse"
        assert hook.database == "database"
        assert hook.role == "role"
        assert hook.schema == "schema"

class TestSqlToSlackApiFileOperator:
    def setup_method(self):
        self.default_op_kwargs = {
            "sql": "SELECT 1",
            "sql_conn_id": "test-sql-conn-id",
            "slack_conn_id": "test-slack-conn-id",
            "sql_hook_params": None,
            "parameters": None,
        }

    @mock.patch("airflow.providers.slack.transfers.sql_to_slack.BaseSqlToSlackOperator._get_query_results")
    @mock.patch("airflow.providers.slack.transfers.sql_to_slack.SlackHook")
    @pytest.mark.parametrize(
        "filename,df_method",
        [
            ("awesome.json", "to_json"),
            ("awesome.json.zip", "to_json"),
            ("awesome.csv", "to_csv"),
            ("awesome.csv.xz", "to_csv"),
            ("awesome.html", "to_html"),
        ],
    )
    @pytest.mark.parametrize("df_kwargs", [None, {}, {"foo": "bar"}])
    @pytest.mark.parametrize("channels", ["#random", "#random,#general", None])
    @pytest.mark.parametrize("initial_comment", [None, "Test Comment"])
    @pytest.mark.parametrize("title", [None, "Test File Title"])
    def test_send_file(
        self,
        mock_slack_hook_cls,
        mock_get_query_results,
        filename,
        df_method,
        df_kwargs,
        channels,
        initial_comment,
        title,
    ):
        # Mock Hook
        mock_send_file = mock.MagicMock()
        mock_slack_hook_cls.return_value.send_file = mock_send_file

        # Mock returns pandas.DataFrame and expected method
        mock_df = mock.MagicMock()
        mock_df_output_method = mock.MagicMock()
        setattr(mock_df, df_method, mock_df_output_method)
        mock_get_query_results.return_value = mock_df

        op_kwargs = {
            **self.default_op_kwargs,
            "slack_conn_id": "expected-test-slack-conn-id",
            "slack_filename": filename,
            "slack_channels": channels,
            "slack_initial_comment": initial_comment,
            "slack_title": title,
            "df_kwargs": df_kwargs,
        }
        op = SqlToSlackApiFileOperator(task_id="test_send_file", **op_kwargs)
        op.execute(mock.MagicMock())

        mock_slack_hook_cls.assert_called_once_with(slack_conn_id="expected-test-slack-conn-id")
        mock_get_query_results.assert_called_once_with()
        mock_df_output_method.assert_called_once_with(mock.ANY, **(df_kwargs or {}))
        mock_send_file.assert_called_once_with(
            channels=channels,
            filename=filename,
            initial_comment=initial_comment,
            title=title,
            file=mock.ANY,
        )

    @pytest.mark.parametrize(
        "filename",
        [
            "foo.parquet",
            "bat.parquet.snappy",
            "spam.xml",
            "egg.xlsx",
        ],
    )
    def test_unsupported_format(self, filename):
        op = SqlToSlackApiFileOperator(
            task_id="test_send_file", slack_filename=filename, **self.default_op_kwargs
        )
        with pytest.raises(ValueError):
            op.execute(mock.MagicMock())


text:
<?php

namespace Ems\XType;

require_once __DIR__.'/NumberTypeTest.php';

class SequenceTypeTest extends NumberTypeTest
{
    protected function newType()
    {
        return new SequenceType();
    }
}


text:
using System;
using System.Runtime.CompilerServices;
using ScriptRuntime;

namespace ScriptRuntime
{
    ///
    /// 粒子系统,控制粒子系统的运行。
    ///
    public class ParticleSystem : Base
    {
         private ParticleSystem(DummyClass__ dummyObj )
        {

        }

        ///
        /// 粒子系统构造函数
        ///
        public ParticleSystem()
        {
            ICall_ParticleSystem_Bind(this);
        }

        ~ParticleSystem()
        {
            ICall_ParticleSystem_Release(this);
        }

        ///
        ///  粒子系统名字的设置和获取.
        ///
        /// <param value>粒子系统的名字.</param>
        /// <returns>粒子系统的名字.</returns>
        public String Name
        {
            set
            {
                ICall_ParticleSystem_SetName(this, value);
            }
            get
            {
                return ICall_ParticleSystem_GetName(this);
            }
        }
        ///
        ///  播放粒子.
        ///
        /**@brief示例
        *@code{.cpp}
        Actor actor = ActorManager.FindActiveActor("test");
        if (null != actor)
        {
            ParticleSystem partial = actor.ParticleRender.GetParticleSystem();
            if (null != partial)
            {
                partial.Play();
            }
        }
        @endcode
        */
        public void Play( )
        {
            ICall_ParticleSystem_Play( this );
        }
        ///
        ///  暂停粒子.
        ///
        /**@brief示例
        *@code{.cpp}
        Actor actor = ActorManager.FindActiveActor("test");
        if (null != actor)
        {
            ParticleSystem partial = actor.ParticleRender.GetParticleSystem();
            if (null != partial)
            {
                partial.Pause();
            }
        }
        @endcode
        */
        public void Pause()
        {
            ICall_ParticleSystem_Pause(this);
        }
        ///
        ///  停止粒子.
        ///
        /**@brief示例
        *@code{.cpp}
        Actor actor = ActorManager.FindActiveActor("test");
        if (null != actor)
        {
            ParticleSystem partial = actor.ParticleRender.GetParticleSystem();
            if (null != partial)
            {
                partial.Stop();
            }
        }
        @endcode
        */
        public void Stop()
        {
            ICall_ParticleSystem_Stop(this);
        }
        ///
        ///  当前粒子系统是否在播放.
        ///
        /// <returns>粒子系统播放与否.</returns>
        /**@brief示例
        *@code{.cpp}
        Actor actor = ActorManager.FindActiveActor("test");
        if (null != actor)
        {
            ParticleSystem partial = actor.ParticleRender.GetParticleSystem();
            if (null != partial)
            {
                bool bIsPlaying = partial.IsPlaying;
            }
        }
        @endcode
        */
        public bool IsPlaying
        {
            get
            {
                return ICall_ParticleSystem_IsPlaying(this);
            }
        }
        ///
        ///  当前粒子系统是否在暂停.
        ///
        /// <returns>粒子系统暂停与否.</returns>
        /**@brief示例
        *@code{.cpp}
        Actor actor = ActorManager.FindActiveActor("test");
        if (null != actor)
        {
            ParticleSystem partial = actor.ParticleRender.GetParticleSystem();
            if (null != partial)
            {
                bool bIsPaused = partial.IsPaused;
            }
        }
        @endcode
        */
        public bool IsPaused
        {
            get
            {
                return ICall_ParticleSystem_IsPaused(this);
            }
        }
        ///
        ///  当前粒子系统是否在停止.
        ///
        /// <returns>粒子系统停止与否.</returns>
        /**@brief示例
        *@code{.cpp}
        Actor actor = ActorManager.FindActiveActor("test");
        if (null != actor)
        {
            ParticleSystem partial = actor.ParticleRender.GetParticleSystem();
            if (null != partial)
            {
                bool bIsStop = partial.IsStop;
            }
        }
        @endcode
        */
        public bool IsStop
        {
            get
            {
                return ICall_ParticleSystem_IsStop(this);
            }
        }
        ///
        ///  粒子系统的播放速率.
        ///
        public float PlayRateScale
        {
            set
            {
                ICall_ParticleSystem_SetPlayRateScale(this, value);
            }
            get
            {
                return ICall_ParticleSystem_GetPlayRateScale(this);
            }
        }

        ///
        /// 获取与设置粒子系统中的粒子数量
        ///
        public int ParticleQuato
        {
            set
            {
                ICall_ParticleSystem_SetQuato(this, value);
            }
            get
            {
                return (int)ICall_ParticleSystem_GetQuato(this);
            }
        }

        // - internal call declare
        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_Bind(ParticleSystem self);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_Release(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_SetName(ParticleSystem ps, String name);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static string ICall_ParticleSystem_GetName(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_Play(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_Pause(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_Stop(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static bool ICall_ParticleSystem_IsPlaying(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static bool ICall_ParticleSystem_IsPaused(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static bool ICall_ParticleSystem_IsStop(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_SetPlayRateScale(ParticleSystem ps, float rateScale);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static float ICall_ParticleSystem_GetPlayRateScale(ParticleSystem ps);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static void ICall_ParticleSystem_SetQuato(ParticleSystem ps, int quato);

        [MethodImplAttribute(MethodImplOptions.InternalCall)]
        extern private static float ICall_ParticleSystem_GetQuato(ParticleSystem ps);
    }
}


text:
package io.github.medjed.jsonpathcompiler.expressions.path;

import org.junit.Test;
import java.util.ArrayList;
import static junit.framework.TestCase.assertEquals;

public class PropertyPathTokenTest {
    @Test
    public void testGetPathFragment() {
        {
            String path = PropertyPathToken.getPathFragment("foo'bar");
            assertEquals("['foo\\\'bar']", path);
        }
        {
            String path = PropertyPathToken.getPathFragment("foo'bar", true);
            assertEquals("['foo\\\'bar']", path);
        }
        {
            String path = PropertyPathToken.getPathFragment("foo'bar", false);
            assertEquals("[\"foo'bar\"]", path);
        }
    }
    @Test
    public void testGetPathFragmentList() {
        {
            ArrayList<String> properties = new ArrayList<>();
            properties.add("foo'bar");
            properties.add("foo'bar");
            String path = PropertyPathToken.getPathFragment(properties);
            assertEquals("['foo\\\'bar','foo\\\'bar']", path);
        }
    }
}


text:
/**
 * @file hmm.hpp
 * @author Ryan Curtin
 * @author Tran Quoc Long
 * @author Michael Fox
 *
 * Definition of HMM class.
 *
 * This file is part of mlpack 2.0.1.
 *
 * mlpack is free software; you may redstribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#ifndef __MLPACK_METHODS_HMM_HMM_HPP
#define __MLPACK_METHODS_HMM_HMM_HPP

#include <mlpack/core.hpp>

namespace mlpack {
namespace hmm /** Hidden Markov Models. */ {

/**
 * A class that represents a Hidden Markov Model with an arbitrary type of
 * emission distribution.  This HMM class supports training (supervised and
 * unsupervised), prediction of state sequences via the Viterbi algorithm,
 * estimation of state probabilities, generation of random sequences, and
 * calculation of the log-likelihood of a given sequence.
 *
 * The template parameter, Distribution, specifies the distribution which the
 * emissions follow.  The class should implement the following functions:
 *
 * @code
 * class Distribution
 * {
 *  public:
 *   // The type of observation used by this distribution.
 *   typedef something DataType;
 *
 *   // Return the probability of the given observation.
 *   double Probability(const DataType& observation) const;
 *
 *   // Estimate the distribution based on the given observations.
 *   void Train(const std::vector<DataType>& observations);
 *
 *   // Estimate the distribution based on the given observations, given also
 *   // the probability of each observation coming from this distribution.
 *   void Train(const std::vector<DataType>& observations,
 *              const std::vector<double>& probabilities);
 * };
 * @endcode
 *
 * See the mlpack::distribution::DiscreteDistribution class for an example.  One
 * would use the DiscreteDistribution class when the observations are
 * non-negative integers.  Other distributions could be Gaussians, a mixture of
 * Gaussians (GMM), or any other probability distribution implementing the
 * four Distribution functions.
 *
 * Usage of the HMM class generally involves either training an HMM or loading
 * an already-known HMM and taking probability measurements of sequences.
 * Example code for supervised training of a Gaussian HMM (that is, where the
 * emission output distribution is a single Gaussian for each hidden state) is
 * given below.
 *
 * @code
 * extern arma::mat observations; // Each column is an observation.
 * extern arma::Row<size_t> states; // Hidden states for each observation.
 * // Create an untrained HMM with 5 hidden states and default (N(0, 1))
 * // Gaussian distributions with the dimensionality of the dataset.
 * HMM<GaussianDistribution> hmm(5, GaussianDistribution(observations.n_rows));
 *
 * // Train the HMM (the labels could be omitted to perform unsupervised
 * // training).
 * hmm.Train(observations, states);
 * @endcode
 *
 * Once initialized, the HMM can evaluate the probability of a certain sequence
 * (with LogLikelihood()), predict the most likely sequence of hidden states
 * (with Predict()), generate a sequence (with Generate()), or estimate the
 * probabilities of each state for a sequence of observations (with Train()).
 *
 * @tparam Distribution Type of emission distribution for this HMM.
 */
template<typename Distribution = distribution::DiscreteDistribution>
class HMM
{
 public:
  /**
   * Create the Hidden Markov Model with the given number of hidden states and
   * the given default distribution for emissions.  The dimensionality of the
   * observations is taken from the emissions variable, so it is important that
   * the given default emission distribution is set with the correct
   * dimensionality.  Alternately, set the dimensionality with Dimensionality().
   * Optionally, the tolerance for convergence of the Baum-Welch algorithm can
   * be set.
   *
   * By default, the transition matrix and initial probability vector are set to
   * contain equal probability for each state.
   *
   * @param states Number of states.
   * @param emissions Default distribution for emissions.
   * @param tolerance Tolerance for convergence of training algorithm
   *      (Baum-Welch).
   */
  HMM(const size_t states = 0,
      const Distribution emissions = Distribution(),
      const double tolerance = 1e-5);

  /**
   * Create the Hidden Markov Model with the given initial probability vector,
   * the given transition matrix, and the given emission distributions.  The
   * dimensionality of the observations of the HMM are taken from the given
   * emission distributions.  Alternately, the dimensionality can be set with
   * Dimensionality().
   *
   * The initial state probability vector should have length equal to the number
   * of states, and each entry represents the probability of being in the given
   * state at time T = 0 (the beginning of a sequence).
   *
   * The transition matrix should be such that T(i, j) is the probability of
   * transition to state i from state j.  The columns of the matrix should sum
   * to 1.
   *
   * The emission matrix should be such that E(i, j) is the probability of
   * emission i while in state j.  The columns of the matrix should sum to 1.
   *
   * Optionally, the tolerance for convergence of the Baum-Welch algorithm can
   * be set.
   *
   * @param initial Initial state probabilities.
   * @param transition Transition matrix.
   * @param emission Emission distributions.
   * @param tolerance Tolerance for convergence of training algorithm
   *      (Baum-Welch).
   */
  HMM(const arma::vec& initial,
      const arma::mat& transition,
      const std::vector<Distribution>& emission,
      const double tolerance = 1e-5);

  /**
   * Train the model using the Baum-Welch algorithm, with only the given
   * unlabeled observations.  Instead of giving a guess transition and emission
   * matrix here, do that in the constructor.  Each matrix in the vector of data
   * sequences holds an individual data sequence; each point in each individual
   * data sequence should be a column in the matrix.  The number of rows in each
   * matrix should be equal to the dimensionality of the HMM (which is set in
   * the constructor).
   *
   * It is preferable to use the other overload of Train(), with labeled data.
   * That will produce much better results.  However, if labeled data is
   * unavailable, this will work.  In addition, it is possible to use Train()
   * with labeled data first, and then continue to train the model using this
   * overload of Train() with unlabeled data.
   *
   * The tolerance of the Baum-Welch algorithm can be set either in the
   * constructor or with the Tolerance() method.  When the change in
   * log-likelihood of the model between iterations is less than the tolerance,
   * the Baum-Welch algorithm terminates.
   *
   * @note
   * Train() can be called multiple times with different sequences; each time it
   * is called, it uses the current parameters of the HMM as a starting point
   * for training.
   * @endnote
   *
   * @param dataSeq Vector of observation sequences.
   */
  void Train(const std::vector<arma::mat>& dataSeq);

  /**
   * Train the model using the given labeled observations; the transition and
   * emission matrices are directly estimated.  Each matrix in the vector of
   * data sequences corresponds to a vector in the vector of state sequences.
   * Each point in each individual data sequence should be a column in the
   * matrix, and its state should be the corresponding element in the state
   * sequence vector.  For instance, dataSeq[0].col(3) corresponds to the fourth
   * observation in the first data sequence, and its state is stateSeq[0][3].
   * The number of rows in each matrix should be equal to the dimensionality of
   * the HMM (which is set in the constructor).
   *
   * @note
   * Train() can be called multiple times with different sequences; each time it
   * is called, it uses the current parameters of the HMM as a starting point
   * for training.
   * @endnote
   *
   * @param dataSeq Vector of observation sequences.
   * @param stateSeq Vector of state sequences, corresponding to each
   *     observation.
   */
  void Train(const std::vector<arma::mat>& dataSeq,
             const std::vector<arma::Row<size_t> >& stateSeq);

  /**
   * Estimate the probabilities of each hidden state at each time step for each
   * given data observation, using the Forward-Backward algorithm.  Each matrix
   * which is returned has columns equal to the number of data observations, and
   * rows equal to the number of hidden states in the model.  The log-likelihood
   * of the most probable sequence is returned.
   *
   * @param dataSeq Sequence of observations.
   * @param stateProb Matrix in which the probabilities of each state at each
   *    time interval will be stored.
   * @param forwardProb Matrix in which the forward probabilities of each state
   *    at each time interval will be stored.
   * @param backwardProb Matrix in which the backward probabilities of each
   *    state at each time interval will be stored.
   * @param scales Vector in which the scaling factors at each time interval
   *    will be stored.
   * @return Log-likelihood of most likely state sequence.
   */
  double Estimate(const arma::mat& dataSeq,
                  arma::mat& stateProb,
                  arma::mat& forwardProb,
                  arma::mat& backwardProb,
                  arma::vec& scales) const;

  /**
   * Estimate the probabilities of each hidden state at each time step of each
   * given data observation, using the Forward-Backward algorithm.  The returned
   * matrix of state probabilities has columns equal to the number of data
   * observations, and rows equal to the number of hidden states in the model.
   * The log-likelihood of the most probable sequence is returned.
   *
   * @param dataSeq Sequence of observations.
   * @param stateProb Probabilities of each state at each time interval.
   * @return Log-likelihood of most likely state sequence.
   */
  double Estimate(const arma::mat& dataSeq,
                  arma::mat& stateProb) const;

  /**
   * Generate a random data sequence of the given length.  The data sequence is
   * stored in the dataSequence parameter, and the state sequence is stored in
   * the stateSequence parameter.  Each column of dataSequence represents a
   * random observation.
   *
   * @param length Length of random sequence to generate.
   * @param dataSequence Vector to store data in.
   * @param stateSequence Vector to store states in.
   * @param startState Hidden state to start sequence in (default 0).
   */
  void Generate(const size_t length,
                arma::mat& dataSequence,
                arma::Row<size_t>& stateSequence,
                const size_t startState = 0) const;

  /**
   * Compute the most probable hidden state sequence for the given data
   * sequence, using the Viterbi algorithm, returning the log-likelihood of the
   * most likely state sequence.
   *
   * @param dataSeq Sequence of observations.
   * @param stateSeq Vector in which the most probable state sequence will be
   *    stored.
   * @return Log-likelihood of most probable state sequence.
   */
  double Predict(const arma::mat& dataSeq,
                 arma::Row<size_t>& stateSeq) const;

  /**
   * Compute the log-likelihood of the given data sequence.
   *
   * @param dataSeq Data sequence to evaluate the likelihood of.
   * @return Log-likelihood of the given sequence.
   */
  double LogLikelihood(const arma::mat& dataSeq) const;

  /**
   * HMM filtering. Computes the k-step-ahead expected emission at each time
   * conditioned only on prior observations. That is
   * E{ Y[t+k] | Y[0], ..., Y[t] }.
   * The returned matrix has columns equal to the number of observations. Note
   * that the expectation may not be meaningful for discrete emissions.
   *
   * @param dataSeq Sequence of observations.
   * @param filterSeq Vector in which the expected emission sequence will be
   *    stored.
   * @param ahead Number of steps ahead (k) for expectations.
   */
  void Filter(const arma::mat& dataSeq,
              arma::mat& filterSeq,
              size_t ahead = 0) const;

  /**
   * HMM smoothing. Computes expected emission at each time conditioned on all
   * observations. That is
   * E{ Y[t] | Y[0], ..., Y[T] }.
   * The returned matrix has columns equal to the number of observations. Note
   * that the expectation may not be meaningful for discrete emissions.
   *
   * @param dataSeq Sequence of observations.
   * @param smoothSeq Vector in which the expected emission sequence will be
   *    stored.
   */
  void Smooth(const arma::mat& dataSeq,
              arma::mat& smoothSeq) const;

  //! Return the vector of initial state probabilities.
  const arma::vec& Initial() const { return initial; }
  //! Modify the vector of initial state probabilities.
  arma::vec& Initial() { return initial; }

  //! Return the transition matrix.
  const arma::mat& Transition() const { return transition; }
  //! Return a modifiable transition matrix reference.
  arma::mat& Transition() { return transition; }

  //! Return the emission distributions.
  const std::vector<Distribution>& Emission() const { return emission; }
  //! Return a modifiable emission probability matrix reference.
  std::vector<Distribution>& Emission() { return emission; }

  //! Get the dimensionality of observations.
  size_t Dimensionality() const { return dimensionality; }
  //! Set the dimensionality of observations.
  size_t& Dimensionality() { return dimensionality; }

  //! Get the tolerance of the Baum-Welch algorithm.
  double Tolerance() const { return tolerance; }
  //! Modify the tolerance of the Baum-Welch algorithm.
  double& Tolerance() { return tolerance; }

  /**
   * Serialize the object.
   */
  template<typename Archive>
  void Serialize(Archive& ar, const unsigned int version);

 protected:
  // Helper functions.
  /**
   * The Forward algorithm (part of the Forward-Backward algorithm).  Computes
   * forward probabilities for each state for each observation in the given data
   * sequence.  The returned matrix has rows equal to the number of hidden
   * states and columns equal to the number of observations.
   *
   * @param dataSeq Data sequence to compute probabilities for.
   * @param scales Vector in which scaling factors will be saved.
   * @param forwardProb Matrix in which forward probabilities will be saved.
   */
  void Forward(const arma::mat& dataSeq,
               arma::vec& scales,
               arma::mat& forwardProb) const;

  /**
   * The Backward algorithm (part of the Forward-Backward algorithm).  Computes
   * backward probabilities for each state for each observation in the given
   * data sequence, using the scaling factors found (presumably) by Forward().
   * The returned matrix has rows equal to the number of hidden states and
   * columns equal to the number of observations.
   *
   * @param dataSeq Data sequence to compute probabilities for.
   * @param scales Vector of scaling factors.
   * @param backwardProb Matrix in which backward probabilities will be saved.
   */
  void Backward(const arma::mat& dataSeq,
                const arma::vec& scales,
                arma::mat& backwardProb) const;

  //! Set of emission probability distributions; one for each state.
  std::vector<Distribution> emission;

  //! Transition probability matrix.
  arma::mat transition;

 private:
  //! Initial state probability vector.
  arma::vec initial;

  //! Dimensionality of observations.
  size_t dimensionality;

  //! Tolerance of Baum-Welch algorithm.
  double tolerance;
};

} // namespace hmm
} // namespace mlpack

// Include implementation.
#include "hmm_impl.hpp"

#endif


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

namespace _2020052001CS_ProcessLauncher
{
    public partial class AppLaucher : Form
    {
        public AppLaucher()
        {
            InitializeComponent();
        }

        private void btnLauncher_Click(object sender, EventArgs e)
        {
            string strQuery = txtQuery.Text.ToString();
            ////running dos internal command
            //using (Process process = new Process())
            //{
            //    process.StartInfo.FileName = "ipconfig.exe";
            //    process.StartInfo.UseShellExecute = false;
            //    process.StartInfo.RedirectStandardOutput = true;
            //    process.Start();

            //    // Synchronously read the standard output of the spawned process.
            //    StreamReader reader = process.StandardOutput;
            //    string output = reader.ReadToEnd();

            //    // Write the redirected output to this application's window.
            //    txtOutput.Text = output;

            //    process.WaitForExit();
            //}

            Process[] processes = Process.GetProcessesByName("Chrome");

            // Loop over processes.
            foreach (Process process in processes)
            {
                txtOutput.Text += process.Id.ToString()+"       " +process.ProcessName+ Environment.NewLine;
            }

        }
    }
}


text:
package cn.zhenghongen.android.common.util;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by ZhengHongEn on 2015/11/2.
 * http://www.cnblogs.com/Amandaliu/archive/2011/11/06/2238177.html
 * http://blog.sina.com.cn/s/blog_77c632410101cy1v.html
 */
public class MacUtils {

    public static String getLocalMacAddressFromWifiInfo(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        String macAdress = info.getMacAddress(); //获取mac地址
        return macAdress;
    }

    public static String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();

                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }

        } catch (SocketException ex) {
            Log.e("MacUtils", "WifiPreference IpAddress" + ex.toString(), ex);
        }

        return null;
    }

    public static String getLocalMacAddressFromIp(Context context) {
        String mac_s = "";

        try {
            byte[] mac;
            NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()));
            mac = ne.getHardwareAddress();
            mac_s = byte2hex(mac);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mac_s;
    }

    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer(b.length);
        String stmp = "";

        int len = b.length;
        for (int n = 0; n < len; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1) {
                hs = hs.append("0").append(stmp);
            } else {
                hs = hs.append(stmp);
            }
        }
        return String.valueOf(hs);
    }

    /*
  *****************************************************************
  *                       子函数:获得本地MAC地址
  *****************************************************************
 */
    public static String getMacAddress() {
        String result = "";
        String Mac = "";
        result = callCmd("busybox ifconfig", "HWaddr");

        //如果返回的result == null,则说明网络不可取
        if (result == null) {
            return "网络出错,请检查网络";
        }

        //对该行数据进行解析
        //例如:eth0      Link encap:Ethernet  HWaddr 00:16:E8:3E:DF:67
        if (result.length() > 0 && result.contains("HWaddr") == true) {
            Mac = result.substring(result.indexOf("HWaddr") + 6, result.length() - 1);
            Log.i("test", "Mac:" + Mac + " Mac.length: " + Mac.length());

            if (Mac.length() > 1) {
                Mac = Mac.replaceAll(" ", "");
                result = "";
                String[] tmp = Mac.split(":");
                for (int i = 0; i < tmp.length; ++i) {
                    result += tmp[i];
                }
            }
            Log.i("test", result + " result.length: " + result.length());
        }
        return result;
    }

    public static String callCmd(String cmd, String filter) {
        String result = "";
        String line = "";
        try {
            Process proc = Runtime.getRuntime().exec(cmd);
            InputStreamReader is = new InputStreamReader(proc.getInputStream());
            BufferedReader br = new BufferedReader(is);

            //执行命令cmd,只取结果中含有filter的这一行
            while ((line = br.readLine()) != null && line.contains(filter) == false) {
                //result += line;
                Log.i("test", "line: " + line);
            }

            result = line;
            Log.i("test", "result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}


text:
FactoryBot.define do
  factory :consultation_response_form do
    transient do
      file { File.open(Rails.root.join("test/fixtures/two-pages.pdf")) }
    end
    association :consultation_participation
    title { "consultation-response-form-title" }
    consultation_response_form_data { build(:consultation_response_form_data, file:) }
  end
end


text:
require 'singleton'
require 'yaml'

require 'libis/tools/logger'
require 'libis/tools/extend/hash'
require 'libis/tools/extend/string'

module Libis
  module Format

    class TypeDatabaseImpl
      include Singleton
      include ::Libis::Tools::Logger

      def typeinfo(t)
        @types[t.to_sym] || {}
      end

      def group_types(group)
        @types.select do |_, v|
          v[:GROUP] == group.to_sym
        end.keys
      end

      def puid_infos(puid)
        @types.select do |_, v|
          v[:PUID].include? puid rescue false
        end.values
      end

      def puid_types(puid)
        @types.select do |_, v|
          v[:PUID].include? puid rescue false
        end.keys
      end

      def mime_infos(mime)
        @types.select do |_, v|
          v[:MIME].include? mime rescue false
        end.values
      end

      def mime_types(mime)
        @types.select do |_, v|
          v[:MIME].include? mime rescue false
        end.keys
      end

      def ext_infos(ext)
        ext = ext.gsub /^\./, ''
        @types.select do |_, v|
          v[:EXTENSIONS].include?(ext) rescue false
        end.values
      end

      def ext_types(ext)
        ext = ext.gsub /^\./, ''
        @types.select do |_, v|
          v[:EXTENSIONS].include?(ext) rescue false
        end.keys
      end

      def puid_typeinfo(puid)
        @types.each do |_, v|
          return v if v[:PUID] and v[:PUID].include?(puid)
        end
        nil
      end

      def known_mime?(mime)
        @types.each do |_, v|
          return true if v[:MIME].include? mime
        end
        false
      end

      def load_types(file_or_hash = {}, append = true)
        hash = file_or_hash.is_a?(Hash) ? file_or_hash : YAML::load_file(file_or_hash)
        # noinspection RubyResolve
        hash.each do |group, type_info|
          type_info.each do |type_name, info|
            type_key = type_name.to_sym
            info.symbolize_keys!
            info[:TYPE] = type_key
            info[:GROUP] = group.to_sym
            info[:MIME] = info[:MIME].strip.split(/[\s,]+/).map(&:strip) rescue []
            info[:EXTENSIONS] = info[:EXTENSIONS].strip.split(/[\s,]+/).map { |v| v.strip } rescue []
            info[:PUID] = info[:PUID].strip.split(/[\s,]+/).map { |v| v.strip } if info[:PUID]
            if @types.has_key?(type_key)
              warn 'Type %s already defined; merging with info from %s.', type_name.to_s, file_or_hash
              info.merge!(@types[type_key]) do |_,v_new,v_old|
                case v_old
                when Array
                  append ? v_old + v_new : v_new + v_old
                when Hash
                  append ? v_new.merge(v_old) : v_old.merge(v_new)
                else
                  append ? v_old : v_new
                end
              end
            end
            @types[type_key] = info
          end
        end
      end

      protected

      def initialize
        @types = Hash.new
        type_database = Libis::Format::Config[:type_database]
        load_types(type_database)
      end

    end

  end
end


text:
<?xml version="1.0"?>
<psalm
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="https://getpsalm.org/schema/config"
    xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
    totallyTyped="true"
    rememberPropertyAssignmentsAfterCall="false"
>
    <projectFiles>
        <directory name="examples"/>
        <directory name="src"/>
        <directory name="tests/static-analysis"/>
        <directory name="tests/ProxyManagerBench"/>
        <directory name="tests/ProxyManagerTest"/>
        <ignoreFiles>
            <!-- remote objects contain references to Laminas\Server, which is not installed -->
            <directory name="tests/ProxyManagerTest/Factory/RemoteObject"/>
            <file name="tests/ProxyManagerTest/Functional/RemoteObjectFunctionalTest.php"/>
            <directory name="vendor"/>
            <!-- uses dependencies that are not available while testing: -->
            <file name="examples/remote-proxy.php"/>
        </ignoreFiles>
    </projectFiles>

    <issueHandlers>
        <UndefinedClass>
            <errorLevel type="suppress">
                <!-- laminas/laminas-server is not a direct package nor build dependency, and it should stay that way -->
                <referencedClass name="Laminas\Http\Client\Adapter\Exception\RuntimeException"/>
                <referencedClass name="Laminas\Server\Client"/>
                <referencedClass name="Laminas\XmlRpc\Server"/>
                <referencedClass name="Laminas\XmlRpc\Client"/>
            </errorLevel>
        </UndefinedClass>

        <InternalMethod errorLevel="suppress"/>

        <PropertyNotSetInConstructor errorLevel="suppress"/>
        <UnresolvableInclude errorLevel="suppress"/>

        <UnusedClosureParam>
            <errorLevel type="suppress">
                <!-- examples/tests use a lot of the initializers, and skip some parameters (uninteresting) by design -->
                <directory name="examples"/>
                <directory name="tests"/>
            </errorLevel>
        </UnusedClosureParam>

        <DeprecatedMethod>
            <errorLevel type="suppress">
                <directory name="tests" />
            </errorLevel>
        </DeprecatedMethod>

        <ForbiddenCode>
            <errorLevel type="suppress">
                <directory name="examples"/>
            </errorLevel>
        </ForbiddenCode>
    </issueHandlers>
</psalm>


text:
/**
 *
 */
package org.openforis.idm.model;

import java.util.BitSet;

/**
 * @author M. Togna
 *
 */
public class State {

	private static final int N_BITS = 8;
	private static final double MAX_VALUE = Math.pow( 2, N_BITS );

	private transient BitSet bitSet;

	public State() {
		bitSet = new BitSet(N_BITS);
	}

	public static State parseState(int value) {
		State state = new State();
		state.set(value);
		return state;
	}

	public void set(int position, boolean state) {
		ensurePositionInRange(position);
		setInternal(position, state);
	}

	public boolean get(int position) {
		ensurePositionInRange(position);
		return getInternal(position);
	}

	public boolean isEmpty() {
		for (int i = 0; i < N_BITS; i++) {
			if (getInternal(i)) {
				return false;
			}
		}
		return true;
	}

	public int intValue() {
		int value = 0;
		for (int i = 0; i < N_BITS; i++) {
			if (getInternal(i)) {
				value += (1 << i); //value += 2 powered by i
			}
		}
		return value;
	}

	public void set(int value) {
		if ( value > MAX_VALUE ) {
			throw new IllegalArgumentException("Value cannot be grater than " + MAX_VALUE + ", but it was " + value);
		}
		int currentValue = value;
		for (int i = 0; i < N_BITS; i++) {
			setInternal(i, currentValue % 2 > 0);
			currentValue >>= 1;
		}
	}

	private void ensurePositionInRange(int position) {
		if( position < 0 || position >= N_BITS ) {
			throw new IllegalArgumentException("Posion must be greather than 0 and less that  " + (N_BITS-1) );
		}
	}

	private boolean getInternal(int position) {
		return bitSet.get(position);
	}

	private void setInternal(int position, boolean state) {
		bitSet.set(position, state);
	}

	@Override
	public String toString() {
		return Integer.toString(intValue(), 2);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((bitSet == null) ? 0 : bitSet.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		State other = (State) obj;
		if (bitSet == null) {
			if (other.bitSet != null)
				return false;
		} else if (!bitSet.equals(other.bitSet))
			return false;
		return true;
	}

}


text:
<?php

namespace App\Model\Admin;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class GroupUser extends Model
{
	use SoftDeletes;

    protected $table 		= 'group_user';
    protected $dates 		= ['deleted_at'];
	protected $softDelete 	= true;
	protected $fillable 	= ['group_name', 'sort_order', 'status'] ;

    public function users()
    {
        return $this->hasMany(User::class, 'group_id');
    }
}


text:
'use strict';

/**
 * Module dependencies.
 */

var index = require('./controllers/index');
var user  = require('./controllers/user');
var movie = require('./controllers/movie');
var admin = require('./controllers/admin');

module.exports = function routes(app) {
	app.get('/', index);

	// user
	app.get('/login', user.show_login);
	app.get('/signup', user.show_signup);
	app.get('/logout', user.logout);
	app.get('/profile', user.show_profile);
	app.get('/ranking', user.show_ranking);
	app.get('/ticket', user.show_ticket);
	app.get('/profile/edit', user.show_profile_edit);
	app.get('/movie', movie.show_movie);
	app.post('/movie/book', movie.book);

	app.post('/user/signup', user.signup);
	app.post('/user/login', user.login);
	app.post('/user/profile', user.profile);
	app.post('/profile/edit', user.profile_edit);
	app.post('/user/advanced_search_movie', user.advanced_search_movie);

	// admin
	app.get('/admin', admin.show);
	app.get('/admin/movie', admin.show_movie);
	app.post('/admin/movie/add_movie', admin.add_movie);
	app.get('/admin/movie/delete_movie', admin.delete_movie);
	app.post('/admin/movie/update_movie', admin.update_movie);
	app.post('/admin/movie/add_show', admin.add_show);

	app.get('/admin/operator', admin.show_operator);
	app.post('/admin/operator/add_operator', admin.add_operator);
	app.get('/admin/operator/delete_operator', admin.delete_operator);

	app.get('/admin/theatre', admin.show_theatre);
	app.post('/admin/theatre/add_theatre', admin.add_theatre);
	app.get('/admin/theatre/delete_theatre', admin.delete_theatre);

	app.get('/admin/director', admin.show_director);
	app.post('/admin/director/add_director', admin.add_director);
	app.get('/admin/director/delete_director', admin.delete_director);

	app.get('/admin/ticket', admin.show_ticket);
	app.get('/admin/movie/delete_ticket', admin.delete_ticket);
	app.post('/admin/director/add_director', admin.add_director);
	app.get('/admin/director/delete_director', admin.delete_director);
	app.post('/admin/ticket/update_ticket', admin.update_ticket);

	app.get('/admin/actor', admin.show_actor);

	app.post('/movie/homepage_movie_search',movie.homepage_movie_search);
	app.post('/admin/add_director', admin.add_director);
	app.post('/admin/delete_director', admin.delete_director);

	app.post('/ajax/check_username', user.check_username);
	app.post('/ajax/store_selected_movie', admin.store_selected_movie);
	app.post('/ajax/get_selected_movie', admin.get_selected_movie);
	app.post('/ajax/get_shows_option', admin.get_shows_option);
	app.post('/ajax/get_selected_seat', admin.get_selected_seat);
	app.post('/ajax/store_selected_ticket', admin.store_selected_ticket);
	app.post('/ajax/get_selected_ticket', admin.get_selected_ticket);

};


text:
<!DOCTYPE html>

<html>

  <head>

    {{common "head"}}

  </head>

  <body class="page--default">

    {% body %}
    <!-- <script src="public/js/vendor.bundle.js"></script>
    <script src="public/js/main.bundle.js"></script>
    <script src="public/js/static-test.js"></script> -->

  </body>

  <link
  href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"  rel="stylesheet" media="none" onload="if(media!='all')media='all'" >

</html>


text:
\hypertarget{dir_72be331ff2864c764c8815794370491a}{\section{devel/lib/python2.7/dist-\/packages/nubot\-\_\-common Directory Reference}
\label{dir_72be331ff2864c764c8815794370491a}\index{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common Directory Reference@{devel/lib/python2.\-7/dist-\/packages/nubot\-\_\-common Directory Reference}}
}
\subsection*{Directories}
\begin{DoxyCompactItemize}
\item
directory \hyperlink{dir_1a158f8bc660c37d40459fb35f2047c4}{msg}
\item
directory \hyperlink{dir_582ef203a310669a0ba4396d41d88947}{srv}
\end{DoxyCompactItemize}
\subsection*{Files}
\begin{DoxyCompactItemize}
\item
file \hyperlink{devel_2lib_2python2_87_2dist-packages_2nubot__common_2____init_____8py}{\-\_\-\-\_\-init\-\_\-\-\_\-.\-py}
\end{DoxyCompactItemize}