text:
tags: [software-engineering, nodejs]
---

Recently, at work, i was tasked with providing a training session to [NodeJS](https://nodejs.org/en/) to help adopt `node` to our organization.

This post is a recap on what i covered on:

### What is NodeJS?
![cname file content]({{ site.url }}/assets/img/nodejs.png)

- Javascript running on the server.
- Run on Chrome V8 javascript engine.
- Single-threaded event loop, Non-blocking I/O.
- [NPM](https://www.npmjs.com) for package management.
- Currently version 8.4.0

### Architecture
![cname file content]({{ site.url }}/assets/img/nodejs_architecture.png)

`NodeJS` is powered by 2 major componenent, [V8](https://github.com/v8/v8) and [libuv](https://github.com/libuv/libuv).

`libuv` brings `asynchronous I/O` to `node`. It should also be noted that the [kestrel](https://github.com/aspnet/KestrelHttpServer) ( aspnet core http server ) is also leveraging `libuv`.

`v8` is the javascript engine in `node`.

### Why Non-Blocking I/O?
![cname file content]({{ site.url }}/assets/img/nodejs_event_loop.png)

NodeJs is designed with non-blocking evented I/O, all I/O calls are returned on `callbacks`. This is very different from traditional frameworks in the sense when an I/O operation is happening, no application threads is blocked.

The nature of most modern web servers are mostly I/O bound by nature. Blocking I/O is not scalable because each I/O would hold up a thread. For example, if we have 1000 I/O calls happening, then there are at least 1000 OS threads created, consuming 1000 * 10 MB of memory, context-switching in the cpu would also be really high. This is an inefficient concurrency model. Most languages/frameworks are not designed with this in mind.

- Non-blocking I/O supports tens of thousands of concurrent connections.
- Non-blocking IO single-threaded concurrency model.
- Can scale to high number of concurrent requests.
- Blocking I/O handle concurrency by having more threads.
- More threads = more memory and cpu context-switching.
- But Non-blocking IO without language support make code hard to read/write.

### Non-Blocking I/O frameworks:
- NodeJS
- Go [https://golang.org](https://golang.org)
- C# [https://www.microsoft.com/net/core#macos](https://www.microsoft.com/net/core#macos)
- Play framework. [https://playframework.com](https://playframework.com)
- Java NIO [https://docs.oracle.com/javase/7/docs/api/java/nio/package-summary.html](https://docs.oracle.com/javase/7/docs/api/java/nio/package-summary.html)

### Language support for concurrency
Language support is important to prevent *spaghetti* code when writing concurrent code. The [callback hell](http://callbackhell.com) in nodejs early days is a good example.

With the new addition of `async` and `await` in nodejs 8, concurrency support is awesome. [https://blog.risingstack.com/mastering-async-await-in-nodejs/](https://blog.risingstack.com/mastering-async-await-in-nodejs/)

IMO, `Golang` & `C#` are by far the best languages with concurrency support baked into the language.

### NPM
- Package manager for javascript.
- Used to install node program/modules.
- Specify dependencies in a file call package.json.
- Modules get installed into `node_modules` folder.
- NPM version 5 generate `package.lock.json` to guarantee similar dependencies are always restored.
- Alternative to npm: [Yarn](http://yarnpkg.com)

### Conclusion
NodeJs is a pretty decent choice for building apps that require high I/O scalability.

redpajama_set_name: RedPajamaGithub


text:
require "fog/scaleway"
require "fog/scaleway/models/compute/server"

#
# We're monkeypatching here to avoid overriding too much of the base
# class. This monkey patch will be removed if we can merge those changes
# upstream
#
class Fog::Scaleway::Compute::Server
  alias start poweron
  alias stop poweroff

  def disassociate_address(ip)
    ip = ip.address if ip.respond_to? :address
    if public_ip && public_ip.address == ip
      public_ip.server = nil
      public_ip.save
    end
    reload
  end
end

class Chef
  module Provisioning
    module FogDriver
      module Providers
        class Scaleway < FogDriver::Driver
          Driver.register_provider_class("Scaleway", FogDriver::Providers::Scaleway)

          def creator
            compute_options[:scaleway_organization]
          end

          def convergence_strategy_for(machine_spec, machine_options)
            machine_options = Cheffish::MergedConfig.new(machine_options,
                                                         convergence_options: { ohai_hints: { "scaleway" => {} } })
            super(machine_spec, machine_options)
          end

          def bootstrap_options_for(action_handler, machine_spec, machine_options)
            opts = super
            opts[:tags] = opts[:tags].map { |key, value| [key, value].join("=") }

            # Let's fetch the id of the volumes if the user didn't provide it
            # Which probably means they were created in chef
            if opts[:volumes]
              managed_entry_store = machine_spec.managed_entry_store
              volumes = Marshal.load(Marshal.dump(opts[:volumes]))

              volumes.each do |_index, volume|
                next if volume[:id]
                volume_spec = managed_entry_store.get(:volume, volume[:name])
                unless volume_spec
                  raise "Volume #{volume[:name]} unknown, create it or provide its id"
                end
                volume[:id] = volume_spec.reference["id"]
              end
              opts[:volumes] = volumes
            end
            opts
          end

          def destroy_machine(action_handler, machine_spec, machine_options)
            server = server_for(machine_spec)
            if server
              action_handler.perform_action "destroy machine #{machine_spec.name} (#{machine_spec.reference['server_id']} at #{driver_url})" do
                # Scaleway's API fail if we try to stop/terminate an instance with
                # certains states
                if server.state == "running"
                  server.stop
                  server.wait_for { server.state != "running" }
                end
                %w{stopping starting}.each do |state|
                  server.wait_for { server.state != state } if server.state == state
                end

                if server.state == "stopped"
                  server.destroy
                else
                  Chef.log.fatal "Server is in an unknown state (#{server.state})"
                end
                machine_spec.reference = nil
              end
            end
            strategy = ConvergenceStrategy::NoConverge.new(machine_options[:convergence_options], config)
            strategy.cleanup_convergence(action_handler, machine_spec)
          end

          def stop_machine(action_handler, machine_spec, _machine_options)
            server = server_for(machine_spec)
            if server && (server.state == "running")
              action_handler.perform_action "stop machine #{machine_spec.name} (#{server.id} at #{driver_url})" do
                server.poweroff(true)
                server.wait_for { server.state == "stopped" }
              end
            end
          end

          def self.compute_options_for(provider, id, config)
            new_compute_options = {}
            new_compute_options[:provider] = provider
            if id && id != ""
              org, region = id.split(":")
              new_compute_options[:scaleway_organization] = org
              new_compute_options[:scaleway_region] = region || "par1"
            end
            new_config = { driver_options: { compute_options: new_compute_options } }

            new_default_compute_options = {}
            new_defaults = {
              driver_options: { compute_options: new_default_compute_options },
              machine_options: { bootstrap_options: {} }
            }

            result = Cheffish::MergedConfig.new(new_config, config, new_defaults)

            credential = Fog.credentials
            new_default_compute_options[:scaleway_organization] ||= credential[:scaleway_organization]
            new_default_compute_options[:scaleway_token] ||= credential[:scaleway_token]

            id = [result[:driver_options][:compute_options][:scaleway_organization],
                  result[:driver_options][:compute_options][:scaleway_region]].join(":")

            [result, id]
          end

          def converge_floating_ips(action_handler, machine_spec, machine_options, server)
            if server.dynamic_ip_required
              Chef::Log.info "Dynamic IP allocation has been enabled, not converging IPs"
            else
              super
            end
          end

          # Scaleway only has one global pool.
          def attach_ip_from_pool(server, _pool)
            return server if server.public_ip

            Chef::Log.info "Scaleway has only one IP pool, ignoring pool argument"
            ip = server.service.ips.all.select { |ip| ip.address.nil? }.first
            if ip
              ip.server = server
              ip.save
              server.reload
            else
              # Allocate a new IP
              ip = server.service.ips.create
              ip.server = server
              ip.save
              server.reload
            end
          end

          def attach_ip(server, floating_ip)
            ip = server.service.ips.get(floating_ip)
            raise "Requested IP (#{floating_ip}) not found" if ip.nil?
            if ip.server && (ip.server.identity != server.identity)
              raise "Requested IP (#{floating_ip}) already attached"
            end

            if server.public_ip
              old_ip = server.public_ip
              Chef::Log.info "Server #{server.identity} already has IP #{old_ip.address}, removing it"
              old_ip.server = nil
              old_ip.save
            end

            ip.server = server
            ip.save
            server.reload
          end

          # Get the public IP if any
          def find_floating_ips(server, action_handler)
            public_ips = []
            Retryable.retryable(RETRYABLE_OPTIONS) do |retries, _exception|
              action_handler.report_progress "Querying for public IP attached to server #{server.id}, API attempt #{retries + 1}/#{RETRYABLE_OPTIONS[:tries]} ..."
              public_ips << server.public_ip.address if server.public_ip
            end
            public_ips
          end

          def create_volume(action_handler, volume_spec, volume_options)
            # Prevent destructive operations on volume_options.
            clean_volume_options = Marshal.load(Marshal.dump(volume_options))

            volume_spec.reference ||= {}
            volume_spec.reference.update(
              "driver_url" => driver_url,
              "driver_version" => FogDriver::VERSION,
              "creator" => creator,
              "allocated_at" => Time.now.to_i
            )

            description = ["Creating volume #{volume_spec.name}"]
            volume_options.each { |k, v| description << "  #{k}: #{v.inspect}" }

            action_handler.report_progress description
            if action_handler.should_perform_actions
              clean_volume_options["name"] = volume_spec.name

              volume = compute.volumes.create(clean_volume_options)

              volume_spec.reference.update(
                "id" => volume.id,
                "volume_type" => volume.volume_type,
                "size" => volume.size
              )
              volume_spec.save(action_handler)
              action_handler.performed_action "volume #{volume_spec.name} created as #{volume.id} on #{driver_url}"
            end
          end

          def destroy_volume(action_handler, volume_spec, _volume_options)
            volume = volume_for(volume_spec)

            if volume && action_handler.should_perform_actions
              begin
                msg = "destroyed volume #{volume_spec.name} at #{driver_url}"
                action_handler.perform_action msg do
                  volume.destroy
                  volume_spec.reference = nil
                  volume_spec.save(action_handler)
                end
              rescue Fog::Scaleway::Compute::InvalidRequestError => e
                Chef::Log.error "Unable to destroy volume #{volume_spec.name} : #{e.message}"
              end
            end
          end

          def volume_for(volume_spec)
            if volume_spec.reference
              compute.volumes.get(volume_spec.reference["id"])
            end
          end
        end
      end
    end
  end
end


text:
from django.db import models
from django.db.models import signals
from django.dispatch.dispatcher import receiver
from django.contrib.auth.models import User

# Create your models here.
from products.models import Product

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    total = models.DecimalField(max_digits=50, default=0, decimal_places=2)
    active = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return str(self.id)

    '''
    def save(self, *args, **kwargs):
        #override the save function
        totals = [item.product.price for item in self.cartitem_set.all()]
        new_total = sum(totals)
        self.total = new_total
        super(Cart, self).save(*args, **kwargs)

        totals = []
        for item in self.cartitem_set.all():
            totals.append(item.product.price)
        '''

class CartItem(models.Model):
    cart = models.ForeignKey(Cart) #create cart model
    product = models.ForeignKey(Product)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return "%s" %(self.product.title)

@receiver([signals.post_save, signals.post_delete], sender=CartItem)
def update_cart_total(sender, instance, **kwargs):
    cart = instance.cart
    totals = [item.product.get_price() for item in cart.cartitem_set.all()]
    cart.total = sum(totals)
    cart.save()


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

<title>WordSizer (WordCram API)</title>
<meta name="date" content="2016-01-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

WordCram 1.0.0

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

wordcram

Interface WordSizer

public interface WordSizer

A WordSizer tells WordCram how big to render each word.
 You'll pass a WordSizer to WordCram via WordCram.withSizer(WordSizer).

 Some useful implementations are available in Sizers.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

float
sizeFor(Word word,
       int wordRank,
       int wordCount)

How big should this Word be rendered?

Method Detail

sizeFor

float sizeFor(Word word,
              int wordRank,
              int wordCount)

How big should this Word be rendered?

 Generally, a word cloud draws more important words bigger. Two typical
 ways to measure word's importance are its weight, and its rank (its
 position in the list of words, sorted by weight).

 Given that, sizeFor is passed the Word (which knows its own weight), its
 rank, and the total number of words.

 For example, given the text "I think I can I think", the words would look
 like this:

"I", weight 1.0 (3/3), rank 1

"think", weight 0.667 (2/3), rank 2

"can", weight 0.333 (1/3), rank 3

 ...and the WordSizer would be called with the following values:

Word "I" (weight 1.0), 1, 3

Word "think" (weight 0.667), 2, 3

Word "can" (weight 0.333), 3, 3

Parameters:

word - the Word to determine the size of

wordRank - the rank of the Word

wordCount - the total number of Words being rendered

Returns:

the size to render the Word

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

WordCram 1.0.0

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <file url="PROJECT" libraries="{Libs, Project}" />
  </component>
</project>


text:
<?php

namespace artkost\attachment\fileapi\actions;

use yii\base\Action;
use yii\base\InvalidConfigException;
use yii\helpers\FileHelper;
use Yii;

/**
 * DeleteAction for images and files.
 */
class DeleteAction extends Action
{
    /**
     * @inheritdoc
     */
    public function init()
    {

    }

    /**
     * @inheritdoc
     */
    public function run()
    {

    }

    /**
     * @return \yii\web\Request
     */
    protected function getRequest()
    {
        return Yii::$app->request;
    }
}


text:
import assert from "assert";

import progressBar from "../src/progressBar";
import initFixture from "./_initFixture";
import Command from "../src/Command";
import {exposeCommands} from "../src/Command";
import logger from "../src/logger";
import stub from "./_stub";

describe("Command", () => {
  describe(".input", () => {
    it("should be added to the instance", () => {
      const command = new Command(["a", "b", "c"]);
      assert.deepEqual(command.input, ["a", "b", "c"]);
    });
  });

  describe(".flags", () => {
    it("should be added to the instance", () => {
      const command = new Command(null, { foo: "bar" });
      assert.deepEqual(command.flags, { foo: "bar" });
    });
  });

  describe(".asiniVersion", () => {
    it("should be added to the instance", () => {
      const command = new Command();
      assert.deepEqual(command.asiniVersion, require("../package.json").version);
    });
  });

  describe(".progressBar", () => {
    it("should be added to the instance", () => {
      const command = new Command();
      assert.equal(command.progressBar, progressBar);
    });
  });

  describe(".logger", () => {
    it("should be added to the instance", () => {
      const command = new Command();
      assert.equal(command.logger, logger);
    });
  });

  describe(".concurrency", () => {
    it("should be added to the instance", () => {
      const command = new Command(null, {concurrency: 6});
      assert.equal(command.concurrency, 6);
    });

    it("should fall back to default if concurrency given is NaN", () => {
      const command = new Command(null, {concurrency: "bla"});
      assert.equal(command.concurrency, 4);
    });

    it("should fall back to default if concurrency given is 0", () => {
      assert.equal(new Command(null, {concurrency: 0}).concurrency, 4);
    });

    it("should fall back to 1 if concurrency given is smaller than 1", () => {
      assert.equal(new Command(null, {concurrency: -1}).concurrency, 1);
    });
  });

  describe(".run()", () => {
    it("should exist", (done) => {
      class TestCommand extends Command {
        initialize(callback) { callback(null, true); }
        execute() {

          done();
        }
      }

      const testCommand = new TestCommand([], {});
      testCommand.run();
    });
  });

  describe(".getOptions()", () => {
    beforeEach((done) => {
      initFixture("Command/basic", done);
    });

    class TestACommand extends Command {
    }
    class TestBCommand extends Command {
    }
    class TestCCommand extends Command {
      get otherCommandConfigs() {
        return ["testb"];
      }
    }

    it("should pick up global options", () => {
      assert.equal(new TestACommand([], {}).getOptions().testOption, "default");
    });

    it("should override global options with command-level options", () => {
      assert.equal(new TestBCommand([], {}).getOptions().testOption, "b");
    });

    it("should override global options with inherited command-level options", () => {
      assert.equal(new TestCCommand([], {}).getOptions().testOption, "b");
    });

    it("should override inherited command-level options with local command-level options", () => {
      assert.equal(new TestCCommand([], {}).getOptions().testOption2, "c");
    });

    it("should override command-level options with passed-in options", () => {
      assert.equal(new TestCCommand([], {}).getOptions({testOption2: "p"}).testOption2, "p");
    });

    it("should sieve properly within passed-in options", () => {
      assert.equal(new TestCCommand([], {}).getOptions({testOption2: "p"}, {testOption2: "p2"}).testOption2, "p2");
    });

    it("should override everything with a CLI flag", () => {
      assert.equal(new TestCCommand([], {testOption2: "f"}).getOptions({testOption2: "p"}).testOption2, "f");
    });

  });

  describe("legacy options", () => {
    beforeEach((done) => {
      initFixture("Command/legacy", done);
    });

    class TestCommand extends Command {
    }

    describe("bootstrapConfig", () => {
      class BootstrapCommand extends Command {
      }
      it("should warn when used", () => {
        let called = false;
        stub(logger, "warn", (message) => {
          called = true;
          assert.equal(message, "`bootstrapConfig.ignore` is deprecated.  Use `commands.bootstrap.ignore`.");
        });
        new BootstrapCommand([], {}).getOptions();
        assert.ok(called, "warning was emitted");
      });
      it("should provide a correct value", () => {
        assert.equal(new BootstrapCommand([], {}).getOptions().ignore, "package-a");
      });
      it("should not warn with other commands", () => {
        let called = false;
        stub(logger, "warn", () => called = true);
        new TestCommand([], {}).getOptions();
        assert.ok(!called, "no warning was emitted");
      });
      it("should not provide a value to other commands", () => {
        assert.equal(new TestCommand([], {}).getOptions().ignore, undefined);
      });
    });

    describe("publishConfig", () => {
      class PublishCommand extends Command {
      }
      it("should warn when used", () => {
        let called = false;
        stub(logger, "warn", (message) => {
          called = true;
          assert.equal(message, "`publishConfig.ignore` is deprecated.  Use `commands.publish.ignore`.");
        });
        new PublishCommand([], {}).getOptions();
        assert.ok(called, "warning was emitted");
      });
      it("should provide a correct value", () => {
        assert.equal(new PublishCommand([], {}).getOptions().ignore, "package-b");
      });
      it("should not warn with other commands", () => {
        let called = false;
        stub(logger, "warn", () => called = true);
        new TestCommand([], {}).getOptions();
        assert.ok(!called, "no warning was emitted");
      });
      it("should not provide a value to other commands", () => {
        assert.equal(new TestCommand([], {}).getOptions().ignore, undefined);
      });
    });
  });

  describe("exposeCommands", () => {
    class FooCommand extends Command {
    }
    class BarCommand extends Command {
    }
    class BadClassName extends Command {
    }
    class NonCommand {
    }

    it("makes a mapping from command names to classes", () => {
      assert.deepEqual(exposeCommands([FooCommand, BarCommand]), {
        foo: FooCommand,
        bar: BarCommand,
      });
    });
    it("fails on bad class name", () => {
      assert.throws(() => exposeCommands([BadClassName]));
    });
    it("fails on duplicate class", () => {
      assert.throws(() => exposeCommands([FooCommand, FooCommand]));
    });
    it("fails on class that doesn't extend Command", () => {
      assert.throws(() => exposeCommands([NonCommand]));
    });
  });
});


text:
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'warzdb');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
mysqli_query($db,"set names utf8");
?>


text:
import re
import collections

from enum import Enum

from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLIST,     REFERENCE_IDENTITY_CLASS, REFERENCE_ENUM_CLASS, REFERENCE_BITS, REFERENCE_UNION, ANYXML_CLASS

from ydk.errors import YPYError, YPYModelError
from ydk.providers._importer import _yang_ns
_meta_table = {
    'AlarmseverityEnum' : _MetaInfoEnum('AlarmseverityEnum', 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB',
        {
            'critical':'critical',
            'major':'major',
            'minor':'minor',
            'info':'info',
        }, 'CISCO-ENTITY-ALARM-MIB', _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB']),
    'CiscoEntityAlarmMib.Cealarmmonitoring' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmmonitoring',
            False,
            [
            _MetaInfoClassMember('ceAlarmCriticalCount', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                The value of this object specifies the number of alarms
                currently asserted with a severity of 'critical'.
                ''',
                'cealarmcriticalcount',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmCutOff', ATTRIBUTE, 'bool' , None, None,
                [], [],
                '''                If the management client writes a value of 'true' to this
                object, the agent stops signalling all external audible alarms
                under the control of the agent.  Reading this object should
                always result in a value of 'false'.

                Observe that alarm cutoff does not have an effect on monitoring,
                history logging, generation of notifications, or syslog message
                generation.  It also does not prevent the agent from signalling
                external audible alarms for alarms asserted after alarm-cutoff.

                This object emulates the 'alarm cut-off' mechanism typically
                installed in a central office (e.g., a big red button).  Observe
                this object should neither affect external visual alarms under
                the control of the agent, nor should it affect the current state
                of alarms being asserted by the system.
                ''',
                'cealarmcutoff',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmMajorCount', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                The value of this object specifies the number of alarms
                currently asserted with a severity of 'major'.
                ''',
                'cealarmmajorcount',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmMinorCount', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                The value of this object specifies the number of alarms
                currently asserted with a severity of 'minor'.
                ''',
                'cealarmminorcount',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmMonitoring',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmhistory' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmhistory',
            False,
            [
            _MetaInfoClassMember('ceAlarmHistLastIndex', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                This object specifies the value of the ceAlarmHistIndex
                object corresponding to the last entry added to the table by the
                agent.

                If the management client uses the notifications defined by this
                module, then it can poll this object to determine whether it has
                missed a notification sent by the agent.
                ''',
                'cealarmhistlastindex',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistTableSize', ATTRIBUTE, 'int' , None, None,
                [('0', '500')], [],
                '''                This object specifies the number of entries that the
                ceAlarmHistTable can contain.  When a physical entity
                generates an unfiltered alarm, and the capacity of the
                ceAlarmHistTable has reached the value specified by
                this object, then the agent deletes the oldest entity in
                order to accommodate the new entry. A value of '0' prevents
                any history from being retained.
                ''',
                'cealarmhisttablesize',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmHistory',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmfiltering' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmfiltering',
            False,
            [
            _MetaInfoClassMember('ceAlarmFilterProfileIndexNext', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                This object contains an appropriate value to be used
                for ceAlarmFilterIndex when creating entries in the
                ceAlarmFilterProfileTable.  The value '0' indicates
                that no unassigned entries are available.  To obtain
                a ceAlarmFilterIndex, the management client issues
                a get request.  The agent has the responsibility of
                modifying the value of this object following each
                successful get request.
                ''',
                'cealarmfilterprofileindexnext',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmNotifiesEnable', ATTRIBUTE, 'int' , None, None,
                [('0', '4')], [],
                '''                This object specifies a severity threshold governing the
                generation of ceAlarmAsserted and ceAlarmCleared
                notifications.  For example, if the value of this object is
                set to 'major', then the agent generates these notifications
                if and only if the severity of the alarm being indicated is
                'major' or 'critical'.  The value of '0' disables the
                generation of notifications.

                Observe that this setting overrides the value of the
                ceAlarmFilterNotifiesEnabled object.

                This object affects notification generation only; that is, it
                does not affect monitoring, history logging, and syslog message
                generation.
                ''',
                'cealarmnotifiesenable',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmSyslogEnable', ATTRIBUTE, 'int' , None, None,
                [('0', '4')], [],
                '''                This object specifies a severity threshold governing the
                generation of syslog messages corresponding to alarms.  For
                example, if the value of this object is set to 'major', then
                the agent generates these a syslog message if and only if the
                severity of the alarm being indicated is 'major' or 'critical'.
                The value of '0' disables the generation of syslog messages
                corresponding to alarms.

                Observe that this setting overrides the value of the
                ceAlarmFilterSyslogEnabled object.

                This object affects syslog message generation only; that is, it
                does not have an effect on monitoring, history logging, and
                generation of notifications.
                ''',
                'cealarmsyslogenable',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmFiltering',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmdescrmaptable.Cealarmdescrmapentry' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmdescrmaptable.Cealarmdescrmapentry',
            False,
            [
            _MetaInfoClassMember('ceAlarmDescrIndex', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                This object uniquely identifies an alarm description.
                ''',
                'cealarmdescrindex',
                'CISCO-ENTITY-ALARM-MIB', True),
            _MetaInfoClassMember('ceAlarmDescrVendorType', ATTRIBUTE, 'str' , None, None,
                [], [b'(([0-1](\\.[1-3]?[0-9]))|(2\\.(0|([1-9]\\d*))))(\\.(0|([1-9]\\d*)))*'],
                '''                This object specifies an object identifier (typically an
                enterprise-specific OID) that uniquely identifies the vendor
                type of those physical entities that this alarm description
                applies to.
                ''',
                'cealarmdescrvendortype',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmDescrMapEntry',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmdescrmaptable' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmdescrmaptable',
            False,
            [
            _MetaInfoClassMember('ceAlarmDescrMapEntry', REFERENCE_LIST, 'Cealarmdescrmapentry' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmdescrmaptable.Cealarmdescrmapentry',
                [], [],
                '''                A mapping between an alarm description and a vendor type.
                ''',
                'cealarmdescrmapentry',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmDescrMapTable',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmdescrtable.Cealarmdescrentry' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmdescrtable.Cealarmdescrentry',
            False,
            [
            _MetaInfoClassMember('ceAlarmDescrIndex', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                ''',
                'cealarmdescrindex',
                'CISCO-ENTITY-ALARM-MIB', True),
            _MetaInfoClassMember('ceAlarmDescrAlarmType', ATTRIBUTE, 'int' , None, None,
                [('0', '255')], [],
                '''                This object specifies the alarm type being described.
                ''',
                'cealarmdescralarmtype',
                'CISCO-ENTITY-ALARM-MIB', True),
            _MetaInfoClassMember('ceAlarmDescrSeverity', ATTRIBUTE, 'int' , None, None,
                [('0', '4')], [],
                '''                This object specifies the severity associated with the
                alarm type.

                An implementation may chose to not allow dynamic severity
                assignment, in which case it would restrict access to this
                object to be read-only.

                If an implementation allows dynamic severity assignment, then
                a management client can revert to the default severity by
                writing the value '0' to this object.

                There exists a class of systems that should implement dynamic
                severity assignment.  For example, consider a DSLAM (Digital
                Subscriber Loop Access Multiplexor) designed for both the
                central office and pedestal environments.  A 'pedestal' is
                typically a dark-green metal box mounted on a concrete or stone
                foundation in which carrier-class companies house equipment.
                The central office typically controls the temperature and
                humidity of the environment, reducing reliance on a system's
                fans.  Thus, the customer probably has a desire to reduce the
                severity of alarms indicating the failure of a fan.  However, a
                pedestal environment has a much greater reliance on a system's
                fans.  Thus, the customer probably has a desire to increase the
                severity of alarms indicating the failure of a fan.
                ''',
                'cealarmdescrseverity',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmDescrText', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                This object specifies a human-readable message describing
                the alarm.
                ''',
                'cealarmdescrtext',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmDescrEntry',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmdescrtable' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmdescrtable',
            False,
            [
            _MetaInfoClassMember('ceAlarmDescrEntry', REFERENCE_LIST, 'Cealarmdescrentry' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmdescrtable.Cealarmdescrentry',
                [], [],
                '''                A collection of attributes that describe an alarm type.
                ''',
                'cealarmdescrentry',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmDescrTable',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmtable.Cealarmentry' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmtable.Cealarmentry',
            False,
            [
            _MetaInfoClassMember('entPhysicalIndex', ATTRIBUTE, 'int' , None, None,
                [('1', '2147483647')], [],
                '''                ''',
                'entphysicalindex',
                'CISCO-ENTITY-ALARM-MIB', True),
            _MetaInfoClassMember('ceAlarmFilterProfile', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                This object specifies the alarm filter profile associated
                with the corresponding physical entity.  An alarm filter
                profile controls which alarm types the agent will monitor
                and signal for the corresponding physical entity.

                If the value of this object is '0', then the agent monitors
                and signals all alarms associated with the corresponding
                physical entity.
                ''',
                'cealarmfilterprofile',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmList', ATTRIBUTE, 'str' , None, None,
                [(0, 32)], [],
                '''                This object specifies those alarms currently being asserted
                by the corresponding physical entity.  Note, an alarm indicates
                a condition, not an event.  An alarm has two states:

                    'asserted'  Indicates that the condition described by the
                                alarm exists.

                    'cleared'   Indicates that the condition described by the
                                alarm does not exist.

                For example, a slot in a chassis may define an alarm that
                specifies whether the slot contains a module.  At the time of
                module insertion, the physical entity corresponding to the slot
                asserts this alarm, and the alarm remains asserted until the
                slot becomes empty.

                If an alarm is being asserted by the physical entity, then the
                corresponding bit in the alarm list is set to a one. Observe
                that if the physical entity is not currently asserting any
                alarms, then the list will have a length of zero.
                ''',
                'cealarmlist',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmSeverity', ATTRIBUTE, 'int' , None, None,
                [('0', '4')], [],
                '''                This object specifies the highest severity alarm currently
                being asserted by the corresponding physical entity.  A value
                of '0' indicates that there the corresponding physical entity
                currently is not asserting any alarms.
                ''',
                'cealarmseverity',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmEntry',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmtable' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmtable',
            False,
            [
            _MetaInfoClassMember('ceAlarmEntry', REFERENCE_LIST, 'Cealarmentry' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmtable.Cealarmentry',
                [], [],
                '''                Alarm control and status information related to the
                corresponding physical entity, including a list of those
                alarms currently being asserted by that physical entity.
                ''',
                'cealarmentry',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmTable',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmhisttable.Cealarmhistentry.CealarmhisttypeEnum' : _MetaInfoEnum('CealarmhisttypeEnum', 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB',
        {
            'asserted':'asserted',
            'cleared':'cleared',
        }, 'CISCO-ENTITY-ALARM-MIB', _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB']),
    'CiscoEntityAlarmMib.Cealarmhisttable.Cealarmhistentry' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmhisttable.Cealarmhistentry',
            False,
            [
            _MetaInfoClassMember('ceAlarmHistIndex', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                An integer value uniquely identifying the entry in the table.
                The value of this object starts at '1' and monotonically
                increases for each alarm condition transition monitored by the
                agent.  If the value of this object is '4294967295', the agent
                will reset it to '1' upon monitoring the next alarm condition
                transition.
                ''',
                'cealarmhistindex',
                'CISCO-ENTITY-ALARM-MIB', True),
            _MetaInfoClassMember('ceAlarmHistAlarmType', ATTRIBUTE, 'int' , None, None,
                [('0', '255')], [],
                '''                This object specifies the type of alarm generated.
                ''',
                'cealarmhistalarmtype',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistEntPhysicalIndex', ATTRIBUTE, 'int' , None, None,
                [('1', '2147483647')], [],
                '''                This object specifies the physical entity that generated
                the alarm.
                ''',
                'cealarmhistentphysicalindex',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistSeverity', REFERENCE_ENUM_CLASS, 'AlarmseverityEnum' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'AlarmseverityEnum',
                [], [],
                '''                This object specifies the severity of the alarm generated.
                ''',
                'cealarmhistseverity',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistTimeStamp', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                This object specifies the value of the sysUpTime object at
                the time the alarm was generated.
                ''',
                'cealarmhisttimestamp',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistType', REFERENCE_ENUM_CLASS, 'CealarmhisttypeEnum' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmhisttable.Cealarmhistentry.CealarmhisttypeEnum',
                [], [],
                '''                This object specifies whether the agent created the entry as
                the result of an alarm being asserted or cleared.
                ''',
                'cealarmhisttype',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmHistEntry',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmhisttable' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmhisttable',
            False,
            [
            _MetaInfoClassMember('ceAlarmHistEntry', REFERENCE_LIST, 'Cealarmhistentry' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmhisttable.Cealarmhistentry',
                [], [],
                '''                The information conveyed by a ceAlarmIndicate or
                ceAlarmClear trap.
                ''',
                'cealarmhistentry',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmHistTable',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmfilterprofiletable.Cealarmfilterprofileentry' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmfilterprofiletable.Cealarmfilterprofileentry',
            False,
            [
            _MetaInfoClassMember('ceAlarmFilterIndex', ATTRIBUTE, 'int' , None, None,
                [('0', '4294967295')], [],
                '''                This object uniquely identifies the alarm filter profile.
                ''',
                'cealarmfilterindex',
                'CISCO-ENTITY-ALARM-MIB', True),
            _MetaInfoClassMember('ceAlarmFilterAlarmsEnabled', ATTRIBUTE, 'str' , None, None,
                [(0, 32)], [],
                '''                This object specifies a list of alarms that are enabled.
                ''',
                'cealarmfilteralarmsenabled',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmFilterAlias', ATTRIBUTE, 'str' , None, None,
                [], [],
                '''                This object specifies an arbitrary name associated with the
                alarm filter profile by the management client, and provides
                a non-volatile 'handle' for the alarm filter profile.

                On the first instantiation of an alarm filter profile, the
                value of this object is a zero-length string.  However, an
                agent may choose to set the value to a locally unique default
                value.

                If an implementation supports write access to this object,
                then the agent is responsible for ensuring the retention
                of any value written to this object until a management client
                deletes it.  The level of retention must span reboots and
                reinitializations of the network management system, including
                those that result in different assignments to the value of
                the entPhysicalIndex associated with the physical entity.
                ''',
                'cealarmfilteralias',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmFilterNotifiesEnabled', ATTRIBUTE, 'str' , None, None,
                [(0, 32)], [],
                '''                This object specifies a list of alarms for which notification
                generation is enabled.
                ''',
                'cealarmfilternotifiesenabled',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmFilterStatus', REFERENCE_ENUM_CLASS, 'RowstatusEnum' , 'ydk.models.cisco_ios_xe.SNMPv2_TC', 'RowstatusEnum',
                [], [],
                '''                This object facilitates the creation, modification, or
                deletion of a conceptual row in this table.

                A management client can create a conceptual row in this
                table by setting this object to 'createAndWait' or
                'createAndGo'.  If a request to create a conceptual row
                in this table fails, then the system is not capable of
                supporting any more alarm filters.

                Before modifying a conceptual row in this table, the
                management client must set this object to 'notInService'.
                After modifying a conceptual row in this table, the
                management client must set this object to 'active'.
                This operation causes the modifications made to an
                alarm filter profile to take effect.

                An implementation should not allow a conceptual row in
                this table to be deleted if one or more physical entities
                reference it.
                ''',
                'cealarmfilterstatus',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmFilterSyslogEnabled', ATTRIBUTE, 'str' , None, None,
                [(0, 32)], [],
                '''                This object specifies a list of alarms for which syslog
                message generation is enabled.
                ''',
                'cealarmfiltersyslogenabled',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmFilterProfileEntry',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib.Cealarmfilterprofiletable' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib.Cealarmfilterprofiletable',
            False,
            [
            _MetaInfoClassMember('ceAlarmFilterProfileEntry', REFERENCE_LIST, 'Cealarmfilterprofileentry' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmfilterprofiletable.Cealarmfilterprofileentry',
                [], [],
                '''                When a physical entity asserts/clears an alarm AND the
                ceAlarmFilterProfile object is not '0', the agent applies
                the specified alarm filter profile in processing the alarm.
                The agent uses the following procedure in processing the
                transition of an alarm condition of a given type:

                1)  If the alarm list specified by the alarm filter profile's
                    ceAlarmFilterAlarmsEnabled object specifies that the alarm
                    type is disabled, then the agent performs no further
                    processing.

                2)  The agent creates an entry in the ceAlarmHistTable.

                3)  If the alarm list specified by the alarm filter profile's
                    ceAlarmFilterNotifiesEnabled object specifies that the alarm
                    type is enabled, then the agent generates the appropriate
                    notification.

                4)  If the alarm list specified by the alarm filter profile's
                    ceAlarmFilterSyslogEnabled object specifies that the alarm
                    type is enabled, then the agent generates the appropriate
                    syslog message.
                ''',
                'cealarmfilterprofileentry',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'ceAlarmFilterProfileTable',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
    'CiscoEntityAlarmMib' : {
        'meta_info' : _MetaInfoClass('CiscoEntityAlarmMib',
            False,
            [
            _MetaInfoClassMember('ceAlarmDescrMapTable', REFERENCE_CLASS, 'Cealarmdescrmaptable' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmdescrmaptable',
                [], [],
                '''                For each type of entity (represented entPhysicalVendorType
                OID), this table contains a mapping between a unique
                ceAlarmDescrIndex and entPhysicalvendorType OID.
                ''',
                'cealarmdescrmaptable',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmDescrTable', REFERENCE_CLASS, 'Cealarmdescrtable' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmdescrtable',
                [], [],
                '''                This table contains a description for each alarm type
                defined by each vendor type employed by the system.
                Observe that this table is sparse in nature, as it is
                rarely the case that a physical entity type needs to
                define every alarm in its alarm space.
                ''',
                'cealarmdescrtable',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmFiltering', REFERENCE_CLASS, 'Cealarmfiltering' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmfiltering',
                [], [],
                '''                ''',
                'cealarmfiltering',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmFilterProfileTable', REFERENCE_CLASS, 'Cealarmfilterprofiletable' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmfilterprofiletable',
                [], [],
                '''                This table contains a list of alarm filter profiles.
                ''',
                'cealarmfilterprofiletable',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistory', REFERENCE_CLASS, 'Cealarmhistory' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmhistory',
                [], [],
                '''                ''',
                'cealarmhistory',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmHistTable', REFERENCE_CLASS, 'Cealarmhisttable' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmhisttable',
                [], [],
                '''                This table contains a history of ceAlarmIndicate and
                ceAlarmClear traps generated by the agent.
                ''',
                'cealarmhisttable',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmMonitoring', REFERENCE_CLASS, 'Cealarmmonitoring' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmmonitoring',
                [], [],
                '''                ''',
                'cealarmmonitoring',
                'CISCO-ENTITY-ALARM-MIB', False),
            _MetaInfoClassMember('ceAlarmTable', REFERENCE_CLASS, 'Cealarmtable' , 'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB', 'CiscoEntityAlarmMib.Cealarmtable',
                [], [],
                '''                This table specifies alarm control and status information
                related to each physical entity contained by the system,
                including the alarms currently being asserted by each physical
                entity capable of generating alarms.
                ''',
                'cealarmtable',
                'CISCO-ENTITY-ALARM-MIB', False),
            ],
            'CISCO-ENTITY-ALARM-MIB',
            'CISCO-ENTITY-ALARM-MIB',
            _yang_ns._namespaces['CISCO-ENTITY-ALARM-MIB'],
        'ydk.models.cisco_ios_xe.CISCO_ENTITY_ALARM_MIB'
        ),
    },
}
_meta_table['CiscoEntityAlarmMib.Cealarmdescrmaptable.Cealarmdescrmapentry']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib.Cealarmdescrmaptable']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmdescrtable.Cealarmdescrentry']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib.Cealarmdescrtable']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmtable.Cealarmentry']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib.Cealarmtable']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmhisttable.Cealarmhistentry']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib.Cealarmhisttable']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmfilterprofiletable.Cealarmfilterprofileentry']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib.Cealarmfilterprofiletable']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmmonitoring']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmhistory']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmfiltering']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmdescrmaptable']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmdescrtable']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmtable']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmhisttable']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']
_meta_table['CiscoEntityAlarmMib.Cealarmfilterprofiletable']['meta_info'].parent =_meta_table['CiscoEntityAlarmMib']['meta_info']


text:
local helpers = require "spec.02-integration.02-dao.helpers"
local Factory = require "kong.dao.factory"

helpers.for_each_dao(function(kong_conf)
  describe("DAO Factory with DB: #"..kong_conf.database, function()
    it("should be instanciable", function()
      local factory
      assert.has_no_errors(function()
        factory = assert(Factory.new(kong_conf))
      end)

      assert.is_table(factory.daos)
      assert.equal(kong_conf.database, factory.db_type)
    end)
    it("should have shorthands to access the underlying daos", function()
      local factory = assert(Factory.new(kong_conf))
      assert.equal(factory.daos.apis, factory.apis)
      assert.equal(factory.daos.consumers, factory.consumers)
      assert.equal(factory.daos.plugins, factory.plugins)
    end)
  end)
end)


text:
package org.springframework.jms;

import javax.jms.JMSException;

import org.springframework.core.NestedRuntimeException;

/**
 * Base class for exception thrown by the framework whenever it
 * encounters a problem related to JMS.
 * @author Les Hazlewood
 * @author Juergen Hoeller
 * @since 1.1
 */
public abstract class JmsException extends NestedRuntimeException {

	/**
	 * Constructor that takes a message.
	 * @param msg the detail message
	 */
	public JmsException(String msg) {
		super(msg);
	}

	/**
	 * Constructor that allows a message and a root cause.
	 * @param msg the detail message
	 * @param cause the cause of the exception. This argument is generally
	 * expected to be a proper subclass of {@link javax.jms.JMSException},
	 * but can also be a JNDI NamingException or the like.
	 */
	public JmsException(String msg, Throwable cause) {
		super(msg, cause);
	}

	/**
	 * Constructor that allows a plain root cause, intended for
	 * subclasses mirroring respective javax.jms exceptions.
	 * @param cause the cause of the exception. This argument is generally
	 * expected to be a proper subclass of {@link javax.jms.JMSException}.
	 */
	protected JmsException(Throwable cause) {
		super(cause.getMessage(), cause);
	}

	/**
	 * Convenience method to get the vendor specific error code if
	 * the root cause was an instance of JMSException.
	 * @return a string specifying the vendor-specific error code if
	 * the root cause is an instance of JMSException.  Otherwise return
	 * text indicating the root cause was not an instance of JMSException.
	 */
	public String getErrorCode() {
		if (getCause() instanceof JMSException) {
			return ((JMSException) getCause()).getErrorCode();
		}
		else {
			return "Root cause not a JMSException";
		}
	}

	/**
	 * Return the detail message, including the message from the linked exception
	 * if there is one.
	 * @see javax.jms.JMSException#getLinkedException
	 */
	public String getMessage() {
		// Even if you cannot set the cause of this exception other than through
		// the constructor, we check for the cause being "this" here, as the cause
		// could still be set to "this" via reflection: for example, by a remoting
		// deserializer like Hessian's.
		if (getCause() == null || getCause() == this) {
			return super.getMessage();
		}
		else {
			if (getCause().getClass().isAssignableFrom(JMSException.class) &&
				  ((JMSException)getCause()).getLinkedException() != null) {
				Exception le = ((JMSException) getCause()).getLinkedException();
					return super.getMessage() + "; nested exception is " + le.getClass().getName() +
							": " + le.getMessage();
			}
			else {
				return super.getMessage() + "; nested exception is " + getCause().getClass().getName() +
						": " + getCause().getMessage();
			}
		}
	}

}


text:
package org.apache.geronimo.testsuite.javaee6.ejbtest.EJBBeans;

import javax.ejb.Singleton;
import java.text.DecimalFormat;

@Singleton
public class CalculatorSingleBean {
    String output = "Start the calculator process:
";
    double result = 0;
    public double add(double d) {
        double tmp = result + d;
        this.output += result + " + " + d + " equals " + tmp + "
";
        result = tmp;
        return result;
    }

    public String getOutput() {
        return this.output;
    }

    public double sub(double d) {
        double tmp = result - d;
        this.output += result + " - " + d + " equals " + tmp + "
";
        result = tmp;
        return result;
    }

}


text:
package io.katharsis.example.dropwizard.managed;

import com.mongodb.MongoClient;
import io.dropwizard.lifecycle.Managed;
import io.katharsis.example.dropwizard.MongoConfiguration;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;

public class MongoManaged implements Managed {
    private final MongoClient mongoClient;
    private final Datastore datastore;

    public MongoManaged (MongoConfiguration mongoConfig) throws Exception {
        mongoClient = new MongoClient(mongoConfig.host, mongoConfig.port);
        datastore = new Morphia().createDatastore(mongoClient, mongoConfig.db);
    }

    public Datastore getDatastore() {
        return datastore;
    }

    public void start() throws Exception {
    }

    public void stop() throws Exception {
        mongoClient.close();
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<calendar-query xmlns='urn:ietf:params:xml:ns:caldav'>
<prop xmlns='DAV:'>
<getetag/>
<calendar-data xmlns='urn:ietf:params:xml:ns:caldav'>
<expand start='$now.year.1:0102T000000Z' end='$now.year.1:0105T000000Z'/>
<comp name='VCALENDAR'>
<allprop/>
<comp name='VEVENT'>
<prop name='X-ABC-GUID'/>
<prop name='UID'/>
<prop name='DTSTART'/>
<prop name='DTEND'/>
<prop name='DURATION'/>
<prop name='EXDATE'/>
<prop name='EXRULE'/>
<prop name='RDATE'/>
<prop name='RRULE'/>
<prop name='RECURRENCE-ID'/>
<prop name='LOCATION'/>
<prop name='SUMMARY'/>
<prop name='DESCRIPTION'/>
</comp>
<comp name='VTIMEZONE'>
<allprop/>
<allcomp/>
</comp>
</comp>
</calendar-data>
</prop>
<filter>
<comp-filter name='VCALENDAR'>
<comp-filter name='VEVENT'>
<time-range start='$now.year.1:0102T000000Z' end='$now.year.1:0105T000000Z'/>
<prop-filter name="SUMMARY">
<text-match>event 6</text-match>
</prop-filter>
</comp-filter>
</comp-filter>
</filter>
</calendar-query>


text:
import Data.List
import Data.List.Extra
import Data.Maybe
import qualified Data.Map as Map

type Distances = Map.Map (String, String) Int

parseLine :: String -> [((String, String), Int)]
parseLine s =
  let [loc1, "would", dir, num, _, _, _, _, _, _, loc2] = words $ filter (/='.') s
      mult = if dir == "gain" then 1 else -1
      dist = read num * mult
  in
   [((loc1, loc2), dist)]

makeMap :: [String] -> Distances
makeMap = Map.fromList . concatMap parseLine

adjPairs :: [a] -> [(a, a)]
adjPairs (a1 : a2 : as) = (a1, a2) : adjPairs (a2 : as)
adjPairs _ = []

lolpairs xs = (last xs, head xs) : adjPairs xs

findShortest :: Distances -> Int
findShortest ds = maximum costs
  where cities = nub $ map fst $ Map.keys ds
        lists = map lolpairs $ permutations cities
        get (k1, k2) = (fromJust $ Map.lookup (k1, k2) ds) +
                       (fromJust $ Map.lookup (k2, k1) ds)
        listcost l = sum $ map get l
        costs = map listcost lists

solve :: String -> Int
solve = findShortest . makeMap . lines

answer f = interact $ (++"\n") . show . f
main = answer solve


text:
layout: post
category: episodes
date: 2016-03-21
episode: 21
title: "All About That Database All Rubble"
audio_file_path: "/audio/sound-security-e021.mp3"
length: 39621093
duration: "38:53"
subtitle: "All the terrible things that happen to massive databases of personal information, plus how to hire good security engineers."

articles:
  -
    title: "China Dabbles in Pre-Crime"
    comment: "The Communist Party has directed one of the country's largest state-run defense contractors, China Electronics Technology Group, to develop software to collate data on jobs, hobbies, consumption habits, and other behavior of ordinary citizens to predict terrorist acts before they occur."
    urls:
      - "http://www.bloomberg.com/news/articles/2016-03-03/china-tries-its-hand-at-pre-crime"
  -
    title: "How to Hire Good Security Engineers"
    comment: "A survey of some good articles about how to do useful interviews and hire good security nerds."
    urls:
      - "https://blog.codinghorror.com/we-hire-the-best-just-like-everyone-else/"
      - "https://danielmiessler.com/study/infosec_interview_questions/"
      - "https://sites.google.com/site/steveyegge2/five-essential-phone-screen-questions"
      - "https://www.digitalocean.com/company/careers#software-engineer:-services-&-applications"
      - "http://philcalcado.com/2016/03/15/on_asking_job_candidates_to_code.html"
  -
    title: "FBI Abandons It's Order to Apple"
    comment: "The FBI files a motion to vacate their order to Apple to help them remove the security controls on the iPhone belonging to one of the San Bernardino shooters."
    urls:
      - "https://threatpost.com/fbi-drops-its-case-against-apple/116918/"
      - "https://assets.documentcloud.org/documents/2773542/031123152171.pdf"
      - "http://www.zdziarski.com/blog/?p=5966"
breach:
  title: "OPM Breach: It's Worse Than You Thought"
  comment: "In which we learn that more and more incredibly personal information was stolen from the OPMs systems."
  urls:
    - "https://www.lawfareblog.com/why-opm-hack-far-worse-you-imagine"
    - "https://blogs.technet.microsoft.com/johnla/2015/04/26/defenders-think-in-lists-attackers-think-in-graphs-as-long-as-this-is-true-attackers-win/"

---
{% include show_notes.html %}


text:
require 'pathname'
require 'smartdown/model/flow'
require 'smartdown/model/node'
require 'smartdown/parser/node_parser'
require 'smartdown/parser/node_transform'

module Smartdown
  module Parser
    class NodeInterpreter
      attr_reader :name, :source, :reporter, :data_module

      def initialize(name, source, options = {})
        @name = name
        @source = source
        @data_module = options.fetch(:data_module, {})
        @parser = options.fetch(:parser, Smartdown::Parser::NodeParser.new)
        @transform = options.fetch(:transform, Smartdown::Parser::NodeTransform.new)
        @reporter = options.fetch(:reporter, Parslet::ErrorReporter::Deepest.new)
      end

      def interpret
        transform.apply(parser.parse(source, reporter: reporter),
          node_name: name,
          data_module: data_module,
        )
      end

    private
      attr_reader :parser, :transform
    end
  end
end


text:
if (typeof define !== 'function') {
  var define = require('amdefine')(module);
}

define(function(require) {

  var BaseView = require('../base');

  var exports = BaseView.extend({
    className: 'repos_index_view'
  });
  exports.id = 'repos/index';

  return exports;

});


text:
"""Tests for tfx.components.tuner.component."""

import tensorflow as tf
from tfx.components.tuner import component
from tfx.proto import trainer_pb2
from tfx.proto import tuner_pb2
from tfx.types import channel_utils
from tfx.types import standard_artifacts

class TunerTest(tf.test.TestCase):

  def setUp(self):
    super().setUp()
    self.examples = channel_utils.as_channel([standard_artifacts.Examples()])
    self.schema = channel_utils.as_channel([standard_artifacts.Schema()])
    self.transform_graph = channel_utils.as_channel(
        [standard_artifacts.TransformGraph()])
    self.train_args = trainer_pb2.TrainArgs(splits=['train'], num_steps=100)
    self.eval_args = trainer_pb2.EvalArgs(splits=['eval'], num_steps=50)
    self.tune_args = tuner_pb2.TuneArgs(num_parallel_trials=3)

  def _verify_output(self, tuner):
    self.assertEqual(standard_artifacts.HyperParameters.TYPE_NAME,
                     tuner.outputs['best_hyperparameters'].type_name)
    self.assertEqual(standard_artifacts.TunerResults.TYPE_NAME,
                     tuner.outputs['tuner_results'].type_name)

  def testConstructWithModuleFile(self):
    tuner = component.Tuner(
        examples=self.examples,
        schema=self.schema,
        train_args=self.train_args,
        eval_args=self.eval_args,
        tune_args=self.tune_args,
        module_file='/path/to/module/file')
    self._verify_output(tuner)

  def testConstructWithTunerFn(self):
    tuner = component.Tuner(
        examples=self.examples,
        transform_graph=self.transform_graph,
        train_args=self.train_args,
        eval_args=self.eval_args,
        tuner_fn='path.to.tuner_fn')
    self._verify_output(tuner)

  def testConstructWithCustomConfig(self):
    tuner = component.Tuner(
        examples=self.examples,
        transform_graph=self.transform_graph,
        train_args=self.train_args,
        eval_args=self.eval_args,
        module_file='/path/to/module/file',
        custom_config={'key': 'value'})
    self._verify_output(tuner)

  def testConstructDuplicateUserModule(self):
    with self.assertRaises(ValueError):
      _ = component.Tuner(
          examples=self.examples,
          schema=self.schema,
          train_args=self.train_args,
          eval_args=self.eval_args,
          module_file='/path/to/module/file',
          tuner_fn='path.to.tuner_fn')

if __name__ == '__main__':
  tf.test.main()


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>

      Notes · Class notes for Nate Harada

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

          Notes

Class notes for Nate Harada

      Home
      About
      Blog

          EECS492

          EECS598

          EECS584

          EECS545

          EECS586

          EECS583

© 2015. All rights reserved.

        Optimization

    11 Feb 2015

Different Types of Optimizing

NP-hard: Try every possible solution

Dynamic Programming: Try everything but do it efficiently

Greedy: Don't try everything

Optimal Binary Search

Given keys and probabilities in advance. Our first try is an exhaustive search: just try everything. Obviously that sucks. We could also try a quick-sortish method where we find the optimal tree on smaller trees until the base case. This is better, but not optimal – we've already seen many of the trees we create. We are solving subproblems repeatedly. We need to memoize our values we've seen. This is a key part of dynamic programming.

        Bayesian Learning

    11 Feb 2015

Gaussian Processes

A Gaussian process is a probability distribution over functions y(x), such that the set of values of y(x) evaluated jointly have a Guassian distribution. What determines a GP? A mean function, a covariance function, and that's all. Normally we say the mean is zero, so the prior is represented by the kernel entirely.

Linear regression, and Gaussian processes. Bayesian linear regression is just a special instance of a Guassian process. Features in Bayesian LR are kernel functions in GPs.

Fix this
 with a weight prior

A Gaussian process will generate data from its parameters (plus noise) but how do we actually learn one of these processes? We can find the next covariance given the current data. The predictive distribution is a Gaussian whose mean and variance depend on X(n+1). Try and ifnd a correspondence between GP and linear regression on your own time.

        More Trees

    09 Feb 2015

Red Black Trees

Red black trees are always balanced by nature. For red black tree insertion we generally need to rotate trees.

Problem for Freshman

We want a BST with insert, delete, search, and search by rank (order statistic). By order statistic, something like "find the 17th key". Once we have the count and the tree constructed, the second two become trivial. We want insert and delete. We can use "augmented trees" where the trees have a count at each node. When we rotate, we update each node with the count of the child nodes. This additional operation is supported by the augment, and we can still insert and delete in log(n) time.

To update the count of each node, we only require two rotations at most during insertion, and we can compute size attributes in constant time, so insertion is lg(n) because insertion is just lg(n). Deletion is similar, reqiring only 3 rotations at most and is again lg(n). Doing augmentaion like this changes our indexing, and changes which query is efficient. We'll also look at interval trees, read the book for this one.

        SVM and Algebra

    09 Feb 2015

SVM Reviews

It's an optimization problem, we want to solve a dual optimization with a Lagrangian function. We introduce slack variables to allow misclassifications. The dual formulation just introduces more constraints. The higher the C value the stricter the classifier is. A value of C=inf will result in the hard boundary classifier.

Multivariate Gaussians

Covariance matrix  is the outer product of

Partitioned Gaussians: We can combine Gaussians via partitions xa and xb, which allows us to partition the covariance matrix into only four covariances! Also notational is that the inverse of the covariance is the precision matrix . The partitioned Guassian can use the Woodbury Matrix Inversion Lemma to invert which is easier than computing it by hand.

In general we can treat matricies that are partitioned as matricies themselves. That is, linear algebra we do with numbers can extend to matricies. Fact: given a linear combo of Gaussian random vars, its distribution is also Gaussian. Its marginal distribution is also Gaussian. Its conditional distribution is also Gaussian.

Bayes' Theorem for Gaussians

We define our probabilities in terms of Guassians. Then we can find the posterior Gaussians just like with normal numbers but in symbolic form.

Bayesian Linear Regression

Doing regression from a truly Bayesian perspective. We have a likelihood and a prior, which gives us a posterior. We also now have probabilities for the weights, which we might assume has zero mean and identity covariance. We get the variance of the weights fo' free, which allows us to do regularization using weight variance instead of L2 norm.

        Trees

    04 Feb 2015

Binary Search Trees

Binary search has insert, delete, and search. These operations are the important part, because searching is easy. To search we just do a compare at each level of the tree, we can search in log(n) no problem. Insert is also easy, just do a search and if it's not where we expect put in our element. Delete is a little more complicated. If our element to delete is a leaf we remove it. If it's a node with one child, just remove it and connect the severed parts. If it's a node with two children, we could just promote one subtree and then hang the other one off of that. This is valid but poor. The better option is to take the smallest part of the right tree and promote it to the delete node's location.

For a given tree, the worst cases are:

Search:  for an unbalanced tree

Insert:

Delete:

The best case to build up a tree is n log n, because any faster would mean that we have a sorting algorithm that's better than n log n, and that's provably impossible.

Expected Search time is different. If all trees are equally likely the expected depth is about . This assumption is dumb though…we don't build trees to be equally likely. We'll instead assume that all input orderings are equally likely (no duplicates).

Time to insert = time to find
average search time = time to build/n

When we build up trees the balanced tree is most likely. The average number of comparisons to build a tree is the same as quicksort. Building a tree is basically quicksort anyway.

Now something totally different:

Assume each new insertion is a new key we've never seen.

IIIDI, this is 72 equally likely trees (4!x3 options for each D). There are 25 possible balanced trees, which is better than 1/3 which is good.

Red-Black Trees

Every node will be either red or black (these are NOT keys). Rule are:

Red parent cannot have red child

From any node to a leaf, the number of blacks is always the same

    Older

      Newer


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
L. Diels, Bot. Jahrb. Syst. 29:461. 1900

#### Original name
null

### Remarks
null


text:
.. _library-keras:

Keras
=====

Keras_ is "a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano".

Keras can be used for many Machine Learning tasks, and it has support for both popular
and experimental neural network architectures.

.. _Keras: https://keras.io/

.. _keras-explain-prediction:

explain_prediction
------------------

Currently ELI5 supports :func:`eli5.explain_prediction` for Keras image classifiers.
:func:`eli5.explain_prediction` explains image classifications through `Grad-CAM <https://arxiv.org/pdf/1610.02391.pdf>`_.

The returned :class:`eli5.base.Explanation` instance contains some important objects:

* ``image`` represents the image input into the model. A Pillow image.

* ``targets`` represents the explanation values for each target class (currently only 1 target is supported). A list of :class:`eli5.base.TargetExplanation` objects with the following attributes set:

    * ``heatmap``  a grayscale "localization map" (rank 2 (2D) numpy array, with float values in the interval `[0, 1]`). The numbers indicate how important the region in the image is for the target class (even if the target class was not the predicted class). Higher numbers mean that the region tends to increase the predicted value for a class. Lower numbers mean that the region has smaller effect on the predicted class score.

    * ``target`` the integer ID of the class (same as the argument to ``targets`` if one was passed, or the predicted class ID if no argument was passed).

    * ``score`` the output of the network for the predicted class.

Important arguments to :func:`eli5.explain_prediction` for ``Model`` and ``Sequential``:

* ``doc`` is an image as a tensor that can be inputted to the model.

    - The tensor must be an instance of ``numpy.ndarray``.

    - Usually the tensor has the format `(batch, dims, ..., channels)` (channels last format, `dims=(height, width)`, `batch=1`, one image), i.e. `BHWC`.

    - Check ``model.input_shape`` to confirm the required dimensions of the input tensor.

* ``image`` Pillow image, corresponds to doc input.

    - Image over which to overlay the heatmap.

    - If not given, the image will be derived from ``doc`` where possible.

    - Useful if ELI5 fails in case you have a custom image model or image input.

* ``targets`` are the output classes to focus on. Possible values include:

    - A list of integers (class ID's). *Only the first prediction from the list is currently taken*. The list must be length one.

    - None for automatically taking the top prediction of the model.

* ``layer`` is the layer in the model from which the heatmap will be generated. Possible values are:

    - An instance of ``Layer``, a name (str), or an index (int)

    - None for automatically getting a suitable layer, if possible.

All other arguments are ignored.

.. note::
    Top-level :func:`eli5.explain_prediction` calls are dispatched
    to :func:`eli5.keras.explain_prediction_keras` for
    ``keras.models.Model`` and ``keras.models.Sequential``.

.. _keras-show-prediction:

show_prediction
---------------

ELI5 supports :func:`eli5.show_prediction` to conveniently
invoke ``explain_prediction`` with ``format_as_image``, and display the explanation in an
IPython cell.

.. _keras-gradcam:

Grad-CAM
--------

ELI5 contains :func:`eli5.keras.gradcam.gradcam` and :func:`eli5.keras.gradcam.gradcam_backend`.

These functions can be used to obtain finer details of a Grad-CAM explanation.


text:
package com.stoyanr.evictor.scheduler;

import static java.util.concurrent.TimeUnit.NANOSECONDS;

import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import com.stoyanr.evictor.EvictionQueue;
import com.stoyanr.evictor.map.EvictibleEntry;

/**
 * A concrete implementation of {@link AbstractQueueEvictionScheduler} which
 * uses a single delayed task scheduled in an
 * {@link java.util.concurrent.ScheduledExecutorService} to manage the automated
 * eviction. The task is rescheduled appropriately each time an entry is added
 * or removed from the queue to ensure that it will always fire at the time of
 * the next scheduled eviction, not sooner or later. If the queue is empty, the
 * task is cancelled until an entry is added.
 *
 * @author Stoyan Rachev
 *
 * @param <K>
 *            the type of keys maintained by this map
 *
 * @param <V>
 *            the type of mapped values
 */
public class DelayedTaskEvictionScheduler<K, V> extends AbstractQueueEvictionScheduler<K, V> {

    public static final int DEFAULT_THREAD_POOL_SIZE = 1;

    private final ScheduledExecutorService ses;

    private volatile ScheduledFuture<?> future = null;

    private volatile long next = 0;

    /**
     * Creates a delayed task eviction scheduler with the default queue
     * implementation (see {@link AbstractQueueEvictionScheduler}) and a
     * {@link java.util.concurrent.ScheduledThreadPoolExecutor}.
     */
    public DelayedTaskEvictionScheduler() {
        this(new ScheduledThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE));
    }

    /**
     * Creates a delayed task eviction scheduler with the default queue
     * implementation (see {@link AbstractQueueEvictionScheduler}) and the
     * specified scheduled executor service.
     *
     * @param ses
     *            the scheduled executor service to be used
     *
     * @throws NullPointerException
     *             if the scheduled executor service is null
     */
    public DelayedTaskEvictionScheduler(ScheduledExecutorService ses) {
        super();

        if (ses == null) {
            throw new NullPointerException("ScheduledExecutorService instance cannot be null");
        }

        this.ses = ses;
    }

    /**
     * Creates a delayed task eviction scheduler with the specified queue and a
     * {@link java.util.concurrent.ScheduledThreadPoolExecutor}.
     *
     * @param queue
     *            the queue to be used
     *
     * @throws NullPointerException
     *             if the queue is null
     */
    public DelayedTaskEvictionScheduler(EvictionQueue<K, V> queue) {
        this(queue, new ScheduledThreadPoolExecutor(DEFAULT_THREAD_POOL_SIZE));
    }

    /**
     * Creates a delayed task eviction scheduler with the specified queue and
     * scheduled executor service.
     *
     * @param queue
     *            the queue to be used
     *
     * @param executorService
     *            the scheduled executor service to be used
     *
     * @throws NullPointerException
     *             if either the queue or the scheduled executor service is
     *             null
     */
    public DelayedTaskEvictionScheduler(EvictionQueue<K, V> queue, ScheduledExecutorService executorService) {
        super(queue);
        if (executorService == null) {
            throw new NullPointerException("ScheduledExecutorService instance cannot be null");
        }

        this.ses = executorService;
    }

    /**
     * {@inheritDoc}
     *
     *

     * This implementation simply invokes the <tt>shutdownNow</tt> method on the
     * scheduled executor service.
     *

     */
    @Override
    public void shutdown() {
        ses.shutdownNow();
    }

    /**
     * {@inheritDoc}
     *
     *

     * This implementation checks if the current next eviction time is different
     * from the last next eviction time, and if so (re)schedules the task.
     *

     *
     * @throws RejectedExecutionException
     *             if the task cannot be scheduled for execution
     */
    @Override
    protected void onScheduleEviction(EvictibleEntry<K, V> e) {
        if (getNextEvictionTime() != next) {
            scheduleTask();
        }
    }

    /**
     * {@inheritDoc}
     *
     *

     * This implementation checks if the current next eviction time is different
     * from the last next eviction time, and if so (re)schedules the task.
     *

     *
     * @throws RejectedExecutionException
     *             if the task cannot be scheduled for execution
     */
    @Override
    protected void onCancelEviction(EvictibleEntry<K, V> e) {
        if (getNextEvictionTime() != next) {
            scheduleTask();
        }
    }

    /**
     * {@inheritDoc}
     *
     *

     * This implementation simply always schedules the task.
     *

     *
     * @throws RejectedExecutionException
     *             if the task cannot be scheduled for execution
     */
    @Override
    protected void onEvictEntries() {
        schedule();
    }

    /**
     * (Re)schedules the task atomically. This method is synchronized to ensure
     * atomicity.
     */
    private synchronized void scheduleTask() {
        // Cancel the task if already scheduled, then call schedule() to
        // schedule a new task.
        if (future != null) {
            future.cancel(false);
        }

        schedule();
    }

    /**
     * Schedules the task atomically. This method is synchronized to ensure
     * atomicity. The next eviction time is always queried within this
     * synchronized method and not passed as parameter to ensure consistency in
     * a concurrent environment.
     */
    private synchronized void schedule() {
        // Get the next eviction time and reschedule the task with a delay
        // corresponding to the
        // difference between this time and the current time. If the next
        // eviction time is 0
        // (the queue is empty), don't schedule anything.
        next = getNextEvictionTime();
        future = (next > 0) ? ses.schedule(new EvictionRunnable(), Math.max(next - System.nanoTime(), 0), NANOSECONDS) : null;
    }

}


text:
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Analytics.Synapse.Artifacts.Models;
using Azure.Core;
using Azure.Core.Pipeline;

namespace Azure.Analytics.Synapse.Artifacts
{
    /// <summary> Unsubscribe event trigger from events. </summary>
    public partial class TriggerUnsubscribeTriggerFromEventsOperation : Operation<TriggerSubscriptionOperationStatus>, IOperationSource<TriggerSubscriptionOperationStatus>
    {
        private readonly OperationInternal<TriggerSubscriptionOperationStatus> _operation;

        /// <summary> Initializes a new instance of TriggerUnsubscribeTriggerFromEventsOperation for mocking. </summary>
        protected TriggerUnsubscribeTriggerFromEventsOperation()
        {
        }

        internal TriggerUnsubscribeTriggerFromEventsOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response)
        {
            IOperation<TriggerSubscriptionOperationStatus> nextLinkOperation = NextLinkOperationImplementation.Create(this, pipeline, request.Method, request.Uri.ToUri(), response, OperationFinalStateVia.Location);
            _operation = new OperationInternal<TriggerSubscriptionOperationStatus>(clientDiagnostics, nextLinkOperation, response, "TriggerUnsubscribeTriggerFromEventsOperation");
        }

        /// <inheritdoc />
#pragma warning disable CA1822
        public override string Id => throw new NotImplementedException();
#pragma warning restore CA1822

        /// <inheritdoc />
        public override TriggerSubscriptionOperationStatus Value => _operation.Value;

        /// <inheritdoc />
        public override bool HasCompleted => _operation.HasCompleted;

        /// <inheritdoc />
        public override bool HasValue => _operation.HasValue;

        /// <inheritdoc />
        public override Response GetRawResponse() => _operation.RawResponse;

        /// <inheritdoc />
        public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken);

        /// <inheritdoc />
        public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);

        /// <inheritdoc />
        public override Response<TriggerSubscriptionOperationStatus> WaitForCompletion(CancellationToken cancellationToken = default) => _operation.WaitForCompletion(cancellationToken);

        /// <inheritdoc />
        public override Response<TriggerSubscriptionOperationStatus> WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletion(pollingInterval, cancellationToken);

        /// <inheritdoc />
        public override ValueTask<Response<TriggerSubscriptionOperationStatus>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken);

        /// <inheritdoc />
        public override ValueTask<Response<TriggerSubscriptionOperationStatus>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken);

        TriggerSubscriptionOperationStatus IOperationSource<TriggerSubscriptionOperationStatus>.CreateResult(Response response, CancellationToken cancellationToken)
        {
            using var document = JsonDocument.Parse(response.ContentStream);
            return TriggerSubscriptionOperationStatus.DeserializeTriggerSubscriptionOperationStatus(document.RootElement);
        }

        async ValueTask<TriggerSubscriptionOperationStatus> IOperationSource<TriggerSubscriptionOperationStatus>.CreateResultAsync(Response response, CancellationToken cancellationToken)
        {
            using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false);
            return TriggerSubscriptionOperationStatus.DeserializeTriggerSubscriptionOperationStatus(document.RootElement);
        }
    }
}


text:
<?php

namespace System\UserBundle\Twig;

use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;

/*
 * Returns the current top level/main request route with a new locale
 */
class LocalizedRouteExtension extends \Twig_Extension
{

	private $request;
	private $router;

	public function __construct(Router $router) {
		// Just retrieve the router here
		$this->router = $router;
	}

	/*
	 * Listen to the 'kernel.request' event to get the main request, this has several reasons:
	 *  - The request can not be injected directly into a Twig extension, this causes a ScopeWideningInjectionException
	 *  - Retrieving the request inside of the 'localize_route' method might yield us an internal request
	 *  - Requesting the request from the container in the constructor breaks the CLI environment (e.g. cache warming)
	 */
	public function onKernelRequest(GetResponseEvent $event) {
		if ($event->getRequestType() === HttpKernel::MASTER_REQUEST) {
			$this->request = $event->getRequest();
		}
	}

	public function getFunctions()
	{
		return array(
			'localize_route' => new \Twig_Function_Method($this, 'localize_route')
		);
	}

	public function localize_route($locale = NULL) {
		// Merge query parameters and route attributes
		$attributes = array_merge($this->request->query->all(), $this->request->attributes->get('_route_params'));

		// Set/override locale
		$attributes['_locale'] = $locale ?: \Locale::getDefault();

		return $this->router->generate($this->request->attributes->get('_route'), $attributes);
	}

	public function getName()
	{
		return 'twig_localized_route_extension';
	}

}


text:
from u2flib_server import u2f
from .soft_u2f_v2 import SoftU2FDevice
import unittest

APP_ID = 'https://www.example.com'
FACET = APP_ID

def register_token(devices=[]):
    token = SoftU2FDevice()
    request_data = u2f.start_register(APP_ID, devices)
    response = token.register(request_data.registerRequests[0].json, FACET)
    device, cert = u2f.complete_register(request_data, response)
    return device, token

class AttestationTest(unittest.TestCase):

    def test_register_soft_u2f(self):
        device, token = register_token()
        assert device

    def test_authenticate_single_soft_u2f(self):
        # Register
        device, token = register_token()

        # Authenticate
        sign_request = u2f.start_authenticate([device])

        response1 = token.getAssertion(
            sign_request.authenticateRequests[0].json,
            FACET
        )

        assert u2f.verify_authenticate([device], sign_request, response1)

    def test_authenticate_multiple_soft_u2f(self):
        # Register
        device1, token1 = register_token()
        device2, token2 = register_token([device1])

        # Authenticate
        auth_request_data = u2f.start_authenticate([device1, device2])

        response = token1.getAssertion(
            auth_request_data.authenticateRequests[0].json,
            FACET
        )

        assert u2f.verify_authenticate([device1, device2],
                                       auth_request_data,
                                       response)


text:
package json

import (
	"testing"

	"github.com/doubledutch/mux/tests"
)

func TestHappyClientServer(t *testing.T) {
	tests.HappyClientServer(t, new(Pool), NewDefaultServer, NewDefaultClient)
}

func TestClientServerErr(t *testing.T) {
	tests.ClientServerErr(t, new(Pool), NewDefaultServer, NewDefaultClient)
}


text:
(function(){
Template.__define__("memberProfiles", (function() {
  var self = this;
  var template = this;
  return [ HTML.Raw('
Search for Existing Members
\n
\n
\n
\n
\n        \n          <button class="btn btn-default btn-large" id="addMember">\n            Actions</button>\n        \n        <input type="text" class="form-control" placeholder="Member Name" id="memberSearch">
\n
\n
\n
\n  '), HTML.DIV({
    "class": "text-center row"
  }, "\n    ", Spacebars.include(self.lookupTemplate("results")), "\n  "), HTML.Raw("\n
\n
\n  "), HTML.DIV({
    "class": "row"
  }, "\n    ", Spacebars.With(function() {
    return Spacebars.call(self.lookup("member"));
  }, UI.block(function() {
    var self = this;
    return [ "\n      ", HTML.H3("User Profile"), "\n      ", HTML.DIV("Name: ", function() {
      return Spacebars.mustache(Spacebars.dot(self.lookup("profile"), "firstName"));
    }, " ", function() {
      return Spacebars.mustache(Spacebars.dot(self.lookup("profile"), "lastName"));
    }), "\n      ", HTML.DIV("Address: ", function() {
      return Spacebars.mustache(Spacebars.dot(self.lookup("profile"), "street"));
    }, " ", function() {
      return Spacebars.mustache(Spacebars.dot(self.lookup("profile"), "city"));
    }, " ", function() {
      return Spacebars.mustache(Spacebars.dot(self.lookup("profile"), "state"));
    }), "\n    " ];
  })), "\n  ") ];
}));

})();