text:
package com.google.cloud.storage;

import static com.google.cloud.storage.StorageV2ProtoUtils.fmtProto;
import static com.google.cloud.storage.StorageV2ProtoUtils.seekReadObjectRequest;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.cloud.storage.jqwik.StorageArbitraries;
import com.google.storage.v2.ReadObjectRequest;
import net.jqwik.api.Arbitraries;
import net.jqwik.api.Arbitrary;
import net.jqwik.api.Combinators;
import net.jqwik.api.Example;
import net.jqwik.api.ForAll;
import net.jqwik.api.Property;
import net.jqwik.api.Provide;

public final class StorageV2ProtoUtilsTest {

  @Example
  void validation_nullOffset_effectiveMin() {
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), null, 0L);
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), null, null);
  }

  @Example
  void validation_nullLimit_effectiveMax() {
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), 0L, null);
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), null, null);
  }

  @Example
  void validation_offset_lteq_limit() {
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), 3L, 2L);
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), 0L, 0L);
    seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), 1L, 1L);
  }

  @Example
  void validation_offset_gteq_0() {
    assertThrows(
        IllegalArgumentException.class,
        () -> seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), -1L, null));
  }

  @Example
  void validation_limit_gteq_0() {
    assertThrows(
        IllegalArgumentException.class,
        () -> seekReadObjectRequest(ReadObjectRequest.getDefaultInstance(), null, -1L));
  }

  @Property(tries = 100_000)
  void seek(@ForAll("seekCases") SeekCase srr) {
    Long offset = srr.offset;
    Long limit = srr.limit;

    // I miss pattern matching...
    if (offset == null && limit == null) {
      ReadObjectRequest seek = seekReadObjectRequest(srr.req, offset, limit);
      assertThat(seek).isSameInstanceAs(srr.req);
    } else if (offset != null && limit == null) {
      ReadObjectRequest seek = seekReadObjectRequest(srr.req, offset, limit);
      assertThat(seek.getReadOffset()).isEqualTo(offset);
    } else if (offset == null && limit != null) {
      ReadObjectRequest seek = seekReadObjectRequest(srr.req, offset, limit);
      assertThat(seek.getReadLimit()).isEqualTo(limit);
    } else {
      ReadObjectRequest seek = seekReadObjectRequest(srr.req, offset, limit);
      assertThat(seek.getReadOffset()).isEqualTo(offset);
      assertThat(seek.getReadLimit()).isEqualTo(limit);
    }
  }

  @Provide("seekCases")
  Arbitrary<SeekCase> arbitrarySeekCase() {
    return Combinators.combine(
            StorageArbitraries.objects().name(),
            Arbitraries.longs().greaterOrEqual(0).injectNull(0.6),
            Arbitraries.longs().greaterOrEqual(0).injectNull(0.6),
            Arbitraries.longs().greaterOrEqual(0).injectNull(0.3),
            Arbitraries.longs().greaterOrEqual(0).injectNull(0.3))
        .as(SeekCase::of);
  }

  private static final class SeekCase {
    private final ReadObjectRequest req;
    private final Long offset;
    private final Long limit;

    public SeekCase(ReadObjectRequest req, Long offset, Long limit) {
      this.req = req;
      this.offset = offset;
      this.limit = limit;
    }

    @Override
    public String toString() {
      return "SeekReadRequest{"
          + "req="
          + fmtProto(req)
          + ", offset="
          + offset
          + ", limit="
          + limit
          + '}';
    }

    private static SeekCase of(
        String name, Long embedOffset, Long embedLimit, Long offset, Long limit) {
      ReadObjectRequest.Builder b = ReadObjectRequest.newBuilder().setObject(name);
      if (embedOffset != null) {
        b.setReadOffset(embedOffset);
      }
      if (embedLimit != null) {
        b.setReadLimit(embedLimit);
      }
      return new SeekCase(b.build(), offset, limit);
    }
  }
}


text:
#ifndef __c2_mantran_mdl_demo_v14_h__
#define __c2_mantran_mdl_demo_v14_h__

/* Include files */
#include "sfc_sf.h"
#include "sfc_mex.h"
#include "rtw_capi.h"
#include "rtw_modelmap.h"

/* Type Definitions */

typedef struct {
  SimStruct *S;
  void *c2_testPointAddrMap[9];
  uint32_T chartNumber;
  uint32_T instanceNumber;
  uint8_T c2_TWAIT;
  uint8_T c2_is_active_c2_mantran_mdl_demo_v14;
  uint8_T c2_is_active_gear_state;
  uint8_T c2_is_active_selection_state;
  uint8_T c2_is_gear_state;
  uint8_T c2_is_selection_state;
  uint8_T c2_temporalCounter_i1;
  uint8_T c2_tp_downshifting;
  uint8_T c2_tp_first;
  uint8_T c2_tp_fourth;
  uint8_T c2_tp_gear_state;
  uint8_T c2_tp_second;
  uint8_T c2_tp_selection_state;
  uint8_T c2_tp_steady_state;
  uint8_T c2_tp_third;
  uint8_T c2_tp_upshifting;
  ChartInfoStruct chartInfo;
  rtwCAPI_ModelMappingInfo c2_testPointMappingInfo;
} SFc2_mantran_mdl_demo_v14InstanceStruct;

/* Named Constants */

/* Variable Declarations */

/* Variable Definitions */

/* Function Declarations */
const mxArray *sf_c2_mantran_mdl_demo_v14_get_eml_resolved_functions_info(void);

/* Function Definitions */

extern void sf_c2_mantran_mdl_demo_v14_get_check_sum(mxArray *plhs[]);
extern void c2_mantran_mdl_demo_v14_method_dispatcher(SimStruct *S, int_T
 method, void *data);

#endif

redpajama_set_name: RedPajamaGithub


text:
namespace Fixtures.Azure.AcceptanceTestsAzureResource.Models
{
    using Azure;
    using AcceptanceTestsAzureResource;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Some resource
    /// <see href="http://tempuri.org" />
    /// </summary>
    public partial class ResourceInner
    {
        /// <summary>
        /// Initializes a new instance of the ResourceInner class.
        /// </summary>
        public ResourceInner() { }

        /// <summary>
        /// Initializes a new instance of the ResourceInner class.
        /// </summary>
        /// <param name="id">Resource Id</param>
        /// <param name="type">Resource Type</param>
        /// <param name="location">Resource Location</param>
        /// <param name="name">Resource Name</param>
        public ResourceInner(string id = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string location = default(string), string name = default(string))
        {
            Id = id;
            Type = type;
            Tags = tags;
            Location = location;
            Name = name;
        }

        /// <summary>
        /// Gets resource Id
        /// </summary>
        [JsonProperty(PropertyName = "id")]
        public string Id { get; protected set; }

        /// <summary>
        /// Gets resource Type
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; protected set; }

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "tags")]
        public IDictionary<string, string> Tags { get; set; }

        /// <summary>
        /// Gets or sets resource Location
        /// </summary>
        [JsonProperty(PropertyName = "location")]
        public string Location { get; set; }

        /// <summary>
        /// Gets resource Name
        /// </summary>
        [JsonProperty(PropertyName = "name")]
        public string Name { get; protected set; }

    }
}


text:
namespace Caliburn.Micro {
    using System;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Collections.Generic;

#if !SILVERLIGHT
    using System.ComponentModel;
#endif

    /// <summary>
    /// A service that is capable of properly binding values to a method's parameters and creating instances of <see cref="IResult"/>.
    /// </summary>
    public static class MessageBinder {
        /// <summary>
        /// The special parameter values recognized by the message binder along with their resolvers.
        /// </summary>
        public static readonly Dictionary<string, Func<ActionExecutionContext, object>> SpecialValues =
            new Dictionary<string, Func<ActionExecutionContext, object>>{
                { "$eventargs", c => c.EventArgs },
                { "$datacontext", c => c.Source.DataContext },
                { "$source", c => c.Source },
                { "$executioncontext", c => c },
                { "$view", c => c.View }
            };

        /// <summary>
        /// Custom converters used by the framework registered by detination type for which the will be selected.
        /// The converter is passed the existing value to convert and a "context" object.
        /// </summary>
        public static readonly Dictionary<Type, Func<object, object, object>> CustomConverters = new Dictionary<Type, Func<object, object, object>>();

        /// <summary>
        /// Determines the parameters that a method should be invoked with.
        /// </summary>
        /// <param name="context">The action execution context.</param>
        /// <param name="requiredParameters">The parameters required to complete the invocation.</param>
        /// <returns>The actual parameter values.</returns>
        public static object[] DetermineParameters(ActionExecutionContext context, ParameterInfo[] requiredParameters) {
            var providedValues = context.Message.Parameters.Select(x => x.Value).ToArray();
            var finalValues = new object[requiredParameters.Length];

            for(int i = 0; i < requiredParameters.Length; i++) {
                var parameterType = requiredParameters[i].ParameterType;
                var parameterValue = providedValues[i];
                var parameterAsString = parameterValue as string;

                if(parameterAsString != null)
                    finalValues[i] = CoerceValue(parameterType, EvaluateParameter(parameterAsString, parameterType, context), context);
                else finalValues[i] = CoerceValue(parameterType, parameterValue, context);
            }

            return finalValues;
        }

        /// <summary>
        /// Transforms the textual parameter into the actual parameter.
        /// </summary>
        public static Func<string, Type, ActionExecutionContext, object> EvaluateParameter = (text, parameterType, context) => {
            var lookup = text.ToLower(CultureInfo.InvariantCulture);
            Func<ActionExecutionContext, object> resolver;
            return SpecialValues.TryGetValue(lookup, out resolver) ? resolver(context) : text;
        };

        /// <summary>
        /// Coerces the provided value to the destination type.
        /// </summary>
        /// <param name="destinationType">The destination type.</param>
        /// <param name="providedValue">The provided value.</param>
        /// <param name="context">An optional context value which can be used during conversion.</param>
        /// <returns>The coerced value.</returns>
        public static object CoerceValue(Type destinationType, object providedValue, object context) {
            if(providedValue == null)
                return GetDefaultValue(destinationType);

            if (CustomConverters.ContainsKey(destinationType))
                return CustomConverters[destinationType](providedValue, context);

            var providedType = providedValue.GetType();

            if(destinationType.IsAssignableFrom(providedType))
                return providedValue;

            try {
                var converter = TypeDescriptor.GetConverter(destinationType);

                if(converter.CanConvertFrom(providedType))
                    return converter.ConvertFrom(providedValue);

                converter = TypeDescriptor.GetConverter(providedType);

                if(converter.CanConvertTo(destinationType))
                    return converter.ConvertTo(providedValue, destinationType);

                if (destinationType.IsEnum) {
                    var stringValue = providedValue as string;
                    if(stringValue != null)
                        return Enum.Parse(destinationType, stringValue, true);
                    return Enum.ToObject(destinationType, providedValue);
                }

                if(typeof(Guid).IsAssignableFrom(destinationType)) {
                    var stringValue = providedValue as string;
                    if(stringValue != null) {
                        return new Guid(stringValue);
                    }
                }
            }
            catch {
                return GetDefaultValue(destinationType);
            }

            try {
                return Convert.ChangeType(providedValue, destinationType, CultureInfo.CurrentUICulture);
            }
            catch {
                return GetDefaultValue(destinationType);
            }
        }

        /// <summary>
        /// Gets the default value for a type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The default value.</returns>
        public static object GetDefaultValue(Type type) {
            return type.IsClass || type.IsInterface ? null : Activator.CreateInstance(type);
        }
    }
}


text:
class EmisorsController < ApplicationController
  before_filter :require_login
  before_filter :is_super_user, except: [:turnos_otros_dias]
  before_filter :is_admin_or_auxiliar_estadistica, only: [:turnos_otros_dias]
  before_action :find_emisor, only: [:new, :turnos_otros_dias]

  def new
    @emisor = Emisor.new
  end

  def edit
    if Emisor.first
      @emisor = Emisor.first
    else
      redirect_to "new"
    end
  end

  def create
    @emisor = Emisor.new(emisor_params)
    if @emisor.save
      redirect_to facturas_path, :notice => "Parámetros configurados correctamente"
    else
      render "new"
    end
  end

  def update
    @emisor = Emisor.first
    @emisor.update(emisor_params)
    respond_to do |format|
      format.html{
        if @emisor
          redirect_to facturas_path, :notice => "Parámetros configurados correctamente"
        else
          render "edit"
        end
      }
      format.json { respond_with_bip(@emisor) }
    end

  end

  def turnos_otros_dias
    if @created_emisor.otros_dias
      @created_emisor.otros_dias = false
    else
      @created_emisor.otros_dias = true
    end
    @created_emisor.save
    render :text => "#{@created_emisor.otros_dias}"
  end

  private

  def emisor_params
    params.require(:emisor).permit(:ruc,
      :nombre_establecimiento,
      :numero_inicial_factura,
      :saldo_inicial_inventario,
      :numero_turnos_fisiatria)
  end

  def find_emisor
    @created_emisor = Emisor.first
  end
end


text:
package sample.helloworld.impl;

import akka.Done;
import akka.NotUsed;
import com.lightbend.lagom.javadsl.api.ServiceCall;
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRef;
import com.lightbend.lagom.javadsl.persistence.PersistentEntityRegistry;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;

import javax.inject.Inject;
import sample.helloworld.api.GreetingMessage;
import sample.helloworld.api.HelloService;
import sample.helloworld.impl.HelloCommand.*;

/**
 * Implementation of the HelloService.
 */
public class HelloServiceImpl implements HelloService {

  private final PersistentEntityRegistry persistentEntityRegistry;

  @Inject
  public HelloServiceImpl(PersistentEntityRegistry persistentEntityRegistry) {
    this.persistentEntityRegistry = persistentEntityRegistry;
    persistentEntityRegistry.register(HelloWorld.class);
  }

  @Override
  public ServiceCall<NotUsed, String> hello(String id) {
    return request -> {
      // The integration test replaces lagom with other text, to test hot reloads
      if (id.equals("lagom")) {
        return CompletableFuture.completedFuture("Hello to you too!");
      } else {
        // Look up the hello world entity for the given ID.
        PersistentEntityRef<HelloCommand> ref = persistentEntityRegistry.refFor(HelloWorld.class, id);
        // Ask the entity the Hello command.
        return ref.ask(new Hello(id, Optional.empty()));
      }
    };
  }

  @Override
  public ServiceCall<GreetingMessage, Done> useGreeting(String id) {
    return request -> {
      // Look up the hello world entity for the given ID.
      PersistentEntityRef<HelloCommand> ref = persistentEntityRegistry.refFor(HelloWorld.class, id);
      // Tell the entity to use the greeting message specified.
      return ref.ask(new UseGreetingMessage(request.message));
    };

  }

}


text:
layout: guide
doc_stub: false
search: true
section: Mutations
title: Mutation Root
desc: The Mutation object is the entry point for mutation operations.
index: 0
---

GraphQL mutations all begin with the `mutation` keyword:

```graphql
mutation($accountNumber: ID!, $newBalance: Int!) {
# ^^^^ here
  setAccountBalance(accountNumber: $accountNumber, newBalance: $newBalance) {
    # ...
  }
}
```

Operations that begin with `mutation` get special treatment by the GraphQL runtime: root fields are guaranteed
to be executed sequentially. This way, the effect of a series of mutations is predictable.

Mutations are executed by a specific GraphQL object, `Mutation`. This object is defined like any other GraphQL object:

```ruby
class Types::Mutation < Types::BaseObject
  # ...
end
```

Then, it must be attached to your schema with the `mutation(...)` configuration:

```ruby
class Schema < GraphQL::Schema
  # ...
  mutation(Types::Mutation)
end
```

Now, whenever an incoming request uses the `mutation` keyword, it will go to `Mutation`.

See {% internal_link "Mutation Classes", "/mutations/mutation_classes" %} for some helpers to define mutation fields.


text:
require 'spec_helper'
require 'ostruct'

describe Agents::PostAgent do
  before do
    @valid_options = {
      'post_url' => "http://www.example.com",
      'expected_receive_period_in_days' => 1,
      'payload' => {
        'default' => 'value'
      }
    }
    @valid_params = {
      name: "somename",
      options: @valid_options
    }

    @checker = Agents::PostAgent.new(@valid_params)
    @checker.user = users(:jane)
    @checker.save!

    @event = Event.new
    @event.agent = agents(:jane_weather_agent)
    @event.payload = {
      'somekey' => 'somevalue',
      'someotherkey' => {
        'somekey' => 'value'
      }
    }
    @requests = 0
    @sent_requests = Hash.new { |hash, method| hash[method] = [] }

    stub_request(:any, /:/).to_return { |request|
      method = request.method
      @requests += 1
      @sent_requests[method] << req = OpenStruct.new(uri: request.uri)
      case method
      when :get, :delete
        req.data = request.uri.query
      else
        case request.headers['Content-Type'][/\A[^;\s]+/]
        when 'application/x-www-form-urlencoded'
          req.data = request.body
        when 'application/json'
          req.data = ActiveSupport::JSON.decode(request.body)
        else
          raise "unexpected Content-Type: #{content_type}"
        end
      end
      { status: 200, body: "ok" }
    }
  end

  it_behaves_like WebRequestConcern

  describe "making requests" do
    it "can make requests of each type" do
      %w[get put post patch delete].each.with_index(1) do |verb, index|
        @checker.options['method'] = verb
        expect(@checker).to be_valid
        @checker.check
        expect(@requests).to eq(index)
        expect(@sent_requests[verb.to_sym].length).to eq(1)
      end
    end
  end

  describe "#receive" do
    it "can handle multiple events and merge the payloads with options['payload']" do
      event1 = Event.new
      event1.agent = agents(:bob_weather_agent)
      event1.payload = {
        'xyz' => 'value1',
        'message' => 'value2',
        'default' => 'value2'
      }

      expect {
        expect {
          @checker.receive([@event, event1])
        }.to change { @sent_requests[:post].length }.by(2)
      }.not_to change { @sent_requests[:get].length }

      expect(@sent_requests[:post][0].data).to eq(@event.payload.merge('default' => 'value').to_query)
      expect(@sent_requests[:post][1].data).to eq(event1.payload.to_query)
    end

    it "can make GET requests" do
      @checker.options['method'] = 'get'

      expect {
        expect {
          @checker.receive([@event])
        }.to change { @sent_requests[:get].length }.by(1)
      }.not_to change { @sent_requests[:post].length }

      expect(@sent_requests[:get][0].data).to eq(@event.payload.merge('default' => 'value').to_query)
    end

    it "can make a GET request merging params in post_url, payload and event" do
      @checker.options['method'] = 'get'
      @checker.options['post_url'] = "http://example.com/a/path?existing_param=existing_value"
      @event.payload = {
        "some_param" => "some_value",
        "another_param" => "another_value"
      }
      @checker.receive([@event])
      uri = @sent_requests[:get].first.uri
      # parameters are alphabetically sorted by Faraday
      expect(uri.request_uri).to eq("/a/path?another_param=another_value&default=value&existing_param=existing_value&some_param=some_value")
    end

    it "can skip merging the incoming event when no_merge is set, but it still interpolates" do
      @checker.options['no_merge'] = 'true'
      @checker.options['payload'] = {
        'key' => 'it said: {{ someotherkey.somekey }}'
      }
      @checker.receive([@event])
      expect(@sent_requests[:post].first.data).to eq({ 'key' => 'it said: value' }.to_query)
    end

    it "interpolates when receiving a payload" do
      @checker.options['post_url'] = "https://{{ domain }}/{{ variable }}?existing_param=existing_value"
      @event.payload = {
        'domain' => 'google.com',
        'variable' => 'a_variable'
      }
      @checker.receive([@event])
      uri = @sent_requests[:post].first.uri
      expect(uri.scheme).to eq('https')
      expect(uri.host).to eq('google.com')
      expect(uri.path).to eq('/a_variable')
      expect(uri.query).to eq("existing_param=existing_value")
    end
  end

  describe "#check" do
    it "sends options['payload'] as a POST request" do
      expect {
        @checker.check
      }.to change { @sent_requests[:post].length }.by(1)

      expect(@sent_requests[:post][0].data).to eq(@checker.options['payload'].to_query)
    end

    it "sends options['payload'] as JSON as a POST request" do
      @checker.options['content_type'] = 'json'
      expect {
        @checker.check
      }.to change { @sent_requests[:post].length }.by(1)

      expect(@sent_requests[:post][0].data).to eq(@checker.options['payload'])
    end

    it "sends options['payload'] as a GET request" do
      @checker.options['method'] = 'get'
      expect {
        expect {
          @checker.check
        }.to change { @sent_requests[:get].length }.by(1)
      }.not_to change { @sent_requests[:post].length }

      expect(@sent_requests[:get][0].data).to eq(@checker.options['payload'].to_query)
    end
  end

  describe "#working?" do
    it "checks if events have been received within expected receive period" do
      expect(@checker).not_to be_working
      Agents::PostAgent.async_receive @checker.id, [@event.id]
      expect(@checker.reload).to be_working
      two_days_from_now = 2.days.from_now
      stub(Time).now { two_days_from_now }
      expect(@checker.reload).not_to be_working
    end
  end

  describe "validation" do
    before do
      expect(@checker).to be_valid
    end

    it "should validate presence of post_url" do
      @checker.options['post_url'] = ""
      expect(@checker).not_to be_valid
    end

    it "should validate presence of expected_receive_period_in_days" do
      @checker.options['expected_receive_period_in_days'] = ""
      expect(@checker).not_to be_valid
    end

    it "should validate method as post, get, put, patch, or delete, defaulting to post" do
      @checker.options['method'] = ""
      expect(@checker.method).to eq("post")
      expect(@checker).to be_valid

      @checker.options['method'] = "POST"
      expect(@checker.method).to eq("post")
      expect(@checker).to be_valid

      @checker.options['method'] = "get"
      expect(@checker.method).to eq("get")
      expect(@checker).to be_valid

      @checker.options['method'] = "patch"
      expect(@checker.method).to eq("patch")
      expect(@checker).to be_valid

      @checker.options['method'] = "wut"
      expect(@checker.method).to eq("wut")
      expect(@checker).not_to be_valid
    end

    it "should validate that no_merge is 'true' or 'false', if present" do
      @checker.options['no_merge'] = ""
      expect(@checker).to be_valid

      @checker.options['no_merge'] = "true"
      expect(@checker).to be_valid

      @checker.options['no_merge'] = "false"
      expect(@checker).to be_valid

      @checker.options['no_merge'] = false
      expect(@checker).to be_valid

      @checker.options['no_merge'] = true
      expect(@checker).to be_valid

      @checker.options['no_merge'] = 'blarg'
      expect(@checker).not_to be_valid
    end

    it "should validate payload as a hash, if present" do
      @checker.options['payload'] = ""
      expect(@checker).to be_valid

      @checker.options['payload'] = "hello"
      expect(@checker).not_to be_valid

      @checker.options['payload'] = ["foo", "bar"]
      expect(@checker).not_to be_valid

      @checker.options['payload'] = { 'this' => 'that' }
      expect(@checker).to be_valid
    end

    it "requires headers to be a hash, if present" do
      @checker.options['headers'] = [1,2,3]
      expect(@checker).not_to be_valid

      @checker.options['headers'] = "hello world"
      expect(@checker).not_to be_valid

      @checker.options['headers'] = ""
      expect(@checker).to be_valid

      @checker.options['headers'] = {}
      expect(@checker).to be_valid

      @checker.options['headers'] = { "Authorization" => "foo bar" }
      expect(@checker).to be_valid
    end
  end
end


text:
#include "postgres.h"
#include "miscadmin.h"
#include "utils/guc.h"
#include "catalog/gp_segment_config.h"
#include "cdb/cdbvars.h"
#include "libpq-fe.h"
#include "libpq-int.h"
#include "cdb/cdbfts.h"
#include "cdb/cdbdisp.h"
#include "cdb/cdbutil.h"
#include "cdb/cdbdisp.h"
#include "lib/stringinfo.h"
#include "libpq/libpq-be.h"
#include "utils/memutils.h"
#include "utils/resource_manager.h"
#include "utils/resgroup-ops.h"
#include "storage/bfz.h"
#include "storage/proc.h"
#include "cdb/memquota.h"

/*
 * ----------------
 *		GUC/global variables
 *
 *	Initial values are set by guc.c function "InitializeGUCOptions" called
 *	*very* early during postmaster, postgres, or bootstrap initialization.
 * ----------------
 */

GpRoleValue Gp_role;			/* Role paid by this Greenplum Database
								 * backend */
char	   *gp_role_string;		/* Staging area for guc.c */
bool		gp_set_read_only;	/* Staging area for guc.c */

GpRoleValue Gp_session_role;	/* Role paid by this Greenplum Database
								 * backend */
char	   *gp_session_role_string; /* Staging area for guc.c */

bool		Gp_is_writer;		/* is this qExec a "writer" process. */

int			gp_session_id;		/* global unique id for session. */

char	   *qdHostname;			/* QD hostname */
int			qdPostmasterPort;	/* Master Segment Postmaster port. */

int			gp_command_count;	/* num of commands from client */

bool		gp_debug_pgproc;	/* print debug info for PGPROC */
bool		Debug_print_prelim_plan;	/* Shall we log argument of
										 * cdbparallelize? */

bool		Debug_print_slice_table;	/* Shall we log the slice table? */

bool		Debug_resource_group;	/* Shall we log the resource group? */

bool		gp_external_enable_exec = true; /* allow ext tables with EXECUTE */

int			gp_external_max_segs;	/* max segdbs per gpfdist/gpfdists URI */

int			gp_safefswritesize; /* set for safe AO writes in non-mature fs */

int			gp_connections_per_thread;	/* How many libpq connections are
										 * handled in each thread */

int			gp_cached_gang_threshold;	/* How many gangs to keep around from
										 * stmt to stmt. */

int			Gp_segment = UNDEF_SEGMENT; /* What content this QE is handling. */

bool		Gp_write_shared_snapshot;	/* tell the writer QE to write the
										 * shared snapshot */

bool		gp_reraise_signal = false;	/* try to dump core when we get
										 * SIGABRT & SIGSEGV */

bool		gp_set_proc_affinity = false;	/* set processor affinity (if
											 * platform supports it) */

int			gp_reject_percent_threshold;	/* SREH reject % kicks off only
											 * after * <num> records have been
											 * processed	*/

int			gp_max_csv_line_length; /* max allowed len for csv data line in
									 * bytes */

bool		gp_select_invisible = false;	/* debug mode to allow select to
											 * see "invisible" rows */

/*
 * Configurable timeout for snapshot add: exceptionally busy systems may take
 * longer than our old hard-coded version -- so here is a tuneable version.
 */
int			gp_snapshotadd_timeout = 10;

/*
 * Probe retry count for fts prober.
 */
int			gp_fts_probe_retries = 5;

/*
 * Probe timeout for fts prober.
 */
int			gp_fts_probe_timeout = 20;

/*
 * Polling interval for the fts prober. A scan of the entire system starts
 * every time this expires.
 */
int			gp_fts_probe_interval = 60;

/*
 * Number of threads to use for probe of segments (it is a good idea to have this
 * larger than the number of segments per host.
 */
int			gp_fts_probe_threadcount = 16;

/*
 * Controls parallel segment transition (failover).
 */
bool		gp_fts_transition_parallel = true;

/* The number of retries to request a segment state transition. */
int			gp_fts_transition_retries = 5;

/* Timeout to request a segment state transition. */
int			gp_fts_transition_timeout = 3600;

/*
 * When we have certain types of failures during gang creation which indicate
 * that a segment is in recovery mode we may be able to retry.
 */
int			gp_gang_creation_retry_count = 5;	/* disable by default */
int			gp_gang_creation_retry_timer = 2000;	/* 2000ms */

/*
 * gp_enable_slow_writer_testmode
 *
 * In order facilitate testing of reader-gang/writer-gang synchronization,
 * this inserts a pg_usleep call at the start of writer-gang processing.
 */
bool		gp_enable_slow_writer_testmode = false;

/*
 * gp_enable_slow_cursor_testmode
 *
 * In order facilitate testing of reader-gang/writer-gang synchronization,
 * this inserts a pg_usleep call at the start of cursor-gang processing.
 */
bool		gp_enable_slow_cursor_testmode = false;

/*
 * TCP port the Interconnect listens on for incoming connections from other
 * backends.  Assigned by initMotionLayerIPC() at process startup.  This port
 * is used for the duration of this process and should never change.
 */
uint32		Gp_listener_port;

int			Gp_max_packet_size; /* max Interconnect packet size */

int			Gp_interconnect_queue_depth = 4;	/* max number of messages
												 * waiting in rx-queue before
												 * we drop. */
int			Gp_interconnect_snd_queue_depth = 2;
int			Gp_interconnect_timer_period = 5;
int			Gp_interconnect_timer_checking_period = 20;
int			Gp_interconnect_default_rtt = 20;
int			Gp_interconnect_min_rto = 20;
int			Gp_interconnect_fc_method = INTERCONNECT_FC_METHOD_LOSS;
int			Gp_interconnect_transmit_timeout = 3600;
int			Gp_interconnect_min_retries_before_timeout = 100;
int			Gp_interconnect_debug_retry_interval = 10;

int			Gp_interconnect_hash_multiplier = 2;	/* sets the size of the
													 * hash table used by the
													 * UDP-IC */

int			interconnect_setup_timeout = 7200;

int			Gp_interconnect_type = INTERCONNECT_TYPE_UDPIFC;

bool		gp_interconnect_aggressive_retry = true;	/* fast-track app-level
														 * retry */

bool		gp_interconnect_full_crc = false;	/* sanity check UDP data. */

bool		gp_interconnect_log_stats = false;	/* emit stats at log-level */

bool		gp_interconnect_cache_future_packets = true;

int			Gp_udp_bufsize_k;	/* UPD recv buf size, in KB */

#ifdef USE_ASSERT_CHECKING
/*
 * UDP-IC Test hooks (for fault injection).
 *
 * Dropseg: specifies which segment to apply the drop_percent to.
 */
int			gp_udpic_dropseg = UNDEF_SEGMENT;
int			gp_udpic_dropxmit_percent = 0;
int			gp_udpic_dropacks_percent = 0;
int			gp_udpic_fault_inject_percent = 0;
int			gp_udpic_fault_inject_bitmap = 0;
int			gp_udpic_network_disable_ipv6 = 0;
#endif

/*
 * Each slice table has a unique ID (certain commands like "vacuum analyze"
 * run many many slice-tables for each gp_command_id).
 */
uint32		gp_interconnect_id = 0;

/* --------------------------------------------------------------------------------------------------
 * Greenplum Optimizer GUCs
 */

double		gp_motion_cost_per_row = 0;
int			gp_segments_for_planner = 0;

int			gp_hashagg_default_nbatches = 32;

bool		gp_adjust_selectivity_for_outerjoins = TRUE;
bool		gp_selectivity_damping_for_scans = false;
bool		gp_selectivity_damping_for_joins = false;
double		gp_selectivity_damping_factor = 1;
bool		gp_selectivity_damping_sigsort = true;

int			gp_hashjoin_tuples_per_bucket = 5;
int			gp_hashagg_groups_per_bucket = 5;

/* default value to 0, which means we do not try to control number of spill batches */
int			gp_hashagg_spillbatch_min = 0;
int			gp_hashagg_spillbatch_max = 0;

/* Analyzing aid */
int			gp_motion_slice_noop = 0;

/* Greenplum Database Experimental Feature GUCs */
int			gp_distinct_grouping_sets_threshold = 32;
bool		gp_enable_explain_allstat = FALSE;
bool		gp_enable_motion_deadlock_sanity = FALSE;	/* planning time sanity
														 * check */

#ifdef USE_ASSERT_CHECKING
bool		gp_mk_sort_check = false;
#endif
int			gp_sort_flags = 0;
int			gp_dbg_flags = 0;
int			gp_sort_max_distinct = 20000;

bool		gp_setwith_alter_storage = FALSE;

bool		gp_enable_tablespace_auto_mkdir = FALSE;

/* MPP-9772, MPP-9773: remove support for CREATE INDEX CONCURRENTLY */
bool		gp_create_index_concurrently = FALSE;

/* Enable check for compatibility of encoding and locale in createdb */
bool		gp_encoding_check_locale_compatibility = true;

/* Priority for the segworkers relative to the postmaster's priority */
int			gp_segworker_relative_priority = PRIO_MAX;

/* Max size of dispatched plans; 0 if no limit */
int			gp_max_plan_size = 0;

/* Disable setting of tuple hints while reading */
bool		gp_disable_tuple_hints = false;

int			gp_workfile_compress_algorithm = 0;
bool		gp_workfile_checksumming = false;
int			gp_workfile_caching_loglevel = DEBUG1;
int			gp_sessionstate_loglevel = DEBUG1;

/* Maximum disk space to use for workfiles on a segment, in kilobytes */
double		gp_workfile_limit_per_segment = 0;

/* Maximum disk space to use for workfiles per query on a segment, in kilobytes */
double		gp_workfile_limit_per_query = 0;

/* Maximum number of workfiles to be created by a query */
int			gp_workfile_limit_files_per_query = 0;
int			gp_workfile_bytes_to_checksum = 16;

/* The type of work files that HashJoin should use */
int			gp_workfile_type_hashjoin = 0;

/* Gpmon */
bool		gp_enable_gpperfmon = false;
int			gp_gpperfmon_send_interval = 1;
int			gpperfmon_log_alert_level = GPPERFMON_LOG_ALERT_LEVEL_NONE;

/* Enable single-slice single-row inserts ?*/
bool		gp_enable_fast_sri = true;

/* Enable single-mirror pair dispatch. */
bool		gp_enable_direct_dispatch = true;

/* Disable logging while creating mapreduce objects */
bool		gp_mapreduce_define = false;

/* request fault-prober pause */
bool		gp_fts_probe_pause = false;

/* Force core dump on memory context error */
bool		coredump_on_memerror = false;

/* Experimental feature for MPP-4082. Please read doc before setting this guc */
int			gp_autostats_mode;
char	   *gp_autostats_mode_string;
int			gp_autostats_mode_in_functions;
char	   *gp_autostats_mode_in_functions_string;
int			gp_autostats_on_change_threshold = 100000;
bool		log_autostats = true;

/* --------------------------------------------------------------------------------------------------
 * Miscellaneous developer use
 */

bool		gp_dev_notice_agg_cost = false;

/* --------------------------------------------------------------------------------------------------
 * Server debugging
 */

/*
 * gp_debug_linger (integer)
 *
 * Upon an error with severity FATAL and error code ERRCODE_INTERNAL_ERROR,
 * errfinish() will sleep() for the specified number of seconds before
 * termination, to let the user attach a debugger.
 */
int			gp_debug_linger = 30;

/* ----------------
 * Non-GUC globals
 */

int			currentSliceId = UNSET_SLICE_ID;	/* used by elog to show the
												 * current slice the process
												 * is executing. */
SeqServerControlBlock *seqServerCtl;

/* Segment id where singleton gangs are to be dispatched. */
int			gp_singleton_segindex;

bool		gp_cost_hashjoin_chainwalk = false;

/* ----------------
 * This variable is initialized by the postmaster from command line arguments
 *
 * Any code needing the "numsegments"
 * can simply #include cdbvars.h, and use GpIdentity.numsegments
 */
GpId		GpIdentity = {UNINITIALIZED_GP_IDENTITY_VALUE, UNINITIALIZED_GP_IDENTITY_VALUE, UNINITIALIZED_GP_IDENTITY_VALUE};

void
verifyGpIdentityIsSet(void)
{
	if (GpIdentity.numsegments == UNINITIALIZED_GP_IDENTITY_VALUE ||
		GpIdentity.dbid == UNINITIALIZED_GP_IDENTITY_VALUE ||
		GpIdentity.segindex == UNINITIALIZED_GP_IDENTITY_VALUE)
	{
		elog(ERROR, "GpIdentity is not set");
	}
}

/*
 * Keep track of a few dispatch-related  statistics:
 */
int			cdb_total_slices = 0;
int			cdb_total_plans = 0;
int			cdb_max_slices = 0;

/*
 * Local macro to provide string values of numeric defines.
 */
#define CppNumericAsString(s) CppAsString(s)

/*
 *	Forward declarations of local function.
 */
GpRoleValue string_to_role(const char *string);
const char *role_to_string(GpRoleValue role);

/*
 * Convert a Greenplum Database role string (as for gp_session_role or gp_role) to an
 * enum value of type GpRoleValue. Return GP_ROLE_UNDEFINED in case the
 * string is unrecognized.
 */
GpRoleValue
string_to_role(const char *string)
{
	GpRoleValue role = GP_ROLE_UNDEFINED;

	if (pg_strcasecmp(string, "dispatch") == 0 || pg_strcasecmp(string, "") == 0)
	{
		role = GP_ROLE_DISPATCH;
	}
	else if (pg_strcasecmp(string, "execute") == 0)
	{
		role = GP_ROLE_EXECUTE;
	}
	else if (pg_strcasecmp(string, "utility") == 0)
	{
		role = GP_ROLE_UTILITY;
	}

	return role;
}

/*
 * Convert a GpRoleValue to a role string (as for gp_session_role or
 * gp_role).  Return eyecatcher in the unexpected event that the value
 * is unknown or undefined.
 */
const char *
role_to_string(GpRoleValue role)
{
	switch (role)
	{
		case GP_ROLE_DISPATCH:
			return "dispatch";
		case GP_ROLE_EXECUTE:
			return "execute";
		case GP_ROLE_UTILITY:
			return "utility";
		case GP_ROLE_UNDEFINED:
		default:
			return "*undefined*";
	}
}

/*
 * Assign hook routine for "gp_session_role" option.  Because this variable
 * has context PGC_BACKEND, we expect this assigment to happen only during
 * setup of a BACKEND, e.g., based on the role value specified on the connect
 * request.
 *
 * See src/backend/util/misc/guc.c for option definition.
 */
const char *
assign_gp_session_role(const char *newval, bool doit, GucSource source __attribute__((unused)))
{
#if FALSE
	elog(DEBUG1, "assign_gp_session_role: gp_session_role=%s, newval=%s, doit=%s",
		 show_gp_session_role(), newval, (doit ? "true" : "false"));
#endif

	GpRoleValue newrole = string_to_role(newval);

	if (newrole == GP_ROLE_UNDEFINED)
	{
		return NULL;
	}

	/* Force utility mode in a stand-alone backend. */
	if (!IsPostmasterEnvironment && newrole != GP_ROLE_UTILITY)
	{
		if (source != PGC_S_DEFAULT)
			elog(WARNING, "gp_session_role forced to 'utility' in single-user mode");

		newval = strdup("utility");
		newrole = GP_ROLE_UTILITY;
	}

	if (doit)
	{
		Gp_session_role = newrole;
		Gp_role = Gp_session_role;

		if (Gp_role == GP_ROLE_DISPATCH)
			Gp_segment = -1;

		if (Gp_role == GP_ROLE_UTILITY && MyProc != NULL)
			MyProc->mppIsWriter = false;
	}
	return newval;
}

/*
 * Assign hook routine for "gp_role" option.  This variable has context
 * PGC_SUSET so that is can only be set by a superuser via the SET command.
 * (It can also be set using an option on postmaster start, but this isn't
 * interesting beccause the derived global CdbRole is always set (along with
 * CdbSessionRole) on backend startup for a new connection.
 *
 * See src/backend/util/misc/guc.c for option definition.
 */
const char *
assign_gp_role(const char *newval, bool doit, GucSource source)
{
#if FALSE
	elog(DEBUG1, "assign_gp_role: gp_role=%s, newval=%s, doit=%s",
		 show_gp_role(), newval, (doit ? "true" : "false"));
#endif

	GpRoleValue newrole = string_to_role(newval);
	GpRoleValue oldrole = Gp_role;

	if (newrole == GP_ROLE_UNDEFINED)
	{
		return NULL;
	}

	if (doit)
	{
		/*
		 * When changing between roles, we must call cdb_cleanup and then
		 * cdb_setup to get setup and connections appropriate to the new role.
		 */
		bool		do_disconnect = false;
		bool		do_connect = false;

		if (Gp_role != newrole && IsUnderPostmaster)
		{
			if (Gp_role != GP_ROLE_UTILITY)
				do_disconnect = true;

			if (newrole != GP_ROLE_UTILITY)
				do_connect = true;
		}

		if (do_disconnect)
			cdb_cleanup(0, 0);

		Gp_role = newrole;

		if (source != PGC_S_DEFAULT)
		{
			if (do_connect)
			{
				/*
				 * In case there are problems with the Greenplum Database
				 * tables or data, we catch any error coming out of
				 * cdblink_setup so we can set the gp_role back to what it
				 * was.  Otherwise we may be left with inappropriate
				 * connections for the new role.
				 */
				PG_TRY();
				{
					cdb_setup();
				}
				PG_CATCH();
				{
					cdb_cleanup(0, 0);
					Gp_role = oldrole;
					if (Gp_role != GP_ROLE_UTILITY)
						cdb_setup();
					PG_RE_THROW();
				}
				PG_END_TRY();
			}
		}
	}

	return newval;
}

/*
 * Assign hook routine for "gp_connections_per_thread" option.  This variable has context
 * PGC_SUSET so that is can only be set by a superuser via the SET command.
 * (It can also be set in config file, but not inside of PGOPTIONS.)
 *
 * See src/backend/util/misc/guc.c for option definition.
 */
bool
assign_gp_connections_per_thread(int newval, bool doit, GucSource source __attribute__((unused)))
{
#if FALSE
	elog(DEBUG1, "assign_gp_connections_per_thread: gp_connections_per_thread=%s, newval=%d, doit=%s",
		 show_gp_connections_per_thread(), newval, (doit ? "true" : "false"));
#endif

	if (doit)
	{
		if (newval < 0)
			return false;

		cdbdisp_setAsync(newval == 0);
		cdbgang_setAsync(newval == 0);
		gp_connections_per_thread = newval;
	}

	return true;
}

/*
 * Show hook routine for "gp_session_role" option.
 *
 * See src/backend/util/misc/guc.c for option definition.
 */
const char *
show_gp_session_role(void)
{
	return role_to_string(Gp_session_role);
}

/*
 * Show hook routine for "gp_role" option.
 *
 * See src/backend/util/misc/guc.c for option definition.
 */
const char *
show_gp_role(void)
{
	return role_to_string(Gp_role);
}

/*
 * Show hook routine for "gp_connections_per_thread" option.
 *
 * See src/backend/util/misc/guc.c for option definition.
 */
const char *
show_gp_connections_per_thread(void)
{
	/*
	 * We rely on the fact that the memory context will clean up the memory
	 * for the buffer.data.
	 */
	StringInfoData buffer;

	initStringInfo(&buffer);

	appendStringInfo(&buffer, "%d", gp_connections_per_thread);

	return buffer.data;
}

/* --------------------------------------------------------------------------------------------------
 * Logging
 */

/*
 * gp_log_gangs (string)
 *
 * Should creation, reallocation and cleanup of gangs of QE processes be logged?
 * "OFF"	 -> only errors are logged
 * "TERSE"	 -> terse logging of routine events, e.g. creation of new qExecs
 * "VERBOSE" -> gang allocation per command is logged
 * "DEBUG"	 -> additional events are logged at severity level DEBUG1 to DEBUG5
 *
 * The messages that are enabled by the TERSE and VERBOSE settings are
 * written with a severity level of LOG.
 */
int gp_log_gang;

/*
 * gp_log_fts (string)
 *
 * What kind of messages should the fault-prober log ?
 * "OFF"	 -> only errors are logged
 * "TERSE"	 -> terse logging of routine events
 * "VERBOSE" -> gang allocation per command is logged
 * "DEBUG"	 -> additional events are logged at severity level DEBUG1 to DEBUG5
 *
 * The messages that are enabled by the TERSE and VERBOSE settings are
 * written with a severity level of LOG.
 */
int gp_log_fts;

/*
 * gp_log_interconnect (string)
 *
 * Should connections between internal processes be logged?  (qDisp/qExec/etc)
 * "OFF"	 -> connection errors are logged
 * "TERSE"	 -> terse logging of routine events, e.g. successful connections
 * "VERBOSE" -> most interconnect setup events are logged
 * "DEBUG"	 -> additional events are logged at severity level DEBUG1 to DEBUG5.
 *
 * The messages that are enabled by the TERSE and VERBOSE settings are
 * written with a severity level of LOG.
 */
int gp_log_interconnect;

/*
 * gp_enable_gpperfmon and gp_gpperfmon_send_interval are GUCs that we'd like
 * to have propagate from master to segments but we don't want non-super users
 * to be able to set it.  Unfortunately, as long as we use libpq to connect to
 * the segments its hard to create a clean way of doing this.
 *
 * Here we check and enforce that if the value is being set on the master its being
 * done as superuser and not a regular user.
 *
 */
bool
gpvars_assign_gp_enable_gpperfmon(bool newval, bool doit, GucSource source)
{
	if (doit)
	{

		if (Gp_role == GP_ROLE_DISPATCH && IsUnderPostmaster && GetCurrentRoleId() != InvalidOid && !superuser())
		{
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg("must be superuser to set gp_enable_gpperfmon")));
		}
		else
		{
			gp_enable_gpperfmon = newval;
		}
	}

	return true;
}

bool
gpvars_assign_gp_gpperfmon_send_interval(int newval, bool doit, GucSource source)
{
	if (doit)
	{
		if (Gp_role == GP_ROLE_DISPATCH && IsUnderPostmaster && GetCurrentRoleId() != InvalidOid && !superuser())
		{
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg("must be superuser to set gp_gpperfmon_send_interval")));
		}
		else
		{
			gp_gpperfmon_send_interval = newval;
		}
	}

	return true;
}

/*
 * gpvars_assign_gp_resource_manager_policy
 * gpvars_show_gp_resource_manager_policy
 */
const char *
gpvars_assign_gp_resource_manager_policy(const char *newval, bool doit, GucSource source __attribute__((unused)))
{
	ResourceManagerPolicy newtype = RESOURCE_MANAGER_POLICY_QUEUE;

	if (newval == NULL || newval[0] == 0)
		newtype = RESOURCE_MANAGER_POLICY_QUEUE;
	else if (!pg_strcasecmp("queue", newval))
		newtype = RESOURCE_MANAGER_POLICY_QUEUE;
	else if (!pg_strcasecmp("group", newval))
	{
		ResGroupOps_Bless();
		newtype = RESOURCE_MANAGER_POLICY_GROUP;
	}
	else
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("invalid value for resource manager policy")));

	if (doit)
	{
		Gp_resource_manager_policy = newtype;

		/*
		 * disable backoff mechanism of resource queue if we are going to
		 * enable resource group
		 */
		if (newtype == RESOURCE_MANAGER_POLICY_GROUP)
			gp_enable_resqueue_priority = false;
	}

	return newval;
}

const char *
gpvars_show_gp_resource_manager_policy(void)
{
	switch (Gp_resource_manager_policy)
	{
		case RESOURCE_MANAGER_POLICY_QUEUE:
			return "queue";
		case RESOURCE_MANAGER_POLICY_GROUP:
			return "group";
		default:
			Assert(!"unexpected resource manager policy");
			return "unknown";
	}
}

/*
 * gpvars_assign_statement_mem
 */
bool
gpvars_assign_statement_mem(int newval, bool doit, GucSource source __attribute__((unused)))
{
	if (doit)
	{
		if (newval >= max_statement_mem)
		{
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("Invalid input for statement_mem, must be less than max_statement_mem (%d kB)",
							max_statement_mem)));
		}

		statement_mem = newval;
	}

	return true;
}

/*
 * increment_command_count
 *	  Increment gp_command_count. If the new command count is 0 or a negative number, reset it to 1.
 */
void
increment_command_count()
{
	if (gp_cancel_query_print_log)
	{
		ereport(LOG,
				(errmsg("Incrementing command count from %d to %d",
						gp_command_count, gp_command_count + 1),
				 errprintstack(true)));
	}

	gp_command_count++;
	if (gp_command_count <= 0)
	{
		gp_command_count = 1;
	}
}

Datum mpp_execution_segment(PG_FUNCTION_ARGS);
Datum gp_execution_dbid(PG_FUNCTION_ARGS);

/*
 * Implements the gp_execution_segment() function to return the contentid
 * of the current executing segment.
 */
Datum
mpp_execution_segment(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT32(Gp_segment);
}

/*
 * Implements the gp_execution_dbid() function to return the dbid of the
 * current executing segment.
 */
Datum
gp_execution_dbid(PG_FUNCTION_ARGS)
{
	PG_RETURN_INT32(GpIdentity.dbid);
}


text:
require 'aws-sdk-core'

require_relative 'snapshot'
require_relative 'snapshot_progress'

module AwsHelpers
  module RDS

    module InstanceState
      AVAILABLE = 'available'
      BACKING_UP = 'backing-up'
      MODIFYING = 'modifying'
      REBOOTING = 'rebooting'
    end

    class Instance

      def initialize(db_instance_id)
        @rds_client = Aws::RDS::Client.new
        @db_instance_id = db_instance_id
      end

      def snapshot
        poll_available
        snapshot = Snapshot.new(@rds_client, @db_instance_id)
        snapshot.create
        SnapshotProgress.report(snapshot)
      end

      private

      def poll_available

        loop do

          instance = @rds_client.describe_db_instances(db_instance_identifier: @db_instance_id)[:db_instances].first
          state = instance[:db_instance_status]
          puts "#{@db_instance_id} is #{state}"

          case state
            when InstanceState::AVAILABLE
              break
            when InstanceState::BACKING_UP, InstanceState::MODIFYING, InstanceState::REBOOTING
              sleep 30
            else
              raise "#{@db_instance_id} will never become #{InstanceState::AVAILABLE}"
          end

        end

      end

    end
  end
end


text:
num: "h14"
desc: "Unix File Permisssions and Octal"
ready: true
assigned: 2017-09-01 09:30:00.00-7:00
due: 2017-09-05 09:30:00.00-7:00
---

READING ASSIGNMENT

Please review the lecture notes from Thursday 08/31 about octal numbers and Unix file permissions, or
consult this web page:

<https://ucsb-cs8.github.io/topics/number_conversions/>

Then complete these problems:

{% include hwk_li_name_10pts.html %}

 (10 pts)
What is the Unix command to list your files in a way that shows the unix file permissions
with strings such as `rwxr-xr-x`?

 (10 pts) If there is a Unix file in my current directory called `index.html` and I want to set its permissions to `rw-r--r--`
what Unix command will do that? (The full command, not just the first word of the command).

Please complete each of the conversions shown.   You can practice at the page:

<https://www.cs.ucsb.edu/~pconrad/cs8/topics/chmodQuiz1/> until you are confident that you know how to solve these.

 (10 pts)
Convert `rwxr-x---` from rwx format to octal:

 (10 pts)
Convert `rwxr-xr-x` from rwx format to octal:

 (10 pts)
Convert 777 from octal to rwx format:

 (10 pts)
Convert `rwxrwx---` from rwx format to octal:

 (10 pts)
Convert 600 from octal to rwx format:

 (10 pts)
Convert 444 from octal to rwx format:

 (10 pts)
Convert `rwx--x--x` from rwx format to octal:


text:
module Watir
  module Locators
    class Cell
      class SelectorBuilder
        class XPath < Element::SelectorBuilder::XPath
          private

          def start_string
            @adjacent ? './' : './*'
          end

          def tag_string
            return super if @adjacent

            "[#{process_attribute(:tag_name, 'th')} or #{process_attribute(:tag_name, 'td')}]"
          end
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<manifest>
<remote name="sub" fetch="ssh://git@github.com" />
  <project path="device/samsung/degaswifi" name="GalaxyTab4/maxicm_device_samsung_degaswifi" remote="sub" revision="cm-11.0"/>
  <project path="device/samsung/marvell-common" name="GalaxyTab4/maxicm_device_samsung_marvell-common" remote="sub" revision="cm-11.0"/>
  <project path="device/qcom/common"       name="CyanogenMod/android_device_qcom_common" remote="github" revision="cm-11.0"/>
  <project path="kernel/samsung/degaswifi" name="GalaxyTab4/maxicm_kernel_samsung_degaswifi" remote="sub" revision="3.10"/>
  <project path="vendor/samsung"           name="GalaxyTab4/maxicm_vendor_samsung"           remote="sub" revision="cm-11.0"/>
  <project path="hardware/marvell"         name="GalaxyTab4/android_hardware_marvell"        remote="sub" revision="cm-11.0"/>
</manifest>


text:
<resources>
    <string name="app_name">Service feature table (cache)</string>
    <string name="sample_service_url">http://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0</string>
</resources>


text:
// +build !appengine
// +build linux darwin freebsd netbsd openbsd solaris

package osutil

import (
	"errors"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"syscall"
)

// if non-nil, osSelfPath is used from selfPath.
var osSelfPath func() (string, error)

// TODO(mpl): document the symlink behaviour in SelfPath for the BSDs when
// I know for sure.

// SelfPath returns the path of the executable for the currently running
// process. At least on linux, the returned path is a symlink to the actual
// executable.
func SelfPath() (string, error) {
	if f := osSelfPath; f != nil {
		return f()
	}
	switch runtime.GOOS {
	case "linux":
		return "/proc/self/exe", nil
	case "netbsd":
		return "/proc/curproc/exe", nil
	case "openbsd":
		return "/proc/curproc/file", nil
	case "darwin":
		// TODO(mpl): maybe do the right thing for darwin too, but that may require changes to runtime.
		// See https://codereview.appspot.com/6736069/
		return exec.LookPath(os.Args[0])
	}
	return "", errors.New("SelfPath not implemented for " + runtime.GOOS)
}

// RestartProcess returns an error if things couldn't be
// restarted.  On success, this function never returns
// because the process becomes the new process.
func RestartProcess() error {
	path, err := SelfPath()
	if err != nil {
		return fmt.Errorf("RestartProcess failed: %v", err)
	}
	return syscall.Exec(path, os.Args, os.Environ())
}


text:
"""iSCSI Driver for DataCore SANsymphony storage array."""

from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils

from cinder.common import constants
from cinder import exception as cinder_exception
from cinder.i18n import _
from cinder import interface
from cinder import utils as cinder_utils
from cinder.volume import configuration
from cinder.volume.drivers.datacore import driver
from cinder.volume.drivers.datacore import exception as datacore_exception
from cinder.volume.drivers.datacore import passwd
from cinder.volume.drivers.datacore import utils as datacore_utils
from cinder.volume import volume_utils as volume_utils

LOG = logging.getLogger(__name__)

datacore_iscsi_opts = [
    cfg.ListOpt('datacore_iscsi_unallowed_targets',
                default=[],
                help='List of iSCSI targets that cannot be used to attach '
                     'volume. To prevent the DataCore iSCSI volume driver '
                     'from using some front-end targets in volume attachment, '
                     'specify this option and list the iqn and target machine '
                     'for each target as the value, such as '
                     '<iqn:target name>, <iqn:target name>, '
                     '<iqn:target name>.'),
    cfg.StrOpt('datacore_iscsi_chap_storage',
               default='$state_path/.datacore_chap',
               help='Fully qualified file name where dynamically generated '
                    'iSCSI CHAP secrets are stored.  This must be changed '
                    'to a unique per-backend value if deploying multiple '
                    'DataCore backends on the same host.'),
]

CONF = cfg.CONF
CONF.register_opts(datacore_iscsi_opts, group=configuration.SHARED_CONF_GROUP)

@interface.volumedriver
class ISCSIVolumeDriver(driver.DataCoreVolumeDriver):
    """DataCore SANsymphony iSCSI volume driver.

    Version history:

    .. code-block:: none

        1.0.0 - Initial driver
        2.0.0 - Reintroduce the driver

    """

    VERSION = '2.0.0'
    STORAGE_PROTOCOL = constants.ISCSI
    CI_WIKI_NAME = 'DataCore_CI'

    def __init__(self, *args, **kwargs):
        super(ISCSIVolumeDriver, self).__init__(*args, **kwargs)
        self.configuration = kwargs.get('configuration', None)
        if self.configuration:
            self.configuration.append_config_values(datacore_iscsi_opts)
        self._password_storage = None

    @classmethod
    def get_driver_options(cls):
        additional_opts = cls._get_oslo_driver_opts(
            'san_ip', 'san_login', 'san_password')
        return driver.datacore_opts + datacore_iscsi_opts + additional_opts

    def do_setup(self, context):
        """Perform validations and establish connection to server.

        :param context: Context information
        """

        super(ISCSIVolumeDriver, self).do_setup(context)

        self._password_storage = passwd.PasswordFileStorage(
            self.configuration.datacore_iscsi_chap_storage)

    def validate_connector(self, connector):
        """Fail if connector doesn't contain all the data needed by the driver.

        :param connector: Connector information
        """

        required_data = ['host', 'initiator']
        for required in required_data:
            if required not in connector:
                LOG.error("The volume driver requires %(data)s "
                          "in the connector.", {'data': required})
                raise cinder_exception.InvalidConnectorException(
                    missing=required)

    def initialize_connection(self, volume, connector):
        """Allow connection to connector and return connection info.

        :param volume: Volume object
        :param connector: Connector information
        :return: Connection information
        """

        LOG.debug("Initialize connection for volume %(volume)s for "
                  "connector %(connector)s.",
                  {'volume': volume.id, 'connector': connector})

        virtual_disk = self._get_virtual_disk_for(volume, raise_not_found=True)

        if virtual_disk.DiskStatus != 'Online':
            LOG.warning("Attempting to attach virtual disk %(disk)s "
                        "that is in %(state)s state.",
                        {'disk': virtual_disk.Id,
                         'state': virtual_disk.DiskStatus})

        server_group = self._get_our_server_group()

        @cinder_utils.synchronized(
            'datacore-backend-%s' % server_group.Id, external=True)
        def serve_virtual_disk():
            available_ports = self._api.get_ports()

            iscsi_initiator = self._get_initiator(connector['host'],
                                                  connector['initiator'],
                                                  available_ports)
            iscsi_targets = self._get_targets(virtual_disk, available_ports)

            if not iscsi_targets:
                msg = (_("Suitable targets not found for "
                         "virtual disk %(disk)s for volume %(volume)s.")
                       % {'disk': virtual_disk.Id, 'volume': volume.id})
                LOG.error(msg)
                raise cinder_exception.VolumeDriverException(message=msg)

            auth_params = self._setup_iscsi_chap_authentication(
                iscsi_targets, iscsi_initiator)

            virtual_logical_units = self._map_virtual_disk(
                virtual_disk, iscsi_targets, iscsi_initiator)

            return iscsi_targets, virtual_logical_units, auth_params

        targets, logical_units, chap_params = serve_virtual_disk()

        target_portal = datacore_utils.build_network_address(
            targets[0].PortConfigInfo.PortalsConfig.iScsiPortalConfigInfo[
                0].Address.Address,
            targets[0].PortConfigInfo.PortalsConfig.iScsiPortalConfigInfo[
                0].TcpPort)

        connection_data = {}

        if chap_params:
            connection_data['auth_method'] = 'CHAP'
            connection_data['auth_username'] = chap_params[0]
            connection_data['auth_password'] = chap_params[1]

        connection_data['target_discovered'] = False
        connection_data['target_iqn'] = targets[0].PortName
        connection_data['target_portal'] = target_portal
        connection_data['target_lun'] = logical_units[targets[0]].Lun.Quad
        connection_data['volume_id'] = volume.id
        connection_data['access_mode'] = 'rw'

        LOG.debug("Connection data: %s", connection_data)

        return {
            'driver_volume_type': 'iscsi',
            'data': connection_data,
        }

    def _map_virtual_disk(self, virtual_disk, targets, initiator):
        logical_disks = self._api.get_logical_disks()

        logical_units = {}
        created_mapping = {}
        created_devices = []
        created_domains = []
        try:
            for target in targets:
                target_domain = self._get_target_domain(target, initiator)
                if not target_domain:
                    target_domain = self._api.create_target_domain(
                        initiator.HostId, target.HostId)
                    created_domains.append(target_domain)

                nexus = self._api.build_scsi_port_nexus_data(
                    initiator.Id, target.Id)

                target_device = self._get_target_device(
                    target_domain, target, initiator)
                if not target_device:
                    target_device = self._api.create_target_device(
                        target_domain.Id, nexus)
                    created_devices.append(target_device)

                logical_disk = self._get_logical_disk_on_host(
                    virtual_disk.Id, target.HostId, logical_disks)

                logical_unit = self._get_logical_unit(
                    logical_disk, target_device)
                if not logical_unit:
                    logical_unit = self._create_logical_unit(
                        logical_disk, nexus, target_device)
                    created_mapping[logical_unit] = target_device
                logical_units[target] = logical_unit
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception("Mapping operation for virtual disk %(disk)s "
                              "failed with error.",
                              {'disk': virtual_disk.Id})
                try:
                    for logical_unit in created_mapping:
                        nexus = self._api.build_scsi_port_nexus_data(
                            created_mapping[logical_unit].InitiatorPortId,
                            created_mapping[logical_unit].TargetPortId)
                        self._api.unmap_logical_disk(
                            logical_unit.LogicalDiskId, nexus)
                    for target_device in created_devices:
                        self._api.delete_target_device(target_device.Id)
                    for target_domain in created_domains:
                        self._api.delete_target_domain(target_domain.Id)
                except datacore_exception.DataCoreException as e:
                    LOG.warning("An error occurred on a cleanup after "
                                "failed mapping operation: %s.", e)

        return logical_units

    def terminate_connection(self, volume, connector, **kwargs):
        super().unserve_virtual_disks_from_host(volume, connector)

    def _get_target_domain(self, target, initiator):
        target_domains = self._api.get_target_domains()
        target_domain = datacore_utils.get_first_or_default(
            lambda domain: (domain.InitiatorHostId == initiator.HostId and
                            domain.TargetHostId == target.HostId),
            target_domains, None)
        return target_domain

    def _get_target_device(self, target_domain, target, initiator):
        target_devices = self._api.get_target_devices()
        target_device = datacore_utils.get_first_or_default(
            lambda device: (device.TargetDomainId == target_domain.Id and
                            device.InitiatorPortId == initiator.Id and
                            device.TargetPortId == target.Id),
            target_devices, None)
        return target_device

    def _get_logical_unit(self, logical_disk, target_device):
        logical_units = self._api.get_logical_units()
        logical_unit = datacore_utils.get_first_or_default(
            lambda unit: (unit.LogicalDiskId == logical_disk.Id and
                          unit.VirtualTargetDeviceId == target_device.Id),
            logical_units, None)
        return logical_unit

    def _create_logical_unit(self, logical_disk, nexus, target_device):
        free_lun = self._api.get_next_free_lun(target_device.Id)
        logical_unit = self._api.map_logical_disk(logical_disk.Id,
                                                  nexus,
                                                  free_lun,
                                                  logical_disk.ServerHostId,
                                                  'Client')
        return logical_unit

    def _check_iscsi_chap_configuration(self, chap, targets):
        logical_units = self._api.get_logical_units()
        target_devices = self._api.get_target_devices()

        for logical_unit in logical_units:
            target_device_id = logical_unit.VirtualTargetDeviceId
            target_device = datacore_utils.get_first(
                lambda device, key=target_device_id: device.Id == key,
                target_devices)
            target_port_id = target_device.TargetPortId
            target = datacore_utils.get_first_or_default(
                lambda target_port, key=target_port_id: target_port.Id == key,
                targets,
                None)
            if (target and
                    chap == (target.ServerPortProperties.Authentication ==
                             'None') and chap ==
                    (target.ServerPortProperties.Authentication == 'Default')):
                msg = _("iSCSI CHAP authentication can't be configured for "
                        "target %s. Device exists that served through "
                        "this target.") % target.PortName
                LOG.error(msg)
                raise cinder_exception.VolumeDriverException(message=msg)

    def _setup_iscsi_chap_authentication(self, targets, initiator):
        iscsi_chap_enabled = self.configuration.use_chap_auth

        self._check_iscsi_chap_configuration(iscsi_chap_enabled, targets)

        server_group = self._get_our_server_group()
        update_access_token = False
        access_token = None
        chap_secret = None
        chap_username = initiator.PortName
        if iscsi_chap_enabled:
            authentication = 'CHAP'
            chap_username = self.configuration.chap_username
            if not chap_username:
                chap_username = initiator.PortName
            chap_secret = (self.configuration.chap_password or
                           self._password_storage.get_password(
                               server_group.Id, initiator.PortName))
            if not chap_secret:
                chap_secret = volume_utils.generate_password(length=15)
                self._password_storage.set_password(
                    server_group.Id, initiator.PortName, chap_secret)
                update_access_token = True
            access_token = self._api.build_access_token(
                initiator.PortName,
                None,
                None,
                False,
                chap_username,
                chap_secret)
        else:
            authentication = 'None'
            if self._password_storage:
                try:
                    self._password_storage.delete_password(server_group.Id,
                                                           initiator.PortName)
                except Exception:
                    pass

        changed_targets = {}
        try:
            for target in targets:
                if iscsi_chap_enabled:
                    target_iscsi_nodes = getattr(target.iSCSINodes, 'Node', [])
                    iscsi_node = datacore_utils.get_first_or_default(
                        lambda node: node.Name == initiator.PortName,
                        target_iscsi_nodes,
                        None)
                    if ((not iscsi_node) or not
                            (iscsi_node.AccessToken.TargetUsername) or
                            (update_access_token)):
                        self._api.set_access_token(target.Id, access_token)
                properties = target.ServerPortProperties
                if properties.Authentication != authentication:
                    changed_targets[target] = properties.Authentication
                    properties.Authentication = authentication
                    self._api.set_server_port_properties(
                        target.Id, properties)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.exception("Configuring of iSCSI CHAP authentication for "
                              "initiator %(initiator)s failed.",
                              {'initiator': initiator.PortName})
                try:
                    for target in changed_targets:
                        properties = target.ServerPortProperties
                        properties.Authentication = changed_targets[target]
                        self._api.set_server_port_properties(
                            target.Id, properties)
                except datacore_exception.DataCoreException as e:
                    LOG.warning("An error occurred on a cleanup after  failed "
                                "configuration of iSCSI CHAP authentication "
                                "on initiator %(initiator)s: %(error)s.",
                                {'initiator': initiator.PortName, 'error': e})
        if iscsi_chap_enabled:
            return chap_username, chap_secret

    def _get_initiator(self, host, iqn, available_ports):
        client = self._get_client(host, create_new=True)

        iscsi_initiator_ports = self._get_host_iscsi_initiator_ports(
            client, available_ports)

        iscsi_initiator = datacore_utils.get_first_or_default(
            lambda port: port.PortName == iqn,
            iscsi_initiator_ports,
            None)
        if not iscsi_initiator:
            scsi_port_data = self._api.build_scsi_port_data(
                client.Id, iqn, 'Initiator', 'iSCSI')
            iscsi_initiator = self._api.register_port(scsi_port_data)
        return iscsi_initiator

    def _get_targets(self, virtual_disk, available_ports):
        unallowed_targets = self.configuration.datacore_iscsi_unallowed_targets
        iscsi_target_ports = self._get_frontend_iscsi_target_ports(
            available_ports)
        server_port_map = {}
        for target_port in iscsi_target_ports:
            if target_port.HostId in server_port_map:
                server_port_map[target_port.HostId].append(target_port)
            else:
                server_port_map[target_port.HostId] = [target_port]
        iscsi_targets = []
        if virtual_disk.FirstHostId in server_port_map:
            iscsi_targets += server_port_map[virtual_disk.FirstHostId]
        if virtual_disk.SecondHostId in server_port_map:
            iscsi_targets += server_port_map[virtual_disk.SecondHostId]
        iscsi_targets = [target for target in iscsi_targets
                         if target.PortName not in unallowed_targets]
        return iscsi_targets

    @staticmethod
    def _get_logical_disk_on_host(virtual_disk_id,
                                  host_id, logical_disks):
        logical_disk = datacore_utils.get_first(
            lambda disk: (disk.ServerHostId == host_id and
                          disk.VirtualDiskId == virtual_disk_id),
            logical_disks)
        return logical_disk

    @staticmethod
    def _is_iscsi_frontend_port(port):
        if (port.PortType == 'iSCSI' and port.PortMode == 'Target' and
                port.HostId and port.PresenceStatus == 'Present' and
                hasattr(port, 'IScsiPortStateInfo')):
            port_roles = port.ServerPortProperties.Role.split()
            port_state = (port.IScsiPortStateInfo.PortalsState
                          .PortalStateInfo[0].State)
            if 'Frontend' in port_roles and port_state == 'Ready':
                return True
        return False

    @staticmethod
    def _get_frontend_iscsi_target_ports(ports):
        return [target_port for target_port in ports
                if ISCSIVolumeDriver._is_iscsi_frontend_port(target_port)]

    @staticmethod
    def _get_host_iscsi_initiator_ports(host, ports):
        return [port for port in ports if
                port.PortType == 'iSCSI' and port.PortMode == 'Initiator' and
                port.HostId == host.Id]


text:
from __future__ import print_function
from __future__ import absolute_import
from builtins import range

from nose.tools import assert_raises
import gevent
import sys

from zerorpc import zmq
import zerorpc
from .testutils import teardown, random_ipc_endpoint, TIME_FACTOR

def test_server_manual():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_channel.emit('lolita', tuple())
    event = client_channel.recv()
    assert list(event.args) == [42]
    client_channel.close()

    client_channel = client.channel()
    client_channel.emit('add', (1, 2))
    event = client_channel.recv()
    assert list(event.args) == [3]
    client_channel.close()
    srv.stop()

def test_client_server():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client()
    client.connect(endpoint)

    print(client.lolita())
    assert client.lolita() == 42

    print(client.add(1, 4))
    assert client.add(1, 4) == 5

def test_client_server_client_timeout():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def lolita(self):
            return 42

        def add(self, a, b):
            gevent.sleep(TIME_FACTOR * 10)
            return a + b

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=TIME_FACTOR * 2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):
        assert_raises(zerorpc.TimeoutExpired, client.add, 1, 4)
    else:
        with assert_raises(zerorpc.TimeoutExpired):
            print(client.add(1, 4))
    client.close()
    srv.close()

def test_client_server_exception():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def raise_something(self, a):
            return a[4]

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=TIME_FACTOR * 2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):
        def _do_with_assert_raises():
            print(client.raise_something(42))
        assert_raises(zerorpc.RemoteError, _do_with_assert_raises)
    else:
        with assert_raises(zerorpc.RemoteError):
            print(client.raise_something(42))
    assert client.raise_something(list(range(5))) == 4
    client.close()
    srv.close()

def test_client_server_detailed_exception():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):

        def raise_error(self):
            raise RuntimeError('oops!')

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client = zerorpc.Client(timeout=TIME_FACTOR * 2)
    client.connect(endpoint)

    if sys.version_info < (2, 7):
        def _do_with_assert_raises():
            print(client.raise_error())
        assert_raises(zerorpc.RemoteError, _do_with_assert_raises)
    else:
        with assert_raises(zerorpc.RemoteError):
            print(client.raise_error())
    try:
        client.raise_error()
    except zerorpc.RemoteError as e:
        print('got that:', e)
        print('name', e.name)
        print('msg', e.msg)
        assert e.name == 'RuntimeError'
        assert e.msg == 'oops!'

    client.close()
    srv.close()

def test_exception_compat_v1():
    endpoint = random_ipc_endpoint()

    class MySrv(zerorpc.Server):
        pass

    srv = MySrv()
    srv.bind(endpoint)
    gevent.spawn(srv.run)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    rpccall = client.channel()
    rpccall.emit('donotexist', tuple())
    event = rpccall.recv()
    print(event)
    assert event.name == 'ERR'
    (name, msg, tb) = event.args
    print('detailed error', name, msg, tb)
    assert name == 'NameError'
    assert msg == 'donotexist'

    rpccall = client.channel()
    rpccall.emit('donotexist', tuple(), xheader={'v': 1})
    event = rpccall.recv()
    print(event)
    assert event.name == 'ERR'
    (msg,) = event.args
    print('msg only', msg)
    assert msg == "NameError('donotexist',)"

    client_events.close()
    srv.close()

def test_removed_unscriptable_error_format_args_spec():

    class MySrv(zerorpc.Server):
        pass

    srv = MySrv()
    return_value = srv._format_args_spec(None)
    assert return_value is None


text:
#if ! defined(EPPCHANGEPOLLOPERATION_HPP)
#define	      EPPCHANGEPOLLOPERATION_HPP	   1

#include "EppEntity.hpp"

/**
 * This EppChangePollOperation class implements EPP Poll Operation
 * as defined in EPP changePoll extension.
 */
class EppChangePollOperation : public EppEntity
{
public:

	/**
	 * Creates an EppChangePollOperation object
	 */
	EppChangePollOperation()
	{
		this->operation = NULLXS;
		this->subOperation = NULLXS;
	};

	/**
	 * Creates an EppChangePollOperation object with a string operation and a subOperation text
	 */
	EppChangePollOperation( const DOMString& operation, const DOMString& subOp)
	{
		this->operation = operation;
		this->subOperation = subOp;
	};

	/**
	 * Destructor
	 */
	virtual ~EppChangePollOperation() {};

	/**
	 * Gets the operation
	 */
	DOMString getOperation() const
	{
		return this->operation;
	};

	/**
	 * Sets the operation
	 */
	void setOperation( const DOMString& operation )
	{
		this->operation = operation;
	};

	/**
	 * Gets subOperation type of the operation
	 */
	DOMString getSubOperation() const
	{
		return this->subOperation;
	};

	/**
	 * Sets subOperation of the operation
	 */
	void setSubOperation( const DOMString& subOp )
	{
		this->subOperation = subOp;
	};

	/**
	 * Converts the EppChangePollOperation object into an XML element
	 *
	 * @param doc the XML Document object
	 * @param tag the tag/element name for the EppChangePollOperation object
	 *
	 * @return an DOMElement object
	 */
	DOMElement* toXML( DOMDocument& doc, const DOMString& tag );

	/**
	 * Converts an XML element into an EppChangePollOperation object.
	 *
	 * @param root root node for an EppChangePollOperation object in XML format
	 *
	 * @return an EppChangePollOperation object, or null if the node is invalid
	 */
	static EppChangePollOperation * fromXML( const DOMNode& root );

	DOMString toString()
	{
		return EppEntity::toString(DOMString("operation"));
	};

private:
	DOMString	operation;
	DOMString	subOperation;
};

#endif


text:
package org.metasyntactic.recreation.life;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Random;

public class LifeFrame extends javax.swing.JFrame {

    private final static Random random = new Random();
    private LifePanel lifePanel;
    private Universe universe;

    private JButton stepButton;
    private JSlider timeLineSlider;

    /**
     * Creates new form LifeFrame
     */
    public LifeFrame(Universe universe) {
        this.universe = universe;
        lifePanel = new LifePanel();
        lifePanel.setUniverse(universe);

        initComponents();
        pack();
    }

    private void initComponents() {
        stepButton = new JButton();
        timeLineSlider = new JSlider();

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                exitForm(evt);
            }
        });

        stepButton.setText("Step");
        stepButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                stepActionPerformed(evt);
            }
        });

        JPanel southPanel = new JPanel(new BorderLayout());
        southPanel.add(stepButton, BorderLayout.EAST);
        southPanel.add(timeLineSlider, BorderLayout.CENTER);

        getContentPane().add(lifePanel, BorderLayout.CENTER);
        getContentPane().add(southPanel, BorderLayout.SOUTH);
    }

    private void stepActionPerformed(ActionEvent evt) {
        while (true) {
            universe = universe.step();
            lifePanel.setUniverse(universe);
            this.update(this.getGraphics());
        }
    }

    private void exitForm(WindowEvent evt) {
        System.exit(0);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        if (args.length != 2) {
            System.out.println(usage());
            System.exit(-1);
        }

        final int rows = Integer.parseInt(args[0]);
        final int columns = Integer.parseInt(args[1]);

        Node node = Leaf.emptyLeaf().push();
        double depth = Math.log(Math.max(rows, columns)) / Math.log(2);
        while (node.depth() < depth) {
            node = node.push();
        }

        Universe universe = new Universe(node);
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < columns; x++) {
                universe = universe.setValue(x, y, random.nextBoolean());
            }
        }

        new LifeFrame(universe).setVisible(true);
    }

    public static String usage() {
        return "java " + LifeFrame.class + " rows columns";
    }
}


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

<TITLE>
Overview List
</TITLE>

<META NAME="date" CONTENT="2014-09-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

Packages

<unnamed package>

app.controllers

app.models

app.services

app.utils

app.views


text:
package org.daisy.dotify.tasks.impl.input.xml;

import java.net.URL;

import javax.xml.namespace.NamespaceContext;

@SuppressWarnings("javadoc")
public interface XMLTestContext {

	public NamespaceContext getNamespaceContext();

	public URL getNormalizationResource();
}


text:
using System.Collections.Immutable;
using System.Composition;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace SpatialAnalyzers
{
    [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UpdateCodeFix))]
    [Shared]
    public class UpdateCodeFix : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create("CS0618");

        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var syntaxRoot = await document.GetSyntaxRootAsync(context.CancellationToken)
                .ConfigureAwait(false);
            var model = await document.GetSemanticModelAsync();

            foreach (var diagnostic in context.Diagnostics)
            {
                var token = syntaxRoot.FindToken(diagnostic.Location.SourceSpan.Start);
                if (string.IsNullOrEmpty(token.ValueText))
                {
                    continue;
                }

                var node = syntaxRoot.FindNode(diagnostic.Location.SourceSpan);
                if (node is ObjectCreationExpressionSyntax objectCreation &&
                    objectCreation.Type is SimpleNameSyntax simpleName)
                {
                    if (simpleName.Identifier.ValueText == "UnitVector3D")
                    {
                        context.RegisterCodeFix(
                            CodeAction.Create(
                                "Use Create",
                                _ => Task.FromResult(document.WithSyntaxRoot(
                                    syntaxRoot.ReplaceNode(
                                        objectCreation,
                                        SyntaxFactory.InvocationExpression(
                                            SyntaxFactory.ParseExpression("UnitVector3D.Create"),
                                            objectCreation.ArgumentList))))),
                            diagnostic);
                    }
                    else if (simpleName.Identifier.ValueText == "Circle3D")
                    {
                        var args = objectCreation.ArgumentList;
                        if (args.Arguments.Count == 3)
                        {
                            var arg3 = args.Arguments[2];
                            if (model.GetTypeInfo(arg3.ChildNodes().First()).Type.Name == "Point3D")
                            {
                                context.RegisterCodeFix(
                                    CodeAction.Create(
                                        "Use Create",
                                        _ => Task.FromResult(document.WithSyntaxRoot(
                                            syntaxRoot.ReplaceNode(
                                                objectCreation,
                                                SyntaxFactory.InvocationExpression(
                                                    SyntaxFactory.ParseExpression("Circle3D.FromPoints"),
                                                    objectCreation.ArgumentList))))),
                                    diagnostic);
                            }
                            else if (model.GetTypeInfo(arg3.ChildNodes().First()).Type.Name == "UnitVector3D")
                            {
                                context.RegisterCodeFix(
                                    CodeAction.Create(
                                        "Use Create",
                                        _ => Task.FromResult(document.WithSyntaxRoot(
                                            syntaxRoot.ReplaceNode(
                                                objectCreation,
                                                SyntaxFactory.InvocationExpression(
                                                    SyntaxFactory.ParseExpression("Circle3D.FromPointsAndAxis"),
                                                    objectCreation.ArgumentList))))),
                                    diagnostic);
                            }
                        }
                    }
                    else if (simpleName.Identifier.ValueText == "Angle" &&
                             objectCreation.ArgumentList != null &&
                             objectCreation.ArgumentList.Arguments.Count == 2 &&
                             objectCreation.ArgumentList.Arguments[1] is ArgumentSyntax argument &&
                             argument.Expression is MemberAccessExpressionSyntax memberAccess &&
                             memberAccess.Name is SimpleNameSyntax unitName)
                    {
                        if (unitName.Identifier.ValueText == "Degrees")
                        {
                            context.RegisterCodeFix(
                                CodeAction.Create(
                                    "Use Create",
                                    _ => Task.FromResult(
                                        document.WithSyntaxRoot(
                                            syntaxRoot.ReplaceNode(
                                                objectCreation,
                                                AngleFromDegrees(objectCreation.ArgumentList.Arguments[0]))))),
                                diagnostic);
                        }
                        else if (unitName.Identifier.ValueText == "Radians")
                        {
                            context.RegisterCodeFix(
                                CodeAction.Create(
                                    "Use Create",
                                    _ => Task.FromResult(document.WithSyntaxRoot(
                                        syntaxRoot.ReplaceNode(
                                            objectCreation,
                                            AngleFromRadians(objectCreation.ArgumentList.Arguments[0]))))),
                                diagnostic);
                        }
                    }
                }
                else if (node is InvocationExpressionSyntax invocation &&
                         invocation.Expression is MemberAccessExpressionSyntax memberAccess)
                {
                    if (memberAccess.Expression is IdentifierNameSyntax identifierName &&
                        identifierName.Identifier.ValueText == "Angle" &&
                        memberAccess.Name.Identifier.ValueText == "From" &&
                        invocation.ArgumentList != null &&
                        invocation.ArgumentList.Arguments.Count == 2 &&
                        invocation.ArgumentList.Arguments[1] is ArgumentSyntax angleArgument)
                    {
                        if (angleArgument.Expression is MemberAccessExpressionSyntax argMemberAccess &&
                            argMemberAccess.Name is SimpleNameSyntax unitName)
                        {
                            if (unitName.Identifier.ValueText == "Degrees")
                            {
                                context.RegisterCodeFix(
                                    CodeAction.Create(
                                        "Use FromDegrees",
                                        _ => Task.FromResult(document.WithSyntaxRoot(
                                            syntaxRoot.ReplaceNode(
                                                invocation,
                                                AngleFromDegrees(invocation.ArgumentList.Arguments[0]))))),
                                    diagnostic);
                            }
                            else if (unitName.Identifier.ValueText == "Radians")
                            {
                                context.RegisterCodeFix(
                                    CodeAction.Create(
                                        "Use FromRadians",
                                        _ => Task.FromResult(document.WithSyntaxRoot(
                                            syntaxRoot.ReplaceNode(
                                                invocation,
                                                AngleFromRadians(invocation.ArgumentList.Arguments[0]))))),
                                    diagnostic);
                            }
                        }
                    }
                    else if (memberAccess.Name.Identifier.ValueText == "Rotate" &&
                             invocation.ArgumentList != null &&
                             invocation.ArgumentList.Arguments.Count == 3 &&
                             invocation.ArgumentList.Arguments[2] is ArgumentSyntax angleArg)
                    {
                        if (angleArg.Expression is MemberAccessExpressionSyntax argMemberAccess &&
                            argMemberAccess.Name is SimpleNameSyntax unitName)
                        {
                            if (unitName.Identifier.ValueText == "Degrees")
                            {
                                context.RegisterCodeFix(
                                    CodeAction.Create(
                                        "Use Angle.FromDegrees",
                                        _ => Task.FromResult(
                                            document.WithSyntaxRoot(
                                                syntaxRoot.ReplaceNode(
                                                    invocation.ArgumentList,
                                                    invocation.ArgumentList.WithArguments(
                                                        invocation.ArgumentList.Arguments
                                                            .Replace(
                                                                angleArg,
                                                                angleArg.WithExpression(AngleFromDegrees(invocation.ArgumentList.Arguments[1])))
                                                            .RemoveAt(1)))))),
                                    diagnostic);
                            }
                            else if (unitName.Identifier.ValueText == "Radians")
                            {
                                context.RegisterCodeFix(
                                    CodeAction.Create(
                                        "Use Angle.FromRadians",
                                        _ => Task.FromResult(
                                            document.WithSyntaxRoot(
                                                syntaxRoot.ReplaceNode(
                                                    invocation.ArgumentList,
                                                    invocation.ArgumentList.WithArguments(
                                                        invocation.ArgumentList.Arguments
                                                            .Replace(
                                                                angleArg,
                                                                angleArg.WithExpression(AngleFromRadians(invocation.ArgumentList.Arguments[1])))
                                                            .RemoveAt(1)))))),
                                    diagnostic);
                            }
                        }
                    }
                }
                else if (node is BinaryExpressionSyntax binaryExpression &&
                         binaryExpression.IsKind(SyntaxKind.MultiplyExpression))
                {
                    var message = diagnostic.GetMessage(CultureInfo.InvariantCulture);
                    if (message.StartsWith("'Degrees.operator *(double, Degrees)' is obsolete"))
                    {
                        context.RegisterCodeFix(
                            CodeAction.Create(
                                "Use Create",
                                _ => Task.FromResult(
                                    document.WithSyntaxRoot(
                                        syntaxRoot.ReplaceNode(
                                            binaryExpression,
                                            SyntaxFactory.InvocationExpression(
                                                SyntaxFactory.ParseExpression("Angle.FromDegrees"),
                                                SyntaxFactory.ArgumentList(
                                                    SyntaxFactory.SingletonSeparatedList(
                                                        SyntaxFactory.Argument(binaryExpression.Left)))))))),
                            diagnostic);
                    }
                    else if (message.StartsWith("'Radians.operator *(double, Radians)' is obsolete"))
                    {
                        context.RegisterCodeFix(
                            CodeAction.Create(
                                "Use Create",
                                _ => Task.FromResult(
                                    document.WithSyntaxRoot(
                                        syntaxRoot.ReplaceNode(
                                            binaryExpression,
                                            SyntaxFactory.InvocationExpression(
                                                SyntaxFactory.ParseExpression("Angle.FromRadians"),
                                                SyntaxFactory.ArgumentList(
                                                    SyntaxFactory.SingletonSeparatedList(
                                                        SyntaxFactory.Argument(binaryExpression.Left)))))))),
                            diagnostic);
                    }
                }
            }
        }

        private static InvocationExpressionSyntax AngleFromDegrees(ArgumentSyntax valueArgument)
        {
            return SyntaxFactory.InvocationExpression(
                SyntaxFactory.ParseExpression("Angle.FromDegrees"),
                SyntaxFactory.ArgumentList(
                    SyntaxFactory.SingletonSeparatedList(valueArgument)));
        }

        private static InvocationExpressionSyntax AngleFromRadians(ArgumentSyntax valueArgument)
        {
            return SyntaxFactory.InvocationExpression(
                SyntaxFactory.ParseExpression("Angle.FromRadians"),
                SyntaxFactory.ArgumentList(
                    SyntaxFactory.SingletonSeparatedList(valueArgument)));
        }
    }
}


text:
package org.smart4j.framework.annotation;

import java.lang.annotation.*;

/**
 * Created by Administrator on 10/27/2016.
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Aspect {
    Class<? extends Annotation> value();
}