text:
Tutorial
========

This tutorial will show you how to interface with a [Cascade Shark](glossary.html#shark)
using the FlyScript Python SDK.  This tutorial assumes a basic understanding of Python
(if not, see the [Beginner's Guide to Python](http://wiki.python.org/moin/BeginnersGuide)).
In addition, if you should be familiar with Shark and [Pilot](glossary.html#pilot).
If you have never used Shark and Pilot, it may be helpful to first read
[a brief introduction](background.html) to the Shark architecture.

The tutorial has been organized so you can follow it sequentially.  Throughout the
examples, you will be expected to fill in details specific to your environment.  These
will be called out using a dollar sign `$<name>` -- for example `$sharkhost` indicates you
should fill in the host name or IP address of a Shark appliance.

Whenever you see `>>>`, this indicates an interactive session using the Python
shell.  The command that you are expected to type follows the `>>>`.  The result of
the command follows.  Any lines with a `#` are just comments to describe what
is happening.  In many cases the exact output will depend on your environment,
so it may not match precisely what you see in this tutorial.

Shark Objects
-------------

As with any Python code, the first step is to import the module(s)
we intend to use.
The FlyScript code for working with Shark appliances resides in a
module called `rvbd.shark`.
The main class in this module is [`Shark`](shark.html#sharkobjects).
This object represents a connection to a Shark appliance.

To start, start python from the shell or command line:

    :::pycon
    $ python
    Python 2.7.3 (default, Apr 19 2012, 00:55:09)
    [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>>

Once in the python shell, let's create a Shark object:

    :::pycon
    >>> import rvbd.shark

    >>> sk = rvbd.shark.Shark('$sharkhost', auth=rvbd.common.UserAuth('$username', '$password'))

The first argument is the hostname or IP address of the Shark appliance.  The
second argument is a named parameter and identifies the authentication method
to use -- in this case, simple username/password is used.

As soon as the Shark object is created, a connection is established to the Shark appliance,
and the authentication credentials are validated.  If the username and password are
not correct, you will immediately see an exception.

The `sk` object is the basis for all communication with the Shark appliance, whether
that is running views, checking configuration, or simply retrieving information
about the appliance.  Lets take a look at some basic information about the
shark that we just connected to:

    :::pycon
    >>> info = sk.get_serverinfo()

    >>> info['version']
    '10.0'

    # Returns the uptime in nanoseconds
    >>> info['uptime']
<PHONE_NUMBER>759000

    # Returns the local_time in nanoseconds since Jan 1, 1970
    >>> info['local_time']
<PHONE_NUMBER>818051000

    # Utility function to print convert this time into a datetime object...
    >>> from rvbd.common.timeutils import nsec_string_to_datetime

    # Now let's see what that time really is...
    >>> str(nsec_string_to_datetime(info['local_time']))
    '2012-12-18 04:10:49.818051+00:00'

    # Let's see the entire info structure
    >>> info
    {'build_time': 'Nov 27 2012 16:10:50',
     'build_type': 'Final',
     'build_variant': 'TurboCap',
     'has_webui': True,
     'hostname': 'shark',
     'internal_version': '10.0.1005.0241',
     'local_time':<PHONE_NUMBER>818051000,
     'protocol_version': '4.0',
     'start_time':<PHONE_NUMBER>202292000,
     'system_type': 'Linux',
     'timezone': '-0800',
     'uptime':<PHONE_NUMBER>759000,
     'version': '10.0',
     'view_version': '3.5',
     'webui_SSL': True,
     'webui_port': 443,
     'webui_root_path': '/'}

Before moving on, exit the python interactive shell:

    :::pycon
    >>> [Ctrl-D]
    $

Views
-----

Let's create our first script.  We're going write a simple script that creates
and applies a view on the first capture interface on our shark appliance.

This script will use packets in a pcap file.  To start, download a copy of
[tutorial-1.pcap](tutorial-1.pcap) and save it in a new directory.

In the same directory as the pcap file, create a file called `view.py`
and insert the following code:

    :::python
    import rvbd.shark
    from rvbd.shark.types import Value, Key
    import pprint

    # Fill these in with appropriate values
    sharkhost = '$sharkhost'
    username = '$username'
    password = '$password'

    # Open a connection to the appliance and authenticate
    sk = rvbd.shark.Shark(sharkhost, auth=rvbd.common.UserAuth(username, password))

    # First, upload our pcap file, if it's not already present
    if not sk.exists('/{0}/tutorial-1.pcap'.format(username)):
        homedir = sk.get_dir(username)
        tracefile = homedir.upload_trace_file('tutorial-1.pcap', 'tutorial-1.pcap')
    else:
        # If it's already there, just grab a handle to it
        tracefile = sk.get_file('/{0}/tutorial-1.pcap'.format(username))

    # Now create a view on this tracefile.  Start by selecting the columns of interest
    columns = [ Key(sk.columns.ip.address),
                Value(sk.columns.generic.packets),
                Value(sk.columns.generic.bytes) ]

    view = sk.create_view(tracefile, columns, name="tutorial view")

    # Retrieve the data
    data = view.get_data(aggregated=True)

    # Close the view
    view.close()

    # Print the output to the screen
    printer = pprint.PrettyPrinter(2)
    printer.pprint(data)

Be sure to fill in appropriate values for `$sharkhost`, `$username` and `$password`.
Run this script as follows and you should see something like the following:

    :::text
    $ python view.py
    [ { 'p': 388,
        't': datetime.datetime(2012, 12, 18, 12, 41, 33, 808202, tzinfo=tzutc()),
        'vals': [ ['<IP_ADDRESS>', 384, 255208],
                  ['<IP_ADDRESS>', 13, 1025],
                  ['<IP_ADDRESS>', 48, 39486],
                  ['<IP_ADDRESS>', 263, 195713],
                  ['<IP_ADDRESS>', 10, 1446],
                  ['<IP_ADDRESS>', 16, 2960],
                  ['<IP_ADDRESS>', 3, 198],
                  ['<IP_ADDRESS>', 7, 1253],
                  ['<IP_ADDRESS>', 16, 10555],
                  ['<IP_ADDRESS>', 2, 100],
                  ['<IP_ADDRESS>', 6, 2472]]}]

Let's take a closer look at what this script is doing.  The first few
lines are simply importing a few libraries that we'll be using:

    :::python
    import rvbd.shark
    from rvbd.shark.types import Value, Key
    import pprint

Next, we create a Shark object that establishes our connection to the target
appliance:

    # Open a connection to the appliance and authenticate
    sk = rvbd.shark.Shark(sharkhost, auth=rvbd.common.UserAuth(username, password))

This next section ensures that the pcap file that we want to analyze is up
on the appliance.

    :::python
    # First, upload our pcap file, if it's not already present
    if not sk.exists('/{0}/tutorial-1.pcap'.format(username)):
        homedir = sk.get_dir(username)
        tracefile = homedir.upload_trace_file('tutorial-1.pcap', 'tutorial-1.pcap')
    else:
        # If it's already there, just grab a handle to it
        tracefile = sk.get_file('/{0}/tutorial-1.pcap'.format(username))

At this point, the variable `tracefile` is a handle to the tracefile 'tutorial-1.pacap'
that now present on the filesystem of the shark appliance.

Next, we're going to actually create a view.  The first step is to select the set
of columns that we're interested in collecting:

    :::python
    columns = [ Key(sk.columns.ip.address),
                Value(sk.columns.generic.packets),
                Value(sk.columns.generic.bytes) ]

Shark supports numerous columns, and any column can be either a key column or a value column.
Each row of data will be aggregated according to the set of key columns selected.  The
value columns define the set of additional data to collect per row.  In this
example, we are asking to collect total packets and bytes for each IP address
seen in the pcap file.

Now create the view:

    :::python
    view = sk.create_view(tracefile, columns, name="tutorial view")

The first argument is the `packet source`.  When creating a view, the packet source can
be one of four types of source objects: Interfaces, Trace Files, Capture Jobs
and Trace Clips.  A packet source can be live (e.g. a Shark capture port) or
offline (e.g. a Trace Clip). General information about packet sources can be
found in the [glossary](glossary.html).  See the [Python classes](shark.html#sourceobjects)
for details on how to work with the various source types as objects.

We can now use the view object to get data:

    :::python
    # Retrieve the data
    data = view.get_data(aggregated=True)

Data Objects
------------

The data object returned by the `get_data()` method contains the key and value columns
requested, but also returns a few addition fields of meta data.

First, edit `view.py` and comment out the line that closes the view - add a '#' in front of `view.close()`:

    :::python
    # Close the view
    # view.close()

Now rerun the python script, but pass the `-i` argument to python to drop into an interactive
shell after running the script.  This will allow us to inspect the data that
was returned:

    :::pycon
    $ python -i view.py
    [ { 'p': 388,
        't': datetime.datetime(2012, 12, 18, 12, 41, 33, 808202, tzinfo=tzutc()),
        'vals': [ ['<IP_ADDRESS>', 384, 255208],
                  ['<IP_ADDRESS>', 13, 1025],
                  ['<IP_ADDRESS>', 48, 39486],
                  ['<IP_ADDRESS>', 263, 195713],
                  ['<IP_ADDRESS>', 10, 1446],
                  ['<IP_ADDRESS>', 16, 2960],
                  ['<IP_ADDRESS>', 3, 198],
                  ['<IP_ADDRESS>', 7, 1253],
                  ['<IP_ADDRESS>', 16, 10555],
                  ['<IP_ADDRESS>', 2, 100],
                  ['<IP_ADDRESS>', 6, 2472]],
        'value_count': 11}]
    >>>

We are now back at the python prompt, but all the variables assigned in the
script are available to use for inspection.

First of all, note that the data object itself is a list of length 1:

    :::pycon
    >>> type(data)
    <type 'list'>

    >>> len(data)
    1

Each element in the list is called a `sample`.  We only have a single sample
in this output - we'll cover more about samples later.

A sample has 3 fields in it:

   - `p` - number of packets processed
   - `t` - timestamp of the beginning of the sample interval
   - `vals` - the key and value columns that were requested when the view was created

For this output, there is only one sample.  In the sample interval, 388
packets were processed.  The sample interval started as 12:41:33.808202 on Dec 18, 2012.

The `get_data()` method supports a number of additional options that
allow us to change how the data is returned. For example, we can ask
for the data to be sorted by bytes, the third column (index 2 starting
from 0):

    :::pycon
    >>> data = view.get_data(aggregated=True, sortby=2)

    # Look only at the 'vals' for the first and only sample (index 0)
    >>> printer.pprint(data[0]['vals'])
    [ ['<IP_ADDRESS>', 384, 255208],
      ['<IP_ADDRESS>', 263, 195713],
      ['<IP_ADDRESS>', 48, 39486],
      ['<IP_ADDRESS>', 16, 10555],
      ['<IP_ADDRESS>', 16, 2960],
      ['<IP_ADDRESS>', 6, 2472],
      ['<IP_ADDRESS>', 10, 1446],
      ['<IP_ADDRESS>', 7, 1253],
      ['<IP_ADDRESS>', 13, 1025],
      ['<IP_ADDRESS>', 3, 198],
      ['<IP_ADDRESS>', 2, 100]]

Or sort by packets (index 1), in ascending order:

    :::pycon
    >>> data = view.get_data(aggregated=True, sortby=1, sorttype="ascending")

    >>> printer.pprint(data[0]['vals'])
    [ ['<IP_ADDRESS>', 2, 100],
      ['<IP_ADDRESS>', 3, 198],
      ['<IP_ADDRESS>', 6, 2472],
      ['<IP_ADDRESS>', 7, 1253],
      ['<IP_ADDRESS>', 10, 1446],
      ['<IP_ADDRESS>', 13, 1025],
      ['<IP_ADDRESS>', 16, 2960],
      ['<IP_ADDRESS>', 16, 10555],
      ['<IP_ADDRESS>', 48, 39486],
      ['<IP_ADDRESS>', 263, 195713],
      ['<IP_ADDRESS>', 384, 255208]]

Note that the list of columns has the same order as requested when the view was created.

Aggregated or Not
-----------------

Notice that with each call to `get_data()`, we are passing the argument `aggregated=True`.
This argument indicates that we are not interested in time-series data, we want
only care about the `Key()` columns that were used to create the view.  But what happens
if you set `aggregated=False`?

Normally all data on the Shark appliance is collected in time intervals and will
return that data by time.  This is what happens when `aggregrated=False`.  The
time interval must be set when you create the view, but by default it is 1 second.

Let's see what the output would look like when it's not aggregated.  Change the True to False
and rerun the script:

    :::pycon
    >>> data = view.get_data(aggregated=False)

The output should look like this:

    :::pycon
    >>> len(data)
    6

    >>> printer.pprint(data)
    [ { 'p': 15,
        't': datetime.datetime(2012, 12, 18, 12, 41, 33, 808202, tzinfo=tzutc()),
        'vals': [['<IP_ADDRESS>', 13, 1025], ['<IP_ADDRESS>', 13, 1025]]},
      { 'p': 289,
        't': datetime.datetime(2012, 12, 18, 12, 41, 34, 808202, tzinfo=tzutc()),
        'vals': [ ['<IP_ADDRESS>', 289, 193299],
                  ['<IP_ADDRESS>', 44, 39222],
                  ['<IP_ADDRESS>', 203, 139597],
                  ['<IP_ADDRESS>', 10, 1446],
                  ['<IP_ADDRESS>', 6, 1028],
                  ['<IP_ADDRESS>', 3, 198],
                  ['<IP_ADDRESS>', 7, 1253],
                  ['<IP_ADDRESS>', 16, 10555]]},
      { 'p': 60,
        't': datetime.datetime(2012, 12, 18, 12, 41, 35, 808202, tzinfo=tzutc()),
        'vals': [['<IP_ADDRESS>', 60, 56116], ['<IP_ADDRESS>', 60, 56116]]},
      { 'p': 3,
        't': datetime.datetime(2012, 12, 18, 12, 41, 36, 808202, tzinfo=tzutc()),
        'vals': [['<IP_ADDRESS>', 2, 380], ['<IP_ADDRESS>', 2, 380]]},
      { 'p': 11,
        't': datetime.datetime(2012, 12, 18, 12, 41, 37, 808202, tzinfo=tzutc()),
        'vals': [ ['<IP_ADDRESS>', 2, 100],
                  ['<IP_ADDRESS>', 10, 2904],
                  ['<IP_ADDRESS>', 2, 332],
                  ['<IP_ADDRESS>', 6, 2472]]},
      { 'p': 10,
        't': datetime.datetime(2012, 12, 18, 12, 41, 39, 808202, tzinfo=tzutc()),
        'vals': [ ['<IP_ADDRESS>', 6, 1220],
                  ['<IP_ADDRESS>', 10, 1484],
                  ['<IP_ADDRESS>', 4, 264]]}]

Where as before `data` was a list of length one, it now has multiple
samples.  Each sample provides a snapshot of the key and value columns requested for
one interval starting at the time indicated by `t`.

Looking in detail at the second sample:

    :::pycon
    >>> data[1]
    {'p': 289,
     't': datetime.datetime(2012, 12, 18, 12, 41, 34, 808202, tzinfo=tzutc()),
     'vals': [['<IP_ADDRESS>', 289, 193299],
      ['<IP_ADDRESS>', 44, 39222],
      ['<IP_ADDRESS>', 203, 139597],
      ['<IP_ADDRESS>', 10, 1446],
      ['<IP_ADDRESS>', 6, 1028],
      ['<IP_ADDRESS>', 3, 198],
      ['<IP_ADDRESS>', 7, 1253],
      ['<IP_ADDRESS>', 16, 10555]]}

    >>> from rvbd.common.timeutils import *

    >>> data[1]['t'].strftime("%x %X")
    '12/18/12 12:41:34'

From this, we can tell that the sample covers the time from 12:41:34 to 12:41:35.
(Note, to be precise, it actually covers from 12:41:34.808202 to 12:41:35.808202)
Within that interval 289 packets were processed and host <IP_ADDRESS> was involved in each and
every one of those packets accountoing for 193,299 bytes.

Let's take a look at the time range covered for each sample using a little Python magic.

    :::python
    >>> for sample in data:
    ...     print "Start: {0}, processed {1} packets".format(sample['t'].strftime("%x %X"), sample['p'])
    ...
    Start: 12/18/12 12:41:33, processed 15 packets
    Start: 12/18/12 12:41:34, processed 289 packets
    Start: 12/18/12 12:41:35, processed 60 packets
    Start: 12/18/12 12:41:36, processed 3 packets
    Start: 12/18/12 12:41:37, processed 11 packets
    Start: 12/18/12 12:41:39, processed 10 packets

> Note: do not type in the leading `... ` for the second and third
lines above.  After typing in the first line (`for sample`), and press
enter, Python will prompt you with `... ` for additional commands to
be executed for each iteration of the for loop.  You *must* type in
the 4 leading spaces before `print`.  At the end of the second
line, when you press enter it will prompt again with `... `,
indicating that you may enter additional commands.  In this case, we are
done so just press enter again, and Python will execute the for loop.
See [Dive Into Python - 2.5: Indenting Code](http://www.diveintopython.net/getting_to_know_python/indenting_code.html) for more information.

Notice that 12:41:38 is missing?  This is not a bug -- it just means that there were no
packets in the trace file during that sample interval, so there is no data to show.

Before continuing on, exit from the Python shell:

Before moving on, exit the python interactive shell:

    :::pycon
    >>> [Ctrl-D]
    $

Processing View Data
--------------------

Ok, now let's enhance the script to do a bit more:

   * compute average packet size (bytes / packets)
   * select hosts sending small packets (< 100 bytes)
   * for each host, print out the protocols in use

Open up view.py and add a new import to the top of the file:

    :::python
    import rvbd.shark
    from rvbd.shark.types import Value, Key
    from rvbd.shark.filters import *            # <--- Add this line
    import pprint

Next, uncomment the line the closes the view, delete the lines that print the data
and replace the last section that prints the output to the screen with the following code:

    :::python
    # Close the view
    view.close()

    # Print the output to the screen            # <--- delete these three lines
    # printer = pprint.PrettyPrinter(2)
    # printer.pprint(data)

    # Compute avg bytes/packet, and resort      # <--- add the rest of this to the script
    rows = data[0].vals
    filtered_rows = [row for row in rows if (row[2] / row[1]) < 100]

    print "{0} Hosts are sending small packets (avg size < 100 bytes)".format(len(filtered_rows))
    for row in filtered_rows:
        print "{0}\t{1} bytes/pkt".format(row[0], row[2] / row[1])

    # Now create a new view that breaks out the protocol / port for each host above
    columns = [ Key(sk.columns.ip.protocol_name),
                Value(sk.columns.generic.packets),
                Value(sk.columns.generic.bytes) ]

    for row in filtered_rows:
        filters = [SharkFilter('ip.address="{0}"'.format(row[0]))]
        view = sk.create_view(tracefile, columns, filters, name="tutorial view - ip {0}".format(row[0]))
        data = view.get_data(aggregated=True)
        view.close()

        print "\nHost {0}".format(row[0])
        for pp_row in data[0].vals:
            print "{0}\t{1} bytes/pkt".format(pp_row[0],pp_row[2] / pp_row[1])

Save your changes and rerun the script (without the `-i` this time):

    :::text
    $ python view.py
    3 Hosts are sending small packets (avg size < 100 bytes)
    <IP_ADDRESS>	78 bytes/pkt
    <IP_ADDRESS>	66 bytes/pkt
    <IP_ADDRESS>	50 bytes/pkt

    Host <IP_ADDRESS>
    TCP	78 bytes/pkt

    Host <IP_ADDRESS>
    TCP	66 bytes/pkt

    Host <IP_ADDRESS>
    ICMP	50 bytes/pkt

This script now runs a total of 4 views, the first view collects bytes and packets per IP address.
The subsequent views collect bytes and packets per protocol for an individual IP address
using a `SharkFilter`:

    :::python
    filters = [SharkFilter('ip.address="{0}"'.format(row[0]))]

A SharkFilter allows you to form complex expressions using operators and various fields
within a packet.

Existing Views
--------------

In the above examples, we have always created a new view from scratch, then
closed that view when we were done.  Often, a view may be created and
running for a longer period of time.  For example, a live view is
continually being updated as new traffic is received.  Views may also be
created using the `Pilot` application.

If there are already open views on the Shark appliance,
we can access them with the `get_open_views()` method.  Start up a new
Python shell and lets give this a try:

    :::pycon
    $ python
    Python 2.7.3 (default, Apr 19 2012, 00:55:09)
    [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.

    >>> import rvbd.shark

    >>> sk = rvbd.shark.Shark('$sharkhost', auth=rvbd.common.UserAuth('$username', '$password'))

    >>> views = sk.get_open_views()

    >>> views
    [<View source="fs/admin/noon.cap" title="Bandwidth Over Time">,
     <View source="fs/admin/noon.cap" title="TCP Flags by Protocol Over Time"
     <View source="fs/admin/tutorial-1.pcap">]

> Your appliance will likely show a different set of open views.  You should
at least see the tutorail-1.pcap view in the list.

This method returns a list of objects, one representing each open
view.  We can get information about the time interval covered by the
view with the `get_timeinfo()` method:

    :::pycon
    >>> view = views[0]

    >>> view.get_timeinfo()
    {'delta':<PHONE_NUMBER>, 'end':<PHONE_NUMBER>719742000, 'start':<PHONE_NUMBER>719742000}

This method returns a struct with 3 fields:

   * `start` and `end` indicate the timestamp of the first and last samples
   covered by the view
   * `delta` specifies the interval of time covered by a single sample
   in nanoseconds (defaults to 1 second)

For a view applied to a `trace clip` or a static file,
the `start` and `end` times will be fixed for a particular view.
For a view applied to a `capture port` or the virtual device
associated with a `capture job`, the `end` time will be
regularly updated as new packets arrive and are processed.

The views created above by the view.py script had only a single `output`
associated with it.  In general,
a view may have multiple outputs associated with it.
Each output has the same basic structure - it contains a list of samples as
described above.

In this example, we are looking at the "TCP Flags by Protocol Over Time"
view which has separate outputs for the different flags that can appear
in TCP headers.
In `Pilot`, these outputs show up as separate graphs.
In FlyScript, there is a separate `output object <outputobjects>`
for each output, we can get at them with the `all_outputs()` method:

    :::pycon
    >>> view.all_outputs()
    [<view output OUID_Fin>,
     <view output OUID_Psh>,
     <view output OUID_Urg>,
     <view output OUID_Ack>,
     <view output OUID_Rst>,
     <view output OUID_Syn>]

> The number of outputs returned is based upon the view selected.  The view
created above as part of the tutorial only has a single output at index 0.
Note that if the view you have selected does not have 6 outputs, adjust the
array index below.

Let's use the helper routine `print_data()` in the module
`rvbd.shark.viewutils` to print the data in the view to the console:

    :::pycon
    >>> from rvbd.shark.viewutils import print_data

    # Grab the 6th output corresponding to the SYN flag, adjust as necessary
    # for the view selected
    >>> output = view.all_outputs()[5]

    >>> output
    <view output OUID_Syn>

    >>> print_data(output.get_legend(), output.get_data())
    Time                        Protocol            Packets
    2012/05/10 12:31:37.502796  http                1
    2012/05/10 12:31:51.502796  http                1
    2012/05/10 12:32:51.502796  http                1
    2012/05/10 12:32:56.502796  http                1
    2012/05/10 12:33:16.502796  https               1
    2012/05/10 12:33:27.502796  http                2
    2012/05/10 12:33:51.502796  http                1
    ...

Note that the method `View.get_data()` simply calls the get_data() function for
the first output of a view.  As such, the following are equivalent:

    :::pycon
    # Retrieving the data for the first output:
    >>> output0 = view.get_output(0)
    >>> data0 = output0.get_data()

    # Equivalent shortcut from the view object:
    >>> data = view.get_data()

repository: riverbed/flyscript

repo_name: riverbed/flyscript


text:
# Changelog {#changelog}

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

- [codedocs](https://codedocs.xyz/) page hosting the
  [documentation of the project](https://codedocs.xyz/lucasguesserts/tower_of_hanoi/index.html).

## [0.1.0] - 2019-11-18

### Added

- [TestLib](./TestLib/) based on the
  [CuTest](http://cutest.sourceforge.net/)
  and its [TestLibTest](./TestLibTest/).
- [TowerOfHanoi](./TowerOfHanoiLib/include/TowerOfHanoi.h)
  structure and basic tools for manipulating it.
- [Interactive Tower of Hanoi app](./InteractiveTowerOfHanoi/).
- [Optimized Algorithm app](./OptimizedAlgorithmTowerOfHanoi/)
  which shows how to solve the game with
  the minimum number of moves.
- [CMake](https://cmake.org/) support for building and testing.
- This informative [README.md](./README.md) file introducing the project.
- [CHANGELOG.md](./CHANGELOG.md) file according
  to [keepachangelog](https://keepachangelog.com/en/1.0.0/).
- [CONTRIBUTING.md](./CONTRIBUTING.md) file with general instructions.
- [MIT license](./LICENSE).
- [Travis CI](travis-ci.org) support for remote building and testing.
- Documentation using [Doxygen](http://www.doxygen.nl/).

license: MIT

branch_name: refs/heads/master

extension: markdown

license_type: permissive


text:
Kotlin/Native GTK bindings preview
======

This is a preview sample of a GTK wrapper library for Kotlin/Native

To test it open project from `CMakeLists.txt` in CLion with Kotlin/Native plugin installed.

Then run `main` function from `main.kt`

It is only tested on Ubuntu 18.04, other distributions and OS will be supported in the future.

Don't forget to install GTK dev dependencies before:
`sudo apt install libgtk-3-dev`

repository: sobotkami/kotlin-native-gtk

extension: md

repo_name: sobotkami/kotlin-native-gtk


text:
swap
====

Change history
--------------

* v0.1.2
    * Run `swapoff -a` every time as instantaneous and can fail if run once
* v0.1.1
    * Allow for tabs or spaces in /etc/fstab
* v0.1.0
    * Made on-off operations one-time use /swapfile as semaphor
* v0.0.3
    * Added feature to leave swap state alone (size = 0) or disable (size = -1)
* v0.0.2
    * Improved comment clarity
* v0.0.1
    * Initial version, creates swap file and turns it on


text:
# big-mult

Extremely fast, low error, sampling based matrix multiplaction algorithm for giant matrices. Implemented in [AssemblyScript](https://docs.assemblyscript.org/) and
tested with [as-pect](https://github.com/jtenner/as-pect);

## Usage

import `giantMult` and use it like a promise (since we need to stream the wasm file from the node_modules folder).

```javascript
import { giantMult, buildMultiplier } from "wasm-big-mult";

const a = [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]];
const b = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]];
const samples = 3;

giantMult(a, b, samples).then(resultMatrix => console.log(resultMatrix));
```

### Note

In this example, a is a 5x2 matrix and b is a 2x5, the result is a 5x5 matrix.
functionality **is not** defined when the dimensions of a and b are not valid.
I will make it throw an error in future iterations.

## Warnings

Parcel does not support assemblyscript, please use webpack if you wish to use this package.

## Credits

- Algorithm: [Hopcroft's book, section 7.2.1](http://www.cs.cornell.edu/courses/cs4850/2014sp/book.pdf)

repository: jtenner/big-mult

gha_license_id: MIT

repo_name: jtenner/big-mult


text:
# Fastly::AclResponse

## Properties

| Name | Type | Description | Notes |
| ---- | ---- | ----------- | ----- |
| **name** | **String** | Name for the ACL. Must start with an alphanumeric character and contain only alphanumeric characters, underscores, and whitespace. | [optional] |
| **created_at** | **Time** | Date and time in ISO 8601 format. | [optional][readonly] |
| **deleted_at** | **Time** | Date and time in ISO 8601 format. | [optional][readonly] |
| **updated_at** | **Time** | Date and time in ISO 8601 format. | [optional][readonly] |
| **service_id** | **String** |  | [optional][readonly] |
| **version** | **String** | String representing the number identifying a version of the service. | [optional][readonly] |
| **id** | **String** |  | [optional][readonly] |

[[Back to API list]](../../README.md#endpoints) [[Back to README]](../../README.md)

repository: fastly/fastly-ruby

branch_name: refs/heads/main

gha_language: Ruby

repo_name: fastly/fastly-ruby


text:
# MapProxyAdmin
Web administrator for mapproxy configurations

[MapProxy](https://mapproxy.org/) is an open source proxy and caching service for WMS, WMTS, TMS and other geospatial data services.

The MapProxy configuration is defined in yaml files. This project, MapProxyAdmin, provides a Web-UI for some common use cases:
* create a new configuration from scratch, based on WMS capabilities
* list the available MapProxy configurations and layers within configurations
* clear the cache for a given layer
* delete configurations

## Install

### Prerequisites
* mapproxy, configured as [MultiMapProxy](https://mapproxy.org/docs/1.11.0/deployment.html#multimapproxy)
* git
* unzip
* node (version 10 or higher) and npm

It is assumed that the MapProxy configuration resides within the bounds of a single configuration root directory:
/path/to/your/mapproxy/config. The directories for the caches and the MultiMapProxy
configurations are assumed to be subdirectories of this root directory.

### Steps
1. Get a copy of this repository

        git clone https://github.com/this/repo

2. copy public/config.json.example to public/config.json and edit the following settings to match your system configuration:

        "adminserver" : "http://host.example.com:8083/",
        "mapproxydir" : "/path/to/root/of/mapproxy",
        "mapproxy_projects": "projects",
        "mapproxy_cache": "mp"

    ***adminserver*** should point to the URL of the mapproxyadmin service, port 8083 is the default port,
    ***mapproxydir*** should point to the root of your mapproxy configuration directory,
    ***mapproxy_projects*** defines the name of the subdirectory for the MultiMapProxy configuration,
    ***mapproxy_cache*** defines the subdirectory that is the root directory for the caches.
3. unzip public/dist.zip, the resulting files and folders should go to public/
4. install dependencies for MapProxyAdmin (index.js)

        npm install

5. start the MapProxyAdmin service

        node index.js

6. open http://host.example.com:8083 in your browser

For MapProxyAdmin to function properly, it should have permissions to alter files in the cache directories and the MultiMapProxy config directory. This can be achieved by letting node run under the same account as MapProxy. For instance, if MapProxy is running as a wsgi service under Linux Apache, then node should run under account www-data:

        sudo -u www-data node index.js

For security, it is strongly advised to thoroughly restrict access to MapProxyAdmin. Users can easily destroy your MapProxy configuration or may find ways to change files on your file system (although some basic measures were taken to try to prevent this).

## Develop
The MapProxyAdmin source code for both client and server are JavaScript. The server uses Node and some node modules (Express, WMSCapabilities and JSYaml to name some), the client is based on WebComponents using [Polymer](https://www.polymer-project.org/) LitElement and LitHtml. Client development requires installation of polymer-cli

### Server dev
The server code is in index.js. Use a debugger to set breakpoints and step through the code.

1. start node in debug mode:

        node --inpect index.js

2. To open the debugger in the (Chrome) browser, type

        chrome://inspect

    in the address bar. Set breakpoints to step through the code

### Client dev
The source code for the browser client resides in directory /client. The code is built using polymer-cli and the build output is copied to the /public directory where it can run indepently of polymer. During development, client and server are separated. The server runs under node (see Server development above), the client runs under polymer, listening on a different port.

### Run client for dev under polymer
1. copy public/confg.json to client/config.json, edit client/config.json and set "adminserver" to http://localhost:8083
2. install polymer-cli

        npm install -g polymer-cli

3. install client dependencies, run the following command in the client directory:

        npm install

4. start the client under polymer

        polymer serve

5. point your browser to http://localhost:8081 (the client runs on port 8081, the server on port 8083)

### Build client for integration into server
Run the following commands in the ***/client*** directory:

      polymer build
      cd build/es5-bundled
      zip -r dist.zip *
      cp dist.zip ../../../public

repository: Geodan/mapproxyadmin

gha_language: JavaScript

repo_name: Geodan/mapproxyadmin


text:
---
title: Badges
description: Displays an alphanumeric value. A user can easily skim object-related values. Best used to provide users with information about an object that is worthy of attention.
demo:
  embedded:
  - name: Default Badge Example
    slug: example-index
---

The classes `error`, `info`, or `alert` associate the element with a status by color. In addition any of the classes from the color-palette can be used. (See [Colors](./colors) docs for more information).

Note that the tags and badges look the same but should not be used interchangeably. A badge is used mainly for alphanumeric values i.e. numbers currency ect. and should not cannot take an icon or text. For text embellishments use a tag. For icons use an icon or status icon or alert icon.

## Code Example

A badge is a CSS only component that uses a `<span>` with the class `badge`. In addition, the following classes are also supported for specific status types: `error`, `info`, or `alert`. Also the class `round` can be added to make a perfectly round badge, when using 1 or 2 digit numbers.

```html
<span class="round info badge ">5</span>
```

## Accessibility

- The traffic light colors are accessibility violations for contrast, however, the high contrast theme provides an alternative that passes. In addition, in context text should be used as color alone cannot provide the meaning.
- An audible span (`class="audible"`) should always be included for accessibility, it should describe the alert status and/or count value in a meaningful way to a non-visual user.

## Keyboard Shortcuts

Badges do not have tab stops and have no keyboard interaction on their own, but they may be placed in a grid cell or object that has tab focus.

## Testability

- Please refer to the [Application Testability Checklist](https://design.infor.com/resources/application-testability-checklist) for further details.

repository: infor-design/enterprise

gha_language: HTML

repo_name: infor-design/enterprise


text:
# rsv_model_fitting
Code for fitting SEIRS transmission models for respiratory syncytial virus (RSV) to incidence data.

## Authors
Code authors: Alexandra B Hogan, Roslyn I Hickson, Geoffry N Mercer, Hannah C Moore, Kathryn Glass (2016).

## About the model
The model here is an ordinary differential equation (ODE) transmission model for RSV transmission for two age classes. This model is published in:

Hogan AB, Glass K, Moore HC, Anderssen R. Exploring the dynamics of respiratory syncytial virus (RSV) transmission in children. *Theor. Popul. Biol.* 2016;110:78–85. Available from: http://dx.doi.org/10.1016/j.tpb.2016.04.003.

The parameters for ageing, birth rates, latency and infectious period duration, are all RSV-specific and specified at two different sections in the code. The timestep is currently in weeks but this can be changed.

## About the fitting
The fitting is implemented using the Nelder Mead algorithm, via the fminsearch function in MATLAB. You will need to start with reasonable parameter guesses for the fitting to work. There is an option in the code to either run the model with the parameter guesses, or run the fitting routine. The fitted parameters are the transmission coefficients for the two age groups; the amplitude of seasonal forcing; the phase shift (used to obtain horizontal alignment); and the duration of immunity.

## Synthetic data
The fitting routine is demonstrated using synthetic data. Note that this 'data' was generated from the model itself, with a negative binomial distribution used to add in noise, and is therefore only for illustrative purposes.


text:
# Session Object

The Session object returned by the `OT.initSession()` method provides access to much of the OpenTok functionality. The Session object exposes functionality through properties, methods and event handlers.

## Properties

* **connection** ([Connection](connection.md)) - The Connection Object for this session. The connection property is only available once the `sessionConnected` event has been triggered. If the session fails to connect, this property shall remain nil.

* **connectionCount** (Integer) - The number of discrete clients connected to this session.

* **sessionId** (String) - The session ID of this instance.  See `OT.initSession()` and `connect()` ).

## Methods

[on()](#on)
[connect()](#connect)
[disconnect()](#disconnect)
[publish()](#publish)
[subscribe()](#subscribe)
[unpublish()](#unpublish)
[unsubscribe()](#unsubscribe)

### on(type:String, listener:Function)

Registers a method as an event listener for a specific event. See [Session Events](sessionEvents.md).

#### Parameters

* **type** (String) — This string identifying the type of event.

* **listener** (Function) - The function to be invoked when the Session object dispatches the event.

Example Code:
```
session.on('streamCreated', (event) => {
  subscriber = session.subscribe(event.stream);
});
```

### connect(token:String, completionHandler:Function)

Connects to an OpenTok session.
Upon connecting successfully, the Session object dispatches a `sessionConnected` event. Call the `on()` method to set up an event listener to process this event before calling other methods of the Session object.

The TB object dispatches an `exceptionEvent` if there is an error connecting to Session

#### Parameters

* **token** (String) - The session token. You generate a session token using the OpenTok Server SDKs or the [OpenTok dashboard](https://dashboard.tokbox.com/projects)

* **completionHandler** (Function) — Optional. A function to be called when the call to the `connect()` method succeeds or fails.

#### Events Dispatched

* **sessionConnected** (SessionConnectEvent) — Dispatched locally when the connection is established.

Example Code:
```
session.connect('1127', 'T1==aeoi3h3...' )
```

### disconnect()

Calling the `disconnect()` method ends your connection with the session. In the course of terminating your connection, it also ceases publishing any stream(s) you were publishing.

#### Events dispatched

* **sessionDisconnected** ([SessionDisconnectEvent](sessionEvents.md)) — Dispatched locally when the connection is disconnected.

* **streamDestroyed** ([StreamEvent](streamEvents.md)) — Dispatched if streams are lost as a result of the session disconnecting.

Example Code:
```
session.disconnect()
```

### publish(publisher:Publisher):[Publisher](publisher.md)

The `publish()` method starts publishing an audio-video stream to the session. Upon successful publishing, the Session objects on all connected web pages dispatch `streamCreated` events.

#### Parameters

* **publisher** ([Publisher](publisher.md)) - You pass a Publisher object as the one parameter of the method. You can initialize a Publisher object by calling the `OT.initPublisher()` method. Before calling `session.publish()`, you can use the Publisher object to set up and test the microphone and camera used by the Publisher.

#### Events Dispatched

* **streamCreated** ([StreamEvent](streamEvents.md)) — The stream has been published. The Session object dispatches this on all clients subscribed to the stream, as well as on the publishers client.

The TB object dispatches an exception event if the users role does not include permissions required to publish. For example, if the users role is set to subscriber, then they cannot publish. You define a users role when you create the user token in your server.

Example Code:

```
var publisher = OT.initPublisher('1127', 'publisherDiv');
session.publish(publisher);
```

### subscribe(stream:Stream, [replaceElementId:String, properties:Object]):Subscriber

Subscribes to a stream that is available to the session. As other publishers connect to the session, the Session object dispatches a streamCreated event. This event object has a streams property, which is an updated array of the Stream objects corresponding to streams connected to the session.

#### Return

**Subscriber** — The Subscriber object for this stream. Stream control functions are exposed through the Subscriber object

#### Parameters

* **stream** ([Stream](stream.md)) — Stream object representing the stream to which we are trying to subscribe.

* **replaceElementId** (String) — String ID of the existing DOM element that the Subscriber replaces. If you do not specify a replaceElementId, the application appends a new DOM element to the HTML body.

* **properties** (Object) - Optional. This is an optional object that contains the following properties:
  * **height** (Number) — The desired height, in pixels, of the displayed Subscriber video stream (default: 198)
  * **width** (Number) — The desired width, in pixels, of the displayed Subscriber video stream (default: 264)
  * **subscribeToAudio** (Boolean) — Whether to initially subscribe to audio (if available) for the stream (default: true)
  * **subscribeToVideo** (Boolean) — Whether to initially subscribe to video (if available) for the stream (default: true)

Example Code:
```
var subscriber = session.subscribe(event.stream, 'streamDiv');
```

### unpublish(publisher:Publisher)

The `unpublish()` method ceases publishing the specified publishers audio-video stream to the session.
Upon successful termination, the Session object on every connected web page dispatches a streamDestroyed event.

#### Parameters
* **publisher** ([Publisher](publisher.md)) — The Publisher object to stop streaming.

#### Events Dispatched
* **streamDestroyed** ([StreamEvent](streamEvents.md)) — The stream associated with the Publisher has been destroyed. Dispatched on the Publishers device and on device for all connections subscribing to the publishers stream.

Example Code:
```
session.unpublish(publisher);
```

### unsubscribe(subscriber:Subscriber)

Stops subscribing to a stream in the session. The display of the audio-video stream is removed

#### Parameters

* **subscriber** ([Subscriber](subscriber.md)) — The Subscriber object to unsubscribe.

Example Code:
```
session.unsubscribe(subscriber);
```

## Session Events:

      sessionConnected

		Triggered when session has successfully connected

      sessionDisconnected

		Triggered when a session has disconnected

      streamCreated

		Triggered when new stream has been created in a session

      streamDestroyed

		Triggered when stream has ended in a session

repository: amatakasap/cordova-plugin-opentok

repo_name: amatakasap/cordova-plugin-opentok


text:
---
category: Blog
tag: Android
comments: true
date: 2019-07-04 15:00:00
layout: post
image:
  twitter: /assets/images/mvvm-flow.png
  facebook: /assets/image/mvvm-flow.png
  height: 220
  width: 120
slug: android-mvvm-intro
title: Introduction to MVVM architecture in Android
description: Learn about best practices of MVVM architecture in Android. Implement a bug-free unidirectional architecture for your app.
keywords: [android mvvm architecture, immutable state, live data mvvm, android pure functions, reactive functional android, redux reducers, mvvm in kotlin]
category_tag: [Android, Kotlin, MVVM]
---

MVVM stands for **Model-View-ViewModel**. Google has started recommending usage of this architecture to develop android apps and have provided a lot of new tools and frameworks to support implementation of this architecture. `ViewModel` and `LiveData` being the basics to implement it. Google is also working towards providing support to integrate these components seamlessly with android activity and fragment lifecycles. Although the current state of these tools is not ideal, it's pretty stable and works well.

## Understanding MVVM

Here, I have added a diagram of the MVVM pattern flow and how it binds everything together.

    MVVM flow diagram

 - ViewModel interacts with the Model (API, database, etc) to get the necessary data and updating it if required.
 - ViewModel exposes data streams of the **state**. Any component can subscribe to the stream and receive updates regarding the _state_. Here, a view component (activity, fragment, viewgroup, etc) will subscribe to the exposed data streams. On every update, the view component will render itself.
 - When user takes a certain action (eg. save a note, etc), the view would ask the ViewModel to perform certain actions. The ViewModel would update the Model, create a new **state** and dispatch it to the data streams.
 - View component would receive the update and render the updated **state**.

The idea behind MVVM pattern is quite simple but the implementation is bit nuanced which we will dive into the upcoming posts.

## Advantages of MVVM

Before the introduction of MVVM, a lot of apps were developed using MVP architecture. Although MVP is okay, MVVM has significant advantages over MVP pattern. Here are some of the key advantages of MVVM over MVP.

### Coupling

View and Presenter are tightly coupled in MVP. As per the pattern, both View and Presenter have a contract (usually defined via interfaces). It's difficult to _reuse_ these contracts with other views or presenters. This problem does not arise in MVVM pattern as ViewModel exposes only data streams and it's up to the view to decide how to use this data. With this pattern, a view can easily use multiple view models and a view model can be _reused_ with multiple views.

### Unit testing

Unit testing in Android is usually quite painful. To make the MVP unit-testable, we create an interface for the View and use a mocked instance for unit tests. Since a ViewModel is not tied to any View component in MVVM, it's much easier to unit test the ViewModel without having to worry about the view. Since Google is supporting MVVM officially, they have also provided a lot of tools to perform unit tests with MVVM and LiveData so that's a plus.

### Unidirectional

There's a bi-directional data flow between View and Presenter in MVP. To set the data to the view, it usually calls `view.setUser(user)` and to update certain data, view would call `presenter.update(data)` which creates a bi-directional data flow. In MVVM, we would still require to call some method on the ViewModel when the user interacts with the View, but we can create an indirect link which does not directly interact with the ViewModel. Instead of calling `viewModel.update(data)`, we can use `viewModel.dispatch(action)` and the ViewModel or some other component inside the ViewModel handles the action and updates the state. With a _Redux like_ approach, we can make MVVM unidirectional.

### Reactive

MVP is passive so any change in model has to be manually updated by the Presenter. On the other hand, the recommended approach with MVVM is to expose data stream (eg. `LiveData`). Once the data is updated, all the subscribers of the data stream will receive the updates.

Apart from these benefits, one of the major benefit is that Google is officially supporting MVVM architecture pattern and actively providing better tools and frameworks.

## References

Here are some useful links that talk about MVVM architecture pattern.

 - [upday devs - Introduction to MVVM](https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b)
 - [ViewModel official docs](https://developer.android.com/topic/libraries/architecture/viewmodel)
 - [AndroidPub - MVVM over MVP](https://android.jlelse.eu/why-to-choose-mvvm-over-mvp-android-architecture-33c0f2de5516)


text:
## $5 Tech Unlocked 2021!
[Buy and download this Video for only $5 on PacktPub.com](https://www.packtpub.com/product/understanding-typescript-2020-edition-video/9781789951905)
-----
*The $5 campaign         runs from __December 15th 2020__ to __January 13th 2021.__*

# Understanding-TypeScript-2020-Edition
Code Repository for Understanding TypeScript – 2020 Edition, published by Packt


text:
## Contents

### US state population

We use this to normaize the number of covid cases and deaths for population:
https://www.kaggle.com/nightranger77/covid19-state-data?select=COVID19_state.csv

* COVID19_state.csv : raw dataset for population
* us_state_population.csv : population estimate per state as of July 2020, cleaned from population_usa.csv

### large_dataset_links.md

* links to the larger datasets that we use that are too big to add to github

### US_election_source_2020
* article from BBC where we got the Democrat/Republican states

### colorado_regulation_data.csv, utah_regulation_data.csv
* taken from https://kubinec.shinyapps.io/coronanet/ (Cheng et al., 2020) for state-regulation data in case studies

### state-abbrevs.csv
* small appendix dataset on state names and abbreviations https://www.kaggle.com/giodev11/usstates-dataset


text:
#Test Plan for Ensuring that Open dialog box
Steps                 | Desired Results                | Complete | Comments
----------------------|--------------------------------|----------| --------
Open Open Live Writer | | |
Click on File | | |
Click on Open Local Draft | Observe dialog box as below | |
 | Observe that Drafts folder is highlighted and any draft posts are available to open | |
 |  |  |
Click on the number next to Show: | Ensure that Show changes the number of posts to be selected | |
Select a draft post | | |
Click on Delete | Ensure that the post is properly deleted | |
                | Verify in %localappdata%\openlivewriter  | |
  |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on Open Local Draft | Observe dialog box as below | |
Enter a term in Filter and hit enter | Observe that appropriate posts are loaded | |
 |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on Open Local Draft | Observe dialog box as below | |
Click on one of the draft posts | Observe that correct post is loaded
 |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on Open Recently Posted | Observe dialog box as below | |
 | Observe that Recently Posted is highlighted and that recent posts are available to open | |
 | | |
Click on the number next to Show: | Ensure that Show changes the number of posts to be selected | |
Select a Recently Posted post | | |
Click on Delete | Ensure that the post is properly deleted | |
                | Verify in %localappdata%\openlivewriter | |
                | Verify with online blog
  |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on Open Recently Posted | Observe dialog box as below | |
Click on Open Recently Posted | Enter a term in Filter and hit enter | Observe that appropriate posts are loaded | |
 |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on Open Recently Posted | Observe dialog box as below | |
Click on one of the Recently Posted posts | Observe that correct post is loaded | |
 |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on any available blog | Observe dialog box as below | |
 | Observe that a list of published posts are available to open | |
 |  |  |
Click on the number next to Show: | Ensure that Show changes the number of posts to be selected | |
Select a published post | | |
Click on Delete | Ensure that the post is properly deleted | |
                | Verify in %localappdata%\openlivewriter |  |
   |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on any available blog
Enter a term in Filter and hit enter | Observe that appropriate posts are loaded | |
 |  |  |
Open Open Live Writer | | |
Click on File | | |
Click on any available blog | Observe dialog box as below | |
Click on one of the posts | Observe that correct post is loaded | |
 |  |  |

 ![Open diaglog box ](images/openDialogbox.png)

repository: DotNetContrib/OpenLiveWriter

gha_license_id: NOASSERTION

repo_name: DotNetContrib/OpenLiveWriter


text:
# pdf2xml
A php command for convert pdf file structure in a xml file (and inversely)

pdf2xml options command are:

      -i         => input file  (pdf or xml) (REQUIRED)
      -o         => output file (xml or pdf) (optionnal)
      --json     => output log in json format
      --validate => to validate a xml file before to converse it in pdf file
      -h, --help => print this help

A xsd file is included to check xml input.

Exemple:

	To converse a pdf in a xml file
		./pdf2xml -i=/path/to/file.pdf
		=> the file output is /path/to/file.xml

		You can precise a file for the xml output:
		./pdf2xml -i=/path/to/file.pdf -o=/path/to/another_file.xml

	the reverse way:
		./pdf2xml -i=/path/to/file.xml
		=> the file output is /path/to/file.pdf

		You can precise a file for the pdf output:
		./pdf2xml -i=/path/to/file.xml -o=/path/to/another_file.pdf

	To converse a xml file in a pdf file, you must validate it with this command
		for a shell output:
			./pdf2xml -i=/path/to/file.xml --validate

		for a json output
			./pdf2xml -i=/path/to/file.xml --validate --json

	You can include this lib:
		include 'phar://pdf2xml.phar/pdf2xml_lib.php';


text:
# BarnBridge Rewards Pool

This is an implementation of a single-token rewards pool with a continuous distribution mechanism.

## Running tests
**Note:** The result of tests is readily available [here](./test-results.md).

### 1. Clone this repo
```shell
git clone git@github.com:BarnBridge/BarnBridge-YieldFarmContinuous.git
```

### 2. Install dependencies
```shell
npm install
```

### 3. Run tests
```shell
npm test

# or if you want to run with coverage
npm run coverage
```

## Deployed contracts
### Mainnet
```shell
PoolFactory deployed at: 0x2e93403C675Ccb9C564edf2dC6001233d0650582
SY cUSDC pool deployed at: 0x68af34129755091e22f91899ceac48657e5a5062
```

# Smart Contract Architecture
![junior pool yf sc architecture](https://gblobscdn.gitbook.com/assets%2F-MIu3rMElIO-jG68zdaV%2F-MXHutr14sDo0hYi6gg3%2F-MXHwLedyIac7BAL_YJO%2Fjunior%20tokens.png?alt=media&token=607fe998-db46-47e1-8c24-397630103da2)


text:
---
title: Support for Istio 1.1 ends on September 19th, 2019
subtitle: Support Announcement
description: Upcoming Istio 1.1 end of life announcement.
publishdate: 2019-08-15
aliases:
    - /blog/2019/announcing-1.1-eol
    - /news/2019/announcing-1.1-eol
---

According to Istio's [support policy](/docs/releases/supported-releases#supported-releases/), LTS releases like 1.1 are supported for three months after the next LTS release.   Since [1.2 was released on June 18th](/news/releases/1.2.x/announcing-1.2/), support for 1.1 will end on September 19th, 2019.

At that point we will stop back-porting fixes for security issues and critical bugs to 1.1, so we encourage you to upgrade to the latest version of Istio ({{<istio_release_name>}}).  If you don't do this you may put yourself in the position of having to do a major upgrade on a short timeframe to pick up a critical fix.

We care about you and your clusters, so please be kind to yourself and upgrade.


text:
---
hrs_structure:
  division: '1'
  volume: '6'
  title: '19'
  chapter: '321'
  section: 321-236
type: hrs_section
tags:
  - Government
menu:
  hrs:
    identifier: HRS_0321-0236
    parent: HRS0321
    name: 321-236 Emergency medical services; use of latex gloves prohibited
weight: 7805
title: Emergency medical services; use of latex gloves prohibited
full_title: 321-236 Emergency medical services; use of latex gloves prohibited
---
**[§321-236]  Emergency medical services; use of latex gloves prohibited.** _[Section effective January 1, 2017.]_ The use of latex gloves by personnel providing ambulance services or emergency medical services pursuant to this part shall be prohibited. [L 2016, c 180, §3]

Cross References

Dental health facilities; health care facilities; use of latex gloves, see §321-11.9.

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# Last.fm Backup

Backup Last fm data - scrobbles, loved/banned tracks, etc.

Modified the [original script](https://gitorious.org/fmthings/lasttolibre/blobs/master/lastexport.py) from the [lasttolibre](https://gitorious.org/fmthings/lasttolibre) project to suit my usecase.

## Todo

* Incremental Backups: Only backup *new* data. Use timestamps to figure out upto what moment we already have stuff and then stop.

* Only backs up scrobbles currently, but has support for other stuff too. Need to test it out.

* Data is currently saved as TSV. I think a SQL DB would be better coz I'd be able to run queries.

license: Unlicense

repository: newhierarchy/Python-Scripts

path: /Last.fm Backup/Readme.md

repo_name: newhierarchy/Python-Scripts


text:
---
title: "Public ASN Peering"
---

### NYC Mesh operates **AS395853**

### Our peering Policy is **Yes**

Please [contact<EMAIL_ADDRESS>to peer with our network.

Note this this is our Public ASN, not the Mesh Network itself.
This community-run public network supplies NYC Mesh with net-neutral internet connectivity to support the community. If you would like to join the Mesh Network, please visit our [Join Page](/join) make use of this network.

**Peering Policy**

*   NYC Mesh has an open peering policy.
*   We have no requirements in terms of traffic, size, support/SLA, etc.
*   We operate both IPv4 and IPv6. Peering via both protocols is appreciated.

**Locations**

| Building | Address                    | Ports    |
| -------- | -------------------------- | -------- |
| Sabey    | 375 Pearl St, New York, NY | 1G / 10G |

**Exchanges**

| Exchange  | City         | IPv4           | IPv6                  | ASNs | Routes | Speed |
| --------- | ------------ | -------------- | --------------------- | ---- | ------ | ----- |
| DE-CIX NY | New York, NY | <IP_ADDRESS> | 2001:504:36::c2ab:0:1 | 105  | ~122K  | 1G    |

**Peering Data**

ASN: 395853
IRR AS-SET: AS-NYCMESH
Peering Contact<EMAIL_ADDRESS>
Recommended Max Prefix IPv4: 10
Recommended Max Prefix IPv6: 10
PeerDB Page: [https://as395853.peeringdb.com](https://as395853.peeringdb.com)
As we are a non-profit, please consider providing as many routes as possible, including upstream or other routes.

**Peers**

We have direct peering sessions with the following networks
Thank you to those who have peered!

| ASN     | Organization                             | Exchange  |
| ------- | ---------------------------------------- | --------- |
| AS42    | WoodyNet / Packet Clearing House         | DE-CIX NY |
| AS714   | Apple Inc.                               | DE-CIX NY |
| AS3856  | Packet Clearing House                    | DE-CIX NY |
| AS6939  | Hurricane Electric, Inc.                 | DE-CIX NY |
| AS9009  | M247 Ltd                                 | DE-CIX NY |
| AS15169 | Google LLC                               | DE-CIX NY |
| AS20940 | Akamai International B.V.                | DE-CIX NY |
| AS27257 | Webair Internet Development Company Inc. | DE-CIX NY |
| AS29838 | Atlantic Metro Communications, LLC       | DE-CIX NY |
| AS32217 | GPIEX INC                                | DE-CIX NY |
| AS33891 | Core-Backbone GmbH                       | DE-CIX NY |
| AS46450 | Pilot Fiber, Inc.                        | DE-CIX NY |
| AS53988 | Digi Desert LLC                          | DE-CIX NY |
| AS54825 | Packet Host, Inc.                        | DE-CIX NY |

repository: nycmeshnet/docs

repo_name: nycmeshnet/docs


text:
# Learning Type-Aware Embeddings for Fashion Compatibility

fashion-compatibility contains a [PyTorch](http://pytorch.org/) implementation for our [paper](https://arxiv.org/pdf/1803.09196.pdf).  If you find this code or our dataset useful in your research, please consider citing:

    @inproceedings{VasilevaECCV18FasionCompatibility,
    Author = {Mariya I. Vasileva and Bryan A. Plummer and Krishna Dusad and Shreya Rajpal and Ranjitha Kumar and David Forsyth},
    Title = {Learning Type-Aware Embeddings for Fashion Compatibility},
    booktitle = {ECCV},
    Year = {2018}
    }

This code was tested on an Ubuntu 16.04 system using Pytorch version 0.1.12.  It is based on the [official implementation](https://github.com/andreasveit/conditional-similarity-networks) of the [Conditional Similarity Networks paper](https://arxiv.org/abs/1603.07810).

## Usage
You can download the Polyvore Outfits dataset including the splits and questions for the compatibility and fill-in-the-blank tasks from [here](). After unpacking the dataset make any necessary updates to the data root directory in polyvore_outfits.py.

Afterwards, you can train the model using `python main.py`.  You can see a listing and description of many tuneable parameters with:

```sh
    python main.py --help
```

For example, to learn masks used for the projections for each type specific embeddings, rather than the default which creates fixed masks, you would use:

```sh
    python main.py --name {your experiment name} --learned
```

By default the code outputs the results on the test set after training. However, if you wanted to re-run the test for many settings you have to use the same flags during testing as you had during training.  For example, if you trained with the `--use_fc` to train fully connected type-specific embeddings rather than a mask, at test time you would use:

```sh
   python main.py --test --use_fc --resume runs/{your experiment name}/model_best.pth.tar
```

repository: MatteoTomassetti/fashion-compatibility

repo_name: MatteoTomassetti/fashion-compatibility


text:
URI for Pony
============

[URI is the most important element of the Web architecture][1]. In addition to parsing and validating, this library offers relative reference resolution.

Here's an example of parsing an URI into five main components:

```pony
let uri = Uri("foo://example.com:8042/over/there?name=ferret#nose")

uri.scheme()    // foo
uri.authority() // Authority with host: example.com, port: 8042
uri.path()      // /over/there
uri.query()     // name=ferret
uri.fragment()  // nose
```

Relative reference is parsed using `RelativeRef` class:

```pony
let rel_ref = RelativeRef("/over/here?name=otter")

rel_ref.path()  // /over/here
rel_ref.query() // name=otter
```

It can then be resolved into a URI

```pony
let uri = Uri("foo://example.com:8042/over/there?name=ferret#nose")
let rel_ref = RelativeRef("../right/here?name=otter")

rel_ref.in_context_of(uri) // Uri("foo://example.com:8042/right/here?name=otter")
```

`Uri` implements the same contract and can be resolved in context of other `Uri`, although the result is always a copy of a reference:

```pony
let uri = Uri("http://example.com")
let base_uri = Uri("ftp://example.org/foo")

uri.in_context_of(base_uri) // Uri("http://example.com")
```

[1]: http://www.ics.uci.edu/~fielding/pubs/dissertation/evaluation.htm#sec_6_2

repository: jonas-l/pony-uri

repo_name: jonas-l/pony-uri


text:
---
layout: default
---

# 1993-12-24 - Re: Happy Holidays

## Header Data

From<EMAIL_ADDRESS>(John E. Kreznar)

To<EMAIL_ADDRESS>Message Hash: d50d1bd94127ba1718a020657686b6ce0b52aa726e15c6b2f2facddfb07cb97f

Message ID: \<9312240958.AA18167@ininx\>

Reply To: _N/A_

UTC Datetime: 1993-12-24 10:01:11 UTC

Raw Date: Fri, 24 Dec 93 02:01:11 PST

## Raw message

```
{% raw  %}From<EMAIL_ADDRESS>(John E. Kreznar)
Date: Fri, 24 Dec 93 02:01:11 PST
To<EMAIL_ADDRESS>Subject: Re: Happy Holidays
Message-ID: <9312240958.AA18167@ininx>
MIME-Version: 1.0
Content-Type: text/plain

-----BEGIN PGP SIGNED MESSAGE-----

Especially in this season of good will, the idea that ``taxation'' and
``civility'' are somehow compatible cannot go unchallenged.  Above all,
``civility'' must mean that relations among people be by mutual consent,
or not at all.  Government is the institutionalization of exactly the
reverse: the imposition by the politically victorious upon all others,
the forceful supplanting of personal choice by collective dictate.  It's
the institutionalization of enmity.

Democratic political government, aka tyranny of the majority, will soon
succeed in inducing a new dark age on Earth, one that may never end.  An
individual who yearns to be free must overcome his mortality and leave
the Earth.  This will soon be practical.  Meanwhile, strong cryptography
and the cypherpunk agenda may provide a temporary defense.

	John E. Kreznar		| Relations among people to be by
<EMAIL_ADDRESS>| mutual consent, or not at all.

-----BEGIN PGP SIGNATURE-----
Version: 2.3a

iQCVAgUBLRq8rcDhz44ugybJAQEJIgQAq2FO6b9GvgSmpcP1H5qIP8rkDMH5FEu9
6FNxMt+jLofPFMz7NtbgqcXg45KlZXBzdPgiCQKLWKTjcG1e2KF+4wB34gIIPDTF
fMOFVDh3f3cNTojBVcFUvMpdC3p+Z/qTy90jgEoVoqWj8NpbBVqqbMegpiNlGePg
glsqEaKMh6A=
=/W55
-----END PGP SIGNATURE-----

{% endraw %}
```

## Thread

+ Return to [December 1993](/archive/1993/12)

+ Return to<EMAIL_ADDRESS>(John E. Kreznar)](/authors/jkreznar_at_ininx_com_john_e_kreznar_)"

+ 1993-12-24 (Fri, 24 Dec 93 02:01:11 PST) - Re: Happy Holidays -<EMAIL_ADDRESS>(John E. Kreznar)_


text:
This repository is dedicated to the Movie recommendation system which designed and developed by Python3 and the data which used in this project is based on the provided dataset by Kaggle, You could find the required dataset at https://www.kaggle.com/rounakbanik/the-movies-dataset .

The first thing for this project is knowing the dataset that we need, among all csv files which provided by Kaggle all we need is credits.csv, keywords.csv, links.csv, links_small.csv, movies_metadata.csv, ratings_small.csv

This code uses demographic filtering and content filtering to recommend movies on the web page. Flask API is used to deploy model on website.

Here is the list of dependecies which used in this project and how you could them:

pip install numpy
pip install pandas
pip install matplotlib
pip install scipy
pip install ast # this dependecy is already covered by python3
pip install sklearn
pip install nltk
pip install flask
pip install warnings # this dependecy is already covered by python3

Onece the dependencies are installed properly you could run the webapp file with this command python3 webapp.py.

![Screenshot_2020-03-03 Recommender System(1)](https://user-images.githubusercontent.com/23243761/75825450-aeb05480-5da5-11ea-885a-31876a9b220e.png)

This recommendation system is working based on three categories which are based on popularity,genere and content

![Screenshot_2020-03-03 Recommender System](https://user-images.githubusercontent.com/23243761/75824500-e61e0180-5da3-11ea-86fa-e1044a212524.png)


text:
# React Portfolio

![React Portfolio Ahrum Noh](https://github.com/ahrumnoh/reactPortfolio/blob/main/image/REACT%20Portfolio.jpg?raw=true)

  ## Overview
  * Let's make a portfolio vis REACT😋

  <p> In this unit, you will learn how to create a single-page application (SPA) using React. React is a powerful and elegant technology, as well as a very in-demand skill to have as a web developer. As you create your SPA, you will learn how to use React components, manage application state, and pass data throughout your app. You'll get a sense for how React works under the hood and the problems it solves in modern web development. By the end of this unit, you will be one step closer to being employer-ready.</p>

 ## 👨🦯Website link ##

   * Deployed Live Github URL: https://ahrumnoh.github.io/reactPortfolio/
  ## Screenshot
  ![Mainpage](https://github.com/ahrumnoh/reactPortfolio/blob/main/image/Screenshot%20(117).png?raw=true)
  ![Mainpage 2](https://github.com/ahrumnoh/reactPortfolio/blob/main/image/Screenshot.png?raw=true)

  ## 🚩License

*   MIT License

* Copyright (c) 2021 ahrumnoh

* Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

* The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

 IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

repository: ahrumnoh/reactPortfolio

repo_name: ahrumnoh/reactPortfolio


text:
# Leaderboard

Leaderboard for the InfoSec CTF. This box contains

- CTFd Leaderboard

## How To

### Setup

You will need to create a ubuntu1604 box file for Vagrant and name it `ctf-ubuntu1604`. Alternatively, use one from [vagrant](https://app.vagrantup.com/boxes/search).

Install plugin requirements and initialize the machine.

```
vagrant plugin install vagrant-proxyconf
vagrant up
```

### Configuration

CTFd will need to be modified by the end user to support use cases such as HTTPS.

CTFd needs to be manually configured for the following

- Admin account
- "Forgot Password" URL
- Title page
- Challenges

repository: intel/ctf-infrastructure

repo_name: intel/ctf-infrastructure


text:
---
layout: post
title: "C++ Dangling else"
excerpt: ""
categories: cpp
tags: [C++]
comments: true
share: true
author: chungyu
---

> * [Dangling else](https://en.wikipedia.org/wiki/Dangling_else)

# Happen when you write: (move-zeroes)[https://leetcode.com/problems/move-zeroes/#/description]

### Fail
```cpp
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int firstZero = -1;

        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] == 0)
                if (firstZero < 0) firstZero = i;
            else
                if (firstZero >= 0) std::swap(nums[i], nums[firstZero++]);
        }
    }
};
```

### Still fail

```cpp
class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int firstZero = -1;

        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] == 0)
                if (firstZero < 0)
                    firstZero = i;
            else
                if (firstZero >= 0)
                    std::swap(nums[i], nums[firstZero++]);
        }
    }
};
```

# [Dr.Dobb's](http://www.drdobbs.com/cpp/dangling-else-yet-again/231602010)

```cpp
if (a)
if (b)
   s;
else
   t;
```
* should it be parsed as:

```cpp
if (a) {
  if (b)
    s;
  else
    t;
}
```
* or

```cpp
if (a) {
  if (b)
    s;
}
else
  t;
```

> * The usual (decades-old) solution for the compiler is to associate the else with the innermost if, and the ambiguity is resolved.

* But what if programmar write

```cpp
if (a)
  if (b)
    s;
else
  t;
```

* ==> it will still parse so that else is actually associated with the inner one, that's where your program has problem


text:
[@redhat-cloud-services/vulnerabilities-client](../README.md) / [Exports](../modules.md) / Links

# Interface: Links

**`Export`**

**`Interface`**

Links

## Table of contents

### Properties

- [first](Links.md#first)
- [last](Links.md#last)
- [next](Links.md#next)
- [previous](Links.md#previous)

## Properties

### first

• **first**: `string`

Link to first page.

**`Memberof`**

Links

#### Defined in

[api.ts:1205](https://github.com/RedHatInsights/javascript-clients/blob/master/packages/vulnerabilities/api.ts#L1205)

___

### last

• **last**: `string`

Link to last page.

**`Memberof`**

Links

#### Defined in

[api.ts:1211](https://github.com/RedHatInsights/javascript-clients/blob/master/packages/vulnerabilities/api.ts#L1211)

___

### next

• **next**: `string`

Link to next page.

**`Memberof`**

Links

#### Defined in

[api.ts:1217](https://github.com/RedHatInsights/javascript-clients/blob/master/packages/vulnerabilities/api.ts#L1217)

___

### previous

• **previous**: `string`

Link to next page.

**`Memberof`**

Links

#### Defined in

[api.ts:1223](https://github.com/RedHatInsights/javascript-clients/blob/master/packages/vulnerabilities/api.ts#L1223)

repository: RedHatInsights/javascript-clients

gha_language: TypeScript

repo_name: RedHatInsights/javascript-clients


text:
# Deploying your app

<walkthrough-tutorial-duration duration="20"></walkthrough-tutorial-duration>

## Testing a production package
This allows to test a production build from Maven, without building a real package.
To use JHipster in “production” mode, use the pre-configured prod profile. With Maven, please run:

```bash
./mvnw -Pprod
```

This profile will compile, test and package your application with all productions settings.
If you want more information on the available profiles, please go the section titled [Development and Production profiles](https://www.jhipster.tech/profiles/).

Next we will deploy our application using Docker, however if you want to build and execute WAR file, you can check it out on [JHipster website](https://www.jhipster.tech/production/).

## Deploying with docker
JHipster provides a complete Docker support, in order to:
* Facilitate development, as you can start a full infrastructure very easily, even when using a complex microservice architecture
* Deploy directly in production if you use Docker Swarm, as it uses the same Docker Compose configuration

One great feature of using Docker Compose is that you can easily scale your containers, using the docker-compose scale command. This is very interesting if you use JHipster with a microservice architecture.

When generating your application, JHipster generates for you:

* A Dockerfile for building a Docker image and running your application inside a container
* Several Docker Compose configurations to help you run your application with third-party services, for example a database

Those files are located in the folder src/main/docker/.

### Prerequisites
You have to install :
* Docker
* Docker Compose
Luckily, you do not need to install it with Google Cloud Shell.

### Build and running a Docker image of your application
To create a Docker image of your application, and push it into your Docker registry:
```bash
./mvnw package -Pprod verify jib:dockerBuild
```
This process takes some time to complete (about 15 minutes with the boost mode on).

To run this image, use the Docker Compose configuration located in the src/main/docker folder of your application:
```bash
docker-compose -f src/main/docker/app.yml up
```

<walkthrough-conclusion-trophy></walkthrough-conclusion-trophy>

Congratulations! Your application is now deployed with Docker !
You can check out your application with the Google Cloud Shell web preview feature.

repository: jhipster/jhipster-guides

gha_language: Shell

repo_name: jhipster/jhipster-guides


text:
---
title: 'The Good News About God, Our Judge'
date: 22/04/2023
---

### Read for This Week’s Study
Psalm 51:1–4; Revelation 20:12; Daniel 7:9, 10, 13; Revelation 4:2–4.

>
Memory Text

> “The angel said in a loud voice, ‘Fear [respect] God and give him praise. The time has come for God to judge all people. Worship God. He made the heavens, the earth, the sea, and the springs [places where the water comes out of the earth] of water’ ” (Revelation 14:7, ERV).

The Bible teaches us that God is our Judge. Not only that, but also God is “ ‘the Judge of the whole earth’ ” (Genesis 18:25, NIrV; also read Psalm 58:11; Psalm 94:2; Psalm 98:9). Sooner or later, God will judge everyone, both the dead and the living. As Paul wrote, “So each of us will have to [must] explain to God about the things we do” (Romans 14:12, ERV).

Scary thought, right? Every person who ever lived will answer to God for everything he or she did. God knows everything. “God will judge everything people do. That includes everything they try to hide. He’ll judge everything, whether [to decide if] it’s good or evil” (Ecclesiastes 12:14, NIrV).

In the end, God’s work as Judge will show His love and mercy to everyone in heaven and on earth. We will see that God is both fair and full of mercy when He judges the saved and the lost.

This week, we will study about God’s work as Judge in the end times. We also will look at what happens to God’s loyal people during “the time when God will judge everyone” (Acts 24:25, NIrV).

repository: Adventech/sabbath-school-lessons

branch_name: refs/heads/stage

repo_name: Adventech/sabbath-school-lessons


text:
# Introduction

There are various idiomatic approaches to solve Grains.
You can use [bit shifting][bit-shifting] to calculate the number on grains on a square.
Or you can use [exponentiation][exponentiation].
Another approach is to use [`pow`][pow].

## General guidance

The key to solving Grains is to focus on each square having double the amount of grains as the square before it.
This means that the amount of grains grows exponentially.
The first square has one grain, which is `2` to the power of `0`.
The second square has two grains, which is `2` to the power of `1`.
The third square has four grains, which is `2` to the power of `2`.
You can see that the exponent, or power, that `2` is raised by is always one less than the square number.

| Square | Power | Value                   |
| ------ | ----- | ----------------------- |
| 1      | 0     | 2 to the power of 0 = 1 |
| 2      | 1     | 2 to the power of 1 = 2 |
| 3      | 2     | 2 to the power of 2 = 4 |
| 4      | 3     | 2 to the power of 3 = 8 |

## Approach: Bit-shifting

```python
def square(number):
    if number < 1 or number > 64:
        raise ValueError('square must be between 1 and 64')

    return 1 << number - 1

def total():
    return (1 << 64) - 1

```

For more information, check the [bit-shifting approach][approach-bit-shifting].

## Approach: Exponentiation

```python
def square(number):
    if number < 1 or number > 64:
        raise ValueError('square must be between 1 and 64')

    return 2 ** (number - 1)

def total():
    return 2 ** 64 - 1

```

For more information, check the [exponentiation approach][approach-exponentiation].

## Approach: `pow`

```python
def square(number):
    if number < 1 or number > 64:
        raise ValueError('square must be between 1 and 64')

    return pow(2, number - 1)

def total():
    return pow(2, 64) - 1

```

For more information, check the [`pow` approach][approach-pow].

## Which approach to use?

- Bit shifting is the fastest for `square`.
- Bit shifting and exponentiation are about the same for `total`.
- Exponentiation and `pow` are about the same for `square`.
- `pow` is significantly the slowest for `total`.

For more information, check the [Performance article][article-performance].

[bit-shifting]: https://realpython.com/python-bitwise-operators/
[exponentiation]: https://www.codingem.com/python-exponent-maths/
[pow]: https://docs.python.org/3/library/functions.html#pow
[approach-bit-shifting]: https://exercism.org/tracks/python/exercises/grains/approaches/bit-shifting
[approach-exponentiation]: https://exercism.org/tracks/python/exercises/grains/approaches/exponentiation
[approach-pow]: https://exercism.org/tracks/python/exercises/grains/approaches/pow
[article-performance]: https://exercism.org/tracks/python/exercises/grains/articles/performance

repository: exercism/python

gha_language: Python

repo_name: exercism/python


text:
# OClass - getName()

This method returns the logical name of the class.

## Retrieving Class Names

Internally, OrientDB manages clsases as [`OClass`](../OClass.md) instance.  But, each database class has a logical name that gets used in [OrientDB SQL](../../../sql) queries.  Using this method, you can retrieve the logical name as string.

### Syntax

```
String OClass().getName()
```

#### Return Type

This method returns a [`String`]({{ javase }}/java/lang/String.html) instance, which provides the logical name of the [`OClass`](../OClass.md).

repository: orientechnologies/orientdb-docs

gha_language: CSS

repo_name: orientechnologies/orientdb-docs


text:
# TeaVendorTally
A program for tallying points from a google forms vote, specificallly designed for the /r/tea subreddit.

## Setup (now outdated)
### Google Form Settings
1. Take the existing vendor list and add the vendor names as options in a multiple choice grid. The choices available should be "1st", "2nd", "3rd", "Runner-up 1" and "Runner-up 2".
2. Check shuffle row order, allow only one answer per person and check limit to one option per column.
3. After the poll closes simply go to the response spreadsheet and download it as a .csv file.

### Processing results with Tea Vendor Tally tool
1. Compile the .exe and move it into a folder you want to use for the tea tally tool.
2. Place the Google Form result csv file in the same folder as the executable or copy the file location.
3. Take the same vendor list used to create the vendor form and copy the table (with markup) into a file named "quotes.csv". Save this with the tally tool executable or copy the file location.
4. Launch a command prompt window with the dirctory in the file location of the executable. if all files are in the same place simply run the program by typing the executable name followed by the result file name. If the files are not all in the same folder simply execute the program with the following flags: -r followed by the result files file location and -q followed by the quote files file location.
5. If the program prints out any mapping errors fix the names in the quote file or manually fix the row in the outputted table.txt file.
6. Copy and paste all the content within the table.txt into the reddit wiki page

repository: Brogie/TeaVendorTally

repo_name: Brogie/TeaVendorTally


text:
# Problem

You must write a program for a robot that navigates a closed maze in search for letters that were printed on the
floor of the maze. The solution consists of the list of all letters, ordered alphabetically. The letters are
capitals (A-Z) and the same letter may exist in multiple locations.

Example

The solution for the following maze is AABQ:

\#############
\#   A                #   #
\# ## ## # #      #
\# Q# #   B           #
\#  #A# #      ####
\#############

\# symbols indicate walls, which are illegal positions. Your robot can navigate on all other cells vertically or
horizontally but not diagonally. You can see the 4 neighbors cells (up, down, left, right) around your current cell.

The initial position of the robot can be any non-wall cell (empty or letter), inside the maze.

Navigation API

Your program will read cell information from stdin, then write a command on stdout, and loop.

Cell information is given as one line of 5 characters indicating the type of the current cell and the type of each
of the neighbor cells in the following order: current, up, down, left, right. In the example, if the current position
is the position of the letter Q, cell information will be given as:

Q#  #

A command is either one of the 4 navigation commands indicating which neighbor cell to move to
(U: up, D: down, L: left, R: right) or the key for escaping the maze starting with the K prefix, e.g. KAABQ which
terminates the game. Commands are terminated by a newline character (LF).

An attempt to move into a wall or giving a wrong key terminates the life of the poor robot.

Here is a very simple maze:

\####
\#AB#
\####

A successful session for this maze, assuming a start position on cell marked with A is:

 input: A###B
output: R
 input: B##A#
output: KAB

# Installation

1. Install Java
https://www.digitalocean.com/community/tutorials/how-to-install-java-on-ubuntu-with-apt-get
2. Install Scala and sbt

on Ubuntu

\#!/bin/sh
\# one way (older scala version will be installed)
\# sudo apt-get install scala
\#2nd way
sudo apt-get remove scala-library scala
wget http://www.scala-lang.org/files/archive/scala-2.11.4.deb
sudo dpkg -i scala-2.11.4.deb
sudo apt-get update
sudo apt-get install scala
\# sbt installation
\# remove sbt:>  sudo apt-get purge sbt.
wget http://dl.bintray.com/sbt/debian/sbt-0.13.6.deb
sudo dpkg -i sbt-0.13.6.deb
sudo apt-get update
sudo apt-get install sbt

3. Build the project

Go to the project directory in the console and issue the command sbt assembly

# To run the program

1. Run by using jar file

1.1 create the jar with sbt assembly - sbt assembly in sbt console
2. Run the jar file by:

java -jar target/scala-2.13/solution.jar  -Dlog4j.configuration=file:src/main/resources/log4j.properties

2.1 Run in the console

Move to the project in the console.  And issue command

>sbt console

Once in the console, you should see:

[info]
import zio._
import java.io.IOException
import zio.console.{getStrLn, putStrLn}
import com.playground.strategy.Common._
import com.playground.strategy.Default._
import com.playground.strategy.Common.{Env, isCapitalLetter}

[info] welcome to sbt 1.3.12 (Oracle Corporation Java 13.0.2)
[info] loading global plugins from /Users/watt/.sbt/1.0/plugins
[info] set current project to data (in build file:/Users/watt/Desktop/PlaygroundZ/data/)
[info] Non-compiled module 'compiler-bridge_2.12' for Scala 2.12.10. Compiling...
[info]   Compilation completed in 4.824s.
[info] Starting scala interpreter...
Welcome to Scala 2.12.10 (OpenJDK 64-Bit Server VM, Java 13.0.2).
Type in expressions for evaluation. Or try :help.

scala>

In the console, issue the following commands:
scala> import com.playground.solution.Main._
scala> main(Array(""))

# For ruby script to test the agent

1. go to the directory where the script is in the shell (which is in data folder).

2. issue the command in the shell ./simulate.rb \<path-to\>/solution.jar \<path-to\>/grids.data.
(which is ./simulate.rb ../target/scala-2.13/solution.jar grids.data)

You should see:

We start the game at:

y is : 69
x is : 52
.....

current position is: #<struct Point x=46, y=106>
output: The agent seems to have completed the grid. Please start again with a new session. The result is KEEEEEEEEHHIIIIJJMMMMMMNNNNNNNNNNNNNNNNOOPPPPPPPPPPPPQQQQQQQQQQQQQQUUUUUUUUWWXXXXXX
next position is: #<struct Point x=46, y=106>
iteration is: 20303

repository: wpoosanguansit/PlaygroundZ

repo_name: wpoosanguansit/PlaygroundZ


text:
# Stenocybe septata (Leight.) A. Massal. SPECIES

#### Status
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Atti Inst. Veneto Sci. lett. , ed Arti, Sér. 3 5: 267 (1860)

#### Original name
Sphinctrina septata Leight.

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone


text:
# Contributors

After reading README.MD to make sure you understand the website, if you have some suggestions or security fortification for the website, we would love to take a look at it.

Please clone the development branch to your own repository, make the changes, and then open a pull request to our 'development' branch.
(Contributions to the production 'master' branch will be denied without further question or appeal, and be asked to resubmit to the 'development' branch.)

We will, at our earliest convenience, review the pull request and if found (to be safe and) beneficial, we will include it in development and move it to production in due time.

You will also be given a shoutout in the README for the site.

## In Closing

Thanks for checking everything out and we hope your contributions will be of use to many others as well.

repository: PEAKStudentCouncil/website-prod

repo_name: PEAKStudentCouncil/website-prod


text:
BlobFamily
==========

A family of physically-based blobs. Soft body simulation using a Verlet-based mass-spring system, modeling point mass as particles with semi-rigid constraints, and rendered using metaballs.

Instruction
-----------

Basic
- 'up/down/left/right': move blob, doing so will disable blob ai
- 'mouse': drag blob around, right-click on the screen and the blob will move towards it
- 'q': enable blob ai (the blob will lazily roll around)
- 'space': reset

Debug
- 'd': display debug info
- 'f': toggle fps info
- 'g': toggle gravity
- 'l': lock particle in place
- 'm': toggle rendering mode (metaballs or mass-spring)
- 'a': decrease metaball size
- 's': increase metaball size
- 'z': decrease metaball render threshold
- 'x': increase metaball render threshold

Create blob
- '1': create a small simple blob
- '2': create a big simple blob
- '3': create a small braced blob
- '4': create a big braced blob
- '5': create a small complex blob
- '6': create a big complex blob
- '7': create a BIG simple blob, disables metaballs to improve performance
- '8': create a BIG braced blob, disables metaballs to improve performance
- '9': create a BIG skinned blob, disables metaballs to improve performance
- '0': create a BIG complex blob, disables metaballs to improve performance

repository: lazykumasensei/blob-family

repo_name: lazykumasensei/blob-family


text:
# Russula luteirosa (Bougher) T. Lebel, 2007 SPECIES

#### Status
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Lebel & Tonkin, Aust. Syst. Bot. 20(4): 378 (2007)

#### Original name
Macowanites luteiroseus Bougher, 1997

### Remarks
null

path: /life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Russulaceae/Macowanites/Macowanites luteiroseus/ Syn. Russula luteirosa/README.md


text:
# check-Asimov-NIBs

Pre-requisites:
- python 3.8.5
- pip install requests
- create 2 subfolders: `NIBs` & `NIBZIPs`
- download `site_index.txt` from [here](https://mirrors.apple2.org.za/ftp.apple.asimov.net/)

Limitations:
- zipped .nibs are skipped (but copied to `NIBZIPs`)
- there are a few false-positive matches for .nibs (eg. MoonPatrol.nib.asm, threshold.nib.readme), which are harmless

repository: tomcw/check-Asimov-NIBs

repo_name: tomcw/check-Asimov-NIBs