text:
<#
    DESCRIPTION:
        Checks if there are any failed SQL Agent jobs.
        Note: The PowerShell module for SQL (SQLPS) is required for this check.

    REQUIRED-INPUTS:
        None

    DEFAULT-VALUES:
        None

    DEFAULT-STATE:
        Disabled

    RESULTS:
        PASS:
            There are no failed SQL Agent jobs
        WARNING:
        FAIL:
            There are one or more failed SQL Agent jobs
        MANUAL:
        NA:

    APPLIES:
        SQL Servers

    REQUIRED-FUNCTIONS:
        Check-Software
#>

Function sql-05-failed-jobs
{
    $result        = newResult
    $result.server = $env:ComputerName
    $result.name   = $script:lang['Name']
    $result.check  = 'sql-05-failed-jobs'

    #... CHECK STARTS HERE ...#

    Try
    {
        [object]$verCheck = (Check-Software -DisplayName 'Microsoft SQL Server')
        If ($verCheck -eq '-1') { Throw $script:lang['trw1'] }

        If ([string]::IsNullOrEmpty($verCheck) -eq $false)
        {
            [string]$sqlScript = @"

SET NOCOUNT ON
DECLARE @V_ROWCOUNT               INT
DECLARE @V_FAILED_JOBS            VARCHAR(200)
DECLARE @V_FAILED_JOBS_DETAIL     VARCHAR(5000)
DECLARE @V_SQL_LASTCHECK          DATETIME

IF DATENAME(dw, GETDATE()) = 'Monday'
    SELECT @V_SQL_LASTCHECK = GETDATE() - 3
ELSE
    SELECT @V_SQL_LASTCHECK = GETDATE() - 1

DECLARE FAILED_JOBS CURSOR FOR
    SELECT jb.name + ': ' + CAST(msdb.dbo.agent_datetime(jh.run_date, jh.run_time) AS VARCHAR)
    FROM msdb.dbo.sysjobs AS jb JOIN msdb.dbo.sysjobhistory AS jh
        ON (jb.job_id = jh.job_id)
    WHERE step_name = '(job outcome)'
    AND run_status = '0'
    AND run_date >= (SELECT CONVERT(CHAR(8), @V_SQL_LASTCHECK, 112))
    ORDER BY jh.run_date, jh.run_time

OPEN FAILED_JOBS
    FETCH NEXT FROM FAILED_JOBS INTO @V_FAILED_JOBS
    SET @V_ROWCOUNT = 0
    SET @V_FAILED_JOBS_DETAIL = @V_FAILED_JOBS
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @V_ROWCOUNT = @V_ROWCOUNT + 1
        FETCH NEXT FROM FAILED_JOBS INTO @V_FAILED_JOBS
        IF @@FETCH_STATUS = 0 SET @V_FAILED_JOBS_DETAIL = @V_FAILED_JOBS_DETAIL + ',#' + @V_FAILED_JOBS
    END
CLOSE FAILED_JOBS
DEALLOCATE FAILED_JOBS

IF @V_ROWCOUNT = 0
    SELECT '$($script:lang['Pass'])' AS 'result',
           '$($script:lang['p001'])' AS 'message',
           '' AS 'data'
ELSE
    SELECT '$($script:lang['Fail'])' AS 'result',
           '$($script:lang['f001'])'  AS 'message',
           @V_FAILED_JOBS_DETAIL AS 'data'

"@
            $sqlCmd = (Invoke-Sqlcmd -ServerInstance $env:ComputerName -Query $sqlScript)
            $result.result  = $sqlCmd.result
            $result.message = $sqlCmd.message
            $result.data    = $sqlCmd.data
        }
        Else
        {
            $result.result  = $script:lang['Not-Applicable']
            $result.message = $script:lang['n001']
        }
    }
    Catch
    {
        $result.result  = $script:lang['Error']
        $result.message = $script:lang['Script-Error']
        $result.data    = $_.Exception.Message
    }

    Return $result
}


text:
package org.openqa.grid.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import com.google.gson.Gson;

import com.beust.jcommander.JCommander;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.internal.utils.configuration.GridNodeConfiguration;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.JsonToBeanConverter;

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

public class BaseRemoteProxyTest {

  private static RemoteProxy p1 = null;
  private static RemoteProxy p2 = null;

  private static Map<String, Object> app1Capability = new HashMap<>();
  private static Map<String, Object> app2Capability = new HashMap<>();
  private static Registry registry = Registry.newInstance();

  @BeforeClass
  public static void setup() throws Exception {

    app1Capability.put(CapabilityType.APPLICATION_NAME, "app1");
    app2Capability.put(CapabilityType.APPLICATION_NAME, "app2");

    p1 =
        RemoteProxyFactory
            .getNewBasicRemoteProxy(app1Capability, "http://machine1:4444/", registry);
    List<Map<String, Object>> caps = new ArrayList<>();
    caps.add(app1Capability);
    caps.add(app2Capability);
    p2 = RemoteProxyFactory.getNewBasicRemoteProxy(caps, "http://machine4:4444/", registry);

  }

  @Test
  public void testEqual() {
    assertTrue(p1.equals(p1));
    assertFalse(p1.equals(p2));
  }

  @Test(expected = GridException.class)
  public void create() {
    Map<String, Object> cap = new HashMap<>();
    cap.put(CapabilityType.APPLICATION_NAME, "corrupted");

    GridNodeConfiguration config = new Gson().fromJson("{\"remoteHost\":\"ebay.com\"}", GridNodeConfiguration.class);

    RegistrationRequest request = new RegistrationRequest();
    request.addDesiredCapability(cap);
    request.setConfiguration(config);

    new BaseRemoteProxy(request, registry);
  }

  @Test
  public void proxyConfigIsInheritedFromRegistry() {
    Registry registry = Registry.newInstance();
    registry.getConfiguration().cleanUpCycle = 42;
    registry.getConfiguration().timeout = 4200;

    GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
    new JCommander(nodeConfiguration, "-role", "webdriver", "-timeout", "100", "-cleanUpCycle", "100");
    RegistrationRequest req = RegistrationRequest.build(nodeConfiguration);
    req.getConfiguration().proxy = null;

    RemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);

    assertEquals(42, p.getConfig().cleanUpCycle.longValue());
    assertEquals(4200, p.getConfig().timeout.longValue());
  }

  @Test
  public void proxyTakesRemoteAsIdIfIdNotSpecified() {
    String remoteHost ="http://machine1:5555";
    Registry registry = Registry.newInstance();

    GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
    new JCommander(nodeConfiguration, "-role", "webdriver","-host", "machine1", "-port", "5555");
    RegistrationRequest req = RegistrationRequest.build(nodeConfiguration);
    req.getConfiguration().proxy = null;
    RemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);

    assertEquals(remoteHost, p.getId());

  }

  @Test
  public void proxyWithIdSpecified() {
    Registry registry = Registry.newInstance();
    GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
    new JCommander(nodeConfiguration, "-role", "webdriver","-host", "machine1", "-port", "5555","-id", "abc");
    RegistrationRequest req = RegistrationRequest.build(nodeConfiguration);
    req.getConfiguration().proxy = null;
    RemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);

    assertEquals("abc", p.getId());

  }

  @Test
  public void timeouts() {
    Registry registry = Registry.newInstance();
    GridNodeConfiguration nodeConfiguration = new GridNodeConfiguration();
    new JCommander(nodeConfiguration, "-role", "webdriver","-host", "machine1", "-port", "5555","-id", "abc","-timeout", "23", "-browserTimeout", "12");
    RegistrationRequest req = RegistrationRequest.build(nodeConfiguration);
    req.getConfiguration().proxy = null;
    RemoteProxy p = BaseRemoteProxy.getNewInstance(req, registry);
    assertEquals(23000, p.getTimeOut());
  }

  @AfterClass
  public static void teardown() {
    registry.stop();
  }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once __DIR__ . '/common.php';


text:
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
    <x:xmpmeta xmlns:x="adobe:ns:meta/" >
      <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
        <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/">
          <xmpMM:DocumentID>uuid:09C78666-2F91-3A9C-92AF-3691A6D594F7</xmpMM:DocumentID>
        </rdf:Description>
        <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" >
          <xmp:ModifyDate>2008-01-18T16:59:54+01:00</xmp:ModifyDate>
          <xmp:MetadataDate>2008-01-18T16:59:54+01:00</xmp:MetadataDate>
          <xmp:CreateDate>2008-01-18T16:59:54+01:00</xmp:CreateDate>
	  <xmp:Thumbnails xmlns:xapGImg="http://ns.adobe.com/xap/1.0/g/img/">
  	    <rdf:Alt>
	      <rdf:li rdf:parseType="Resource">
		 <xapGImg:height>162</xapGImg:height>
		 <xapGImg:width>216</xapGImg:width>
		 <xapGImg:format>JPEG</xapGImg:format>
		 <xapGImg:image>/9j/4AAQSkZJRgABAgEASABIAAD</xapGImg:image>
	       </rdf:li>
	    </rdf:Alt>
	  </xmp:Thumbnails>

        </rdf:Description >
        <rdf:Description rdf:about="" xmlns:pdfaExtension="http://www.aiim.org/pdfa/ns/extension/" xmlns:pdfaSchema="http://www.aiim.org/pdfa/ns/schema#" xmlns:pdfaProperty="http://www.aiim.org/pdfa/ns/property#" xmlns:pdfaType="http://www.aiim.org/pdfa/ns/type#" xmlns:pdfaField="http://www.aiim.org/pdfa/ns/field#">
          <pdfaExtension:schemas>
            <rdf:Bag>
              <rdf:li rdf:parseType="Resource">
                <pdfaSchema:schema>ACME E-Mail Schema</pdfaSchema:schema>
                <pdfaSchema:namespaceURI>http://www.acme.com/ns/email/1/</pdfaSchema:namespaceURI>
                <pdfaSchema:prefix>acmeemail</pdfaSchema:prefix>
                <pdfaSchema:property>
                  <rdf:Seq>
                    <rdf:li rdf:parseType="Resource">
                      <pdfaProperty:name>Delivery-Date</pdfaProperty:name>
                      <pdfaProperty:valueType>Date</pdfaProperty:valueType>
                      <pdfaProperty:category>internal</pdfaProperty:category>
                      <pdfaProperty:description>date of email delivery</pdfaProperty:description>
                    </rdf:li>
                    <rdf:li rdf:parseType="Resource">
                      <pdfaProperty:name>From</pdfaProperty:name>
                      <pdfaProperty:valueType>mailaddress</pdfaProperty:valueType>
                      <pdfaProperty:category>internal</pdfaProperty:category>
                      <pdfaProperty:description>sender email address</pdfaProperty:description>
                    </rdf:li>
                  </rdf:Seq>
                </pdfaSchema:property>
<pdfaSchema:valueType>
                  <rdf:Seq>
                    <rdf:li rdf:parseType="Resource">
                      <pdfaType:type>mailaddress</pdfaType:type>
                      <pdfaType:namespaceURI>http://www.acme.com/ns/email/1/mailaddress/</pdfaType:namespaceURI>
                      <pdfaType:description>mailaddress value</pdfaType:description>
         		<pdfaType:prefix>add</pdfaType:prefix>
                      <pdfaType:field>
                        <rdf:Seq>
                          <rdf:li rdf:parseType="Resource">
                            <pdfaField:name>name</pdfaField:name>
                            <pdfaField:valueType>Text</pdfaField:valueType>
                            <pdfaField:description>plaintext name</pdfaField:description>
                          </rdf:li>
                          <rdf:li rdf:parseType="Resource">
                            <pdfaField:name>mailto</pdfaField:name>
                            <pdfaField:valueType>Text</pdfaField:valueType>
                            <pdfaField:description>email address</pdfaField:description>
                          </rdf:li>
                        </rdf:Seq>
                      </pdfaType:field>
                    </rdf:li>
                  </rdf:Seq>
                </pdfaSchema:valueType>
              </rdf:li>
            </rdf:Bag>
          </pdfaExtension:schemas>
        </rdf:Description>
        <rdf:Description rdf:about="" xmlns:acmeemail="http://www.acme.com/ns/email/1/" xmlns:add="http://www.acme.com/ns/email/1/mailaddress/">
          <acmeemail:Delivery-Date>2007-11-09T09:55:36+01:00</acmeemail:Delivery-Date>
          <acmeemail:From rdf:parseType="Resource">
            <add:name>John Doe</add:name>
            <add:mailto>john@acme.com</add:mailto>
          </acmeemail:From>
        </rdf:Description>
        <rdf:Description rdf:about="" xmlns:pdfaid="http://www.aiim.org/pdfa/ns/id/">
          <pdfaid:part>1</pdfaid:part>
          <pdfaid:conformance>B</pdfaid:conformance>
          <pdfaid:amd>1:2005</pdfaid:amd>
        </rdf:Description>
        <rdf:Description rdf:about="" xmlns:pdf="http://ns.adobe.com/pdf/1.3/">
          <pdf:Producer>PDFlib Personalization Server 7.0.2p5 (Win32)</pdf:Producer>
        </rdf:Description>
      </rdf:RDF>
    </x:xmpmeta>
<?xpacket end="r"?>


text:
```plpgsql
CREATE OR REPLACE FUNCTION inventory.is_parent_unit(parent integer, child integer)
RETURNS boolean
```
* Schema : [inventory](../../schemas/inventory.md)
* Function Name : is_parent_unit
* Arguments : parent integer, child integer
* Owner : frapid_db_user
* Result Type : boolean
* Description :

**Source:**
```sql
CREATE OR REPLACE FUNCTION inventory.is_parent_unit(parent integer, child integer)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
BEGIN
    IF $1!=$2 THEN
        IF EXISTS
        (
            WITH RECURSIVE unit_cte(unit_id) AS
            (
             SELECT tn.compare_unit_id
                FROM inventory.compound_units AS tn
				WHERE tn.base_unit_id = $1
				AND NOT tn.deleted
            UNION ALL
             SELECT
                c.compare_unit_id
                FROM unit_cte AS p,
              inventory.compound_units AS c
                WHERE base_unit_id = p.unit_id
            )

            SELECT * FROM unit_cte
            WHERE unit_id=$2
        ) THEN
            RETURN TRUE;
        END IF;
    END IF;
    RETURN false;
END
$function$

```

### Related Contents
* [Schema List](../../schemas.md)
* [Function List](../../functions.md)
* [Trigger List](../../triggers.md)
* [Table of Contents](../../README.md)


text:
from common_imports import *
from tkFileDialog import *
from tkMessageBox import *
from tkFont import Font
from ScrolledText import *
import file_menu
import edit_menu
import format_menu
import help_menu

root = Tk()

root.title("Text Editor-Untiltled")
root.geometry("300x250+300+300")
root.minsize(width=400, height=400)

font = Font(family="Verdana", size=10)

text = ScrolledText(root, state='normal', height=400, width=400, wrap='word', font = font, pady=2, padx=3, undo=True)
text.pack(fill=Y, expand=1)
text.focus_set()

menubar = Menu(root)

file_menu.main(root,text,menubar)
edit_menu.main(root,text,menubar)
format_menu.main(root,text,menubar)
help_menu.main(root,text,menubar)
root.mainloop()


text:
A set of useful tools to work with Alef.

## Installation
```sh
yarn add alef-tools
```
You may alternatively use `npm i --save alef-tools`.

## Usage
The API is exported by the `alef-tools` package by default e.g.

```javascript
import { StyleSheet } from 'alef-tools'
```

## API Reference

* [`mapValueToMediaQuery(queryValueMap, mapper)`](docs/mapValueToMediaQuery.md)
* [`renderToString(renderer)`](docs/renderToString.md)
* [StyleSheet](docs/StyleSheet.md)

## License
Alef is licensed under the [MIT License](http://opensource.org/licenses/MIT).

Documentation is licensed under [Creative Common License](http://creativecommons.org/licenses/by/4.0/).

Created with ♥ by [@rofrischmann](http://rofrischmann.de) and all the great contributors.


text:
package org.gradle.api.internal.tasks.scala;

import org.gradle.api.GradleException;
import org.gradle.api.file.FileCollection;
import org.gradle.api.internal.project.IsolatedAntBuilder;
import org.gradle.api.internal.tasks.compile.JavaCompileSpec;
import org.gradle.api.internal.tasks.compile.JavaCompilerFactory;
import org.gradle.api.internal.tasks.compile.daemon.CompilerDaemonFactory;
import org.gradle.api.tasks.scala.ScalaCompileOptions;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.language.base.internal.compile.CompilerFactory;

import java.io.File;
import java.util.Set;

public class ScalaCompilerFactory implements CompilerFactory<ScalaJavaJointCompileSpec> {
    private final IsolatedAntBuilder antBuilder;
    private final JavaCompilerFactory javaCompilerFactory;
    private final CompilerDaemonFactory compilerDaemonFactory;
    private FileCollection scalaClasspath;
    private FileCollection zincClasspath;
    private final File rootProjectDirectory;

    public ScalaCompilerFactory(File rootProjectDirectory, IsolatedAntBuilder antBuilder, JavaCompilerFactory javaCompilerFactory, CompilerDaemonFactory compilerDaemonFactory, FileCollection scalaClasspath, FileCollection zincClasspath) {
        this.rootProjectDirectory = rootProjectDirectory;
        this.antBuilder = antBuilder;
        this.javaCompilerFactory = javaCompilerFactory;
        this.compilerDaemonFactory = compilerDaemonFactory;
        this.scalaClasspath = scalaClasspath;
        this.zincClasspath = zincClasspath;
    }

    @SuppressWarnings("unchecked")
    public Compiler<ScalaJavaJointCompileSpec> newCompiler(ScalaJavaJointCompileSpec spec) {
        ScalaCompileOptions scalaOptions = (ScalaCompileOptions) spec.getScalaCompileOptions();
        Set<File> scalaClasspathFiles = scalaClasspath.getFiles();
        if (scalaOptions.isUseAnt()) {
            Compiler<ScalaCompileSpec> scalaCompiler = new AntScalaCompiler(antBuilder, scalaClasspathFiles);
            Compiler<JavaCompileSpec> javaCompiler = javaCompilerFactory.createForJointCompilation(spec.getClass());
            return new NormalizingScalaCompiler(new DefaultScalaJavaJointCompiler(scalaCompiler, javaCompiler));
        }

        if (!scalaOptions.isFork()) {
            throw new GradleException("The Zinc based Scala compiler ('scalaCompileOptions.useAnt=false') "
                    + "requires forking ('scalaCompileOptions.fork=true'), but the latter is set to 'false'.");
        }

        Set<File> zincClasspathFiles = zincClasspath.getFiles();

        // currently, we leave it to ZincScalaCompiler to also compile the Java code
        Compiler<ScalaJavaJointCompileSpec> scalaCompiler = new DaemonScalaCompiler<ScalaJavaJointCompileSpec>(rootProjectDirectory, new ZincScalaCompiler(scalaClasspathFiles, zincClasspathFiles), compilerDaemonFactory, zincClasspathFiles);
        return new NormalizingScalaCompiler(scalaCompiler);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>ANDROID_API_MIN — CMake 3.8.1 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="ANDROID_ARCH" href="ANDROID_ARCH.html" />
    <link rel="prev" title="ANDROID_API" href="ANDROID_API.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-properties(7) »

ANDROID_API_MIN¶

Set the Android MIN API version (e.g. 9).  The version number
must be a positive decimal integer.  This property is initialized by
the value of the CMAKE_ANDROID_API_MIN variable if it is set
when a target is created.  Native code builds using this API version.

Previous topic

ANDROID_API

Next topic

ANDROID_ARCH

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-properties(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


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

namespace EnvironmentVariablesNamespaceExtension
{
    public partial class EnvironmentVariablesView : UserControl
    {
        public EnvironmentVariablesView()
        {
            InitializeComponent();

            Load += EnvironmentVariablesView_Load;
        }

        void EnvironmentVariablesView_Load(object sender, EventArgs e)
        {
            //  Get the system environment variables.
            var systemEnvironmentVariables =
                System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine);

            //  Add each to the list.
            foreach (string variableKey in systemEnvironmentVariables.Keys)
            {
                listViewEnvironmentVariables.Items.Add(
                    new ListViewItem(
                        new[]
                        {
                            variableKey,
                            systemEnvironmentVariables[variableKey].ToString()
                        }));
            }
        }

    }
}


text:
/// <reference path="../hw/dux_paraio.d.ts"/>

declare namespace Dux {
    /**
     * Pin specify (both number and string with prefix "D"/"d" are accepted)
     *
     * Example: 1, "D2", "d3"
     */
    type PeridotPin = number | string;
}

declare module "peridot" {
    export const startLed: Dux.ParallelIO;
}


text:
Gitlab::Seeder.quiet do
  Project.all.each do |project|
    (1..10).each  do |i|
      issue_params = {
        title: Faker::Lorem.sentence(6),
        description: Faker::Lorem.sentence,
        state: ['opened', 'closed'].sample,
        milestone: project.milestones.sample,
        assignee: project.team.users.sample
      }

      Issues::CreateService.new(project, project.team.users.sample, issue_params).execute
      print '.'
    end
  end
end


text:
#include "api-control-client.hpp"

#include "api-client.hpp"
#include "command-macro.hpp"
#include "proto/proto-control-client.hpp"

result register_control_client(text_info nName)
{ return master_register_client(nName, type_control_client_all); }

command_handle find_control_clients(text_info nName)
{ DEFAULT_QUEUE_SERVER_COMMAND(new proto_find_control_clients(nName)) }


text:
var socket;

(function(window, document, undefined){
    "use strict";
    var host = document.location.hostname;
    var port = document.location.port;

    function start_chatting(e) {
        e.preventDefault();
        var username = document.getElementById('username').value;
        var connect_form = document.getElementById('connect-form');
        var chat_app = document.getElementById('chat-app');

        connect_form.style.display = 'none';

        var status = document.getElementById('status');
        var chats = document.getElementById('chats');

        status.innerHTML = 'Connecting...';
        status.className = 'connecting';

        socket = new WebSocket('ws://' + host + ':' + port + '/');

        socket.onopen = function () {
            status.innerHTML = 'Connected';
            status.className = 'connected';
            chat_app.style.display = 'block';
            send_message({
                type: 'new_user',
                username: username
            });
        };

        socket.onmessage = function (response) {
            var tr = document.createElement('tr');
            var data = JSON.parse(response.data);
            console.log(data);
            if(data.type === 'notice') {
                data.username = '*Server Message*'
            }
            tr.innerHTML = '[$1]	$2	$3	'
                .replace('$1', data.datetime)
                .replace('$2', data.username)
                .replace('$3', data.message);
            chats.appendChild(tr);
        };

        function handle_input(e) {
            e.preventDefault();
            var chat_input = document.getElementById('enter-chat');
            send_message({
                type: 'user_message',
                message: chat_input.value
             });
            chat_input.value = '';
        }

        var submit = document.getElementById('submit');
        submit.addEventListener('click', handle_input);
        var my_form = document.getElementById('my-form');
        my_form.addEventListener('submit', handle_input);
    }

    function send_message(data){
        socket.send(JSON.stringify(data));
    }

    window.onload = function () {
        var start_chat_form = document.getElementById('start-chat-form');
        start_chat_form.addEventListener('submit', start_chatting);
    };
})(window, document);


text:
package hu.rbr.sfinapp.transaction.validator;

import hu.rbr.sfinapp.transaction.Transaction;
import hu.rbr.sfinapp.transaction.TransactionType;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

public class ValidTransferTypeValidatorTest {

    private ValidTransferTypeValidator validator;

    @Before
    public void init() {
        validator = new ValidTransferTypeValidator();
    }

    @Test
    public void valid() {
        Transaction tr = new Transaction();
        tr.type = TransactionType.Transfer;
        tr.toAccountId = 5;

        boolean valid = validator.isValid(tr, null);
        assertThat(valid, equalTo(true));
    }

    @Test
    public void typeIsNull() {
        Transaction tr = new Transaction();
        tr.type = null;

        boolean valid = validator.isValid(tr, null);
        assertThat(valid, equalTo(true));
    }

    @Test
    public void missingToAccountIdOnTransfer() {
        Transaction tr = new Transaction();
        tr.type = TransactionType.Transfer;
        tr.toAccountId = null;

        boolean valid = validator.isValid(tr, null);
        assertThat(valid, equalTo(false));
    }

    @Test
    public void missingToAccountIdOnIncome() {
        Transaction tr = new Transaction();
        tr.type = TransactionType.Income;
        tr.toAccountId = null;

        boolean valid = validator.isValid(tr, null);
        assertThat(valid, equalTo(true));
    }

    @Test
    public void missingToAccountIdOnExpense() {
        Transaction tr = new Transaction();
        tr.type = TransactionType.Expense;
        tr.toAccountId = null;

        boolean valid = validator.isValid(tr, null);
        assertThat(valid, equalTo(true));
    }
}


text:
namespace Envoy {
namespace Network {

REGISTER_FACTORY(UdpDefaultWriterFactoryFactory, UdpPacketWriterFactoryFactory);

} // namespace Network
} // namespace Envoy


text:
<TITLE>Review for Edward II (1991)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Edward II (1991)

reviewed by
Frank Maloney

                                  EDWARD II
                       A film review by Frank Maloney
                        Copyright 1992 Frank Maloney

     EDWARD II is a film by Derek Jarman, written by Jarman, Stephen
McBride, and Ken Butler, based on the play by Christopher Marlowe.  It
stars Steven Waddington, Kevin Collins, Andrew Tiernan, Jody G. Raber,
Jerome Flynn, Tilda Swinton, and Nigel Terry.  Art direction by
Christopher Hobbs.  The film is rated R for violence and sexual
situations.

     EDWARD II is Jarman's ninth feature film and it's a stunner.  You
will either love it or hate it.  There is no middle ground here.
Jarman, the director of SEBASTIANE, CARAVAGGIO, JUBILEE, and THE
TEMPEST, is in no mood to shilly-shally here and has produced an angry,
provocative film, a polemic against homophobia, agit-prop, radical
propaganda.  I think it is very good theater; I don't think that it's
perfect film-making, however much I applaud its politics.

     The only problem I have is that EDWARD II looks like a filmed stage
play, not like a movie, except for the fast-paced editing.  The
minimalist sets, designed by Christopher Hobbs, consist of slablike
blocks and walls; there are no exteriors at all.  This is a response to
Jarman's shoestring budget, but it must always be a fault in film.
This is not to say the sets are ineffective; they communicate the
primitive world of Plantagenet England (Edward II ruled from 1307-1327),
the even more primitive world of power politics and bloody hatreds that
are not, unfortunately, so bound by time.  The costumes are mostly
contemporary.  Edward and his lover Piers Gaveston appear in dark,
stylish suits and ties, the Queen Isabella (Tilda Swinton) stalks
through the entire movie as a fashion parade of campy haute couture
fashion, the rebellious Mortimer (Nigel Terry) wears the uniform of a
British officer, right down the bristly little mustache.

     Jarman never stops reminding us that this is not just a costume
flick, that this is about now, that it is happening now.  The most
blatant exercise of this insistence is the battle scene that becomes a
confrontation between OutRage activists with very contemporary placards
and riot police with truncheons and plastic shields.  (The extras were
real-life members of OutRage, a British group somewhat akin to ACT-Up in
the U.S.)

     The language, however, is purely Marlowe's, although Jarman and his
co-writers use only a third of the 1592 play.  The writers have several
characters repeat the question "How can you love what the rest of the
world hates?" (remembered approximately).  How indeed?  Is this the
crux?  The antique blank verse and modern costumes fuse powerfully at
this moment to open the play and the film to the largest possible scope
of meaning.

     Jarman also does something very interesting with the ending, which
he rewrites for Marlowe.  It can be justified from contemporary
documents, I am told, and it certainly can be justified from the
political demands of the movie.  Marlowe's ending is foreshadowed
throughout the action and is enacted in all its brutality and then
thrown away as a bad dream.  Instead, we have a symbol of what happens
when the oppressed help each other, instead of the oppressors, as moving
in its own way as the ending to the novel THE GRAPES OF WRATH.

     As for the performances, let me say first off that I deeply
appreciate the care and precision with which the British actors spoke
Marlowe's words.  I understood every one of them, not something one can
usually say, especially with U.S. productions of Elizabethan drama.
The lovers, Waddington as Edward and Tiernan as Gaveston, were
energetic, impudent, imprudent, and very passionate, without chewing any
scenery.  However, Swinton as the Queen steals the entire movie.  She
took Best Actress at Venice and deservedly.  She has the carriage of a
runway fashion model, slinking, slouching, projecting her bony shoulders
like leathern wings.  She is passionate, too, and much more dangerous
than any of the males; she doesn't quite eat her mate, but she comes as
close as possible, familially speaking.

     When Gaveston and Edward part, we head Annie Lennox's version of
Cole Porter's "Ev'ry Time We Say Goodbye" from the AIDS fund-raiser
album, "Red, Hot & Blue."  Lennox then appears and gives us a new
interpretation of this beautiful song, bringing out its quiet sadness.
(Jarman came out in 1987 when he announced he was HIV+.  Since then the
British press, in particular, has mounted a death watch on each of his
films, WAR WORKS, THE GARDEN, and now EDWARD II; Jarman, by all reports,
continues to be creative and productive, despite a series of
opportunistic infections last year.)

     I don't have the name of Jarman's cinematographer.  I should
because the film is beautifully shot, relying on carefully arranged
tableaux vivants and chiaroscuro lighting, as it does in the main, the
effects are stagey but visually rich.

     I kept thinking of Peter Greenaway throughout this film, that
despite the contrast of Jarman's stripped down sparseness and
modern-dress plainness the two had much in common in their painterly
sensibilities and their determination to shock and challenge us, the
success with which they entertain us at the same time with the passion
and purity of their anger.

     There is male nudity, homoeroticism, brutality and violence in this
film.  Be forewarned, this may not be your cup of tea.  But for those
whose cup it is, or who are willing to take a bit of a flutter, EDWARD
II will reward them handsomely.  It is not going to be easy to find;
even in Seattle, it is only playing at the Broadway Market in the heart
of the gay ghetto of Capital Hill.  Pay whatever you must; it's worth
it.

--
Frank Richard Aloysius Jude Maloney

.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
using Ibt.Ortc.Api.Extensibility;
using System.Collections.Generic;
using System.Reflection;
using System;
using System.IO;

namespace Ibt.Ortc.Plugin.IbtRealTimeSJ
{
    /// <summary>
    /// IBT Real Time SJ type factory.
    /// </summary>
    /// <remarks>
    /// Factory Type = IbtRealTimeSJ.
    /// </remarks>
    [ExportOrtcFactory(FactoryType = "IbtRealTimeSJ")]
    public class IbtRealTimeSJFactory : IOrtcFactory
    {
        #region Attributes

        /// <summary>
        /// To load the assemblies just once.
        /// </summary>
        private readonly IDictionary<string, Assembly> _loadedAssemblies;

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="IbtRealTimeKFactory"/> class.
        /// </summary>
        public IbtRealTimeSJFactory()
        {
            _loadedAssemblies = new Dictionary<string, Assembly>();

            //LoadWebSocket4NetAssembly();
        }

        #endregion

        #region Methods

        /// <summary>
        /// Creates a new instance of a ortc client.
        /// </summary>
        /// <returns>
        /// New instance of <see cref="OrtcClient"/>.
        /// </returns>
        public OrtcClient CreateClient()
        {
            return new IbtRealTimeSJClient();
        }

        /// <summary>
        /// Loads the WebSocket4Net assembly so the client do not need to add a project reference to this dll.
        /// </summary>
        private void LoadWebSocket4NetAssembly()
        {
            string[] test = Assembly.GetExecutingAssembly().GetManifestResourceNames();

            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                string resourceName = Assembly.GetExecutingAssembly().GetName().Name + ".Lib." + new AssemblyName(args.Name).Name + ".dll";

                if (!_loadedAssemblies.ContainsKey(resourceName))
                {
                    lock (_loadedAssemblies)
                    {
                        using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                        {
                            if (stream != null)
                            {
                                var assemblyData = new byte[stream.Length];

                                stream.Read(assemblyData, 0, assemblyData.Length);

                                Assembly newAssembly = Assembly.Load(assemblyData);

                                _loadedAssemblies.Add(resourceName, newAssembly);
                            }
                        }
                    }
                }

                return _loadedAssemblies.ContainsKey(resourceName) ? _loadedAssemblies[resourceName] : null;
            };
        }

        #endregion
    }
}


text:
layout: post
title: "How to un-brick a Sony Xperia S and install Oneofakind Android 6.0.1_r10"
author: "Carlos Camacho"
categories:
  - blog
tags:
  - hobbies
commentIssueId: 17
refimage: '/static/fist.gif'
---

Ok, after playing converting partitions to f2fs I made a huge mistake
and corrupted the partitions table of my mobile.. Yeahp, I messed it up.

![](/static/fist.gif)

The following notes are meant to be a reminder about how to follow this
process as it's a cumbersome and time consuming task
to get the correct version of the firmware and tools needed.

A hard brick is the state of android device that occurs when your device
won't boot at all i.e. no boot loop, no recovery and also not charging.

The steps in order to fix the phone will try to flash a new ROM and
upgrade it to Android 6.0.1.

# Prerequisites

* Download all the required files from [here](http://goo.gl/aBYq5w)
  (TWRP, flashtool, flashtool drivers, OEM firmware, root exploit and
  Oneofakind ROM).
* Have a PC near to you.
* A USB cable.
* 1 beer (Save it for the end of the tutorial).

# Part 1

The first part of the tutorial will get you a working
installation of Android 4.1 Jelly Bean in our bricked phone.

## Install Flashtool

Download and install Flashtool, this tool is in the package that
you should have downloaded from the prerequisites.

## Install flashtool drivers for your phone

In order to install the flashtool drivers you need to run some
previous steps as Windows won't let you install them as they are
not signed (Also inside the prerequisites package).

Run the following steps from your PC

* Press the Windows key + R together and in the 'Run' box type
  `shutdown.exe /r /o /f /t 00`
* Now make the following selections to boot into
  the Start Up Setting Screen:
  Troubleshoot > Advanced options > Start Up Settings > Restart
* Then, when the machine restarts, select number 7 i.e.
  'Disable driver signature enforcement'. Your machine will start
  with Driver signing enforcement disabled until the next reboot.

Now you can install the Flashtool drivers.

* Select from the options to install, flashmode drivers and fastboot driver.

Windows will warn that the driver is not signed
and will require you to confirm the installation.
Once the installation is complete, reboot the machine.

## Start the Xperia S in flashmode

Switch off your Xperia S first, then
press and hold the `Volume Down` button.
Connect to your PC using a USB Cable
while holding down the `Volume Down`
button on your Xperia S. Your phone
should be in Flash Mode now and the
device's LED light should turn into Green.

## Flash the image using flashtool

With your phone in flashmode, open Flashtool
and then click on the lightning bolt.
Select the folder where you have the
firmware image `LT26i_6.2.B.1.96_World.ftf`
(downloaded from the prerequisites package).
Check all the items from wipe list and
uncheck all items from exlude list.
Click flash and wait until finish.

Reboot the phone and you should have
Android 4.1 Jelly Bean installed and ready to use,
but we still want to install Android 6.1,
so the first part of the tutorial is finished.

---

# Part 2

After having a working installation of Android
in our already un-bricked phone,
the next steps allow to upgrade the stantard
ROM to Oneofakind Android 6.0.1_r10.

## Unlock the phone boot loader

Follow the instructions from the official
[Sony website](http://developer.sonymobile.com/unlockbootloader/unlock-yourboot-loader/)

## Gain root access to the phone.

First in your mobile phone.

*  Activate USB Debugging, Setting -> Developer Options

*  Activate Unknown Sources, Setting -> Security

Now open the application `RunMe.bat` within
Root_with_Restore_by_Bin4ry_v36
and select option 2. Your phone should be rooted and rebooted.

## Installing TWRP

Switch off your Xperia S first.
Press and hold the `Volume Up` button.
Connect to your PC using a USB Cable while
holding down the `Volume Up` button on your Xperia S.
Your Xperia S should be in Fast Mode now and the
device's LED light should turn into Blue. Then run:

```
fastboot flash boot twrp-3.0.2-0-nozomi.img
```

At this point you should have the recovery installed.

## Re-partitioning

Let's start TWRP. Turn on the phone and the the Sony
screen appears press the `Volume Up` button.

Go to Mount on TWRP gui (uncheck system, data, cache)
Open the terminal and run:

```
fdisk -l /dev/block/mmcblk0
```

Copy the output of the command to a file with your backup.

Interesting parts are the following lines:

```
/dev/block/mmcblk0p14 42945 261695 7000024 83 Linux
/dev/block/mmcblk0p15 261696 954240 22161424 83 Linux
```

It can be not exactly the same values for you depending
the size of your /data (p14) and /sdcard (p15), run:

```
fdisk /dev/block/mmcblk0
```

The following steps will merge p14 and 15 into one big partition for data,
do this or otherwise you won't be able to use the internal SD.

```
Command (m for help): p

Command (m for help): d
Partition number (1-15): 15

Command (m for help): d
Partition number (1-14): 14

Command (m for help): n
First cylinder (769-954240, default 769): 42945
Last cylinder or +size or +sizeM or +sizeK (42945-954240, default 954240): (just press enter if the default value is the good one)
Using default value 954240

Command (m for help): t
Partition number (1-14): 14
Hex code (type L to list codes): 83

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table
```

Once re-partitioning done, do NOT do anything
else and just reboot the device (to be sure
that the partition table is take into account by the kernel)

Now we will convert /data and /cache to F2FS.
Ext4 is not supported anymore on nAOSProm. You don't
need to take care about the 16384 byte to reserve
for encryption. TWRP will do it for you.

## Install and run TWRP again

Switch off your Xperia S first.
Press and hold the `Volume Up` button
Connect to your PC using a USB Cable while holding down the `Volume Up` button on your Xperia S
Your phone should be in Fast Mode now and the device's LED light should turn into Blue, then run

```
fastboot flash boot twrp-3.0.2-0-nozomi.img
```

Let's start TWRP. Turn on the phone and the the Sony
screen appears press the `Volume Up` button.

Mount all the partitions.

From the menu click:

* Wipe -> Advanced Wipe -> select Data -> Repair or Change File system -> Change File System -> F2FS -> Swipe to Change

* Wipe -> Advanced Wipe -> select Cache -> Repair or Change File system -> Change File System -> F2FS -> Swipe to Change

Once done, again, do NOT do anything else and just reboot the device (required by TWRP).

Congratulation, if everything is fine you should be able to mount /cache and /data and to see a big /data volume around 28 GiB.

Boot the phone again in recovery mode (TWRP).

Start TWRP, mount all partitions and from your PC run:

```
adb push open_gapps-arm-6.0-pico-20161006.zip /sdcard/
adb push oneofakind_nozomi-27-Jan-2016.zip /sdcard/
```
This will load those files into your smartphone allowing
the installation of Oneofakind.

## Final installation of Oneofakind....

From TWRP menu click install and select the two images that
we just have uploaded (oneofakind_nozomi-27-Jan-2016.zip and open_gapps-arm-6.0-pico-20161006.zip).

Click flash and wait until the installation is complete, in the mean while
open the beer (Last prerequisite) and drink it.

Cheers!


text:
package modelo;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

@NamedQueries(
	{
		@NamedQuery(name="PlanoModelo.recuperarPlPerModsPorPlanoModelo",
					query = "select pl " +
						  	"from PlanoModelo pl " +
						  	"left outer join fetch pl.plPerMods " +
						  	"where pl = ? "
		),
		@NamedQuery(name="PlanoModelo.recuperarPlanoModeloPorCodigoModeloECodigoCadPlan",
					query = "select pl " +
						  	"from PlanoModelo pl " +
						  	"left outer join fetch pl.cadPlan cp " +
						  	"left outer join fetch pl.modelo m " +
						  	"where cp.codPlan = ? "	+
						  	"and m.codModelo = ? "
		)
	}
)

@Entity
@Table(name = "PLANOMODELO")
@SequenceGenerator(name = "SEQUENCIA", sequenceName = "SEQ_PLANOMODELO", allocationSize = 1)
public class PlanoModelo implements Serializable, Comparable<PlanoModelo> {

	private static final long serialVersionUID = 1L;

	public PlanoModelo(){
		 this.escorePlanPerModMin=0.0;
		 this.varEstqPercEscMin =0.0;
		 this.varProdDiaPercEscMin=0.0;
		 this.prodDiariaMediaPlanoModelo=0.0;
		 this.escore=0.0;
	}

	public PlanoModelo(CadPlan cadPlan, Modelo modelo){

		this.cadPlan = cadPlan;
		this.modelo = modelo;
	}

	/**
	 * identificador do registro planoModelo
	 *
	 */
	private Long id;

	/**
	 * Define o escore resultante da avaliação do plano para um determinado modelo.
	 * corresponde a media dos escores de cada periodo do modelo(plPerMods).
	 */
	private Double escore;

	/**
	 * Informa se o modelo foi planejado ou não, caso tenha sido permite a implementação do plano.
	 * Funciona como um controle para o planejador, permitindo identificar os planos
	 * de que modelos ja foram analisados.
	 */
	private boolean modeloPlanejado;

	/**
	 * Objeto que representa a classe Modelo de um determinado plano.
	 */
	private Modelo modelo;

	/**
	 * Objeto que representa o cadPlan desse planoModelo
	 */
	private CadPlan cadPlan;

	/**
	 * booleano que indica se o campo produção pode ser recalculado pelo algoritmo ("livre')
	 * ou se é "fixo", não pode ser recalculado automaticamente pelo algoritmo.
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	 */
	private Boolean flagProducaoModelOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	 */
	private Double indiceCobOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	 */
	private Double tamLoteOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	 */
	private Double trOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	 */
	private Double coberturaOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	 */
	private Double estqInicModelOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	*
     */
	private Double estqEmFaltaOriginal;

	/**
	 * Este campo armazena o valor original da tabela modelo no momento em que foi gerado o plano.
	 * É util pois esse campo pode ser alterado na tabela de modelo mas nao sera alterado nos PlPerMod
	 * gerados anteriormente a essa alteração.
	*
     */
	private Double recebimentoPendenteOriginal;

	/**
	 * Menor escore dentre os escores obtidos para todos os periodos desse modelo nesse plano(plPerMod).
	 */
	private Double escorePlanPerModMin;

	/**
	 * Variacao do estoque percentual relativa ao periodo de escore minimo, para esse plano x modelo.
	 */
	private Double varEstqPercEscMin;

	/**
	 * Variacao percentual na producao diaria em lote relativa ao periodo de escore minimo, para esse plano x modelo.
	 */
	private Double varProdDiaPercEscMin;

	private Double prodDiariaMediaPlanoModelo;

	/**
	 * Objeto que representa os PlPerMods relacionado a um planoModelo.
	 */
	private Set<PlPerMod> plPerMods;

	/**
	 *   Variável criada unica e exclusivamente para fins de exibicao em tela da coleção de PlPerMods associada a
	 * entidade.  ATENÇÃO: Esta variável é exatamente uma CÓPIA do Set declarado acima, por isso, este atributo não
	 * é persistido, ou seja, é declarado como transiente.
	 *
	 *@author wallanem figueiredo
	 *
	 */
	private transient List<PlPerMod> plPerModsList;

	/**
	 * Objeto que representa os PlPerMods relacionado a um planoModelo.
	 */
	private List<ExcecaoMens> excecaoMenss;

	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCIA")
	@Column(name = "ID")
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Double getEscore() {
		return escore;
	}

	public boolean isModeloPlanejado() {
		return modeloPlanejado;
	}

	public void setEscore(Double escore) {
		this.escore = escore;
	}

	public void setModeloPlanejado(boolean modeloPlanejado) {
		this.modeloPlanejado = modeloPlanejado;
	}

	public void setModelo(Modelo modelo) {
		this.modelo = modelo;
	}

	@ManyToOne
	@JoinColumn(name="MODELO_ID", nullable = false)
	public Modelo getModelo() {
		return modelo;
	}

	public void setCadPlan(CadPlan cadPlan) {
		this.cadPlan = cadPlan;
	}

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name="CADPLAN_ID", nullable = false)
	public CadPlan getCadPlan() {
		return cadPlan;
	}

	public Boolean getFlagProducaoModelOriginal() {
		return flagProducaoModelOriginal;
	}

	public Double getIndiceCobOriginal() {
		return indiceCobOriginal;
	}

	public Double getTamLoteOriginal() {
		return tamLoteOriginal;
	}

	public Double getTrOriginal() {
		return trOriginal;
	}

	public Double getCoberturaOriginal() {
		return coberturaOriginal;
	}

	public Double getEstqInicModelOriginal() {
		return estqInicModelOriginal;
	}

	public Double getRecebimentoPendenteOriginal() {
		return recebimentoPendenteOriginal;
	}

	public void setRecebimentoPendenteOriginal(Double recebimentoPendenteOriginal) {
		this.recebimentoPendenteOriginal = recebimentoPendenteOriginal;
	}

	public Double getEstqEmFaltaOriginal() {
		return estqEmFaltaOriginal;
	}

	public void setEstqEmFaltaOriginal(Double estqEmFaltaOriginal) {
		this.estqEmFaltaOriginal = estqEmFaltaOriginal;
	}

	public Double getEscorePlanPerModMin() {
		return escorePlanPerModMin;
	}

	public void setEscorePlanPerModMin(Double escorePlanPerModMin) {
		this.escorePlanPerModMin = escorePlanPerModMin;
	}

	public Double getVarEstqPercEscMin() {
		return varEstqPercEscMin;
	}

	public void setVarEstqPercEscMin(Double varEstqPercEscMin) {
		this.varEstqPercEscMin = varEstqPercEscMin;
	}

	public Double getVarProdDiaPercEscMin() {
		return varProdDiaPercEscMin;
	}

	public void setVarProdDiaPercEscMin(Double varProdDiaPercEscMin) {
		this.varProdDiaPercEscMin = varProdDiaPercEscMin;
	}

	public void setFlagProducaoModelOriginal(Boolean flagProducaoModelOriginal) {
		this.flagProducaoModelOriginal = flagProducaoModelOriginal;
	}

	public void setIndiceCobOriginal(Double indiceCobOriginal) {
		this.indiceCobOriginal = indiceCobOriginal;
	}

	public void setTamLoteOriginal(Double tamLoteOriginal) {
		this.tamLoteOriginal = tamLoteOriginal;
	}

	public void setTrOriginal(Double trOriginal) {
		this.trOriginal = trOriginal;
	}

	public void setCoberturaOriginal(Double coberturaOriginal) {
		this.coberturaOriginal = coberturaOriginal;
	}

	public void setEstqInicModelOriginal(Double estqInicModelOriginal) {
		this.estqInicModelOriginal = estqInicModelOriginal;
	}

	public void setPlPerMods(Set<PlPerMod> plPerMods) {
		this.plPerMods = plPerMods;
	}

	@OneToMany(mappedBy="planoModelo", cascade={CascadeType.REMOVE, CascadeType.PERSIST})
	public Set<PlPerMod> getPlPerMods() {
		return plPerMods;
	}

	@OneToMany(mappedBy="planoModelo")
	public List<ExcecaoMens> getExcecaoMenss() {
		return excecaoMenss;
	}

	public void setExcecaoMenss(List<ExcecaoMens> excecaoMenss) {
		this.excecaoMenss = excecaoMenss;
	}

	//  ------------------------ Métodos get() e set() dos atributos transientes ------------------------

	public void setPlPerModsList(List<PlPerMod> plPerModsList) {
		this.plPerModsList = plPerModsList;
	}

	@Transient
	public List<PlPerMod> getPlPerModsList() {
		return plPerModsList;
	}

	public Double getProdDiariaMediaPlanoModelo() {
		return prodDiariaMediaPlanoModelo;
	}

	public void setProdDiariaMediaPlanoModelo(Double prodDiariaMediaPlanoModelo) {
		this.prodDiariaMediaPlanoModelo = prodDiariaMediaPlanoModelo;
	}

	/**
	 * 	Aqui, estamos dizendo que a Ordem Natural de Objetos, ou seja a ordem que sao inseridos em uma lista,
	 *  do tipo 'PlanoModelo' deve se basear em como é implementada a ordem natural na classe 'Modelo' neste
	 *  caso por codigo do modelo.
	 *
	 *  @param PlanoModelo
	 *  @return int
	 */
	@Override
	public int compareTo(PlanoModelo o) {
		return this.modelo.compareTo(o.getModelo());
	}

	/**
	 * Este método poder ser gerado AUTOMATICAMENTE pelo Java , juntamente com o método  "equals(Object obj)".
	 * Eles São necessários para determinarmos um criterio de igualdade entre 2 objetos.
	 *
	 * Obs.: É primoridal dar atenção para este detalhe, principalmente quando trabalhamos com Estruturas
	 * 		 de Dados como Set.
	 *
	 * @return int
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((cadPlan == null) ? 0 : cadPlan.hashCode());
		result = prime * result + ((modelo == null) ? 0 : modelo.hashCode());
		return result;
	}

	/**
	 *
	 * Este método é gerado AUTOMATICAMENTE pelo Java , juntamente com o método
	 * "hashCode()". Eles São necessários pois como o critério principal de igualdade entre 2 objetos PlanoModelo é o campo
	 * 'cadPlan' exige que haja a implementação deste método.
	 *  Caso contrário, fica impossível diferenciar 2 objetos do tipo PlanoModelo, e consequentemente temos a impressão
	 * de que 'sumiram' registros, entre outros possiveis problemas.
	 *
	 * OBS: É PRIMORDIAL DAR ATENÇÃO PARA ESTE DETALHE (PRINCIPALMENTE QUANDO TRABALHARMOS COM ESTRUTURAS COMO 'Set')
	 *
	 * @author felipe.arruda
	 * @param Object
	 * @return int
	 *
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof PlanoModelo)) {
			return false;
		}
		PlanoModelo other = (PlanoModelo) obj;
		if (cadPlan == null) {
			if (other.cadPlan != null) {
				return false;
			}
		} else if (!cadPlan.equals(other.cadPlan)) {
			return false;
		}
		if (modelo == null) {
			if (other.modelo != null) {
				return false;
			}
		} else if (!modelo.equals(other.modelo)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return "PlanoModelo [cadPlan=" + cadPlan + ", modelo=" + modelo + "]";
	}

}


text:
using SwissAcademic.Citavi.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SwissAcademic.Addons.ReferenceEvaluationAddon
{
    internal abstract class BaseEvaluator
    {
        // Fields

        protected StringBuilder _stringBuilder;

        // Constructors

        protected BaseEvaluator() => _stringBuilder = new StringBuilder();

        // Properties

        public abstract string Caption { get; }

        public bool ShowHeader { get; set; }

        // Methods

        public abstract string Run(MainForm mainForm);

        internal static IEnumerable<BaseEvaluator> GetAvailableEvaluators()
        {
            return typeof(BaseEvaluator)
                   .Assembly
                   .GetTypes()
                   .Where(type => type.BaseType.Equals(typeof(BaseEvaluator)))
                   .Select(type => Activator.CreateInstance(type) as BaseEvaluator)
                   .ToList();
        }
    }
}


text:
#include "src/tracing/ipc/producer/producer_ipc_client_impl.h"

#include <cinttypes>

#include <string.h>

#include "perfetto/base/logging.h"
#include "perfetto/base/task_runner.h"
#include "perfetto/ext/base/version.h"
#include "perfetto/ext/ipc/client.h"
#include "perfetto/ext/tracing/core/commit_data_request.h"
#include "perfetto/ext/tracing/core/producer.h"
#include "perfetto/ext/tracing/core/shared_memory_arbiter.h"
#include "perfetto/ext/tracing/core/trace_writer.h"
#include "perfetto/tracing/core/data_source_config.h"
#include "perfetto/tracing/core/data_source_descriptor.h"
#include "perfetto/tracing/core/trace_config.h"

#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
#include "src/tracing/ipc/shared_memory_windows.h"
#else
#include "src/tracing/ipc/posix_shared_memory.h"
#endif

// TODO(fmayer): think to what happens when ProducerIPCClientImpl gets destroyed
// w.r.t. the Producer pointer. Also think to lifetime of the Producer* during
// the callbacks.

namespace perfetto {

// static. (Declared in include/tracing/ipc/producer_ipc_client.h).
std::unique_ptr<TracingService::ProducerEndpoint> ProducerIPCClient::Connect(
    const char* service_sock_name,
    Producer* producer,
    const std::string& producer_name,
    base::TaskRunner* task_runner,
    TracingService::ProducerSMBScrapingMode smb_scraping_mode,
    size_t shared_memory_size_hint_bytes,
    size_t shared_memory_page_size_hint_bytes,
    std::unique_ptr<SharedMemory> shm,
    std::unique_ptr<SharedMemoryArbiter> shm_arbiter,
    ConnectionFlags conn_flags) {
  return std::unique_ptr<TracingService::ProducerEndpoint>(
      new ProducerIPCClientImpl(
          {service_sock_name,
           conn_flags ==
               ProducerIPCClient::ConnectionFlags::kRetryIfUnreachable},
          producer, producer_name, task_runner, smb_scraping_mode,
          shared_memory_size_hint_bytes, shared_memory_page_size_hint_bytes,
          std::move(shm), std::move(shm_arbiter)));
}

// static. (Declared in include/tracing/ipc/producer_ipc_client.h).
std::unique_ptr<TracingService::ProducerEndpoint> ProducerIPCClient::Connect(
    ipc::Client::ConnArgs conn_args,
    Producer* producer,
    const std::string& producer_name,
    base::TaskRunner* task_runner,
    TracingService::ProducerSMBScrapingMode smb_scraping_mode,
    size_t shared_memory_size_hint_bytes,
    size_t shared_memory_page_size_hint_bytes,
    std::unique_ptr<SharedMemory> shm,
    std::unique_ptr<SharedMemoryArbiter> shm_arbiter) {
  return std::unique_ptr<TracingService::ProducerEndpoint>(
      new ProducerIPCClientImpl(std::move(conn_args), producer, producer_name,
                                task_runner, smb_scraping_mode,
                                shared_memory_size_hint_bytes,
                                shared_memory_page_size_hint_bytes,
                                std::move(shm), std::move(shm_arbiter)));
}

ProducerIPCClientImpl::ProducerIPCClientImpl(
    ipc::Client::ConnArgs conn_args,
    Producer* producer,
    const std::string& producer_name,
    base::TaskRunner* task_runner,
    TracingService::ProducerSMBScrapingMode smb_scraping_mode,
    size_t shared_memory_size_hint_bytes,
    size_t shared_memory_page_size_hint_bytes,
    std::unique_ptr<SharedMemory> shm,
    std::unique_ptr<SharedMemoryArbiter> shm_arbiter)
    : producer_(producer),
      task_runner_(task_runner),
      receive_shmem_fd_cb_fuchsia_(
          std::move(conn_args.receive_shmem_fd_cb_fuchsia)),
      ipc_channel_(
          ipc::Client::CreateInstance(std::move(conn_args), task_runner)),
      producer_port_(
          new protos::gen::ProducerPortProxy(this /* event_listener */)),
      shared_memory_(std::move(shm)),
      shared_memory_arbiter_(std::move(shm_arbiter)),
      name_(producer_name),
      shared_memory_page_size_hint_bytes_(shared_memory_page_size_hint_bytes),
      shared_memory_size_hint_bytes_(shared_memory_size_hint_bytes),
      smb_scraping_mode_(smb_scraping_mode) {
  // Check for producer-provided SMB (used by Chrome for startup tracing).
  if (shared_memory_) {
    // We also expect a valid (unbound) arbiter. Bind it to this endpoint now.
    PERFETTO_CHECK(shared_memory_arbiter_);
    shared_memory_arbiter_->BindToProducerEndpoint(this, task_runner_);

    // If the service accepts our SMB, then it must match our requested page
    // layout. The protocol doesn't allow the service to change the size and
    // layout when the SMB is provided by the producer.
    shared_buffer_page_size_kb_ = shared_memory_page_size_hint_bytes_ / 1024;
  }

  ipc_channel_->BindService(producer_port_->GetWeakPtr());
  PERFETTO_DCHECK_THREAD(thread_checker_);
}

ProducerIPCClientImpl::~ProducerIPCClientImpl() {
  PERFETTO_DCHECK_THREAD(thread_checker_);
}

void ProducerIPCClientImpl::Disconnect() {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!producer_port_)
    return;
  // Reset the producer port so that no further IPCs are received and IPC
  // callbacks are no longer executed. Also reset the IPC channel so that the
  // service is notified of the disconnection.
  producer_port_.reset();
  ipc_channel_.reset();
  // Perform disconnect synchronously.
  OnDisconnect();
}

// Called by the IPC layer if the BindService() succeeds.
void ProducerIPCClientImpl::OnConnect() {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  connected_ = true;

  // The IPC layer guarantees that any outstanding callback will be dropped on
  // the floor if producer_port_ is destroyed between the request and the reply.
  // Binding |this| is hence safe.
  ipc::Deferred<protos::gen::InitializeConnectionResponse> on_init;
  on_init.Bind(
      [this](ipc::AsyncResult<protos::gen::InitializeConnectionResponse> resp) {
        OnConnectionInitialized(
            resp.success(),
            resp.success() ? resp->using_shmem_provided_by_producer() : false,
            resp.success() ? resp->direct_smb_patching_supported() : false);
      });
  protos::gen::InitializeConnectionRequest req;
  req.set_producer_name(name_);
  req.set_shared_memory_size_hint_bytes(
      static_cast<uint32_t>(shared_memory_size_hint_bytes_));
  req.set_shared_memory_page_size_hint_bytes(
      static_cast<uint32_t>(shared_memory_page_size_hint_bytes_));
  switch (smb_scraping_mode_) {
    case TracingService::ProducerSMBScrapingMode::kDefault:
      // No need to set the mode, it defaults to use the service default if
      // unspecified.
      break;
    case TracingService::ProducerSMBScrapingMode::kEnabled:
      req.set_smb_scraping_mode(
          protos::gen::InitializeConnectionRequest::SMB_SCRAPING_ENABLED);
      break;
    case TracingService::ProducerSMBScrapingMode::kDisabled:
      req.set_smb_scraping_mode(
          protos::gen::InitializeConnectionRequest::SMB_SCRAPING_DISABLED);
      break;
  }

  int shm_fd = -1;
  if (shared_memory_) {
    req.set_producer_provided_shmem(true);
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
    auto key = static_cast<SharedMemoryWindows*>(shared_memory_.get())->key();
    req.set_shm_key_windows(key);
#else
    shm_fd = static_cast<PosixSharedMemory*>(shared_memory_.get())->fd();
#endif
  }

  req.set_sdk_version(base::GetVersionString());
  producer_port_->InitializeConnection(req, std::move(on_init), shm_fd);

  // Create the back channel to receive commands from the Service.
  ipc::Deferred<protos::gen::GetAsyncCommandResponse> on_cmd;
  on_cmd.Bind(
      [this](ipc::AsyncResult<protos::gen::GetAsyncCommandResponse> resp) {
        if (!resp)
          return;  // The IPC channel was closed and |resp| was auto-rejected.
        OnServiceRequest(*resp);
      });
  producer_port_->GetAsyncCommand(protos::gen::GetAsyncCommandRequest(),
                                  std::move(on_cmd));

  // If there are pending Sync() requests, send them now.
  for (const auto& pending_sync : pending_sync_reqs_)
    Sync(std::move(pending_sync));
  pending_sync_reqs_.clear();
}

void ProducerIPCClientImpl::OnDisconnect() {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  PERFETTO_DLOG("Tracing service connection failure");
  connected_ = false;
  data_sources_setup_.clear();
  producer_->OnDisconnect();  // Note: may delete |this|.
}

void ProducerIPCClientImpl::ScheduleDisconnect() {
  // |ipc_channel| doesn't allow disconnection in the middle of handling
  // an IPC call, so the connection drop must take place over two phases.

  // First, synchronously drop the |producer_port_| so that no more IPC
  // messages are handled.
  producer_port_.reset();

  // Then schedule an async task for performing the remainder of the
  // disconnection operations outside the context of the IPC method handler.
  auto weak_this = weak_factory_.GetWeakPtr();
  task_runner_->PostTask([weak_this]() {
    if (weak_this) {
      weak_this->Disconnect();
    }
  });
}

void ProducerIPCClientImpl::OnConnectionInitialized(
    bool connection_succeeded,
    bool using_shmem_provided_by_producer,
    bool direct_smb_patching_supported) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  // If connection_succeeded == false, the OnDisconnect() call will follow next
  // and there we'll notify the |producer_|. TODO: add a test for this.
  if (!connection_succeeded)
    return;
  is_shmem_provided_by_producer_ = using_shmem_provided_by_producer;
  direct_smb_patching_supported_ = direct_smb_patching_supported;
  producer_->OnConnect();

  // Bail out if the service failed to adopt our producer-allocated SMB.
  // TODO(eseckler): Handle adoption failure more gracefully.
  if (shared_memory_ && !is_shmem_provided_by_producer_) {
    PERFETTO_DLOG("Service failed adopt producer-provided SMB, disconnecting.");
    Disconnect();
    return;
  }
}

void ProducerIPCClientImpl::OnServiceRequest(
    const protos::gen::GetAsyncCommandResponse& cmd) {
  PERFETTO_DCHECK_THREAD(thread_checker_);

  // This message is sent only when connecting to a service running Android Q+.
  // See comment below in kStartDataSource.
  if (cmd.has_setup_data_source()) {
    const auto& req = cmd.setup_data_source();
    const DataSourceInstanceID dsid = req.new_instance_id();
    data_sources_setup_.insert(dsid);
    producer_->SetupDataSource(dsid, req.config());
    return;
  }

  if (cmd.has_start_data_source()) {
    const auto& req = cmd.start_data_source();
    const DataSourceInstanceID dsid = req.new_instance_id();
    const DataSourceConfig& cfg = req.config();
    if (!data_sources_setup_.count(dsid)) {
      // When connecting with an older (Android P) service, the service will not
      // send a SetupDataSource message. We synthesize it here in that case.
      producer_->SetupDataSource(dsid, cfg);
    }
    producer_->StartDataSource(dsid, cfg);
    return;
  }

  if (cmd.has_stop_data_source()) {
    const DataSourceInstanceID dsid = cmd.stop_data_source().instance_id();
    producer_->StopDataSource(dsid);
    data_sources_setup_.erase(dsid);
    return;
  }

  if (cmd.has_setup_tracing()) {
    std::unique_ptr<SharedMemory> ipc_shared_memory;
#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
    const std::string& shm_key = cmd.setup_tracing().shm_key_windows();
    if (!shm_key.empty())
      ipc_shared_memory = SharedMemoryWindows::Attach(shm_key);
#elif PERFETTO_BUILDFLAG(PERFETTO_OS_FUCHSIA)
    // On Fuchsia, the embedder is responsible for routing the shared memory
    // FD, which is provided to this code via a blocking callback.
    PERFETTO_CHECK(receive_shmem_fd_cb_fuchsia_);

    base::ScopedFile shmem_fd(receive_shmem_fd_cb_fuchsia_());
    if (!shmem_fd) {
      // Failure to get a shared memory buffer is a protocol violation and
      // therefore we should drop the Protocol connection.
      PERFETTO_ELOG("Could not get shared memory FD from embedder.");
      ScheduleDisconnect();
      return;
    }

    ipc_shared_memory =
        PosixSharedMemory::AttachToFd(std::move(shmem_fd),
                                      /*require_seals_if_supported=*/false);
#else
    base::ScopedFile shmem_fd = ipc_channel_->TakeReceivedFD();
    if (shmem_fd) {
      // TODO(primiano): handle mmap failure in case of OOM.
      ipc_shared_memory =
          PosixSharedMemory::AttachToFd(std::move(shmem_fd),
                                        /*require_seals_if_supported=*/false);
    }
#endif
    if (ipc_shared_memory) {
      // This is the nominal case used in most configurations, where the service
      // provides the SMB.
      PERFETTO_CHECK(!is_shmem_provided_by_producer_ && !shared_memory_);
      shared_memory_ = std::move(ipc_shared_memory);
      shared_buffer_page_size_kb_ =
          cmd.setup_tracing().shared_buffer_page_size_kb();
      shared_memory_arbiter_ = SharedMemoryArbiter::CreateInstance(
          shared_memory_.get(), shared_buffer_page_size_kb_ * 1024, this,
          task_runner_);
      if (direct_smb_patching_supported_)
        shared_memory_arbiter_->SetDirectSMBPatchingSupportedByService();
    } else {
      // Producer-provided SMB (used by Chrome for startup tracing).
      PERFETTO_CHECK(is_shmem_provided_by_producer_ && shared_memory_ &&
                     shared_memory_arbiter_);
    }
    producer_->OnTracingSetup();
    return;
  }

  if (cmd.has_flush()) {
    // This cast boilerplate is required only because protobuf uses its own
    // uint64 and not stdint's uint64_t. On some 64 bit archs they differ on the
    // type (long vs long long) even though they have the same size.
    const auto* data_source_ids = cmd.flush().data_source_ids().data();
    static_assert(sizeof(data_source_ids[0]) == sizeof(DataSourceInstanceID),
                  "data_source_ids should be 64-bit");
    producer_->Flush(
        cmd.flush().request_id(),
        reinterpret_cast<const DataSourceInstanceID*>(data_source_ids),
        static_cast<size_t>(cmd.flush().data_source_ids().size()));
    return;
  }

  if (cmd.has_clear_incremental_state()) {
    const auto* data_source_ids =
        cmd.clear_incremental_state().data_source_ids().data();
    static_assert(sizeof(data_source_ids[0]) == sizeof(DataSourceInstanceID),
                  "data_source_ids should be 64-bit");
    producer_->ClearIncrementalState(
        reinterpret_cast<const DataSourceInstanceID*>(data_source_ids),
        static_cast<size_t>(
            cmd.clear_incremental_state().data_source_ids().size()));
    return;
  }

  PERFETTO_DFATAL("Unknown async request received from tracing service");
}

void ProducerIPCClientImpl::RegisterDataSource(
    const DataSourceDescriptor& descriptor) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot RegisterDataSource(), not connected to tracing service");
  }
  protos::gen::RegisterDataSourceRequest req;
  *req.mutable_data_source_descriptor() = descriptor;
  ipc::Deferred<protos::gen::RegisterDataSourceResponse> async_response;
  async_response.Bind(
      [](ipc::AsyncResult<protos::gen::RegisterDataSourceResponse> response) {
        if (!response)
          PERFETTO_DLOG("RegisterDataSource() failed: connection reset");
      });
  producer_port_->RegisterDataSource(req, std::move(async_response));
}

void ProducerIPCClientImpl::UpdateDataSource(
    const DataSourceDescriptor& descriptor) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot UpdateDataSource(), not connected to tracing service");
  }
  protos::gen::UpdateDataSourceRequest req;
  *req.mutable_data_source_descriptor() = descriptor;
  ipc::Deferred<protos::gen::UpdateDataSourceResponse> async_response;
  async_response.Bind(
      [](ipc::AsyncResult<protos::gen::UpdateDataSourceResponse> response) {
        if (!response)
          PERFETTO_DLOG("UpdateDataSource() failed: connection reset");
      });
  producer_port_->UpdateDataSource(req, std::move(async_response));
}

void ProducerIPCClientImpl::UnregisterDataSource(const std::string& name) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot UnregisterDataSource(), not connected to tracing service");
    return;
  }
  protos::gen::UnregisterDataSourceRequest req;
  req.set_data_source_name(name);
  producer_port_->UnregisterDataSource(
      req, ipc::Deferred<protos::gen::UnregisterDataSourceResponse>());
}

void ProducerIPCClientImpl::RegisterTraceWriter(uint32_t writer_id,
                                                uint32_t target_buffer) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot RegisterTraceWriter(), not connected to tracing service");
    return;
  }
  protos::gen::RegisterTraceWriterRequest req;
  req.set_trace_writer_id(writer_id);
  req.set_target_buffer(target_buffer);
  producer_port_->RegisterTraceWriter(
      req, ipc::Deferred<protos::gen::RegisterTraceWriterResponse>());
}

void ProducerIPCClientImpl::UnregisterTraceWriter(uint32_t writer_id) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot UnregisterTraceWriter(), not connected to tracing service");
    return;
  }
  protos::gen::UnregisterTraceWriterRequest req;
  req.set_trace_writer_id(writer_id);
  producer_port_->UnregisterTraceWriter(
      req, ipc::Deferred<protos::gen::UnregisterTraceWriterResponse>());
}

void ProducerIPCClientImpl::CommitData(const CommitDataRequest& req,
                                       CommitDataCallback callback) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG("Cannot CommitData(), not connected to tracing service");
    return;
  }
  ipc::Deferred<protos::gen::CommitDataResponse> async_response;
  // TODO(primiano): add a test that destroys ProducerIPCClientImpl soon after
  // this call and checks that the callback is dropped.
  if (callback) {
    async_response.Bind(
        [callback](ipc::AsyncResult<protos::gen::CommitDataResponse> response) {
          if (!response) {
            PERFETTO_DLOG("CommitData() failed: connection reset");
            return;
          }
          callback();
        });
  }
  producer_port_->CommitData(req, std::move(async_response));
}

void ProducerIPCClientImpl::NotifyDataSourceStarted(DataSourceInstanceID id) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot NotifyDataSourceStarted(), not connected to tracing service");
    return;
  }
  protos::gen::NotifyDataSourceStartedRequest req;
  req.set_data_source_id(id);
  producer_port_->NotifyDataSourceStarted(
      req, ipc::Deferred<protos::gen::NotifyDataSourceStartedResponse>());
}

void ProducerIPCClientImpl::NotifyDataSourceStopped(DataSourceInstanceID id) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot NotifyDataSourceStopped(), not connected to tracing service");
    return;
  }
  protos::gen::NotifyDataSourceStoppedRequest req;
  req.set_data_source_id(id);
  producer_port_->NotifyDataSourceStopped(
      req, ipc::Deferred<protos::gen::NotifyDataSourceStoppedResponse>());
}

void ProducerIPCClientImpl::ActivateTriggers(
    const std::vector<std::string>& triggers) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    PERFETTO_DLOG(
        "Cannot ActivateTriggers(), not connected to tracing service");
    return;
  }
  protos::gen::ActivateTriggersRequest proto_req;
  for (const auto& name : triggers) {
    *proto_req.add_trigger_names() = name;
  }
  producer_port_->ActivateTriggers(
      proto_req, ipc::Deferred<protos::gen::ActivateTriggersResponse>());
}

void ProducerIPCClientImpl::Sync(std::function<void()> callback) {
  PERFETTO_DCHECK_THREAD(thread_checker_);
  if (!connected_) {
    pending_sync_reqs_.emplace_back(std::move(callback));
    return;
  }
  ipc::Deferred<protos::gen::SyncResponse> resp;
  resp.Bind([callback](ipc::AsyncResult<protos::gen::SyncResponse>) {
    // Here we ACK the callback even if the service replies with a failure
    // (i.e. the service is too old and doesn't understand Sync()). In that
    // case the service has still seen the request, the IPC roundtrip is
    // still a (weaker) linearization fence.
    callback();
  });
  producer_port_->Sync(protos::gen::SyncRequest(), std::move(resp));
}

std::unique_ptr<TraceWriter> ProducerIPCClientImpl::CreateTraceWriter(
    BufferID target_buffer,
    BufferExhaustedPolicy buffer_exhausted_policy) {
  // This method can be called by different threads. |shared_memory_arbiter_| is
  // thread-safe but be aware of accessing any other state in this function.
  return shared_memory_arbiter_->CreateTraceWriter(target_buffer,
                                                   buffer_exhausted_policy);
}

SharedMemoryArbiter* ProducerIPCClientImpl::MaybeSharedMemoryArbiter() {
  return shared_memory_arbiter_.get();
}

bool ProducerIPCClientImpl::IsShmemProvidedByProducer() const {
  return is_shmem_provided_by_producer_;
}

void ProducerIPCClientImpl::NotifyFlushComplete(FlushRequestID req_id) {
  return shared_memory_arbiter_->NotifyFlushComplete(req_id);
}

SharedMemory* ProducerIPCClientImpl::shared_memory() const {
  return shared_memory_.get();
}

size_t ProducerIPCClientImpl::shared_buffer_page_size_kb() const {
  return shared_buffer_page_size_kb_;
}

}  // namespace perfetto