1624089760
As of now, some may treat consumer tokens as utility tokens but it is absolutely not a right one to agree. It is necessary to understand that utility tokens will be varying at any time and can sell and buy on the exchange platform. Thus, while considering the consumer tokens, then it is completely designed for consuming services and goods.
Regulator’s Reaction to Approve CTO
Some of the following reasons mentioned that why SEC needs to get approved Consumer Token Offering:
These tokens are preferably designed to be utilized or consumed.
Consumer tokens are designed utilizing the consumer token framework developed by ConsenSys, The Brooklyn Project.
Tokens are not found with high securities and thus there is no necessity to get registered with the SEC.
It helps token holders to claim service or product with consumer tokens.
Consumer tokens will not be sold again once it is sold as speculative financial elements.
Once SEC gets approved the CTOs, then investors will arise with the question and are also eager to know about the creation or launch of a Consumer Token Offering.
Consumer Tokens Creation
At present, to launch or create a consumer token, one should follow the below guidelines that is mentioned by the consumer token framework.
The consumer token framework focuses on the below listed concepts:
Design of Consumer Token
Project governance and operation
Accountable token distribution
Defining the intention of token distribution
Supply of tokens
Explaining the token Safety and Security
Exact goal on marketing practices
Defining how the token empowering the consumer
Compliance with the applicable law
Securitytokenizer is the top rated STO development company furnish abrupt consumer token offering development services and solutions according to your business needs
1659707040
Simplifying Kafka for Ruby apps!
Phobos is a micro framework and library for applications dealing with Apache Kafka.
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.
Add this line to your application's Gemfile:
gem 'phobos'
And then execute:
$ bundle
Or install it yourself as:
$ gem install phobos
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 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.
To create an application with Phobos you need two things:
phobos_boot.rb
(or the name of your choice) to properly load your code into Phobos executorUse 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.
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
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
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::BatchMessage
s 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
.
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
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
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
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.
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.
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.
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.
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.retry_listener_error
is sent when the listener crashes and the executor wait for a restart. It includes the following payload:executor.stop
is sent when executor stopslistener.start_handler
is sent when invoking handler.start(kafka_client)
. It includes the following payload:listener.start
is sent when listener starts. It includes the following payload:listener.process_batch
is sent after process a batch. It includes the following payload:listener.process_message
is sent after processing a message. It includes the following payload:listener.process_batch_inline
is sent after processing a batch with batch_inline
mode. It includes the following payload:listener.retry_handler_error
is sent after waiting for handler#consume
retry. It includes the following payload:listener.retry_handler_error_batch
is sent after waiting for handler#consume_batch
retry. It includes the following payload: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.stopping
is sent when the listener receives signal to stop.listener.stop_handler
is sent after stopping the handler.listener.stop
is send after stopping the listener.List of gems that enhance Phobos:
Phobos DB Checkpoint is drop in replacement to Phobos::Handler, extending it with the following features:
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:
Phobos Prometheus adds prometheus metrics to your phobos consumer.
/metrics
endpoit to scrape dataAfter checking out the repo:
docker
is installed and running (for windows and mac this also includes docker-compose
).docker-compose
is installed and running.bin/setup
to install dependenciesdocker-compose up -d --force-recreate kafka zookeeper
to start the required kafka containerssleep 30
docker-compose run --rm test
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.
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
Version 2.0 removes deprecated ways of defining producers and consumers:
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.
Bug reports and pull requests are welcome on GitHub at https://github.com/klarna/phobos.
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.
Thanks to Sebastian Norde for the awesome logo!
Author: Phobos
Source Code: https://github.com/phobos/phobos
License: Apache-2.0 license
1617951201
Security Token Offerings can be created on efficient blockchain networks like Ethereum, Hyperledger, and Stellar. We are experts in developing a Security Token Platform.
##security token offerings ##security token platform ##sto development ##security token development ##security token offering services
1618488735
An STO is an optimized way for startups and entrepreneurs to raise funds for their businesses. By pledging tangible assets against digital tokens, STOs protect the interests of the investors. Moreover, STOs are also recognized by the US SEC, which makes them a promising investment avenue.
Today, by using the services of a security token offerings provider, one can launch their project with relative ease. However, a businessperson should keep the following things in mind when going about the STO process:
Every Idea Matters: Make sure your business project creatively addresses the target problem. This will give you leverage over your competitors.
Start Marketing Early On: Experts believe that the success of blockchain-based crowdfunding lies in marketing. Hence, it is highly recommended to begin marketing your product or service from the word go!
Choosing The Right Service Provider: Every STO development firm offers a wide range of solutions that come with their own set of pros and cons. Therefore, do your research before selecting your service provider.
Assembling Your Team: The success of an STO also depends on the people behind it. Take your time to select and hire individuals who will make your stellar team!
If you are on the lookout for an STO development service, your search ends with Infinite Block Tech. They have extensive experience in the domain and offer 100% whitelabel solutions. They help you with every stage of your STO project such as publishing your whitepaper, creating your issuance platform, and even marketing your token.
#security token launch service #security token offering development #sto token offering #security token platform
1658068560
WordsCounted
We are all in the gutter, but some of us are looking at the stars.
-- Oscar Wilde
WordsCounted is a Ruby NLP (natural language processor). WordsCounted lets you implement powerful tokensation strategies with a very flexible tokeniser class.
["Bayrūt"]
and not ["Bayr", "ū", "t"]
, for example.Add this line to your application's Gemfile:
gem 'words_counted'
And then execute:
$ bundle
Or install it yourself as:
$ gem install words_counted
Pass in a string or a file path, and an optional filter and/or regexp.
counter = WordsCounted.count(
"We are all in the gutter, but some of us are looking at the stars."
)
# Using a file
counter = WordsCounted.from_file("path/or/url/to/my/file.txt")
.count
and .from_file
are convenience methods that take an input, tokenise it, and return an instance of WordsCounted::Counter
initialized with the tokens. The WordsCounted::Tokeniser
and WordsCounted::Counter
classes can be used alone, however.
WordsCounted.count(input, options = {})
Tokenises input and initializes a WordsCounted::Counter
object with the resulting tokens.
counter = WordsCounted.count("Hello Beirut!")
Accepts two options: exclude
and regexp
. See Excluding tokens from the analyser and Passing in a custom regexp respectively.
WordsCounted.from_file(path, options = {})
Reads and tokenises a file, and initializes a WordsCounted::Counter
object with the resulting tokens.
counter = WordsCounted.from_file("hello_beirut.txt")
Accepts the same options as .count
.
The tokeniser allows you to tokenise text in a variety of ways. You can pass in your own rules for tokenisation, and apply a powerful filter with any combination of rules as long as they can boil down into a lambda.
Out of the box the tokeniser includes only alpha chars. Hyphenated tokens and tokens with apostrophes are considered a single token.
#tokenise([pattern: TOKEN_REGEXP, exclude: nil])
tokeniser = WordsCounted::Tokeniser.new("Hello Beirut!").tokenise
# With `exclude`
tokeniser = WordsCounted::Tokeniser.new("Hello Beirut!").tokenise(exclude: "hello")
# With `pattern`
tokeniser = WordsCounted::Tokeniser.new("I <3 Beirut!").tokenise(pattern: /[a-z]/i)
See Excluding tokens from the analyser and Passing in a custom regexp for more information.
The WordsCounted::Counter
class allows you to collect various statistics from an array of tokens.
#token_count
Returns the token count of a given string.
counter.token_count #=> 15
#token_frequency
Returns a sorted (unstable) two-dimensional array where each element is a token and its frequency. The array is sorted by frequency in descending order.
counter.token_frequency
[
["the", 2],
["are", 2],
["we", 1],
# ...
["all", 1]
]
#most_frequent_tokens
Returns a hash where each key-value pair is a token and its frequency.
counter.most_frequent_tokens
{ "are" => 2, "the" => 2 }
#token_lengths
Returns a sorted (unstable) two-dimentional array where each element contains a token and its length. The array is sorted by length in descending order.
counter.token_lengths
[
["looking", 7],
["gutter", 6],
["stars", 5],
# ...
["in", 2]
]
#longest_tokens
Returns a hash where each key-value pair is a token and its length.
counter.longest_tokens
{ "looking" => 7 }
#token_density([ precision: 2 ])
Returns a sorted (unstable) two-dimentional array where each element contains a token and its density as a float, rounded to a precision of two. The array is sorted by density in descending order. It accepts a precision
argument, which must be a float.
counter.token_density
[
["are", 0.13],
["the", 0.13],
["but", 0.07 ],
# ...
["we", 0.07 ]
]
#char_count
Returns the char count of tokens.
counter.char_count #=> 76
#average_chars_per_token([ precision: 2 ])
Returns the average char count per token rounded to two decimal places. Accepts a precision argument which defaults to two. Precision must be a float.
counter.average_chars_per_token #=> 4
#uniq_token_count
Returns the number of unique tokens.
counter.uniq_token_count #=> 13
You can exclude anything you want from the input by passing the exclude
option. The exclude option accepts a variety of filters and is extremely flexible.
:odd?
.tokeniser =
WordsCounted::Tokeniser.new(
"Magnificent! That was magnificent, Trevor."
)
# Using a string
tokeniser.tokenise(exclude: "was magnificent")
# => ["that", "trevor"]
# Using a regular expression
tokeniser.tokenise(exclude: /trevor/)
# => ["magnificent", "that", "was", "magnificent"]
# Using a lambda
tokeniser.tokenise(exclude: ->(t) { t.length < 4 })
# => ["magnificent", "that", "magnificent", "trevor"]
# Using symbol
tokeniser = WordsCounted::Tokeniser.new("Hello! محمد")
tokeniser.tokenise(exclude: :ascii_only?)
# => ["محمد"]
# Using an array
tokeniser = WordsCounted::Tokeniser.new(
"Hello! اسماءنا هي محمد، كارولينا، سامي، وداني"
)
tokeniser.tokenise(
exclude: [:ascii_only?, /محمد/, ->(t) { t.length > 6}, "و"]
)
# => ["هي", "سامي", "وداني"]
The default regexp accounts for letters, hyphenated tokens, and apostrophes. This means twenty-one is treated as one token. So is Mohamad's.
/[\p{Alpha}\-']+/
You can pass your own criteria as a Ruby regular expression to split your string as desired.
For example, if you wanted to include numbers, you can override the regular expression:
counter = WordsCounted.count("Numbers 1, 2, and 3", pattern: /[\p{Alnum}\-']+/)
counter.tokens
#=> ["numbers", "1", "2", "and", "3"]
Use the from_file
method to open files. from_file
accepts the same options as .count
. The file path can be a URL.
counter = WordsCounted.from_file("url/or/path/to/file.text")
A hyphen used in leu of an em or en dash will form part of the token. This affects the tokeniser algorithm.
counter = WordsCounted.count("How do you do?-you are well, I see.")
counter.token_frequency
[
["do", 2],
["how", 1],
["you", 1],
["-you", 1], # WTF, mate!
["are", 1],
# ...
]
In this example -you
and you
are separate tokens. Also, the tokeniser does not include numbers by default. Remember that you can pass your own regular expression if the default behaviour does not fit your needs.
The program will normalise (downcase) all incoming strings for consistency and filters.
def self.from_url
# open url and send string here after removing html
end
Are you using WordsCounted to do something interesting? Please tell me about it.
Visit this website for one example of what you can do with WordsCounted.
Contributors
See contributors.
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)Author: Abitdodgy
Source Code: https://github.com/abitdodgy/words_counted
License: MIT license
1659601560
We are all in the gutter, but some of us are looking at the stars.
-- Oscar Wilde
WordsCounted is a Ruby NLP (natural language processor). WordsCounted lets you implement powerful tokensation strategies with a very flexible tokeniser class.
Are you using WordsCounted to do something interesting? Please tell me about it.
Visit this website for one example of what you can do with WordsCounted.
["Bayrūt"]
and not ["Bayr", "ū", "t"]
, for example.Add this line to your application's Gemfile:
gem 'words_counted'
And then execute:
$ bundle
Or install it yourself as:
$ gem install words_counted
Pass in a string or a file path, and an optional filter and/or regexp.
counter = WordsCounted.count(
"We are all in the gutter, but some of us are looking at the stars."
)
# Using a file
counter = WordsCounted.from_file("path/or/url/to/my/file.txt")
.count
and .from_file
are convenience methods that take an input, tokenise it, and return an instance of WordsCounted::Counter
initialized with the tokens. The WordsCounted::Tokeniser
and WordsCounted::Counter
classes can be used alone, however.
WordsCounted.count(input, options = {})
Tokenises input and initializes a WordsCounted::Counter
object with the resulting tokens.
counter = WordsCounted.count("Hello Beirut!")
Accepts two options: exclude
and regexp
. See Excluding tokens from the analyser and Passing in a custom regexp respectively.
WordsCounted.from_file(path, options = {})
Reads and tokenises a file, and initializes a WordsCounted::Counter
object with the resulting tokens.
counter = WordsCounted.from_file("hello_beirut.txt")
Accepts the same options as .count
.
The tokeniser allows you to tokenise text in a variety of ways. You can pass in your own rules for tokenisation, and apply a powerful filter with any combination of rules as long as they can boil down into a lambda.
Out of the box the tokeniser includes only alpha chars. Hyphenated tokens and tokens with apostrophes are considered a single token.
#tokenise([pattern: TOKEN_REGEXP, exclude: nil])
tokeniser = WordsCounted::Tokeniser.new("Hello Beirut!").tokenise
# With `exclude`
tokeniser = WordsCounted::Tokeniser.new("Hello Beirut!").tokenise(exclude: "hello")
# With `pattern`
tokeniser = WordsCounted::Tokeniser.new("I <3 Beirut!").tokenise(pattern: /[a-z]/i)
See Excluding tokens from the analyser and Passing in a custom regexp for more information.
The WordsCounted::Counter
class allows you to collect various statistics from an array of tokens.
#token_count
Returns the token count of a given string.
counter.token_count #=> 15
#token_frequency
Returns a sorted (unstable) two-dimensional array where each element is a token and its frequency. The array is sorted by frequency in descending order.
counter.token_frequency
[
["the", 2],
["are", 2],
["we", 1],
# ...
["all", 1]
]
#most_frequent_tokens
Returns a hash where each key-value pair is a token and its frequency.
counter.most_frequent_tokens
{ "are" => 2, "the" => 2 }
#token_lengths
Returns a sorted (unstable) two-dimentional array where each element contains a token and its length. The array is sorted by length in descending order.
counter.token_lengths
[
["looking", 7],
["gutter", 6],
["stars", 5],
# ...
["in", 2]
]
#longest_tokens
Returns a hash where each key-value pair is a token and its length.
counter.longest_tokens
{ "looking" => 7 }
#token_density([ precision: 2 ])
Returns a sorted (unstable) two-dimentional array where each element contains a token and its density as a float, rounded to a precision of two. The array is sorted by density in descending order. It accepts a precision
argument, which must be a float.
counter.token_density
[
["are", 0.13],
["the", 0.13],
["but", 0.07 ],
# ...
["we", 0.07 ]
]
#char_count
Returns the char count of tokens.
counter.char_count #=> 76
#average_chars_per_token([ precision: 2 ])
Returns the average char count per token rounded to two decimal places. Accepts a precision argument which defaults to two. Precision must be a float.
counter.average_chars_per_token #=> 4
#uniq_token_count
Returns the number of unique tokens.
counter.uniq_token_count #=> 13
You can exclude anything you want from the input by passing the exclude
option. The exclude option accepts a variety of filters and is extremely flexible.
:odd?
.tokeniser =
WordsCounted::Tokeniser.new(
"Magnificent! That was magnificent, Trevor."
)
# Using a string
tokeniser.tokenise(exclude: "was magnificent")
# => ["that", "trevor"]
# Using a regular expression
tokeniser.tokenise(exclude: /trevor/)
# => ["magnificent", "that", "was", "magnificent"]
# Using a lambda
tokeniser.tokenise(exclude: ->(t) { t.length < 4 })
# => ["magnificent", "that", "magnificent", "trevor"]
# Using symbol
tokeniser = WordsCounted::Tokeniser.new("Hello! محمد")
tokeniser.tokenise(exclude: :ascii_only?)
# => ["محمد"]
# Using an array
tokeniser = WordsCounted::Tokeniser.new(
"Hello! اسماءنا هي محمد، كارولينا، سامي، وداني"
)
tokeniser.tokenise(
exclude: [:ascii_only?, /محمد/, ->(t) { t.length > 6}, "و"]
)
# => ["هي", "سامي", "وداني"]
The default regexp accounts for letters, hyphenated tokens, and apostrophes. This means twenty-one is treated as one token. So is Mohamad's.
/[\p{Alpha}\-']+/
You can pass your own criteria as a Ruby regular expression to split your string as desired.
For example, if you wanted to include numbers, you can override the regular expression:
counter = WordsCounted.count("Numbers 1, 2, and 3", pattern: /[\p{Alnum}\-']+/)
counter.tokens
#=> ["numbers", "1", "2", "and", "3"]
Use the from_file
method to open files. from_file
accepts the same options as .count
. The file path can be a URL.
counter = WordsCounted.from_file("url/or/path/to/file.text")
A hyphen used in leu of an em or en dash will form part of the token. This affects the tokeniser algorithm.
counter = WordsCounted.count("How do you do?-you are well, I see.")
counter.token_frequency
[
["do", 2],
["how", 1],
["you", 1],
["-you", 1], # WTF, mate!
["are", 1],
# ...
]
In this example -you
and you
are separate tokens. Also, the tokeniser does not include numbers by default. Remember that you can pass your own regular expression if the default behaviour does not fit your needs.
The program will normalise (downcase) all incoming strings for consistency and filters.
def self.from_url
# open url and send string here after removing html
end
See contributors.
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)Author: abitdodgy
Source code: https://github.com/abitdodgy/words_counted
License: MIT license
#ruby #ruby-on-rails