Myah  Conn

Myah Conn

1592263020

Loopin’ Around

Having covered conditional statements, it’s time for the next step in control flow: loops. Again, even though it might sound like a basic topic (and it is), there’s a lot to say about it that’s too nuanced for the first time around, and is worth a revision.
Many Loops
There are many different loops out there, so it’s alright to not be proficient in all of them—but it’s less alright to not be proficient in the ones you use. The most common loop by far is the while loop, which goes like that:

#loop #software-design #python

What is GEEK

Buddha Community

Loopin’ Around
Royce  Reinger

Royce Reinger

1659707040

Phobos: Simplifying Kafka for Ruby Apps

Phobos

Simplifying Kafka for Ruby apps!

Phobos is a micro framework and library for applications dealing with Apache Kafka.

  • It wraps common behaviors needed by consumers and producers in an easy and convenient API
  • It uses ruby-kafka as its Kafka client and core component
  • It provides a CLI for starting and stopping a standalone application ready to be used for production purposes

Why Phobos? Why not ruby-kafka directly? Well, ruby-kafka is just a client. You still need to write a lot of code to manage proper consuming and producing of messages. You need to do proper message routing, error handling, retrying, backing off and maybe logging/instrumenting the message management process. You also need to worry about setting up a platform independent test environment that works on CI as well as any local machine, and even on your deployment pipeline. Finally, you also need to consider how to deploy your app and how to start it.

With Phobos by your side, all this becomes smooth sailing.

Installation

Add this line to your application's Gemfile:

gem 'phobos'

And then execute:

$ bundle

Or install it yourself as:

$ gem install phobos

Usage

Phobos can be used in two ways: as a standalone application or to support Kafka features in your existing project - including Rails apps. It provides a CLI tool to run it.

Standalone apps

Standalone apps have benefits such as individual deploys and smaller code bases. If consuming from Kafka is your version of microservices, Phobos can be of great help.

Setup

To create an application with Phobos you need two things:

  • A configuration file (more details in the Configuration file section)
  • A phobos_boot.rb (or the name of your choice) to properly load your code into Phobos executor

Use the Phobos CLI command init to bootstrap your application. Example:

# call this command inside your app folder
$ phobos init
    create  config/phobos.yml
    create  phobos_boot.rb

phobos.yml is the configuration file and phobos_boot.rb is the place to load your code.

Consumers (listeners and handlers)

In Phobos apps listeners are configured against Kafka - they are our consumers. A listener requires a handler (a ruby class where you should process incoming messages), a Kafka topic, and a Kafka group_id. Consumer groups are used to coordinate the listeners across machines. We write the handlers and Phobos makes sure to run them for us. An example of a handler is:

class MyHandler
  include Phobos::Handler

  def consume(payload, metadata)
    # payload  - This is the content of your Kafka message, Phobos does not attempt to
    #            parse this content, it is delivered raw to you
    # metadata - A hash with useful information about this event, it contains: The event key,
    #            partition number, offset, retry_count, topic, group_id, and listener_id
  end
end

Writing a handler is all you need to allow Phobos to work - it will take care of execution, retries and concurrency.

To start Phobos the start command is used, example:

$ phobos start
[2016-08-13T17:29:59:218+0200Z] INFO  -- Phobos : <Hash> {:message=>"Phobos configured", :env=>"development"}
______ _           _
| ___ \ |         | |
| |_/ / |__   ___ | |__   ___  ___
|  __/| '_ \ / _ \| '_ \ / _ \/ __|
| |   | | | | (_) | |_) | (_) \__ \
\_|   |_| |_|\___/|_.__/ \___/|___/

phobos_boot.rb - find this file at ~/Projects/example/phobos_boot.rb

[2016-08-13T17:29:59:272+0200Z] INFO  -- Phobos : <Hash> {:message=>"Listener started", :listener_id=>"6d5d2c", :group_id=>"test-1", :topic=>"test"}

By default, the start command will look for the configuration file at config/phobos.yml and it will load the file phobos_boot.rb if it exists. In the example above all example files generated by the init command are used as is. It is possible to change both files, use -c for the configuration file and -b for the boot file. Example:

$ phobos start -c /var/configs/my.yml -b /opt/apps/boot.rb

You may also choose to configure phobos with a hash from within your boot file. In this case, disable loading the config file with the --skip-config option:

$ phobos start -b /opt/apps/boot.rb --skip-config

Consuming messages from Kafka

Messages from Kafka are consumed using handlers. You can use Phobos executors or include it in your own project as a library, but handlers will always be used. To create a handler class, simply include the module Phobos::Handler. This module allows Phobos to manage the life cycle of your handler.

A handler is required to implement the method #consume(payload, metadata).

Instances of your handler will be created for every message, so keep a constructor without arguments. If consume raises an exception, Phobos will retry the message indefinitely, applying the back off configuration presented in the configuration file. The metadata hash will contain a key called retry_count with the current number of retries for this message. To skip a message, simply return from #consume.

The metadata hash will also contain a key called headers with the headers of the consumed message.

When the listener starts, the class method .start will be called with the kafka_client used by the listener. Use this hook as a chance to setup necessary code for your handler. The class method .stop will be called during listener shutdown.

class MyHandler
  include Phobos::Handler

  def self.start(kafka_client)
    # setup handler
  end

  def self.stop
    # teardown
  end

  def consume(payload, metadata)
    # consume or skip message
  end
end

It is also possible to control the execution of #consume with the method #around_consume(payload, metadata). This method receives the payload and metadata, and then invokes #consume method by means of a block; example:

class MyHandler
  include Phobos::Handler

  def around_consume(payload, metadata)
    Phobos.logger.info "consuming..."
    output = yield payload, metadata
    Phobos.logger.info "done, output: #{output}"
  end

  def consume(payload, metadata)
    # consume or skip message
  end
end

Note: around_consume was previously defined as a class method. The current code supports both implementations, giving precendence to the class method, but future versions will no longer support .around_consume.

class MyHandler
  include Phobos::Handler

  def self.around_consume(payload, metadata)
    Phobos.logger.info "consuming..."
    output = yield payload, metadata
    Phobos.logger.info "done, output: #{output}"
  end

  def consume(payload, metadata)
    # consume or skip message
  end
end

Take a look at the examples folder for some ideas.

The hander life cycle can be illustrated as:

.start -> #consume -> .stop

or optionally,

.start -> #around_consume [ #consume ] -> .stop

Batch Consumption

In addition to the regular handler, Phobos provides a BatchHandler. The basic ideas are identical, except that instead of being passed a single message at a time, the BatchHandler is passed a batch of messages. All methods follow the same pattern as the regular handler except that they each end in _batch and are passed an array of Phobos::BatchMessages instead of a single payload.

To enable handling of batches on the consumer side, you must specify a delivery method of inline_batch in phobos.yml, and your handler must include BatchHandler. Using a delivery method of batch assumes that you are still processing the messages one at a time and should use Handler.

When using inline_batch, each instance of Phobos::BatchMessage will contain an instance method headers with the headers for that message.

class MyBatchHandler
  include Phobos::BatchHandler

  def around_consume_batch(payloads, metadata)
    payloads.each do |p|
      p.payload[:timestamp] = Time.zone.now
    end

    yield payloads, metadata
  end

  def consume_batch(payloads, metadata)
    payloads.each do |p|
      logger.info("Got payload #{p.payload}, #{p.partition}, #{p.offset}, #{p.key}, #{p.payload[:timestamp]}")
    end
  end

end

Note that retry logic will happen on the batch level in this case. If you are processing messages individually and an error happens in the middle, Phobos's retry logic will retry the entire batch. If this is not the behavior you want, consider using batch instead of inline_batch.

Producing messages to Kafka

ruby-kafka provides several options for publishing messages, Phobos offers them through the module Phobos::Producer. It is possible to turn any ruby class into a producer (including your handlers), just include the producer module, example:

class MyProducer
  include Phobos::Producer
end

Phobos is designed for multi threading, thus the producer is always bound to the current thread. It is possible to publish messages from objects and classes, pick the option that suits your code better. The producer module doesn't pollute your classes with a thousand methods, it includes a single method the class and in the instance level: producer.

my = MyProducer.new
my.producer.publish(topic: 'topic', payload: 'message-payload', key: 'partition and message key')

# The code above has the same effect of this code:
MyProducer.producer.publish(topic: 'topic', payload: 'message-payload', key: 'partition and message key')

The signature for the publish method is as follows:

def publish(topic: topic, payload: payload, key: nil, partition_key: nil, headers: nil)

When publishing a message with headers, the headers argument must be a hash:

my = MyProducer.new
my.producer.publish(topic: 'topic', payload: 'message-payload', key: 'partition and message key', headers: { header_1: 'value 1' })

It is also possible to publish several messages at once:

MyProducer
  .producer
  .publish_list([
    { topic: 'A', payload: 'message-1', key: '1' },
    { topic: 'B', payload: 'message-2', key: '2' },
    { topic: 'B', payload: 'message-3', key: '3', headers: { header_1: 'value 1', header_2: 'value 2' } }
  ])

There are two flavors of producers: regular producers and async producers.

Regular producers will deliver the messages synchronously and disconnect, it doesn't matter if you use publish or publish_list; by default, after the messages get delivered the producer will disconnect.

Async producers will accept your messages without blocking, use the methods async_publish and async_publish_list to use async producers.

An example of using handlers to publish messages:

class MyHandler
  include Phobos::Handler
  include Phobos::Producer

  PUBLISH_TO = 'topic2'

  def consume(payload, metadata)
    producer.async_publish(topic: PUBLISH_TO, payload: {key: 'value'}.to_json)
  end
end

Note about configuring producers

Since the handler life cycle is managed by the Listener, it will make sure the producer is properly closed before it stops. When calling the producer outside a handler remember, you need to shutdown them manually before you close the application. Use the class method async_producer_shutdown to safely shutdown the producer.

Without configuring the Kafka client, the producers will create a new one when needed (once per thread). To disconnect from kafka call kafka_client.close.

# This method will block until everything is safely closed
MyProducer
  .producer
  .async_producer_shutdown

MyProducer
  .producer
  .kafka_client
  .close

Note about producers with persistent connections

By default, regular producers will automatically disconnect after every publish call. You can change this behavior (which reduces connection overhead, TLS etc - which increases speed significantly) by setting the persistent_connections config in phobos.yml. When set, regular producers behave identically to async producers and will also need to be shutdown manually using the sync_producer_shutdown method.

Since regular producers with persistent connections have open connections, you need to manually disconnect from Kafka when ending your producers' life cycle:

MyProducer
  .producer
  .sync_producer_shutdown

Phobos as a library in an existing project

When running as a standalone service, Phobos sets up a Listener and Executor for you. When you use Phobos as a library in your own project, you need to set these components up yourself.

First, call the method configure with the path of your configuration file or with configuration settings hash.

Phobos.configure('config/phobos.yml')

or

Phobos.configure(kafka: { client_id: 'phobos' }, logger: { file: 'log/phobos.log' })

Listener connects to Kafka and acts as your consumer. To create a listener you need a handler class, a topic, and a group id.

listener = Phobos::Listener.new(
  handler: Phobos::EchoHandler,
  group_id: 'group1',
  topic: 'test'
)

# start method blocks
Thread.new { listener.start }

listener.id # 6d5d2c (all listeners have an id)
listener.stop # stop doesn't block

This is all you need to consume from Kafka with back off retries.

An executor is the supervisor of all listeners. It loads all listeners configured in phobos.yml. The executor keeps the listeners running and restarts them when needed.

executor = Phobos::Executor.new

# start doesn't block
executor.start

# stop will block until all listers are properly stopped
executor.stop

When using Phobos executors you don't care about how listeners are created, just provide the configuration under the listeners section in the configuration file and you are good to go.

Configuration file

The configuration file is organized in 6 sections. Take a look at the example file, config/phobos.yml.example.

The file will be parsed through ERB so ERB syntax/file extension is supported beside the YML format.

logger configures the logger for all Phobos components. It automatically outputs to STDOUT and it saves the log in the configured file.

kafka provides configurations for every Kafka::Client created over the application. All options supported by ruby-kafka can be provided.

producer provides configurations for all producers created over the application, the options are the same for regular and async producers. All options supported by ruby-kafka can be provided. If the kafka key is present under producer, it is merged into the top-level kafka, allowing different connection configuration for producers.

consumer provides configurations for all consumer groups created over the application. All options supported by ruby-kafka can be provided. If the kafka key is present under consumer, it is merged into the top-level kafka, allowing different connection configuration for consumers.

backoff Phobos provides automatic retries for your handlers. If an exception is raised, the listener will retry following the back off configured here. Backoff can also be configured per listener.

listeners is the list of listeners configured. Each listener represents a consumer group.

Additional listener configuration

In some cases it's useful to share most of the configuration between multiple phobos processes, but have each process run different listeners. In that case, a separate yaml file can be created and loaded with the -l flag. Example:

$ phobos start -c /var/configs/my.yml -l /var/configs/additional_listeners.yml

Note that the config file must still specify a listeners section, though it can be empty.

Custom configuration/logging

Phobos can be configured using a hash rather than the config file directly. This can be useful if you want to do some pre-processing before sending the file to Phobos. One particularly useful aspect is the ability to provide Phobos with a custom logger, e.g. by reusing the Rails logger:

Phobos.configure(
  custom_logger: Rails.logger,
  custom_kafka_logger: Rails.logger
)

If these keys are given, they will override the logger keys in the Phobos config file.

Instrumentation

Some operations are instrumented using Active Support Notifications.

In order to receive notifications you can use the module Phobos::Instrumentation, example:

Phobos::Instrumentation.subscribe('listener.start') do |event|
  puts(event.payload)
end

Phobos::Instrumentation is a convenience module around ActiveSupport::Notifications, feel free to use it or not. All Phobos events are in the phobos namespace. Phobos::Instrumentation will always look at phobos. events.

Executor notifications

  • executor.retry_listener_error is sent when the listener crashes and the executor wait for a restart. It includes the following payload:
    • listener_id
    • retry_count
    • waiting_time
    • exception_class
    • exception_message
    • backtrace
  • executor.stop is sent when executor stops

Listener notifications

  • listener.start_handler is sent when invoking handler.start(kafka_client). It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
  • listener.start is sent when listener starts. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
  • listener.process_batch is sent after process a batch. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
    • batch_size
    • partition
    • offset_lag
    • highwater_mark_offset
  • listener.process_message is sent after processing a message. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
    • key
    • partition
    • offset
    • retry_count
  • listener.process_batch_inline is sent after processing a batch with batch_inline mode. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
    • batch_size
    • partition
    • offset_lag
    • retry_count
  • listener.retry_handler_error is sent after waiting for handler#consume retry. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
    • key
    • partition
    • offset
    • retry_count
    • waiting_time
    • exception_class
    • exception_message
    • backtrace
  • listener.retry_handler_error_batch is sent after waiting for handler#consume_batch retry. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
    • batch_size
    • partition
    • offset_lag
    • retry_count
    • waiting_time
    • exception_class
    • exception_message
    • backtrace
  • listener.retry_aborted is sent after waiting for a retry but the listener was stopped before the retry happened. It includes the following payload:
    • listener_id
    • group_id
    • topic
    • handler
  • listener.stopping is sent when the listener receives signal to stop.
    • listener_id
    • group_id
    • topic
    • handler
  • listener.stop_handler is sent after stopping the handler.
    • listener_id
    • group_id
    • topic
    • handler
  • listener.stop is send after stopping the listener.
    • listener_id
    • group_id
    • topic
    • handler

Plugins

List of gems that enhance Phobos:

Phobos DB Checkpoint is drop in replacement to Phobos::Handler, extending it with the following features:

  • Persists your Kafka events to an active record compatible database
  • Ensures that your handler will consume messages only once
  • Allows your system to quickly reprocess events in case of failures

Phobos Checkpoint UI gives your Phobos DB Checkpoint powered app a web gui with the features below. Maintaining a Kafka consumer app has never been smoother:

  • Search events and inspect payload
  • See failures and retry / delete them

Phobos Prometheus adds prometheus metrics to your phobos consumer.

  • Measures total messages and batches processed
  • Measures total duration needed to process each message (and batch)
  • Adds /metrics endpoit to scrape data

Development

After checking out the repo:

  • make sure docker is installed and running (for windows and mac this also includes docker-compose).
  • Linux: make sure docker-compose is installed and running.
  • run bin/setup to install dependencies
  • run docker-compose up -d --force-recreate kafka zookeeper to start the required kafka containers
  • run tests to confirm no environmental issues
    • wait a few seconds for kafka broker to get set up - sleep 30
    • run docker-compose run --rm test
    • make sure it reports X examples, 0 failures

You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Test

Phobos exports a spec helper that can help you test your consumer. The Phobos lifecycle will conveniently be activated for you with minimal setup required.

  • process_message(handler:, payload:, metadata: {}, encoding: nil) - Invokes your handler with payload and metadata, using a dummy listener (encoding and metadata are optional).
### spec_helper.rb
require 'phobos/test/helper'
RSpec.configure do |config|
  config.include Phobos::Test::Helper
  config.before(:each) do
    Phobos.configure(path_to_my_config_file)
  end
end 

### Spec file
describe MyConsumer do
  let(:payload) { 'foo' }
  let(:metadata) { Hash(foo: 'bar') }

  it 'consumes my message' do
    expect_any_instance_of(described_class).to receive(:around_consume).with(payload, metadata).once.and_call_original
    expect_any_instance_of(described_class).to receive(:consume).with(payload, metadata).once.and_call_original

    process_message(handler: described_class, payload: payload, metadata: metadata)
  end
end

Upgrade Notes

Version 2.0 removes deprecated ways of defining producers and consumers:

  • The before_consume method has been removed. You can have this behavior in the first part of an around_consume method.
  • around_consume is now only available as an instance method, and it must yield the values to pass to the consume method.
  • publish and async_publish now only accept keyword arguments, not positional arguments.

Example pre-2.0:

class MyHandler
  include Phobos::Handler

  def before_consume(payload, metadata)
    payload[:id] = 1
  end

  def self.around_consume(payload, metadata)
    metadata[:key] = 5
    yield
  end
end

In 2.0:

class MyHandler
  include Phobos::Handler

  def around_consume(payload, metadata)
    new_payload = payload.dup
    new_metadata = metadata.dup
    new_payload[:id] = 1
    new_metadata[:key] = 5
    yield new_payload, new_metadata
  end
end

Producer, 1.9:

  producer.publish('my-topic', { payload_value: 1}, 5, 3, {header_val: 5})

Producer 2.0:

  producer.publish(topic: 'my-topic', payload: { payload_value: 1}, key: 5, 
     partition_key: 3, headers: { header_val: 5})

Version 1.8.2 introduced a new persistent_connections setting for regular producers. This reduces the number of connections used to produce messages and you should consider setting it to true. This does require a manual shutdown call - please see Producers with persistent connections.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/klarna/phobos.

Linting

Phobos projects Rubocop to lint the code, and in addition all projects use Rubocop Rules to maintain a shared rubocop configuration. Updates to the shared configurations are done in phobos/shared repo, where you can also find instructions on how to apply the new settings to the Phobos projects.

Acknowledgements

Thanks to Sebastian Norde for the awesome logo!

Author: Phobos
Source Code: https://github.com/phobos/phobos 
License: Apache-2.0 license

#ruby #kafka 

Ruth  Nabimanya

Ruth Nabimanya

1624850863

Azure Data Catalog: A Quick Introduction to Data Handling Service Around

What is Azure Data Catalog?

Azure Data Catalog is a Data Catalog cloud service of Microsoft using a crowdsourced approach. It provides an inventory of data used for discovering and understanding the data sources. Microsoft Azure is a Software as a Service (SaaS) application.

“Build Confidence in Azure Data Catalog even having more than millions of accounts”

**Source: **Gartner, Inc

Azure Data Catalog enhances old investments’ performance, adding metadata and notation around the Azure environment’s data. It informs about the Data sources which we have discovered or which we already have. It expresses documentation and describes the schema of the data source. The data source location and a copy of the metadata are present in the Azure Data Catalog. The user can access it easily when needed, and the indexing of metadata helps discover data through a search.### What is Azure Data Catalog?

Azure Data Catalog is a Data Catalog cloud service of Microsoft using a crowdsourced approach. It provides an inventory of data used for discovering and understanding the data sources. Microsoft Azure is a Software as a Service (SaaS) application.

“Build Confidence in Azure Data Catalog even having more than millions of accounts”

**Source: **Gartner, Inc

Azure Data Catalog enhances old investments’ performance, adding metadata and notation around the Azure environment’s data. It informs about the Data sources which we have discovered or which we already have. It expresses documentation and describes the schema of the data source. The data source location and a copy of the metadata are present in the Azure Data Catalog. The user can access it easily when needed, and the indexing of metadata helps discover data through a search.

#big data engineering #blogs #azure data catalog: a quick introduction to data handling service around #azure data catalog #data handling service around #service

SFrames.jl: Wrapper Around The Open-source Components Of Graphlab

SFrames

Wrapper around SFrames SFrame.

Work in progress, most functionality missing

Installation

  1. Install Cxx, the Julia C++ FFI.
  2. Clone and make a debug build of SFrame
  3. Set an environment variable SFRAME_PATH to the directory that SFrame was cloned to. By default, it is assumed to be in a folder called SFrame in your home directory.
  4. Then just type using SFrames in your Julia REPL. Ssee the tests for usage.

Usage

SArray([1,2]) + SArray([3,4]) == SArray([4, 6]  # true

Download Details:

Author: malmaud
Source Code: https://github.com/malmaud/SFrames.jl 
License: View license

#julia #wrapper #around 

Julia Wrapper Around Google's Gumbo C Library for Parsing HTML

Gumbo.jl

Gumbo.jl is a Julia wrapper around Google's gumbo library for parsing HTML.

Getting started is very easy:

julia> using Gumbo

julia> parsehtml("<h1> Hello, world! </h1>")
HTML Document:
<!DOCTYPE >
HTMLElement{:HTML}:
<HTML>
  <head></head>
  <body>
    <h1>
       Hello, world!
    </h1>
  </body>
</HTML>

Read on for further documentation.

Installation

using Pkg
Pkg.add("Gumbo")

or activate Pkg mode in the REPL by typing ], and then:

add Gumbo

Basic usage

The workhorse is the parsehtml function, which takes a single argument, a valid UTF8 string, which is interpreted as HTML data to be parsed, e.g.:

parsehtml("<h1> Hello, world! </h1>")

Parsing an HTML file named filenamecan be done using:

julia> parsehtml(read(filename, String))

The result of a call to parsehtml is an HTMLDocument, a type which has two fields: doctype, which is the doctype of the parsed document (this will be the empty string if no doctype is provided), and root, which is a reference to the HTMLElement that is the root of the document.

Note that gumbo is a very permissive HTML parser, designed to gracefully handle the insanity that passes for HTML out on the wild, wild web. It will return a valid HTML document for any input, doing all sorts of algorithmic gymnastics to twist what you give it into valid HTML.

If you want an HTML validator, this is probably not your library. That said, parsehtml does take an optional Bool keyword argument, strict which, if true, causes an InvalidHTMLError to be thrown if the call to the gumbo C library produces any errors.

HTML types

This library defines a number of types for representing HTML.

HTMLDocument

HTMlDocument is what is returned from a call to parsehtml it has a doctype field, which contains the doctype of the parsed document, and a root field, which is a reference to the root of the document.

HTMLNodes

A document contains a tree of HTML Nodes, which are represented as children of the HTMLNode abstract type. The first of these is HTMLElement.

HTMLElement

mutable struct HTMLElement{T} <: HTMLNode
    children::Vector{HTMLNode}
    parent::HTMLNode
    attributes::Dict{String, String}
end

HTMLElement is probably the most interesting and frequently used type. An HTMLElement is parameterized by a symbol representing its tag. So an HTMLElement{:a} is a different type from an HTMLElement{:body}, etc. An empty HTMLElement of a given tag can be constructed as follows:

julia> HTMLElement(:div)
HTMLElement{:div}:
<div></div>

HTMLElements have a parent field, which refers to another HTMLNode. parent will always be an HTMLElement, unless the element has no parent (as is the case with the root of a document), in which case it will be a NullNode, a special type of HTMLNode which exists for just this purpose. Empty HTMLElements constructed as in the example above will also have a NullNode for a parent.

HTMLElements also have children, which is a vector of HTMLElement containing the children of this element, and attributes, which is a Dict mapping attribute names to values.

HTMLElements implement getindex, setindex!, and push!; indexing into or pushing onto an HTMLElement operates on its children array.

There are a number of convenience methods for working with HTMLElements:

tag(elem) get the tag of this element as a symbol

attrs(elem) return the attributes dict of this element

children(elem) return the children array of this element

getattr(elem, name) get the value of attribute name or raise a KeyError. Also supports being called with a default value (getattr(elem, name, default)) or function (getattr(f, elem, name)).

setattr!(elem, name, value) set the value of attribute name to value

HTMLText

type HTMLText <: HTMLNode
    parent::HTMLNode
    text::String
end

Represents text appearing in an HTML document. For example:

julia> doc = parsehtml("<h1> Hello, world! </h1>")
HTML Document:
<!DOCTYPE >
HTMLElement{:HTML}:
<HTML>
  <head></head>
  <body>
    <h1>
       Hello, world!
    </h1>
  </body>
</HTML>

julia> doc.root[2][1][1]
HTML Text:  Hello, world!

This type is quite simple, just a reference to its parent and the actual text it represents (this is also accessible by a text function). You can construct HTMLText instances as follows:

julia> HTMLText("Example text")
HTML Text: Example text

Just as with HTMLElements, the parent of an instance so constructed will be a NullNode.

Tree traversal

Use the iterators defined in AbstractTrees.jl, e.g.:

julia> using AbstractTrees

julia> using Gumbo

julia> doc = parsehtml("""
                     <html>
                       <body>
                         <div>
                           <p></p> <a></a> <p></p>
                         </div>
                         <div>
                            <span></span>
                         </div>
                        </body>
                     </html>
                     """);

julia> for elem in PreOrderDFS(doc.root) println(tag(elem)) end
HTML
head
body
div
p
a
p
div
span

julia> for elem in PostOrderDFS(doc.root) println(tag(elem)) end
head
p
a
p
div
span
div
body
HTML

julia> for elem in StatelessBFS(doc.root) println(tag(elem)) end
HTML
head
body
div
div
p
a
p
span

julia>

TODOS

  • support CDATA
  • support comments

Download Details:

Author: JuliaWeb
Source Code: https://github.com/JuliaWeb/Gumbo.jl 
License: View license

#julia #wrapper #around 

Myah  Conn

Myah Conn

1592263020

Loopin’ Around

Having covered conditional statements, it’s time for the next step in control flow: loops. Again, even though it might sound like a basic topic (and it is), there’s a lot to say about it that’s too nuanced for the first time around, and is worth a revision.
Many Loops
There are many different loops out there, so it’s alright to not be proficient in all of them—but it’s less alright to not be proficient in the ones you use. The most common loop by far is the while loop, which goes like that:

#loop #software-design #python