text:
provider_path = Pathname.new(__FILE__).parent.parent
require 'puppet/idrac/util'
require 'nokogiri'
require 'erb'
require 'tempfile'
require 'asm/util'
require 'asm/wsman'
require "asm/firmware"
require 'puppet/idrac/util'
require File.join(provider_path, 'idrac')

Puppet::Type.type(:idrac_fw_installfromuri).provide(
  :wsman,
  :parent => Puppet::Provider::Idrac
) do
  # Special component ids
  IDRAC_ID = 25227
  LC_ID = 28897
  UEFI_DIAGNOSTICS_ID = 25806
  DRIVER_PACK = 18981
  OS_COLLECTOR = 101734

  # Component ids that do not require a reboot (DIRECT UPDATES)
  NO_REBOOT_COMPONENT_IDS = [IDRAC_ID, LC_ID, UEFI_DIAGNOSTICS_ID, DRIVER_PACK, OS_COLLECTOR]

  # Max time to wait for a job to complete
  MAX_WAIT_SECONDS = 3600

  def exists?
    transport # Force initialization, Puppet::Idrac::Util depends on it
    @force_restart = resource[:force_restart]
    @firmwares = ASM::Util.asm_json_array(resource[:idrac_firmware])
    false
  end

  def create
    firmware_instance = ASM::Firmware.new(transport, :logger => Puppet)
    wsman_instance = ASM::WsMan.new(transport, :logger => Puppet)
    firmware_instance.clear_job_queue_retry(wsman_instance) unless resource[:install_staged_firmware]

    sleep 20
    pre = []
    main = []
    @firmwares.each do |firmware|
      Puppet.debug(firmware)
      if [LC_ID, IDRAC_ID].include? firmware['component_id'].to_i
        pre << firmware
      else
        main << firmware
      end
    end
    if pre.size > 0 && !resource[:install_staged_firmware]
      Puppet.debug("LC Update required, installing first")
      update(pre)
    end
    update(main)
    # Ensure LC is up and in good state before exiting
    Puppet::Idrac::Util.wait_for_lc_ready
  end

  def downloaded_jobs
    @scheduled_jobs ||= begin
      jobs = wsman_client.enumerate("http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/root/dcim/DCIM_LifecycleJob")

      jobs.select {|j| j[:job_status] == "Downloaded"}
    end
  end

  def find_downloaded_firmware_job(firmware)
    downloaded_jobs.find do |j|
      j[:name] =~ /Firmware Update:\s+(\S+)/
      match = $1

      firmware["instance_id"] =~ /#{match}/i || firmware["uri_path"] =~ /#{match}/i
    end
  end

  def update(firmware_list)
    statuses = {}

    # Initiate all firmware update jobs
    firmware_list.each do |fw|
      Puppet.debug(fw)

      # Ensure LC is up and in good state before installing the next package, previous update may rebooted iDRAC
      Puppet::Idrac::Util.wait_for_lc_ready

      if resource[:install_staged_firmware]
        job = find_downloaded_firmware_job(fw)
        job_id = job[:instance_id] if job
      else
        config_file = create_xml_config_file(fw["instance_id"],fw["uri_path"])
        job_id = install_from_uri(config_file)
      end

      raise(Puppet::Error, "Failed to initiate firmware job for #{fw}") unless job_id
      raise(Puppet::Error, "Duplicate job id #{job_id} for firmware #{fw}: #{statuses[job_id]}") if statuses[job_id]
      statuses[job_id] = { :job_id => job_id, :status => 'new', :firmware => fw, :start_time => Time.now }
      until statuses[job_id][:status] =~ /Downloaded|Completed|Failed/
        sleep 30
        begin
          statuses[job_id][:status] = checkjobstatus job_id
        rescue ASM::WsMan::Error, RuntimeError => e
          raise if e.is_a?(RuntimeError) && !e.to_s.match(/Job ID not created/)

          statuses[job_id][:status] = 'TemporaryFailure'
          Puppet.warning("Look up job status for #{job_id} failed: #{e}")
        end
        Puppet.debug("Job Status: #{statuses[job_id][:status]}")
        if Time.now - statuses[job_id][:start_time] > MAX_WAIT_SECONDS
          Puppet.warning("Timed out waiting for firmware job #{job_id} to complete")
          statuses[job_id][:status] = 'Failed'
        end
      end
      if statuses[job_id][:status] ==  "Completed"
        Puppet.debug("Firmware update completed successfully")
      elsif statuses[job_id][:status]  ==  "Failed"
        raise Puppet::Error, "Firmware update failed in the lifecycle controller.  Please refer to LifeCycle job logs"
      elsif statuses[job_id][:status] ==  "Downloaded"
        Puppet.debug("Firmware downloaded to idrac")
      end
    end

    statuses.each do |_,v|
      if NO_REBOOT_COMPONENT_IDS.include?(v[:firmware]['component_id'].to_i)
        v[:desired] = "Completed"
        v[:reboot_required] = false
      else
        @force_restart ? v[:desired] = "Completed" : v[:desired] = "Scheduled"
        v[:reboot_required] = true
      end
    end

    Puppet.debug("Disruptive update: %s" % [resource[:disruptive_firmware_update]])
    Puppet.debug("Force Restart: %s" % [resource[:force_restart]])

    if resource[:disruptive_firmware_update] && !resource[:force_restart]
      Puppet.debug("Inside blank loop")
      reboot_firmwares = []
      completed_endstate_firmwares = []
      scheduled_endstate_firmwares = []
    else
      Puppet.debug("Inside normal loop")
      reboot_firmwares = statuses.select {|_,v| v[:reboot_required]}
      completed_endstate_firmwares = statuses.select {|_,v| v[:desired] == "Completed"}
      scheduled_endstate_firmwares = statuses.select{|_,v| v[:desired] == "Scheduled"}
    end

    unless reboot_firmwares.empty?
      reboot_id = nil
      if @force_restart
        reboot_config_file = create_reboot_config_file
        reboot_id = create_reboot_job(reboot_config_file)
      end
      job_queue_config_file = create_job_queue_config(reboot_firmwares.keys,reboot_id)
      Puppet.debug("#{File.read(job_queue_config_file.path)}")
      setup_job_queue(job_queue_config_file)
      if @force_restart
        reboot_status = 'new'
        until reboot_status == 'Reboot Completed'
          sleep 30
          reboot_status = checkjobstatus reboot_id
          Puppet.debug("Reboot Status: #{reboot_status}")
        end
      end
    end

    [scheduled_endstate_firmwares, completed_endstate_firmwares].each do |firmware_set|
      next if firmware_set.empty?

      until firmware_set.values.all? {|v| v[:status] =~ /#{v[:desired]}|Failed|InternalTimeout/}
        firmware_set.each do |key, val|
          if val[:status] != val[:desired] && Time.now - val[:start_time] > MAX_WAIT_SECONDS
            val[:status] = 'InternalTimeout'
          else
            val[:status] = checkjobstatus key
            Puppet.debug("Job Status #{key}: #{val[:status]}")
          end
        end
        sleep 30
      end
    end

    # Raise an error if any firmware jobs failed
    failures = statuses.values.find_all { |v| v[:status] =~ /Failed|InternalTimeout/ }
    if failures.empty?
      Puppet.debug("Firmware update completed successfully")
    else
      Puppet.info("Failed firmware jobs: #{failures}")
      raise Puppet::Error, "Firmware update failed in the lifecycle controller.  Please refer to LifeCycle job logs"
    end
  end

  def wsman_client
    @wsman_client ||= ASM::WsMan::Client.new(transport, {:logger => Puppet})
  end

  def install_from_uri(config_file)
    config_file_path = config_file.path
    schema = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/root/dcim/DCIM_SoftwareInstallationService?CreationClassName=DCIM_SoftwareInstallationService&SystemCreationClassName=DCIM_ComputerSystem&SystemName=IDRAC:ID&Name=SoftwareUpdate"
    resp = wsman_client.invoke("InstallFromURI", schema, :input_file => config_file_path)
    if resp[:return_value] == '4096'
      job_id = resp[:job]
      Puppet.debug("InstallFromURI started")
      Puppet.debug("JOB_ID: #{job_id}")
      return job_id
    else
      Puppet.debug("Error installing From URI config: #{config_file.read}")
      raise Puppet::Error, "Problem running InstallFromURI: #{resp[:message]}"
    end
  end

  def create_xml_config_file(instance_id,path)
    template = <<-EOF
<p:InstallFromURI_INPUT xmlns:p="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/root/dcim/DCIM_SoftwareInstallationService">
<p:URI><%= path %></p:URI>
<p:Target xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
<a:Address>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
<a:ReferenceParameters>
<w:ResourceURI>http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_SoftwareIdentity</w:ResourceURI>
<w:SelectorSet>
<w:Selector Name="InstanceID"><%= instance_id %></w:Selector>
</w:SelectorSet> </a:ReferenceParameters> </p:Target> </p:InstallFromURI_INPUT>
    EOF
    xmlout = ERB.new(template)
    temp_file = Tempfile.new('xml_config')
    temp_file.write(xmlout.result(binding))
    temp_file.close
    temp_file
  end

  def create_reboot_config_file
    template = <<-EOF
<p:CreateRebootJob_INPUT xmlns:p="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/root/dcim/DCIM_SoftwareInstallationService">
  <p:RebootJobType>1</p:RebootJobType>
</p:CreateRebootJob_INPUT>
EOF
    temp_file = Tempfile.new('reboot_config')
    temp_file.write(template)
    temp_file.close
    temp_file
  end

  def create_job_queue_config(job_ids,reboot_id=nil)
    template = <<-EOF
<p:SetupJobQueue_INPUT xmlns:p="http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_JobService"><% job_ids.each do |job_id| %>
<p:JobArray><%= job_id %></p:JobArray><% end %><% if reboot_id %>
<p:JobArray><%= reboot_id %></p:JobArray><% end %>
<p:RunMonth>6</p:RunMonth>
  <p:RunDay>18</p:RunDay>
<p:StartTimeInterval>TIME_NOW</p:StartTimeInterval>
</p:SetupJobQueue_INPUT>
EOF
    xmlout = ERB.new(template)
    temp_file = Tempfile.new('jq_config')
    temp_file.write(xmlout.result(binding))
    temp_file.close
    temp_file
  end

  def create_reboot_job(reboot_file)
    url = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/root/dcim/DCIM_SoftwareInstallationService?CreationClassName=DCIM_SoftwareInstallationService&SystemCreationClassName=DCIM_ComputerSystem&SystemName=IDRAC:ID&Name=SoftwareUpdate"
    Puppet.debug("Creating Reboot Job")
    resp = wsman_client.invoke("CreateRebootJob", url, :input_file => reboot_file.path)
    if resp[:return_value] == '4096'
      reboot_id = resp[:reboot_job_id]
      Puppet.debug("Reboot Job scheduled successfully")
      Puppet.debug("Reboot Job ID: #{reboot_id}")
      return reboot_id
    else
      Puppet.debug("Error with Reboot Job config: #{reboot_file.read}")
      raise Puppet::Error, "Problem scheduling reboot.  Problem message: #{resp[:message]}"
    end
  end

  def setup_job_queue(job_queue_config_file)
    url = "http://schemas.dell.com/wbem/wscim/1/cim-schema/2/DCIM_JobService?CreationClassName=\"DCIM_JobService\"&SystemName=\"Idrac\"&Name=\"JobService\"&SystemCreationClassName=\"DCIM_ComputerSystem\" -N root/dcim"
    Puppet.debug("Setting up Job Queue")
    4.times do |t|
      resp = wsman_client.invoke("SetupJobQueue", url, :input_file => job_queue_config_file.path)
      if resp[:return_value] == '0'
        Puppet.debug("Job Queue created successfully")
        break
      else
        if t < 3
          Puppet.debug('Error scheduling Job Queue.  ..retrying')
          sleep 10
        else
          Puppet.debug("Error Job Queue config: #{File.read(job_queue_config_file.path)}")
          raise Puppet::Error, "Problem scheduling the job queue.  Message: #{resp[:message]}"
        end
      end
    end
  end
end


text:
'use strict';

var fs        = require('fs');
var path      = require('path');
var basename  = path.basename(module.filename);
var db        = {};
const Sequelize = require('sequelize');
const DATABASE_URL = process.env.DATABASE_URL || 'postgres://localhost:5432/rescuerr'
const sequelize = new Sequelize(DATABASE_URL);
fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CarteBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * DieuRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class DieuRepository extends EntityRepository
{
}


text:
import { ElementOffcanvasContent } from '../elements'

export default {
  name: 'VkOffcanvasContent',
  functional: true,
  render: ElementOffcanvasContent.render
}


text:
# CallbackEvent.DeliveryState Property

Delivery state of message

**Namespace:** Bandwidth.Net
**Assembly:** Bandwidth.Net (in Bandwidth.Net.dll) Version: 3.0.3

## Syntax

**C#**

``` C#
public MessageDeliveryState DeliveryState { get; set; }
```

#### Property Value
Type: MessageDeliveryState

## See Also

#### Reference
CallbackEvent Class
Bandwidth.Net Namespace


text:
Simple tool to move randomicaly files from a directory to another

Usage:
```
mv_subset <source_dir> <dest_dir> <amount>
```


text:
import uuid

from manilaclient.openstack.common.apiclient import exceptions as manila_ex
import mock
import testtools

from sahara import exceptions
from sahara.service import shares
from sahara.tests.unit import base

_NAMENODE_IPS = ['192.168.122.3', '192.168.122.4']
_DATANODE_IPS = ['192.168.122.5', '192.168.122.6', '192.168.122.7']

class _FakeShare(object):

    def __init__(self, id='12345678-1234-1234-1234-123456789012',
                 share_proto='NFS',
                 export_location='192.168.122.1:/path'):
        self.id = id
        self.share_proto = share_proto
        self.export_location = export_location
        self.allow = mock.Mock()

def _mock_node_group(ips, share_list):
    # Returns a mocked node group and a list of mocked
    # execute_command functions for its instances.

    execute_mocks = [mock.Mock(return_value=(None, "centos")) for ip in ips]
    get_id = mock.Mock(return_value=uuid.uuid4())
    instances = [
        mock.Mock(
            internal_ip=ip,
            remote=mock.Mock(
                return_value=mock.Mock(
                    __enter__=mock.Mock(
                        return_value=mock.Mock(
                            execute_command=execute_mocks[index])),
                    __exit__=mock.Mock())))
        for index, ip in enumerate(ips)]

    node_group = mock.Mock(instances=instances,
                           shares=share_list,
                           __getitem__=get_id)
    return node_group, execute_mocks

def _setup_calls():
    return [
        mock.call('lsb_release -is'),
        mock.call('rpm -q nfs-utils || yum install -y nfs-utils',
                  run_as_root=True)]

def _expected_calls(local_path, remote_path, access_argument):
    return [
        mock.call('mkdir -p %s' % local_path, run_as_root=True),
        mock.call("mount | grep '%(remote_path)s' | grep '%(local_path)s' | "
                  "grep nfs || mount -t nfs %(access_argument)s "
                  "%(remote_path)s %(local_path)s" %
                  {
                      "local_path": local_path,
                      "remote_path": remote_path,
                      "access_argument": access_argument
                  },
                  run_as_root=True)]

class TestShares(base.SaharaTestCase):

    @mock.patch('sahara.context.set_current_instance_id')
    @mock.patch('sahara.utils.openstack.manila.client')
    def test_mount_nfs_shares_to_ng(self, f_manilaclient, f_context):

        share = _FakeShare()
        f_manilaclient.return_value = mock.Mock(
            shares=mock.Mock(
                get=mock.Mock(return_value=share)))

        namenode_group, namenode_executors = _mock_node_group(
            _NAMENODE_IPS,
            [{
                'id': '12345678-1234-1234-1234-123456789012',
                'access_level': 'rw',
                'path': '/mnt/localpath'
            }])

        datanode_group, datanode_executors = _mock_node_group(
            _DATANODE_IPS, [])

        cluster = mock.Mock(
            node_groups=[namenode_group, datanode_group], shares=[])

        shares.mount_shares(cluster)

        permissions = [mock.call('ip', ip, 'rw') for ip in _NAMENODE_IPS]
        share.allow.assert_has_calls(permissions, any_order=True)

        for executor in namenode_executors:
            executor.assert_has_calls(
                _expected_calls('/mnt/localpath', '192.168.122.1:/path', '-w'))
        for executor in datanode_executors:
            self.assertEqual(0, executor.call_count)

    @mock.patch('sahara.context.set_current_instance_id')
    @mock.patch('sahara.utils.openstack.manila.client')
    def test_mount_nfs_shares_to_cluster(self, f_manilaclient, f_context):

        global_share = _FakeShare()
        namenode_only_share = _FakeShare(
            id='DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF',
            export_location='192.168.122.2:/path')
        all_shares = {share.id: share for share in
                      (global_share, namenode_only_share)}

        f_manilaclient.return_value = mock.Mock(
            shares=mock.Mock(
                get=mock.Mock(
                    side_effect=lambda x: all_shares[x])))

        namenode_group, namenode_executors = _mock_node_group(
            ['192.168.122.3', '192.168.122.4'],
            [
                {
                    'id': '12345678-1234-1234-1234-123456789012',
                    'access_level': 'rw',
                    'path': '/mnt/localpath'
                },
                {
                    'id': 'DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF'
                }
            ])

        datanode_group, datanode_executors = _mock_node_group(
            ['192.168.122.5', '192.168.122.6', '192.168.122.7'], [])

        cluster = mock.Mock(
            node_groups=[namenode_group, datanode_group],
            shares=[
                {
                    'id': '12345678-1234-1234-1234-123456789012',
                    'access_level': 'ro',
                    'path': '/mnt/somanylocalpaths'
                }
            ])

        shares.mount_shares(cluster)

        all_permissions = [mock.call('ip', ip, 'ro')
                           for ip in _NAMENODE_IPS + _DATANODE_IPS]
        global_share.allow.assert_has_calls(all_permissions, any_order=True)

        namenode_permissions = [mock.call('ip', ip, 'rw')
                                for ip in _NAMENODE_IPS]
        namenode_only_share.allow.assert_has_calls(namenode_permissions,
                                                   any_order=True)

        for executor in namenode_executors:
            executor.assert_has_calls(
                _setup_calls() +
                _expected_calls('/mnt/somanylocalpaths',
                                '192.168.122.1:/path', '-r') +
                _expected_calls('/mnt/DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF',
                                '192.168.122.2:/path', '-w'),
                any_order=True)
            self.assertEqual(6, executor.call_count)

        for executor in datanode_executors:
            executor.assert_has_calls(
                _expected_calls('/mnt/somanylocalpaths',
                                '192.168.122.1:/path', '-r'))
            self.assertEqual(4, executor.call_count)

    @mock.patch('sahara.context.set_current_instance_id')
    @mock.patch('sahara.utils.openstack.manila.client')
    def test_share_does_not_exist(self, f_manilaclient, f_context):

        f_manilaclient.return_value = mock.Mock(
            shares=mock.Mock(
                get=mock.Mock(
                    side_effect=manila_ex.NotFound)))

        namenode_group, namenode_executors = _mock_node_group(
            ['192.168.122.3', '192.168.122.4'],
            [
                {
                    'id': '12345678-1234-1234-1234-123456789012',
                    'access_level': 'rw',
                    'path': '/mnt/localpath'
                },
                {
                    'id': 'DEADBEEF-DEAD-BEEF-DEAD-BEEFDEADBEEF'
                }
            ])

        datanode_group, datanode_executors = _mock_node_group(
            ['192.168.122.5', '192.168.122.6', '192.168.122.7'], [])

        cluster = mock.Mock(
            node_groups=[namenode_group, datanode_group],
            shares=[
                {
                    'id': '12345678-1234-1234-1234-123456789012',
                    'access_level': 'ro',
                    'path': '/mnt/somanylocalpaths'
                }
            ])

        with testtools.ExpectedException(exceptions.NotFoundException):
            shares.mount_shares(cluster)


text:
package flannelmigration

import (
	"context"
	"fmt"
	"strconv"
	"time"

	client "github.com/projectcalico/libcalico-go/lib/clientv3"
	log "github.com/sirupsen/logrus"
	v1 "k8s.io/api/core/v1"
	"k8s.io/client-go/kubernetes"
)

const (
	calicoNodeContainerName     = "calico-node"
	calicoCniContainerName      = "install-cni"
	calicoCniConfigEnvName      = "CNI_CONF_NAME"
	calicoVxlanTunnelDeviceName = "vxlan.calico"

	// Sync period between kubelet and CNI config file change.
	// see https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/dockershim/network/cni/cni.go#L48
	defaultSyncConfigPeriod = time.Second * 5

	// For testing
	flannelMigrationPauseSecondsKey = "projectcalico.org/flannel-migration-pause-seconds"
)

// networkMigrator responsible for migrating Flannel vxlan data plane to Calico vxlan data plane.
type networkMigrator struct {
	ctx          context.Context
	calicoClient client.Interface
	k8sClientset *kubernetes.Clientset
	config       *Config

	// Calico node image used by network migrator.
	calicoImage string

	// Calico CNI config file name
	calicoCNIConfigName string
}

func NewNetworkMigrator(ctx context.Context, k8sClientset *kubernetes.Clientset, calicoClient client.Interface, config *Config) *networkMigrator {
	return &networkMigrator{
		ctx:          ctx,
		calicoClient: calicoClient,
		k8sClientset: k8sClientset,
		config:       config,
	}
}

// Initialise network migrator.
func (m *networkMigrator) Initialise() error {
	// Set calico image
	d := daemonset(m.config.CalicoDaemonsetName)
	image, err := d.GetContainerImage(m.k8sClientset, namespaceKubeSystem, calicoNodeContainerName)
	if err != nil {
		return err
	}
	m.calicoImage = image

	// Set calico CNI config file name
	cniConf, err := d.GetContainerEnv(m.k8sClientset, namespaceKubeSystem, calicoCniContainerName, calicoCniConfigEnvName)
	if err != nil {
		return err
	}
	m.calicoCNIConfigName = cniConf

	log.Infof("Network migrator initialised, container image %s, CNI config %s/%s.", m.calicoImage, m.config.CniConfigDir, m.calicoCNIConfigName)
	return nil
}

// Remove Flannel network device/routes on node.
// Write a dummy calico cni config file in front of Flannel/Canal CNI config.
// This will prevent Flannel CNI from running and make sure new pod created will not get networked
// until Calico CNI been correctly installed.
func (m *networkMigrator) removeFlannelNetworkAndInstallDummyCalicoCNI(node *v1.Node) error {
	// Deleting a tunnel device will remove routes, ARP and FDB entries related with the device.
	// Deleting cni0 device to remove routes to local pods.
	// It is possible tunnel device or cni0 has been deleted already.
	dummyCNI := `{ "name": "dummy", "plugins": [{ "type": "flannel-migration-in-progress" }]}`

	var cmd string
	if m.config.IsRunningCanal() {
		// Canal creates tunnel device but with no bridge. It uses Calico CNI.
		cmd = fmt.Sprintf("ip link show flannel.%d || exit 0 && { echo '%s' > /host/%s/%s ; ip link delete flannel.%d; } && exit 0 || exit 1",
			m.config.FlannelVNI, dummyCNI, m.config.CniConfigDir, m.calicoCNIConfigName, m.config.FlannelVNI)
	} else {
		// Flannel creates cni0 bridge and tunnel device. It delegates to bridge CNI.
		cmd = fmt.Sprintf("{ ip link show cni0; ip link show flannel.%d; } || exit 0 && { echo '%s' > /host/%s/%s ; ip link delete cni0 type bridge; ip link delete flannel.%d; } && exit 0 || exit 1",
			m.config.FlannelVNI, dummyCNI, m.config.CniConfigDir, m.calicoCNIConfigName, m.config.FlannelVNI)
	}

	// Run a remove-flannel pod with specified nodeName, this will bypass kube-scheduler.
	// https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodename
	pod := k8spod("remove-flannel")
	podLog, err := pod.RunPodOnNodeTillComplete(m.k8sClientset, namespaceKubeSystem, m.calicoImage, node.Name, cmd, m.config.CniConfigDir, true, true)
	if podLog != "" {
		log.Infof("remove-flannel pod logs: %s.", podLog)
	}

	// Wait twice as long as default sync period so kubelet has picked up dummy CNI config.
	// We probably need something better here but currently no API available for us to know
	// if kubelet sees new config.
	time.Sleep(2 * defaultSyncConfigPeriod)
	return err
}

// Check if node has got Calico vxlan network.
func (m *networkMigrator) checkCalicoVxlan(node *v1.Node) error {
	// Check if Calico tunnel device exists for 10 seconds.
	cmd := fmt.Sprintf("for i in $(seq 1 10); do ip link show %s && code=0 && break || code=$? && sleep 1; done; (exit $code)", calicoVxlanTunnelDeviceName)

	pod := k8spod("check-calico")
	podLog, err := pod.RunPodOnNodeTillComplete(m.k8sClientset, namespaceKubeSystem, m.calicoImage, node.Name, cmd, m.config.CniConfigDir, true, true)
	if podLog != "" {
		log.Infof("check-calico pod logs: %s.", podLog)
	}

	return err
}

// Drain node, remove Flannel and setup Calico network for a node.
func (m *networkMigrator) setupCalicoNetworkForNode(node *v1.Node) error {
	log.Infof("Setting node label to disable Flannel daemonset pod on node %s.", node.Name)
	// Set two node labels at the beginning of network migration.
	// - Label nodeNetworkNone stops Flannel pod from being scheduled on this node.
	//   Flannel pod currently running on the node starts to be evicted as the side effect.
	// - Label nodeMigrationInProgress marks that the node is in migration process.
	n := k8snode(node.Name)
	err := n.addNodeLabels(m.k8sClientset, nodeNetworkNone, nodeMigrationInProgress)
	if err != nil {
		log.WithError(err).Errorf("Error adding node labels to disable Flannel network and mark migration in process for node %s.", node.Name)
		return err
	}

	// Cordon and Drain node. Make sure no pod (except daemonset pod or pod with nodeName selector) can run on this node.
	err = n.Drain()
	if err != nil {
		log.WithError(err).Errorf("failed to drain node %s", node.Name)
		return err
	}

	log.Infof("Removing flannel tunnel device/routes on %s.", node.Name)
	// Remove Flannel network from node.
	// Note Flannel vxlan tunnel device (flannel.1) is created by Flannel daemonset pod (not Flannel CNI)
	// Therefor if Flannel daemonset pod can not run on this node, the tunnel device will not be recreated
	// after we delete it.
	err = m.removeFlannelNetworkAndInstallDummyCalicoCNI(node)
	if err != nil {
		log.WithError(err).Errorf("failed to remove flannel network on node %s", node.Name)
		return err
	}

	log.Infof("Deleting non-host-networked pods on %s.", node.Name)
	// Delete all pods on the node which is not host networked.
	err = n.deletePodsForNode(m.k8sClientset, func(pod *v1.Pod) bool {
		return !pod.Spec.HostNetwork
	})
	if err != nil {
		log.WithError(err).Errorf("failed to delete non-host-networked pods on node %s", node.Name)
		return err
	}

	// Set node label so that Calico daemonset pod start to run on this node.
	// This will install Calico CNI configuration file.
	// It will take the preference over Flannel CNI config or Canal CNI config.
	log.Infof("Setting node lable to enable Calico daemonset pod on %s.", node.Name)
	err = n.addNodeLabels(m.k8sClientset, nodeNetworkCalico)
	if err != nil {
		log.WithError(err).Errorf("Error adding node label to enable Calico network for node %s.", node.Name)
		return err
	}

	log.Infof("Wait up to 5 minutes for Calico daemonset pod to become Ready on %s.", node.Name)
	// Calico daemonset pod should start running now.
	err = n.waitPodReadyForNode(m.k8sClientset, namespaceKubeSystem, 1*time.Second, 5*time.Minute, calicoPodLabel)
	if err != nil {
		log.WithError(err).Errorf("Calico node pod failed on node %s", node.Name)
		return err
	}
	log.Infof("Calico daemonset pod is Ready on %s.", node.Name)

	// Calico network should have been setup.
	err = m.checkCalicoVxlan(node)
	if err != nil {
		log.WithError(err).Errorf("failed to check calico vxlan network on node %s", node.Name)
		return err
	}

	// Uncordon node.
	err = n.Uncordon()
	if err != nil {
		log.WithError(err).Errorf("failed to uncordon node %s", node.Name)
		return err
	}

	// Remove nodeMigrationInProgress label so that if migration controller restarts,
	// it will not try to to migrate this node again.
	err = n.removeNodeLabels(m.k8sClientset, nodeMigrationInProgress)
	if err != nil {
		log.WithError(err).Errorf("failed to remove node migration in process label for node %s", node.Name)
		return err
	}

	log.Infof("Calico networking is running on %s.", node.Name)
	return nil
}

// MigrateNodes setup Calico network for array of nodes.
func (m *networkMigrator) MigrateNodes(nodes []*v1.Node) error {
	log.Infof("Start network migration process for %d nodes.", len(nodes))
	for i, node := range nodes {
		// This is for testing purpose.
		// Pause until user remove a pause-seconds label.
		// This label has to be added to node before running migration controller.
		val, err := getNodeLabelValue(node, flannelMigrationPauseSecondsKey)
		if err == nil {
			// Label exists.
			if seconds, err := strconv.Atoi(val); err == nil && seconds > 0 {
				// Timeout is a valid number
				n := k8snode(node.Name)
				err = n.waitForNodeLabelDisappear(m.k8sClientset, flannelMigrationPauseSecondsKey, 1*time.Second, time.Duration(seconds)*time.Second)
				if err != nil {
					log.WithError(err).Warnf("Error waiting for pause migration label.")
				}
			}
		}

		log.Infof("Start setting up Calico network for node %s[index %d].", node.Name, i)
		err = m.setupCalicoNetworkForNode(node)
		if err != nil {
			// Error migrating a node. However, if the node has been removed before migration controller started,
			// just log and continue on to next node.
			n := k8snode(node.Name)
			notFound, checkErr := n.CheckNotExists(m.k8sClientset)
			if checkErr != nil {
				log.WithError(checkErr).Errorf("Check existence of %s failed.", node.Name)
			} else if notFound {
				log.Infof("Node %s has been removed, continue on to next node...", node.Name)
				continue
			}
			return err
		}
	}
	log.Infof("%d nodes completed network migration process.", len(nodes))

	return nil
}


text:
layout: post
status: publish
published: true
title: Autenticidade no git com o uso de chave GPG
author:
  display_name: Endrigo Antonini
  url: http://blog.endrigoantonini.com.br
author_url: http://blog.endrigoantonini.com.br
excerpt: "É muito comum o uso do git no dia a dia, seja ele para controlar o código fonte de sua organização, projetos pessoais ou outras funcionalidades. Enquanto o repositório é utilizado por apenas uma pessoa e até mesmo em grandes corporações é difícil que alguém faça a seguinte pergunta: \"Mas o que garante que aquele commit foi determinada pessoa quem fez?\"."
date: '2018-12-22 12:00:00 -0300'
date_gmt: '2018-12-22 12:00:00 -0300'
categories:
- Tecnologia
- Segurança
tags:
- Tecnologia
- Autenticidade
- Segurança
- git
- GPG
- commit
comments: []
---

É muito comum o uso do git no dia a dia, seja ele para controlar o código fonte de sua organização, projetos pessoais entre outros. Mas uma coisas que é comum em qualquer ambiente é de que as pessoas façam a seguinte pergunta: "Mas o que garante que aquele commit realmente foi determinada pessoa que o fez?".

Essa é uma pergunta que quase não é feita, mas que todo desenvolvedor, product owner, product manager deveria fazer. Isso pois todo commit está atrelado a um nome e um e-mail, mas não existem travas que impeçam que uma pessoa utilize o nome e e-mail de outra para realizar commits.

O GIT é um repositório descentralizado e é tão aberto e permissivo que não é necessário a existência de um nó principal para que um projeto exista ou seja controlado por ele. Hipoteticamente falando, o protocolo permite que um determinado "desenvolvedor A" possa ter acesso ao repositório que está armazenado na máquina do "desenvolvedor B" sem que ele faça qualquer consulta ao servidor que eles utilizaram para fazer o clone, isso sem levar em conta controle de acesso que é aplicado em outras camadas.

Apesar de o cenário descrito acima não ser tão comum, nada impede que uma pessoa faça o clone de um repositório, configure o git local para utilizar o nome "John Doe" e email "fulano@example.com" execute qualquer alteração, realizar o commit e mandar este commit para um repositório em comum (Exemplo: GitHub, GitLab, Bitbucket...) ou mesmo submeta para o repositório do colaborador que foi utilizado como ponto de partida para o git clone. (Óbvio, para realizar o clone e pull é primordial ter permissão de leitura e o push permissão de escrita no repositório).

Com esse cenário acabamos de exemplificar como que um desenvolvedor de má índole, pode criar problemas para um projeto e ao mesmo tempo tentar colocar a culpa em outro desenvolvedor.

E como resolver esse problema?

Essa situação pode ser resolvida usando chaves GPG, onde cada desenvolvedor utiliza um par de chaves para assinar aquele commit e assim garantir a autenticidade deste.

Não irei abordar nesse artigo como gerar uma chave GPG (quem sabe seja conteúdo para um próximo post). Por isso vou considerar que você já possui o cliente GPG instalado e um par de chaves criado. Vale lembrar que o e-mail utilizado na chave GPG também deve ser o mesmo utilizado nas configurações do GIT. Com o par de chaves na máquina iremos realizar a configuração para que o GIT utilize o GPG para assinar todos os seus commits.

Para isso execute o comando abaixo para listar as chaves que você possui em sua máquina:

{% highlight bash %}
$ gpg --list-secret-keys --keyid-format LONG
/root/.gnupg/secring.gpg
-----------------------------------
sec   9999X/ABCDEFGHIJ123456 2016-01-01
uid                          My Name (Comment of the key) <fulano@example.com>
ssb   9999X/1234567890ABCEDF 2016-09-06
{% endhighlight %}

Para fazer a configuração utilize o ID que encontrasse na linha sec logo após o caracter /, ou seja, nesse caso utilize o valor ABCDEFGHIJ123456 no comando abaixo para identificar qual a chave deve ser utilizada para assinar o commit.

{% highlight bash %}
$ git config --global user.signingkey "ABCDEFGHIJ123456"
#                                      ^ Coloque aqui o ID da chave GPG
{% endhighlight %}

Sendo que o comando acima simplesmente indica qual a chave que o GIT deve utilizar. Para assinar o commit adicione o parâmetro -s na chamada do git, mas o melhor a se fazer é executar a sequência de comandos abaixo que irá realizar a configuração do GIT para sempre assinar os commits.

{% highlight bash %}
# Configura que o GIT utilize o executável gpg para realizar o processo de assinatura.
$ git config --global gpg.program gpg
# Configura para que execute a assinatura de commits
$ git config --global commit.gpgsign true
{% endhighlight %}

Os comandos acima configuram para que o GIT sempre assine os commits com a chave previamente configurada e também adicionamos a linha que efetua a configuração de qual executável deve ser utilizado para realizar a assinatura.

Dos repositórios que utilizo, apenas o GitHub exibe os commits que são assinados de uma forma diferente conforme pode ser visto na imagem abaixo:

Outros repositórios como Bitbucket e GitLab possuem essa funcionalidade no backlog mas ainda não foram implementados. Considerando que você não utiliza o GitHub, ou que você não utiliza nenhum gerenciador, execute o comando abaixo para exibir informações de assinatura do commit.

{% highlight bash %}
# Exibe no log informações de assinatura do commit
$ git log --show-signature
# Exibe informações de assinatura do commit selecionado
$ git show --show-signature <commit_hash>
{% endhighlight %}

Conclusão

As ações acima fazem com que seu repositório se torne muito mais seguro nos quesitos de integridade e também de não repúdio. Isso pois com o uso dessa configuração garantimos que o commit que está no repositório foi criado por aquela pessoa efetivamente.

IMPORTANTE:Não esqueça de utilizar passphrase no seu par de chaves GPG!

Referências:

Git Tools - Signing Your Work


text:
package rx.redis.commands.it

import rx.redis._
import serialization.ByteBufReader

class HashCommandsSpec extends ItCommandsSuite {

  implicit val frameless = ByteBufReader.readFramelessString

  test("HGET") {
    client.command(cmd"HSET foo bar baz")

    assert(client.hget[String]("foo", "bar").synch == Some("baz"))
    assert(client.hget[String]("foo", "baz").synch == None)
    assert(client.hget[String]("bar", "baz").synch == None)
  }

  test("HGETALL") {
    val m = Map("bar" -> "1", "baz" -> "2", "qux" -> "3")
    m foreach {
      case (k, v) => client.command(cmd"HSET foo $k $v")
    }

    val result = client.hgetAll[String]("foo").synchAll.toMap
    assert(result == m)

    assert(client.hgetAll[String]("bar").synchAll.isEmpty)
  }

}


text:
package org.jkiss.dbeaver.ext.oracle.model;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.access.DBAUser;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCUtils;
import org.jkiss.dbeaver.model.meta.Association;
import org.jkiss.dbeaver.model.meta.IPropertyCacheValidator;
import org.jkiss.dbeaver.model.meta.LazyProperty;
import org.jkiss.dbeaver.model.meta.Property;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSObject;
import org.jkiss.dbeaver.model.struct.DBSObjectLazy;

import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Collection;

/**
 * OracleUser
 */
public class OracleUser extends OracleGrantee implements DBAUser, DBSObjectLazy<OracleDataSource>
{
    private static final Log log = Log.getLog(OracleUser.class);

    private long id;
    private String name;
    private String externalName;
    private String status;
    private Timestamp createDate;
    private Timestamp lockDate;
    private Timestamp expiryDate;
    private Object defaultTablespace;
    private Object tempTablespace;
    private Object profile;
    private String consumerGroup;
    private transient String password;

    public OracleUser(OracleDataSource dataSource)
    {
        super(dataSource);
    }

    public OracleUser(OracleDataSource dataSource, ResultSet resultSet) {
        super(dataSource);
        this.id = JDBCUtils.safeGetLong(resultSet, "USER_ID");
        this.name = JDBCUtils.safeGetString(resultSet, "USERNAME");
        this.externalName = JDBCUtils.safeGetString(resultSet, "EXTERNAL_NAME");
        this.status = JDBCUtils.safeGetString(resultSet, "ACCOUNT_STATUS");

        this.createDate = JDBCUtils.safeGetTimestamp(resultSet, "CREATED");
        this.lockDate = JDBCUtils.safeGetTimestamp(resultSet, "LOCK_DATE");
        this.expiryDate = JDBCUtils.safeGetTimestamp(resultSet, "EXPIRY_DATE");
        this.defaultTablespace = JDBCUtils.safeGetString(resultSet, "DEFAULT_TABLESPACE");
        this.tempTablespace = JDBCUtils.safeGetString(resultSet, "TEMPORARY_TABLESPACE");

        this.profile = JDBCUtils.safeGetString(resultSet, "PROFILE");
        this.consumerGroup = JDBCUtils.safeGetString(resultSet, "INITIAL_RSRC_CONSUMER_GROUP");
    }

    @Property(order = 1)
    public long getId()
    {
        return id;
    }

    @NotNull
    @Override
    @Property(viewable = true, order = 2)
    public String getName() {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    @Property(order = 3)
    public String getExternalName()
    {
        return externalName;
    }

    @Property(viewable = true, order = 4)
    public String getStatus()
    {
        return status;
    }

    @Property(viewable = true, order = 5)
    public Timestamp getCreateDate()
    {
        return createDate;
    }

    @Property(order = 6)
    public Timestamp getLockDate()
    {
        return lockDate;
    }

    @Property(order = 7)
    public Timestamp getExpiryDate()
    {
        return expiryDate;
    }

    @Property(order = 8)
    @LazyProperty(cacheValidator = OracleTablespace.TablespaceReferenceValidator.class)
    public Object getDefaultTablespace(DBRProgressMonitor monitor) throws DBException
    {
        return OracleTablespace.resolveTablespaceReference(monitor, this, "defaultTablespace");
    }

    @Property(order = 9)
    @LazyProperty(cacheValidator = OracleTablespace.TablespaceReferenceValidator.class)
    public Object getTempTablespace(DBRProgressMonitor monitor) throws DBException
    {
        return OracleTablespace.resolveTablespaceReference(monitor, this, "tempTablespace");
    }

    @Override
    public Object getLazyReference(Object propertyId)
    {
        if ("defaultTablespace".equals(propertyId)) {
            return defaultTablespace;
        } else if ("tempTablespace".equals(propertyId)) {
            return tempTablespace;
        } else if ("profile".equals(propertyId)) {
            return profile;
        } else {
            return null;
        }
    }

    @Property(order = 10)
    @LazyProperty(cacheValidator = ProfileReferenceValidator.class)
    public Object getProfile(DBRProgressMonitor monitor) throws DBException
    {
        return OracleUtils.resolveLazyReference(monitor, getDataSource(), getDataSource().profileCache, this, "profile");
    }

    @Property(order = 11)
    public String getConsumerGroup()
    {
        return consumerGroup;
    }

    /**
     * Passwords are never read from database. It is used to create/alter schema/user
     * @return password or null
     */
    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    @Override
    @Association
    public Collection<OraclePrivRole> getRolePrivs(DBRProgressMonitor monitor) throws DBException
    {
        return rolePrivCache.getAllObjects(monitor, this);
    }

    @Nullable
    @Override
    public DBSObject refreshObject(@NotNull DBRProgressMonitor monitor) throws DBException {
        return super.refreshObject(monitor);
    }

    public static class ProfileReferenceValidator implements IPropertyCacheValidator<OracleUser> {
        @Override
        public boolean isPropertyCached(OracleUser object, Object propertyId)
        {
            return
                object.getLazyReference(propertyId) instanceof OracleUserProfile ||
                object.getLazyReference(propertyId) == null ||
                object.getDataSource().profileCache.isFullyCached();
        }
    }

}


text:
#ifndef RTTR_DATA_ADDRESS_CONTAINER_H_
#define RTTR_DATA_ADDRESS_CONTAINER_H_

#include "rttr/detail/base/core_prerequisites.h"

#include <memory>

namespace rttr
{

class type;

namespace detail
{

/*!
 * This class bundles all the data necessary to forward
 * data to ctors, dtors, properties or methods.
 */
struct data_address_container
{
    type    m_type;
    type    m_wrapped_type;
    void*   m_data_address;
    void*   m_data_address_wrapped_type;
};

} // end namespace detail
} // end namespace rttr

#endif // RTTR_DATA_ADDRESS_CONTAINER_H_


text:
"""
Read tuples from a corpus consisting of categorized strings.
For example, from the question classification corpus:

NUM:dist How far is it from Denver to Aspen ?
LOC:city What county is Modesto , California in ?
HUM:desc Who was Galileo ?
DESC:def What is an atom ?
NUM:date When did Hawaii become a state ?
"""

# based on PPAttachmentCorpusReader
from six import string_types

from nltk import compat
from nltk.corpus.reader.util import *
from nltk.corpus.reader.api import *

# [xx] Should the order of the tuple be reversed -- in most other places
# in nltk, we use the form (data, tag) -- e.g., tagged words and
# labeled texts for classifiers.
class StringCategoryCorpusReader(CorpusReader):
    def __init__(self, root, fileids, delimiter=' ', encoding='utf8'):
        """
        :param root: The root directory for this corpus.
        :param fileids: A list or regexp specifying the fileids in this corpus.
        :param delimiter: Field delimiter
        """
        CorpusReader.__init__(self, root, fileids, encoding)
        self._delimiter = delimiter

    def tuples(self, fileids=None):
        if fileids is None: fileids = self._fileids
        elif isinstance(fileids, string_types): fileids = [fileids]
        return concat([StreamBackedCorpusView(fileid, self._read_tuple_block,
                                              encoding=enc)
                       for (fileid, enc) in self.abspaths(fileids, True)])

    def raw(self, fileids=None):
        """
        :return: the text contents of the given fileids, as a single string.
        """
        if fileids is None: fileids = self._fileids
        elif isinstance(fileids, string_types): fileids = [fileids]
        return concat([self.open(f).read() for f in fileids])

    def _read_tuple_block(self, stream):
        line = stream.readline().strip()
        if line:
            return [tuple(line.split(self._delimiter, 1))]
        else:
            return []


text:
layout: post
title: "SSIS Basics: Move data"
permalink: ssis-basics-move-data
date: 2017-10-28 01:56:22
comments: true
description: "SSIS Basics: Move data"
keywords: ""
category: "MSSQL Server SSIS"

tags:

---
Using SQL Server Integration Services (SSIS), we can easily move data between data sources and schedule the task as a SQL Agent job.
To demonstrate, below are the steps required to upload data from a SQL Server database into a Netezza database (using OLE DB to ODBC).

1. Install Visual Studio and SQL Server Data Tools (SSDT)

2. Create a Visual Studio SSIS project.
   * Set project compatibility to match SQL Server version:
     * `Properties > Configuration Properties > General > TargetServerVersion`
     * If you are prompted to reload all files, select "Yes to All".

3. In the package designer's "Control Flow" tab, add a [Data Flow Task](https://docs.microsoft.com/en-us/sql/integration-services/control-flow/data-flow-task) from the SSIS Toolbox. I recommend attaching success and failure notifications.

   ![control_flow](../images/ssis_odbc/zcontrol_flow.png){:class="img-border"}

4. In the Data Flow Task, add a "Source Assistant" to create the OLE DB connection to SQL Server and add an "ODBC Destination" to Netezza.
   * ODBC connection must exist on all servers that run this SSIS package

   ![data_flow](../images/ssis_odbc/zdata_flow.png){:class="img-border"}

5. Select `Project > Deploy` to upload the package into an SSIS catalog.

   ![ssis_catalog](../images/ssis_odbc/zssis_catalog.png){:class="img-border"}

6. Create a SQL Agent job to schedule and run the uploaded SSIS package.
   * You will encounter an error at this step if the proper compatibility is not set (step 2).

   ![agent_job](../images/ssis_odbc/zagent_job.png){:class="img-border"}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /home/debian/www/jobeet/src/Erlem/JobeetBundle</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/home/debian/www/jobeet/src/Erlem/JobeetBundle

(Dashboard)

Code Coverage

Lines

Functions and Methods

Classes and Traits

      Total

           60.64% covered (warning)

60.64%

245 / 404

           52.53% covered (warning)

52.53%

52 / 99

           35.71% covered (danger)

35.71%

5 / 14

       Controller

           35.45% covered (danger)

35.45%

39 / 110

           25.00% covered (danger)

25.00%

3 / 12

           0.00% covered (danger)

0.00%

0 / 3

       DataFixtures

           100.00% covered (success)

100.00%

85 / 85

           100.00% covered (success)

100.00%

4 / 4

           100.00% covered (success)

100.00%

2 / 2

       DependencyInjection

           0.00% covered (danger)

0.00%

0 / 11

           0.00% covered (danger)

0.00%

0 / 2

           0.00% covered (danger)

0.00%

0 / 2

       Entity

           58.47% covered (warning)

58.47%

69 / 118

           54.79% covered (warning)

54.79%

40 / 73

           0.00% covered (danger)

0.00%

0 / 3

       Form

           0.00% covered (danger)

0.00%

0 / 28

           0.00% covered (danger)

0.00%

0 / 3

           0.00% covered (danger)

0.00%

0 / 1

       Repository

           100.00% covered (success)

100.00%

40 / 40

           100.00% covered (success)

100.00%

4 / 4

           100.00% covered (success)

100.00%

2 / 2

       Utils

           100.00% covered (success)

100.00%

12 / 12

           100.00% covered (success)

100.00%

1 / 1

           100.00% covered (success)

100.00%

1 / 1

Legend

     Low: 0% to 50%
     Medium: 50% to 90%
     High: 90% to 100%

     Generated by PHP_CodeCoverage 2.0.5 using PHP 5.4.4-14+deb7u12 and PHPUnit 4.0.17 at Fri Aug 15 14:08:59 CEST 2014.


text:
package com.experimental.workshops.willtmwu.httprequester;

import android.os.AsyncTask;
import android.os.Debug;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by William on 24/08/2015.
 */
public class WebRequestAsync extends AsyncTask<String, Void, String>{

    private static final String LOG_TAG = WebRequestAsync.class.getSimpleName();

    private TextView responseView;
    private WebView webResponseView;

    /* NOTES
    AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue> .

    The AsyncTask does not handle configuration changes automatically, i.e. if the activity is recreated, the programmer has to handle that in his coding.

    A common solution to this is to declare the AsyncTask in a retained headless fragment.
     */

    public WebRequestAsync (TextView tv) {
        this(tv, null);
    }
    public WebRequestAsync (TextView tv, WebView wb) {
        this.responseView = tv;
        this.webResponseView = wb;
    }

    // Get the website, in all the html glory
    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        String response = "ERROR!!!";

        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream in = urlConnection.getInputStream();
            StringBuffer sb = new StringBuffer();

            if (in == null) {
                return "";
            }
            reader = new BufferedReader(new InputStreamReader(in));

            String line = "";
            while ((line = reader.readLine()) != null){
                sb.append(line);
            }

            return sb.toString();

        } catch (MalformedURLException urlException){
            response = "MALFORMED URL";
            Log.e(LOG_TAG, urlException.toString());
        } catch (IOException ioException){
            response = "IO Exception";
            Log.e(LOG_TAG, ioException.toString());
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }

            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e){
                    Log.e(LOG_TAG, e.toString());
                }
            }
        }

        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        //super.onPostExecute(s);
        responseView.setText(s);
        if (webResponseView != null) {
            webResponseView.loadData(s, "text/html" , "utf-8");
        }
    }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>OPTRAJ: Référence de l'espace de nommage src.interfacebdd.ConsumerDAO</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

OPTRAJ

Page principale

Paquetages

Classes

Fichiers

          <input type="text" id="MSearchField" value="Recherche" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Paquetages

Fonctions de paquetage

 Tout Classes Espaces de nommage Fichiers Fonctions Variables

src

interfacebdd

ConsumerDAO

Classes |
Variables

Référence de l'espace de nommage src.interfacebdd.ConsumerDAO

Classes

class  	ConsumerDAO

Variables

tuple 	conIns = Consumer(lvl=1, login="fdumoulin", pwd="admin", firstname="Dumoulin", name="François")

tuple 	conn = Connexion()

tuple 	res = ConsumerDAO()

Documentation des variables

          tuple src.interfacebdd.ConsumerDAO.conIns = Consumer(lvl=1, login="fdumoulin", pwd="admin", firstname="Dumoulin", name="François")

          tuple src.interfacebdd.ConsumerDAO.conn = Connexion()

          tuple src.interfacebdd.ConsumerDAO.res = ConsumerDAO()

<address class="footer">
Généré le Jeudi Avril 24 2014 13:03:21 pour OPTRAJ par

 1.8.4
</address>


text:
"""This module contains the general information for AaaLdapRoleGroup ManagedObject."""

from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta

class AaaLdapRoleGroupConsts:
    ADMIN_ACTION_CLEAR = "clear"
    ROLE_ = ""
    ROLE_ADMIN = "admin"
    ROLE_READ_ONLY = "read-only"
    ROLE_USER = "user"

class AaaLdapRoleGroup(ManagedObject):
    """This is AaaLdapRoleGroup class."""

    consts = AaaLdapRoleGroupConsts()
    naming_props = set([u'id'])

    mo_meta = {
        "classic": MoMeta("AaaLdapRoleGroup", "aaaLdapRoleGroup", "rolegroup-[id]", VersionMeta.Version151f, "InputOutput", 0x1ff, [], ["admin", "read-only", "user"], [u'aaaLdap'], [], ["Get", "Set"]),
        "modular": MoMeta("AaaLdapRoleGroup", "aaaLdapRoleGroup", "rolegroup-[id]", VersionMeta.Version2013e, "InputOutput", 0x1ff, [], ["admin", "read-only", "user"], [u'aaaLdap'], [], ["Get", "Set"])
    }

    prop_meta = {

        "classic": {
            "admin_action": MoPropertyMeta("admin_action", "adminAction", "string", VersionMeta.Version202c, MoPropertyMeta.READ_WRITE, 0x2, 0, 510, None, ["clear"], []),
            "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
            "domain": MoPropertyMeta("domain", "domain", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x8, 1, 255, None, [], []),
            "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version151f, MoPropertyMeta.NAMING, 0x10, None, None, None, [], ["1-28"]),
            "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x20, 0, 127, r"""([^+\-][a-zA-Z0-9=!#$%()*+,-.:;@ _{|}~?&]*){0,127}""", [], []),
            "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x40, 0, 255, None, [], []),
            "role": MoPropertyMeta("role", "role", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x80, None, None, None, ["", "admin", "read-only", "user"], []),
            "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version151f, MoPropertyMeta.READ_WRITE, 0x100, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
            "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version151f, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
        },

        "modular": {
            "admin_action": MoPropertyMeta("admin_action", "adminAction", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x2, 0, 510, None, ["clear"], []),
            "dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
            "domain": MoPropertyMeta("domain", "domain", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x8, 1, 255, None, [], []),
            "id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version2013e, MoPropertyMeta.NAMING, 0x10, None, None, None, [], ["1-28"]),
            "name": MoPropertyMeta("name", "name", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x20, 0, 127, r"""([^+\-][a-zA-Z0-9=!#$%()*+,-.:;@ _{|}~?&]*){0,127}""", [], []),
            "rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x40, 0, 255, None, [], []),
            "role": MoPropertyMeta("role", "role", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x80, None, None, None, ["", "admin", "read-only", "user"], []),
            "status": MoPropertyMeta("status", "status", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_WRITE, 0x100, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
            "child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version2013e, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
        },

    }

    prop_map = {

        "classic": {
            "adminAction": "admin_action",
            "dn": "dn",
            "domain": "domain",
            "id": "id",
            "name": "name",
            "rn": "rn",
            "role": "role",
            "status": "status",
            "childAction": "child_action",
        },

        "modular": {
            "adminAction": "admin_action",
            "dn": "dn",
            "domain": "domain",
            "id": "id",
            "name": "name",
            "rn": "rn",
            "role": "role",
            "status": "status",
            "childAction": "child_action",
        },

    }

    def __init__(self, parent_mo_or_dn, id, **kwargs):
        self._dirty_mask = 0
        self.id = id
        self.admin_action = None
        self.domain = None
        self.name = None
        self.role = None
        self.status = None
        self.child_action = None

        ManagedObject.__init__(self, "AaaLdapRoleGroup", parent_mo_or_dn, **kwargs)


text:
package com.sleepycat.je.util;

import java.io.IOException;
import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import java.util.logging.Level;

import com.sleepycat.je.config.EnvironmentParams;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.utilint.LoggerUtils;

/**
 * JE instances of java.util.logging.Logger are configured to use this
 * implementation of java.util.logging.FileHandler. By default, the handler's
 * level is {@link Level#INFO} To enable the console output, use the standard
 * java.util.logging.LogManager configuration to set the desired level:
 *

 * com.sleepycat.je.util.FileHandler.level=INFO
 *

 *

 * The default destination for this output is a circular set of files named
 * <environmentHome>/je.info.# The logging file size can be configured
 * with standard java.util.logging.FileHandler configuration.
 *

 * JE augments the java.util.logging API with a JE environment parameter for
 * setting handler levels. This is described in greater detail in
 * {@link
 * Chapter 12.Administering Berkeley DB Java Edition Applications}
 *
 * @see
 * Chapter 12. Logging
 * @see Using JE Trace Logging
 */
public class FileHandler extends java.util.logging.FileHandler {

    /*
     * The default ErrorManager will blindly write to stderr when it sees an
     * exception.  For instance, when we send an interrupt() to the Rep Node
     * we can see an InterruptedIOException written to stderr, but it never
     * gets passed to the caller.  For several tests, this causes irrelevant
     * stack traces to spew out even though no execption is ever thrown at us.
     * e.g.
     *
     * ------------- Standard Error -----------------
     * java.util.logging.ErrorManager: 2
     * java.io.InterruptedIOException
     *     at java.io.FileOutputStream.writeBytes(Native Method)
     *     at java.io.FileOutputStream.write(FileOutputStream.java:260)
     *     at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
     *     at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
     *     at java.util.logging.FileHandler$MeteredStream.flush(FileHandler.java:143)
     *     at sun.nio.cs.StreamEncoder.implFlush(StreamEncoder.java:278)
     *     at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:122)
     *     at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:212)        at java.util.logging.StreamHandler.flush(StreamHandler.java:225)        at java.util.logging.FileHandler.publish(FileHandler.java:556)
     *     at com.sleepycat.je.utilint.FileRedirectHandler.publish(FileRedirectHandler.java:54)
     *     at java.util.logging.Logger.log(Logger.java:458)
     *     at java.util.logging.Logger.doLog(Logger.java:480)
     *     at java.util.logging.Logger.log(Logger.java:503)
     *     at com.sleepycat.je.utilint.LoggerUtils.logMsg(LoggerUtils.java:343)
     *     at com.sleepycat.je.utilint.LoggerUtils.info(LoggerUtils.java:395)
     *     at com.sleepycat.je.rep.impl.node.FeederManager.runFeeders(FeederManager.java:449)
     *     at com.sleepycat.je.rep.impl.node.RepNode.run(RepNode.java:1198)
     */
    public static boolean STIFLE_DEFAULT_ERROR_MANAGER = false;

    /*
     * Using a JE specific handler lets us enable and disable output for the
     * entire library, and specify an environment specific format and level
     * default.
     */
    public FileHandler(String pattern,
                       int limit,
                       int count,
                       Formatter formatter,
                       EnvironmentImpl envImpl)
        throws SecurityException, IOException {

        super(pattern, limit, count, true /* append */);

            ErrorManager em = new ErrorManager() {
                    public void error(String msg, Exception e, int code) {
                        if (STIFLE_DEFAULT_ERROR_MANAGER) {
                            System.out.println
                                ("FileHandler stifled exception: " + e);
                        } else {
                            super.error(msg, e, code);
                        }
                    }
                };
            setErrorManager(em);

        /* Messages may be formatted with an environment specific tag. */
        setFormatter(formatter);

        Level level = LoggerUtils.getHandlerLevel
            (envImpl.getConfigManager(), EnvironmentParams.JE_FILE_LEVEL,
             getClass().getName() + ".level");

        setLevel(level);
    }
}


text: <?	include($rootPath."/0_standard/scripts_standard.php"); ?>


text:
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/bootstrap.min.css">

Dropdowns

The .dropdown class is used to indicate a dropdown menu.

Use the .dropdown-menu class to actually build the dropdown menu.

      <button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials
      </button>

HTML

CSS

JavaScript

About Us


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <!-- Padding -->
    <dimen name="minimum_padding">2dp</dimen>
    <dimen name="default_padding">5dp</dimen>
    <dimen name="very_large_padding">32dp</dimen>
    <dimen name="large_padding">16dp</dimen>
    <dimen name="medium_padding">8dp</dimen>
    <!-- Fonts -->
    <dimen name="very_large_font">30sp</dimen>
    <dimen name="large_font">22sp</dimen>
    <dimen name="medium_font">18sp</dimen>
    <dimen name="small_font">14sp</dimen>
    <dimen name="very_small_font">10sp</dimen>
    <dimen name="tiny_font">8sp</dimen>
    <!-- Specifics -->
    <dimen name="level_display_size">64dp</dimen>
    <dimen name="level_display_size_buffer">74dp</dimen>
    <!-- Image Sizes -->
    <dimen name="small_image">25dp</dimen>

</resources>


text:
using BrandesBank.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace BrandesBank
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class Bank1 : System.Web.Services.WebService
    {
        private BankDB bankDB = new BankDB();

        [WebMethod]
        public bool hasBankAccount(int id)
        {
            if (bankDB.Accounts.Find(id) != null)
                return true;
            else
                return false;
        }

        [WebMethod]
        public bool CreateBankAccount(int id)
        {
            if (hasBankAccount(id) == false)
            {
                Accounts bankAccount = new Accounts();
                bankAccount.UserID = id;
                bankAccount.TotalCash = 1000000f;

                try
                {
                    bankDB.Accounts.Add(bankAccount);
                    bankDB.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    var exception = new FormattedDbEntityValidationException(e);
                    throw exception;
                }
                if (hasBankAccount(id))
                {
                    return true;
                }
                else
                    return false;
            }
            else
                return false;
        }

        [WebMethod]
        public double CashInAccount(int id)
        {
            if (hasBankAccount(id))
            {
                return bankDB.Accounts.Find(id).TotalCash;
            }
            else
                return 0;
        }

        [WebMethod]
        public bool ChargeAccount(int id, double CashToCharge)
        {
            if (hasBankAccount(id))
            {
                double money = bankDB.Accounts.Find(id).TotalCash;

                List<SqlParameter> param = new List<SqlParameter>();
                param.Add(new SqlParameter("@id", id));
                param.Add(new SqlParameter("@cash", (money - CashToCharge)));
                object[] parameters = param.ToArray();

                bankDB.Database.ExecuteSqlCommand("UPDATE dbo.Accounts SET TotalCash = @cash WHERE UserID = @id", parameters);

                if (bankDB.Accounts.Find(id).TotalCash == (money + CashToCharge))
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
    }
}


text:
package oauth

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"

	"github.com/robdimsdale/wl"
)

// Notes gets all tasks for all lists.
func (c oauthClient) Notes() ([]wl.Note, error) {
	lists, err := c.Lists()
	if err != nil {
		return nil, err
	}

	listCount := len(lists)
	c.logger.Debug(
		"tasks",
		map[string]interface{}{"listCount": listCount},
	)

	notesChan := make(chan []wl.Note, listCount)
	idErrChan := make(chan idErr, listCount)
	for _, l := range lists {
		go func(list wl.List) {
			c.logger.Debug(
				"notes - getting notes for list",
				map[string]interface{}{"listID": list.ID},
			)
			notes, err := c.NotesForListID(list.ID)
			idErrChan <- idErr{idType: "list", id: list.ID, err: err}
			notesChan <- notes
		}(l)
	}

	e := multiIDErr{}
	for i := 0; i < listCount; i++ {
		idErr := <-idErrChan
		if idErr.err != nil {
			c.logger.Debug(
				"notes - error received getting notes for list",
				map[string]interface{}{"listID": idErr.id, "err": err},
			)
			e.addError(idErr)
		}
	}

	totalNotes := []wl.Note{}
	for i := 0; i < listCount; i++ {
		notes := <-notesChan
		totalNotes = append(totalNotes, notes...)
	}

	if len(e.errors()) > 0 {
		return totalNotes, e
	}

	return totalNotes, nil
}

// NotesForListID returns Notes for the provided listID.
func (c oauthClient) NotesForListID(listID uint) ([]wl.Note, error) {
	if listID == 0 {
		return nil, errors.New("listID must be > 0")
	}

	url := fmt.Sprintf(
		"%s/notes?list_id=%d",
		c.apiURL,
		listID,
	)

	req, err := c.newGetRequest(url)
	if err != nil {
		return nil, err
	}

	resp, err := c.do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	notes := []wl.Note{}
	err = json.NewDecoder(resp.Body).Decode(&notes)
	if err != nil {
		return nil, err
	}
	return notes, nil
}

// NotesForTaskID returns Notes for the provided taskID.
func (c oauthClient) NotesForTaskID(taskID uint) ([]wl.Note, error) {
	if taskID == 0 {
		return nil, errors.New("taskID must be > 0")
	}

	url := fmt.Sprintf(
		"%s/notes?task_id=%d",
		c.apiURL,
		taskID,
	)

	req, err := c.newGetRequest(url)
	if err != nil {
		return nil, err
	}

	resp, err := c.do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	notes := []wl.Note{}
	err = json.NewDecoder(resp.Body).Decode(&notes)
	if err != nil {
		return nil, err
	}
	return notes, nil
}

// Note returns the Note for the corresponding noteID.
func (c oauthClient) Note(noteID uint) (wl.Note, error) {
	if noteID == 0 {
		return wl.Note{}, errors.New("noteID must be > 0")
	}

	url := fmt.Sprintf(
		"%s/notes/%d",
		c.apiURL,
		noteID,
	)

	req, err := c.newGetRequest(url)
	if err != nil {
		return wl.Note{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Note{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.Note{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	note := wl.Note{}
	err = json.NewDecoder(resp.Body).Decode(&note)
	if err != nil {
		return wl.Note{}, err
	}
	return note, nil
}

// CreateNote creates a note with the provided content associated with the
// Task for the corresponding taskID.
func (c oauthClient) CreateNote(content string, taskID uint) (wl.Note, error) {
	if taskID == 0 {
		return wl.Note{}, errors.New("taskID must be > 0")
	}

	body := []byte(fmt.Sprintf(`{"content":"%s","task_id":%d}`, content, taskID))

	url := fmt.Sprintf("%s/notes", c.apiURL)

	req, err := c.newPostRequest(url, body)
	if err != nil {
		return wl.Note{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Note{}, err
	}

	if resp.StatusCode != http.StatusCreated {
		return wl.Note{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusCreated)
	}

	note := wl.Note{}
	err = json.NewDecoder(resp.Body).Decode(&note)
	if err != nil {
		return wl.Note{}, err
	}
	return note, nil
}

// UpdateNote updates the provided Note.
// Notes cannot be moved between tasks; note.TaskID is ignored
func (c oauthClient) UpdateNote(note wl.Note) (wl.Note, error) {
	body, err := json.Marshal(note)
	if err != nil {
		return wl.Note{}, err
	}

	url := fmt.Sprintf(
		"%s/notes/%d",
		c.apiURL,
		note.ID,
	)

	req, err := c.newPatchRequest(url, body)
	if err != nil {
		return wl.Note{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Note{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return wl.Note{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusOK)
	}

	returnedNote := wl.Note{}
	err = json.NewDecoder(resp.Body).Decode(&returnedNote)
	if err != nil {
		return wl.Note{}, err
	}
	return returnedNote, nil
}

// DeleteNote deletes the provided note.
func (c oauthClient) DeleteNote(note wl.Note) error {
	url := fmt.Sprintf(
		"%s/notes/%d?revision=%d",
		c.apiURL,
		note.ID,
		note.Revision,
	)

	req, err := c.newDeleteRequest(url)
	if err != nil {
		return err
	}

	resp, err := c.do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusNoContent {
		return fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusNoContent)
	}

	return nil
}


text:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ImportAppComponent } from './import-app.component';

export const routes: Routes = [
  {
    path: '',
    component: ImportAppComponent,
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class ImportAppRoutingModule {}


text:
"""Functions to print object information."""

import wrapper

unsorted = 0
ascending = 1
descending = -1

def printsizes(wrappers, sorted = descending, threshold = 0, count = None,
               size = lambda w: w.size, show = lambda w: w.show()):
    """Print all objects in wrappers with size above threshold, sorted as
    specified.

    size is optionally a function that takes a wrapper and returns
    its size, by default w.size.

    show is optionally a function that takes a wrapper and returns
    a string representation of it, by default str(w.obj)"""

    vals = wrappers.values()
    if sorted != unsorted:
        vals.sort(lambda w1, w2: sorted * (size(w1) - size(w2)))

    print "Size".rjust(8), "Total".rjust(8), "Object"
    total = 0
    for w in vals[:count]:
        if size(w) >= threshold:
            total += size(w)
            print str(size(w)).rjust(8), str(total).rjust(8), show(w)

def printsizesop(wrappers, sorted = descending, threshold = 0, count = None):
    """Print wrappers from operations.byType or operations.bySize.
    If showobjects is true the objects themselves will be shown instead of
    their wrappers."""

    def size(t):
        return t[1]

    def show(t):
        return str(t[0])

    printsizes(wrappers, sorted, threshold, count, size, show)


text:
namespace RE {
	class GLProgram : public Object {
	public:
		enum {
			VERTEX_ATTRIB_POSITION,
			VERTEX_ATTRIB_COLOR,
			VERTEX_ATTRIB_TEX_COORD,
		};
		static const char* ATTRIBUTE_NAME_COLOR;
		static const char* ATTRIBUTE_NAME_POSITION;
		static const char* ATTRIBUTE_NAME_TEX_COORD;
	public:
		GLProgram();
		~GLProgram();

		bool Init(const char* vert, const char* frag);
		bool Init(Path vert, Path frag);
		bool InitWithBuff(const char* vert, const char* frag);

		void OnGUI();

		bool Apply();
		bool Apply(float* matp);

		GLuint GetProgramHandle();
		GLuint GetMatPHandle();
		GLuint GetMatMHandle();
	protected:
		bool compile(GLuint& handle, GLenum type, const GLchar* code);
		bool link();

		std::string getShaderLog(GLuint handle);
		void reset();
		void clearShader();
		void clearProgram();

	protected:
		GLuint _program = 0;
		GLuint _vertHandle = 0;
		GLuint _fragHandle = 0;
		GLint  _matPHandle = 0;
		GLint  _matMHandle = 0;
	};
}


text:
(function() {
  var Declaration, Filter,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  Declaration = require('../declaration');

  Filter = (function(_super) {
    __extends(Filter, _super);

    Filter.names = ['filter'];

    function Filter() {
      Filter.__super__.constructor.apply(this, arguments);
      if (this.value.indexOf('DXImageTransform.Microsoft') !== -1) {
        this.unprefixed = this.prop = '-ms-filter';
      }
    }

    return Filter;

  })(Declaration);

  module.exports = Filter;

}).call(this);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 50: 37 (1953)

#### Original name
Meliola togoensis S. Hughes

### Remarks
null


text:
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef __BT_APP_COMMON_H__
#define __BT_APP_COMMON_H__

#include <stdint.h>
#include "osi.h"
#include "bt_common_types.h"
#include "esp_err.h"

enum BLUFI_SIG {
    BLUFI_SIG_SWITCH_CONTEXT = 0,
    BLUFI_SIG_ENABLE,
    BLUFI_SIG_DISABLE,
};

typedef esp_err_t (*blufi_task_cb_t)(void *arg);

void blufi_init(void);
void blufi_deinit(void);

esp_err_t blufi_enable(void *arg);
esp_err_t blufi_disable(void *arg);

esp_err_t blufi_transfer_context(blufi_task_cb_t cb, void *arg);

#endif /* __BT_APP_COMMON_H__ */


text:
import {Direction} from '@angular/cdk/bidi';
import {ComponentPortal, Portal, PortalOutlet, TemplatePortal} from '@angular/cdk/portal';
import {ComponentRef, EmbeddedViewRef, NgZone} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {take} from 'rxjs/operators';
import {OverlayKeyboardDispatcher} from './keyboard/overlay-keyboard-dispatcher';
import {OverlayConfig} from './overlay-config';
import {coerceCssPixelValue} from '@angular/cdk/coercion';

/** An object where all of its properties cannot be written. */
export type ImmutableObject<T> = {
  readonly [P in keyof T]: T[P];
};

/**
 * Reference to an overlay that has been created with the Overlay service.
 * Used to manipulate or dispose of said overlay.
 */
export class OverlayRef implements PortalOutlet {
  private _backdropElement: HTMLElement | null = null;
  private _backdropClick: Subject<MouseEvent> = new Subject();
  private _attachments = new Subject<void>();
  private _detachments = new Subject<void>();

  /** Stream of keydown events dispatched to this overlay. */
  _keydownEvents = new Subject<KeyboardEvent>();

  constructor(
      private _portalOutlet: PortalOutlet,
      private _host: HTMLElement,
      private _pane: HTMLElement,
      private _config: ImmutableObject<OverlayConfig>,
      private _ngZone: NgZone,
      private _keyboardDispatcher: OverlayKeyboardDispatcher,
      private _document: Document) {

    if (_config.scrollStrategy) {
      _config.scrollStrategy.attach(this);
    }
  }

  /** The overlay's HTML element */
  get overlayElement(): HTMLElement {
    return this._pane;
  }

  /** The overlay's backdrop HTML element. */
  get backdropElement(): HTMLElement | null {
    return this._backdropElement;
  }

  /**
   * Wrapper around the panel element. Can be used for advanced
   * positioning where a wrapper with specific styling is
   * required around the overlay pane.
   */
  get hostElement(): HTMLElement {
    return this._host;
  }

  attach<T>(portal: ComponentPortal<T>): ComponentRef<T>;
  attach<T>(portal: TemplatePortal<T>): EmbeddedViewRef<T>;
  attach(portal: any): any;

  /**
   * Attaches content, given via a Portal, to the overlay.
   * If the overlay is configured to have a backdrop, it will be created.
   *
   * @param portal Portal instance to which to attach the overlay.
   * @returns The portal attachment result.
   */
  attach(portal: Portal<any>): any {
    let attachResult = this._portalOutlet.attach(portal);

    if (this._config.positionStrategy) {
      this._config.positionStrategy.attach(this);
    }

    // Update the pane element with the given configuration.
    this._updateStackingOrder();
    this._updateElementSize();
    this._updateElementDirection();

    if (this._config.scrollStrategy) {
      this._config.scrollStrategy.enable();
    }

    // Update the position once the zone is stable so that the overlay will be fully rendered
    // before attempting to position it, as the position may depend on the size of the rendered
    // content.
    this._ngZone.onStable
      .asObservable()
      .pipe(take(1))
      .subscribe(() => {
        // The overlay could've been detached before the zone has stabilized.
        if (this.hasAttached()) {
          this.updatePosition();
        }
      });

    // Enable pointer events for the overlay pane element.
    this._togglePointerEvents(true);

    if (this._config.hasBackdrop) {
      this._attachBackdrop();
    }

    if (this._config.panelClass) {
      // We can't do a spread here, because IE doesn't support setting multiple classes.
      if (Array.isArray(this._config.panelClass)) {
        this._config.panelClass.forEach(cssClass => this._pane.classList.add(cssClass));
      } else {
        this._pane.classList.add(this._config.panelClass);
      }
    }

    // Only emit the `attachments` event once all other setup is done.
    this._attachments.next();

    // Track this overlay by the keyboard dispatcher
    this._keyboardDispatcher.add(this);

    return attachResult;
  }

  /**
   * Detaches an overlay from a portal.
   * @returns The portal detachment result.
   */
  detach(): any {
    if (!this.hasAttached()) {
      return;
    }

    this.detachBackdrop();

    // When the overlay is detached, the pane element should disable pointer events.
    // This is necessary because otherwise the pane element will cover the page and disable
    // pointer events therefore. Depends on the position strategy and the applied pane boundaries.
    this._togglePointerEvents(false);

    if (this._config.positionStrategy && this._config.positionStrategy.detach) {
      this._config.positionStrategy.detach();
    }

    if (this._config.scrollStrategy) {
      this._config.scrollStrategy.disable();
    }

    const detachmentResult = this._portalOutlet.detach();

    // Only emit after everything is detached.
    this._detachments.next();

    // Remove this overlay from keyboard dispatcher tracking
    this._keyboardDispatcher.remove(this);

    return detachmentResult;
  }

  /** Cleans up the overlay from the DOM. */
  dispose(): void {
    const isAttached = this.hasAttached();

    if (this._config.positionStrategy) {
      this._config.positionStrategy.dispose();
    }

    if (this._config.scrollStrategy) {
      this._config.scrollStrategy.disable();
    }

    this.detachBackdrop();
    this._keyboardDispatcher.remove(this);
    this._portalOutlet.dispose();
    this._attachments.complete();
    this._backdropClick.complete();
    this._keydownEvents.complete();

    if (this._host && this._host.parentNode) {
      this._host.parentNode.removeChild(this._host);
      this._host = null!;
    }

    if (isAttached) {
      this._detachments.next();
    }

    this._detachments.complete();
  }

  /** Whether the overlay has attached content. */
  hasAttached(): boolean {
    return this._portalOutlet.hasAttached();
  }

  /** Gets an observable that emits when the backdrop has been clicked. */
  backdropClick(): Observable<MouseEvent> {
    return this._backdropClick.asObservable();
  }

  /** Gets an observable that emits when the overlay has been attached. */
  attachments(): Observable<void> {
    return this._attachments.asObservable();
  }

  /** Gets an observable that emits when the overlay has been detached. */
  detachments(): Observable<void> {
    return this._detachments.asObservable();
  }

  /** Gets an observable of keydown events targeted to this overlay. */
  keydownEvents(): Observable<KeyboardEvent> {
    return this._keydownEvents.asObservable();
  }

  /** Gets the the current overlay configuration, which is immutable. */
  getConfig(): OverlayConfig {
    return this._config;
  }

  /** Updates the position of the overlay based on the position strategy. */
  updatePosition() {
    if (this._config.positionStrategy) {
      this._config.positionStrategy.apply();
    }
  }

  /** Update the size properties of the overlay. */
  updateSize(sizeConfig: OverlaySizeConfig) {
    this._config = {...this._config, ...sizeConfig};
    this._updateElementSize();
  }

  /** Sets the LTR/RTL direction for the overlay. */
  setDirection(dir: Direction) {
    this._config = {...this._config, direction: dir};
    this._updateElementDirection();
  }

  /** Updates the text direction of the overlay panel. */
  private _updateElementDirection() {
    this._pane.setAttribute('dir', this._config.direction!);
  }

  /** Updates the size of the overlay element based on the overlay config. */
  private _updateElementSize() {
    if (this._config.width || this._config.width === 0) {
      this._pane.style.width = coerceCssPixelValue(this._config.width);
    }

    if (this._config.height || this._config.height === 0) {
      this._pane.style.height = coerceCssPixelValue(this._config.height);
    }

    if (this._config.minWidth || this._config.minWidth === 0) {
      this._pane.style.minWidth = coerceCssPixelValue(this._config.minWidth);
    }

    if (this._config.minHeight || this._config.minHeight === 0) {
      this._pane.style.minHeight = coerceCssPixelValue(this._config.minHeight);
    }

    if (this._config.maxWidth || this._config.maxWidth === 0) {
      this._pane.style.maxWidth = coerceCssPixelValue(this._config.maxWidth);
    }

    if (this._config.maxHeight || this._config.maxHeight === 0) {
      this._pane.style.maxHeight = coerceCssPixelValue(this._config.maxHeight);
    }
  }

  /** Toggles the pointer events for the overlay pane element. */
  private _togglePointerEvents(enablePointer: boolean) {
    this._pane.style.pointerEvents = enablePointer ? 'auto' : 'none';
  }

  /** Attaches a backdrop for this overlay. */
  private _attachBackdrop() {
    const showingClass = 'cdk-overlay-backdrop-showing';

    this._backdropElement = this._document.createElement('div');
    this._backdropElement.classList.add('cdk-overlay-backdrop');

    if (this._config.backdropClass) {
      this._backdropElement.classList.add(this._config.backdropClass);
    }

    // Insert the backdrop before the pane in the DOM order,
    // in order to handle stacked overlays properly.
    this._host.parentElement!.insertBefore(this._backdropElement, this._host);

    // Forward backdrop clicks such that the consumer of the overlay can perform whatever
    // action desired when such a click occurs (usually closing the overlay).
    this._backdropElement.addEventListener('click',
        (event: MouseEvent) => this._backdropClick.next(event));

    // Add class to fade-in the backdrop after one frame.
    if (typeof requestAnimationFrame !== 'undefined') {
      this._ngZone.runOutsideAngular(() => {
        requestAnimationFrame(() => {
          if (this._backdropElement) {
            this._backdropElement.classList.add(showingClass);
          }
        });
      });
    } else {
      this._backdropElement.classList.add(showingClass);
    }
  }

  /**
   * Updates the stacking order of the element, moving it to the top if necessary.
   * This is required in cases where one overlay was detached, while another one,
   * that should be behind it, was destroyed. The next time both of them are opened,
   * the stacking will be wrong, because the detached element's pane will still be
   * in its original DOM position.
   */
  private _updateStackingOrder() {
    if (this._host.nextSibling) {
      this._host.parentNode!.appendChild(this._host);
    }
  }

  /** Detaches the backdrop (if any) associated with the overlay. */
  detachBackdrop(): void {
    let backdropToDetach = this._backdropElement;

    if (backdropToDetach) {
      let finishDetach = () => {
        // It may not be attached to anything in certain cases (e.g. unit tests).
        if (backdropToDetach && backdropToDetach.parentNode) {
          backdropToDetach.parentNode.removeChild(backdropToDetach);
        }

        // It is possible that a new portal has been attached to this overlay since we started
        // removing the backdrop. If that is the case, only clear the backdrop reference if it
        // is still the same instance that we started to remove.
        if (this._backdropElement == backdropToDetach) {
          this._backdropElement = null;
        }
      };

      backdropToDetach.classList.remove('cdk-overlay-backdrop-showing');

      if (this._config.backdropClass) {
        backdropToDetach.classList.remove(this._config.backdropClass);
      }

      backdropToDetach.addEventListener('transitionend', finishDetach);

      // If the backdrop doesn't have a transition, the `transitionend` event won't fire.
      // In this case we make it unclickable and we try to remove it after a delay.
      backdropToDetach.style.pointerEvents = 'none';

      // Run this outside the Angular zone because there's nothing that Angular cares about.
      // If it were to run inside the Angular zone, every test that used Overlay would have to be
      // either async or fakeAsync.
      this._ngZone.runOutsideAngular(() => setTimeout(finishDetach, 500));
    }
  }
}

/** Size properties for an overlay. */
export interface OverlaySizeConfig {
  width?: number | string;
  height?: number | string;
  minWidth?: number | string;
  minHeight?: number | string;
  maxWidth?: number | string;
  maxHeight?: number | string;
}


text:
var FCKToolbarBreak = function()
{
	var oBreakDiv = document.createElement( 'div' ) ;

	oBreakDiv.style.clear = oBreakDiv.style.cssFloat = FCKLang.Dir == 'rtl' ? 'right' : 'left' ;

	FCKToolbarSet.DOMElement.appendChild( oBreakDiv ) ;
}


text:
using Microsoft.Framework.Logging;

namespace OmniSharp.Tests
{
    public class FakeLoggerFactory : ILoggerFactory
    {
        private static FakeLogger logger = new FakeLogger();
        public void AddProvider(ILoggerProvider provider)
        {
        }

        public LogLevel MinimumLevel { get; set; } = LogLevel.Verbose;

        public ILogger CreateLogger(string name)
        {
            return logger;
        }
    }
}


text:
from __future__ import (unicode_literals, division, absolute_import, print_function)

import re

from collections import namedtuple

from powerline.lib.threaded import KwThreadedSegment
from powerline.segments import with_docstring

_IMAPKey = namedtuple('Key', 'username password server port folder')

class EmailIMAPSegment(KwThreadedSegment):
	interval = 60

	@staticmethod
	def key(username, password, server='imap.gmail.com', port=993, folder='INBOX', **kwargs):
		return _IMAPKey(username, password, server, port, folder)

	def compute_state(self, key):
		if not key.username or not key.password:
			self.warn('Username and password are not configured')
			return None
		try:
			import imaplib
		except imaplib.IMAP4.error as e:
			unread_count = str(e)
		else:
			mail = imaplib.IMAP4_SSL(key.server, key.port)
			mail.login(key.username, key.password)
			rc, message = mail.status(key.folder, '(UNSEEN)')
			unread_str = message[0].decode('utf-8')
			unread_count = int(re.search('UNSEEN (\d+)', unread_str).group(1))
		return unread_count

	@staticmethod
	def render_one(unread_count, max_msgs=None, **kwargs):
		if not unread_count:
			return None
		elif type(unread_count) != int or not max_msgs:
			return [{
				'contents': str(unread_count),
				'highlight_group': ['email_alert'],
			}]
		else:
			return [{
				'contents': str(unread_count),
				'highlight_group': ['email_alert_gradient', 'email_alert'],
				'gradient_level': min(unread_count * 100.0 / max_msgs, 100),
			}]

email_imap_alert = with_docstring(EmailIMAPSegment(),
'''Return unread e-mail count for IMAP servers.

:param str username:
	login username
:param str password:
	login password
:param str server:
	e-mail server
:param int port:
	e-mail server port
:param str folder:
	folder to check for e-mails
:param int max_msgs:
	Maximum number of messages. If there are more messages then max_msgs then it
	will use gradient level equal to 100, otherwise gradient level is equal to
	``100 * msgs_num / max_msgs``. If not present gradient is not computed.

Highlight groups used: ``email_alert_gradient`` (gradient), ``email_alert``.
''')


text:
package org.jrimum.bopepo.campolivre;

import java.util.Calendar;

import org.jrimum.bopepo.BancosSuportados;
import org.jrimum.domkee.banco.Agencia;
import org.jrimum.domkee.banco.Carteira;
import org.jrimum.domkee.banco.TipoDeCobranca;
import org.junit.Before;
import org.junit.Test;

/**
 *

 * Teste unitário do campo livre do banco unibanco para cobrança não registrada
 *

 *
 * @author Gilmar P.S.L
 * @author Misael Barreto
 * @author Rômulo Augusto
 * @author Nordeste Fomento Mercantil
 *
 * @since 0.2
 *
 * @version 0.2
 *
 */
public class TestCLUnibancoCobrancaRegistrada extends AbstractCampoLivreBaseTest<CLUnibancoCobrancaRegistrada> {

	/**
	 *

	 * Cobrança com registro
	 *
	 * Situação: precisamos emitir um título para um sacado com essas
	 * características:
	 *

	 *

	 * Banco: UNIBANCO – identificação 409
	 * Agência: 0001-9
	 * Moeda: Real – R$ - identificação 9
	 * Vencimento: 31 de dezembro de 2001
	 * Valor: R$1000,00
	 * Código para transação CVT: 04 (cobrança com registro – 5539-5)
	 * "Nosso Número": 11223344554
	 *

	 *
	 *

	 * NÚMERO DE ORIGEM DO CÓDIGO DE BARRAS:
	 *
	 *
	 *

	 * 409 9  1  1546  0000100000  04  011231  0001  9  11223344554  0
	 *

	 *
	 *
	 * LINHA DIGITÁVEL:
	 *
	 *

	 * 40990.40117  20100.019110  22334.455403  1  15460000100000
	 *

	 *
	 *

	 *
	 *
	 * @throws Exception
	 *
	 * @since
	 */
	@Before
	public void setUp(){

		Calendar cal = Calendar.getInstance();

		cal.set(2001,Calendar.DECEMBER,31);

		titulo.getContaBancaria().setBanco(BancosSuportados.UNIBANCO.create());
		titulo.getContaBancaria().setAgencia(new Agencia(1, "9"));
		titulo.getContaBancaria().setCarteira(new Carteira(123,TipoDeCobranca.COM_REGISTRO));
		titulo.setNumeroDoDocumento("1234567");
		titulo.setNossoNumero("11223344554");
		titulo.setDataDoVencimento(cal.getTime());

		createCampoLivreToTest();

		setCampoLivreEsperadoComoString("0401123100019112233445540");
	}

	@Test(expected = CampoLivreException.class)
	public final void testGetInstanceComAgenciaNula() {

		titulo.getContaBancaria().setAgencia(null);
		createCampoLivreToTest();
	}

	@Test(expected = CampoLivreException.class)
	public final void testGetInstanceComNossoNumeroNulo() {

		titulo.setNossoNumero(null);
		createCampoLivreToTest();
	}

	@Test(expected = CampoLivreException.class)
	public final void testGetInstanceComNossoNumeroNegativo() {

		titulo.setNossoNumero("-012345679012345");
		createCampoLivreToTest();
	}

	@Test(expected = CampoLivreException.class)
	public final void testGetInstanceComNossoNumeroNaoNumerico() {

		titulo.setNossoNumero("123456790123y45");
		createCampoLivreToTest();
	}

}


text:
package com.bot4s.telegram.methods

import com.bot4s.telegram.models.{ InlineKeyboardMarkup, Message }
import com.bot4s.telegram.models.ChatId

/**
 * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
 * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
 *
 * @param chatId           Integer or String Required if inline_message_id is not specified. Unique identifier for the target chat or username of the target channel (in the format @channelusername)
 * @param messageId        Integer Required if inline_message_id is not specified. Unique identifier of the sent message
 * @param inlineMessageId  String Required if chat_id and message_id are not specified. Identifier of the inline message
 * @param replyMarkup      InlineKeyboardMarkup Optional A JSON-serialized object for an inline keyboard.
 */
case class EditMessageReplyMarkup(
  chatId: Option[ChatId] = None,
  messageId: Option[Int] = None,
  inlineMessageId: Option[String] = None,
  replyMarkup: Option[InlineKeyboardMarkup] = None
) extends JsonRequest[Either[Boolean, Message]] {
  if (inlineMessageId.isEmpty) {
    require(chatId.isDefined, "Required if inlineMessageId is not specified")
    require(messageId.isDefined, "Required if inlineMessageId is not specified")
  }

  if (chatId.isEmpty && messageId.isEmpty)
    require(inlineMessageId.isDefined, "Required if chatId and messageId are not specified")
}