text:
# Welcome to Adhearsion Testing!

## Start Your Engines
Begin by setting up the telephony engines that will be tested. The included .env files for foreman are set up with the assumption that Telephony Dev Box will be used.

## Start Adhearsion
Start up Adhearsion for the telephony engine that is to be tested.

```
#Start up with FreeSwitch Rayo
foreman start --env freeswitch-rayo.env

#Start up with FreeSwitch EventSocket
foreman start --env freeswitch-eventsocket.env

#Start up with Asterisk
foreman start --env asterisk.env
```

# Set up SIPP

In order to run the tests located in sipp/ sipp should be built from source or the TDB loadtesting VM should be started up.  The basic steps for installing SIPP are as below:

```
wget <SIPPDOWNLoADLINK>
sudo apt-get install libpcap-dev
./configure --with-pcap
make
sudo cp sipp /usr/local/bin/
```

## Run through the desired SIPP profiles
SIPP profiles for various tests are included in sipp/ to begin testing quickly. Sample run commands for the included tests can be found in MANUAL_TEST_COMMANDS

## Side Notes ##
```canreinvite = no``` should be set in asterisk to allow for the listener scenario to work properly

If not running the sipp tests from the VM under test, make certain to update the two .csv files and the sipp comands in MANUAL_TEST_COMMANDS appropriately for your environment

repository: vindir/adhearsion-versus

repo_name: vindir/adhearsion-versus


text:
---
title: Computers
layout: post
author: benjamin.jackson
permalink: /computers/
source-id: 1NarV0Sdy62Woicp5jJpmcjsNaX8v5M--T8zO0fGPCKw
published: true
---
**Computers**

**Peripherals**

**Peripherals are the outputs and inputs of the computer. It is used to put infomation in and get infomation out of the computer. You can also use peripherals to store storage. **

**There are three different types of peripherals:**

**Input devices**

**Output devices**

**Storage devices**

**Hard drive**

**The hard drive is a disk that spins very fast inside the computer. It spins around 7,200 rpm (revolutions per minute) in a box inside the computer. The hard drive stores  a lot of data of data.**

**Ram**

**Ram stands for ****_'random access memory'._**** Ram is the most common type of memory found in computers.**

**There are two types of Ram:**

**DRAM**

**SRAM**

**Malware/virus**

**Malware is a cobination of 'software', and ‘maliciuos’. Malware can also include viruses like worms, spyware or trojans. A virus is a program designed to cause trouble for your computer. It can slow your computer down or even copy your personal data.**

**worm**

**A worm can spread through your device very quickly and not like a virus they don't need to attach them selfs to and programs. Worms can copy them selves up to one hundred times very quickly. So it’s easy to harm your divice.**

**Trojan**

**A trojan is like a undercover program. It proteneds to be a safe helpful program but it's not. Trojan gets its name from the story of the trojan horse because the greek tricked the city of troy pretending to be a present.**

**Zombinet**

**Zominet also known as 'zombie computer' is a computer virus that is very dangerous virus.  They can make you feel in danger because hackers can copy your personal data or even change it. They can change your password of your computer so you can't access it.**

license: MIT

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
---
title: "SplitContainer Control Overview (Windows Forms) | Microsoft Docs"
ms.custom: ""
ms.date: "03/30/2017"
ms.prod: ".net-framework"
ms.reviewer: ""
ms.suite: ""
ms.technology:
  - "dotnet-winforms"
ms.tgt_pltfrm: ""
ms.topic: "article"
f1_keywords:
  - "SplitContainer"
dev_langs:
  - "jsharp"
helpviewer_keywords:
  - "SplitContainer control [Windows Forms], about SplitContainer control"
ms.assetid: 6de5a5f7-97a5-402d-be6d-7e2785483db5
caps.latest.revision: 11
author: dotnet-bot
ms.author: dotnetcontent
manager: "wpickett"
---
# SplitContainer Control Overview (Windows Forms)
The Windows Forms <xref:System.Windows.Forms.SplitContainer> control can be thought of as a composite; it is two panels separated by a movable bar. When the mouse pointer is over the bar, the pointer changes shape to show that the bar is movable.

> [!IMPORTANT]
>  In the **Toolbox**, <xref:System.Windows.Forms.SplitContainer> control replaces the <xref:System.Windows.Forms.Splitter> control that was there in the previous version of [!INCLUDE[vsprvs](../../../../includes/vsprvs-md.md)]. The <xref:System.Windows.Forms.SplitContainer> control is much preferred over the <xref:System.Windows.Forms.Splitter> control. The <xref:System.Windows.Forms.Splitter> class is still included in the [!INCLUDE[dnprdnshort](../../../../includes/dnprdnshort-md.md)] for compatibility with existing applications, but we strongly encourage you to use the <xref:System.Windows.Forms.SplitContainer> control for new projects.

 With the <xref:System.Windows.Forms.SplitContainer> control, you can create complex user interfaces; often, a selection in one panel determines what objects are shown in the other panel. This arrangement is very effective for displaying and browsing information. Having two panels lets you aggregate information in areas, and the bar, or "splitter," makes it easy for users to resize the panels.

 More than one <xref:System.Windows.Forms.SplitContainer> control can also be nested, with the second <xref:System.Windows.Forms.SplitContainer> control oriented horizontally, to create top and bottom panels.

 Be aware that the <xref:System.Windows.Forms.SplitContainer> control is keyboard-accessible by default; users can press the ARROW keys to move the splitter if the <xref:System.Windows.Forms.SplitContainer.IsSplitterFixed%2A> property is set to `false`.

 The <xref:System.Windows.Forms.SplitContainer.Orientation%2A> property of the <xref:System.Windows.Forms.SplitContainer> control determines the direction of the splitter, not of the control itself. Hence, when this property is set to <xref:System.Windows.Forms.Orientation>, the splitter runs from top to bottom, creating left and right panels.

 Additionally, be aware that the value of the <xref:System.Windows.Forms.SplitContainer.SplitterRectangle%2A> property varies depending on the value of the <xref:System.Windows.Forms.SplitContainer.Orientation%2A> property. For more information, see <xref:System.Windows.Forms.SplitContainer.SplitterRectangle%2A> property.

 You can also restrict the size and movement of the <xref:System.Windows.Forms.SplitContainer> control. The <xref:System.Windows.Forms.SplitContainer.FixedPanel%2A> property determines which panel will remain the same size after the <xref:System.Windows.Forms.SplitContainer> control is resized, and the <xref:System.Windows.Forms.SplitContainer.IsSplitterFixed%2A> property determines if the splitter is movable by the keyboard or mouse.

> [!NOTE]
>  Even if the <xref:System.Windows.Forms.SplitContainer.IsSplitterFixed%2A> property is set to `true`, the splitter may still be moved programmatically; for example, by using the <xref:System.Windows.Forms.SplitContainer.SplitterDistance%2A> property.

 Finally, each panel of the <xref:System.Windows.Forms.SplitContainer> control has properties to determine its individual size.

## Commonly Used Properties, Methods, and Events

|Name|Description|
|----------|-----------------|
|<xref:System.Windows.Forms.SplitContainer.FixedPanel%2A> property|Determines which panel will remain the same size after the <xref:System.Windows.Forms.SplitContainer> control is resized.|
|<xref:System.Windows.Forms.SplitContainer.IsSplitterFixed%2A> property|Determines if the splitter can be moved with the keyboard or mouse.|
|<xref:System.Windows.Forms.SplitContainer.Orientation%2A> property|Determines if the splitter is arranged vertically or horizontally.|
|<xref:System.Windows.Forms.SplitContainer.SplitterDistance%2A> property|Determines the distance in pixels from the left or upper edge to the movable splitter bar.|
|<xref:System.Windows.Forms.SplitContainer.SplitterIncrement%2A> property|Determines the minimum distance, in pixels, that the splitter can be moved by the user.|
|<xref:System.Windows.Forms.SplitContainer.SplitterWidth%2A> property|Determines the thickness, in pixels, of the splitter.|
|<xref:System.Windows.Forms.SplitContainer.SplitterMoving> event|Occurs when the splitter is moving.|
|<xref:System.Windows.Forms.SplitContainer.SplitterMoved> event|Occurs when the splitter has moved.|

## See Also
 <xref:System.Windows.Forms.SplitContainer>
 [SplitContainer Control](../../../../docs/framework/winforms/controls/splitcontainer-control-windows-forms.md)
 [SplitContainer Control Sample](http://msdn.microsoft.com/en-us/9015fad0-7108-4d85-a83a-a72d038c4f65)


text:
---
layout: sidebar
sidebar_align: right
title: Acupuncture Safety
permalink: /about-acupuncture/acupuncture-safety.html
image: /images/uploads/child-on-beach-with-spade551x297.jpg
---

British Medical Journal research has identified Acupuncture as extremely safe, it is  one of the safest medical treatments you can have.

When practised by a fully qualified practitioner of Traditional Acupuncture, it is rare to have any side effects from Acupuncture other than feeling better of course.  Any minor side effects that can rarely occur are mild and self-correcting.

### Research Into The Safety Of Acupuncture

Two independent surveys were published in the British Medical Journal. The 2001 study showed that the risk of a serious adverse reaction to Acupuncture is very very low, and much less than many orthodox medical treatments. One survey was of ‘Traditional Acupuncturists’, who are trained fully in Chinese medicine, and the other of doctors practising the more limited form of ‘medical acupuncture’. A total of 66,000 treatments were reviewed altogether, with only a handful of minor and transient side effects recorded.

In 2003 a survey of 6,000 patients of acupuncture produced almost identical figures.

### Professional Standards

I work to the highest professional standards as laid down by the British Acupuncture Council which is the largest body governing Acupuncturists in the UK. [You can read more about these professional standards here](https://www.acupuncture.org.uk/public-content/effective-practice/82-bacc-professional-codes.html)

gha_language: HTML

gha_license_id: MIT


text:
Problem is updates *may* break things.
And obviously you need to know what may have broke before pushing your code to production.
Before running your test suite and checking everything is fine,
the first thing you do is probably to look for the changelogs of updated gems.

This process can be quite time consumming:
you need to check on the internet for every updated gems, find where their changelog is hosted,
and probably link to it in your commit message so that other developers will have a chance
to review it too.

`gem_update` will do exactly that for you.
It updates your `Gemfile` (via `bundle update`) and finds links for changelogs of updated gems.
All you have to do is to copy paste the output to the commit message, and you're done!
Obviously, you still have to read changelogs and adapt your code though ;)

## Installation and usage

```
gem install gem_updater
gem_update
<copy paste of output to commit message>
```

If you prefer to, you can ask gem_update to commit straight away:

```
gem_update --commit
```

This will use the generated message as a commit message template, allowing you
to edit before commit.

### Diff format

By default, diff for your gems will look like the following:

```
* gem_1 0.1 → 0.2
[changelog](https://github.com/maintainer/gem_1/CHANGELOG.md#02)

* gem_2 3.4.2 → 3.4.3
[changelog](https://github.com/maintainer/gem_2/CHANGELOG.md#343)
```

You can change it if you like by writing you own template `.gem_updater_template.erb` in your home directory.
[Look at default template](lib/gem_updater_template.erb) for an example on how to do it.

## Contributing

PRs are always welcome!
If you wish to contribute, do not hesitate to submit an issue or to open a pull request.

gha_language: Ruby


text:
---
templateKey: blog-post
title: "Notional Remix 1"
date: 2019-11-17T12:00:00.000Z
featuredpost: false
description: >-
  Lowering the water level, role-playing death, and happy countries.
tags:
 - Notional Remix
 - Toyota
 - Lean Methodology
 - North Star Podcast
 - South Korea
 - Meaning
 - Victor Frankl
 - Happiness
---
### Lowering the water level to see the rocks

I first learnt about this concept from this episode of the North Star podcast:

<dl>
<iframe style="border: none" src="//html5-player.libsyn.com/embed/episode/id/11873162/height/90/theme/custom/thumbnail/yes/direction/backward/render-playlist/no/custom-color/87A93A/" height="90" width="100%" scrolling="no"  allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>
</dl>

When trying to refine their car production process, Toyota introduced an interesting model which compares inventory levels to the water levels in a river. This idea is now a fundamental part of the [Lean business methodology](https://leankit.com/learn/lean/lean-methodology/). Here’s the idea:

Suppose your goal is to build the safest river for ships. You inspect the closest natural river. The water is murky, and you wonder if there are any rocks below that might damage your ships. When the water level is high, you can't see any rocks. But that's fine because your ships float well above any rocks – the rocks are not a problem and therefore go unnoticed. But the water level is not always high. As the water level drops, the rocks become more visible and more of a problem. If the water level were to drop quickly, there would not be enough time to remove the rocks and ships would be damaged. A good approach would be to slowly lower the water level, giving you enough time to remove rocks as you discover them.

In Toyota’s analogy, the water level is their level of inventory, and the rocks are production process risks such as unreliable suppliers. When Toyota's inventory levels are high (they have many finished cars available and ready to be sold), a delay in production caused by an unreliable supplier might be ignored – as long as Toyota has cars to sell to eager customers, revenue will continue to pour in, and the supply chain problems go unnoticed, unsolved, and remain a risk.

But what if Toyota's inventory (their water level) is suddenly depleted, perhaps by an earthquake destroying the warehouse? Now, if production stops because of an unreliable supplier (the rock in the river), Toyota may run out of cars to sell, and their eager customers will have no choice but to go to Toyota's competitors. Toyota's revenue drops, managers take notice, and the supply chain problem is suddenly visible.

Toyota's solution was to slowly lower their water levels (such as inventory) intentionally, in order to uncover the problems in their process. As these problems became visible, Toyota could solve them while minimizing the negative financial impact. When all the visible problems were solved, Toyota would once again lower the "water levels", see the "rocks", and remove risk and inefficiency from their process.

The same concept can be applied to areas in your personal life, like time management. As you reduce the amount of time you allocate to tasks, your inefficiencies in performing these tasks will become more apparent. If you were to cut your workday from 8 hours to 2 hours, you would quickly notice when you're spending time on less important tasks. This would allow you to identify tasks that waste your time, remove them from your daily routine, and become more effective with your time.

Lower your water level to see your rocks.

___

### Role-playing death for a new perspective on life

There’s a growing trend in South Korea where people are [role-playing their own funerals](https://www.youtube.com/watch?v=ejEaJUEOhjs) to get a better perspective on life.

South Korean students on average spend roughly 16 hours per day on school-related activities. The South Korean work environment is even more competitive. This highly competitive and stressful environment has led to a surge of searching for meaning through simulated death.

Participants write their wills and farewell letters to loved ones. They see their framed portraits alongside candles at coffins. They then lie inside the closed caskets and reflect on the meaning of their life and death.

It seems that when we are more aware of our mortality, we find greater meaning in life.

As automation continues to displace jobs, unskilled labour markets will become increasingly competitive. This will likely lead to the proliferation of similar meaning-seeking activities.

>*“Life is never made unbearable by circumstances, but only by lack of meaning and purpose.”* – Victor Frankl

___

### Which countries are the happiest?

The World Happiness Report measures and ranks the happiness of countries each year. Here are the top and bottom five countries in their [2019 ranking](https://s3.amazonaws.com/happiness-report/2019/WHR19.pdf):

1. Finland
2. Denmark
3. Norway
4. Iceland
5. Netherlands

>-

152. Rwanda
153. Tanzania
154. Afghanistan
155. Central African Republic
156. South Sudan

repository: BenSparksCode/personal-blog

gha_language: JavaScript

repo_name: BenSparksCode/personal-blog


text:
## How to run

```bash
g++ --std=c++17 main.cpp ./Commands/*.cpp ./Project/*.cpp -o result
```

## Result

```
File Name: text1.txt
File Path: /path/_posts/design-pattern/14-Command/codes/c++/Examples
File Size: 137
File Content:
Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.

File Name: text1.txt
File Path: /path/_posts/design-pattern/14-Command/codes/c++/Examples
File Size: 137
File Content:
Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.

File Name: text1.txt
File Path: /path/_posts/design-pattern/14-Command/codes/c++/Examples
File Size: 171
File Content:
Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.
Hello, it's me
How are you doing?

File Name: text1.txt
File Path: /path/_posts/design-pattern/14-Command/codes/c++/Examples
File Size: 152
File Content:
Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.
Hello, it's me

File Name: text1.txt
File Path: /path/_posts/design-pattern/14-Command/codes/c++/Examples
File Size: 137
File Content:
Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.
```


text:
# Running on OpenShift

This project uses the scripts found in [openshift-project-tools](https://github.com/BCDevOps/openshift-project-tools) to setup and maintain OpenShift environments (both local and hosted).  Refer to the [OpenShift Scripts](https://github.com/BCDevOps/openshift-project-tools/blob/master/bin/README.md) documentation for details.

**IMPORTANT:  These scripts are designed to be run on the command line (using Git Bash for example) in the root `./openshift` directory of your project.**

## Table of Contents

- [Before you begin](#before-you-begin)
- [Scenario #1 - Running on a Local OpenShift Cluster](#scenario-1---running-on-a-local-openshift-cluster)
- [Scenario #2 - Running on the BC Government Pathfinder OpenShift instance](#scenario-2---running-on-the-bc-government-pathfinder-openshift-instance)
- [Advanced Stuff](#advanced-stuff)

## Before you begin...

### Working with OpenShift

When working with OpenShift, commands are typically issued against the **server-project** pair to which you are currently connected. Therefore, when you are working with multiple servers (local, and remote for instance) you should always be aware of your current context so you don't inadvertently issue a command against the wrong server and project.

**NOTE:**  Although you can login to more than one server at a time it's always a good idea to completely logout of one server before working on another.

The automation scripts provided by [openshift-project-tools](https://github.com/BCDevOps/openshift-project-tools) will hide some of these details from you, in that they perform project context switching automatically. However, what they don't do is provide server context switching. They assume you are aware of your server context and you have logged into the correct server.

Here are some useful commands to help you determine your current context:

- `oc whoami -c`  *// Lists your current server and user context*
- `oc project`  *// Lists your current project context*
- `oc project [NAME]`  *// Switch to a different project context*
- `oc projects` *// Lists the projects available to you on the current server*

### Project Set Initialization

Before you can run your applications in the Pathfinder (BC Gov) instance of OpenShift, the DevOps team will have to provision a set of OpenShift projects to house your CI/CD tooling (e.g. build pipeline, functional tests, etc.) as well as deployment environments. Typically this set consists of **tools**, **dev**, **test**, and **prod** projects. Collectively, this is referred to as a "Project Set".

**NOTE:**  "Project Set" is a fabricated term used to describe two or more OpenShift projects that relate to the same app/product. There is no such construct in OpenShift or Kubernetes.

### Naming Conventions

The projects follow a naming convention similar to "{team_name}-{product_name}-{environment_name}". For example, "gcpe-news-tools" would be the "tools" environment for the news product, owned by the GCPE team.

The 'tools' project will house various *build configurations*, or **`BuildConfig`** for your app. It will also host a Jenkins instance that will be responsible for promoting application images across your deployment environments (e.g. "dev", "test" and "prod").  Image promotion is achieved in OpenShift via *image stream tags*, or **`ImageStreamTag`**.

### Background Reading and Resources

The commands and instructions in the next sections assume a moderate to advanced knowledge of OpenShift. There are two good PDFs available from Red Hat and O'Reilly:

* [OpenShift for Developers](https://www.openshift.com/for-developers/)
* [DevOps with OpenShift](https://www.openshift.com/devops-with-openshift/)

* OpenShift Developer Guide:
  * [What Is a Build?](https://docs.openshift.com/container-platform/3.9/dev_guide/builds/index.html#dev-guide-what-is-a-build)
  * [What Is a Deployment?](https://docs.openshift.com/container-platform/3.9/dev_guide/deployments/how_deployments_work.html#what-is-a-deployment)
  * [What Is an Image Stream?](https://docs.openshift.com/container-platform/3.9/architecture/core_concepts/builds_and_image_streams.html#image-streams)

## Scenario #1 - Running on a Local OpenShift Cluster

At times running in a local cluster is a little different than running in the production (Pathfinder) cluster.

Differences can include:
* Resource settings.
* Available image runtimes.
* Source repositories (such as your development repo).
* Etc.

This section is intended for application developers, and provides instructions for setting up and configuring a workstation to develop and deploy applications in a Local OpenShift Cluster environment. The following procedure uses the **`oc cluster up`** approach to provision an OpenShift Cluster directly in [Docker](https://www.docker.com/get-started).

### Before you begin...

**IMPORTANT!**  **You must increase the memory available to Docker. Not doing so will lead to failed builds and crashes in your local OpenShift cluster.**

Docker uses only **2 GB** of memory by default, which is not enough to run OpenShift. If you experience hangs when trying to run builds and deployments in OpenShift, you should do the following:

On Windows;

1. Open Docker > **Settings** > **Advanced**.
2. Increase the amount of memory available to Docker to **6 GB** (or more).
3. You should also increase the Swap space to **2 GB** (or more).
4. Click **Apply**.

### Getting Started Locally

1. Install OpenShift [command line tools](https://github.com/openshift/origin/releases/) (CLI)
2. Change into the top level **`openshift`** folder
3. Create **`settings.local.sh`** file
4. Provision your local OpenShift cluster (**`oc cluster up`**)
5. Login to local cluster with the command-line **`oc`** tools
6. Run `generateLocalProjects.sh` to generate a local set of projects (e.g. dev, test, prod and tools)
7. Run `initOSProjects.sh` to initialize your projects
8. Run `genParams.sh -f` to generate settings files
9. Run `genParams.sh -f -l` to generate settings files for your local cluster
10. Review generated settings files, make edits as needed
11. Run `genBuilds.sh -l` to generate the *build configurations*, or **`BuildConfig`** for your app
12. Run `genDepls.sh -l -e dev` to generate the *deployment configurations*, or **`DeploymentConfig`** for your DEV environment
    * Run `genDepls.sh -l -e test` for your TEST environment
    * Run `genDepls.sh -l -e prod` for your PROD environment
13. Run `updateRoutes.sh -e dev` to fix the routes (server URLs) on your DEV environment
    * Run `updateRoutes.sh -e test` to fix the routes (server URLs) on your TEST environment
    * Run `updateRoutes.sh -e prod` to fix the routes (server URLs) on your PROD environment

### 1. Install OpenShift command line tools (CLI)

1. Download OpenShift [command line tools](https://github.com/openshift/origin/releases/).
2. Unzip the downloaded file.
3. Add `oc` to your PATH.

The CLI is now available using the `oc` command:

```bash
oc <command>
```

**WINDOWS USERS:**  Ensure that you do not have a linux "oc" binary on your path if using Git Bash on a Windows PC to run the scripts.  A windows "oc.exe" binary will work fine.

### 2. Change into the top level OpenShift folder

```bash
cd /[Path-To-Working-Copy]/openshift
```

### 3. Settings.local.sh

To target a different repo and branch, create a `settings.local.sh` file in your project top level **`openshift`** directory. Within this file, override the GIT parameters.

**For Example:**

```bash
export GIT_URI="https://github.com/bcgov/gcpe-news-dashboard.git"
export GIT_REF="openshift-updates"  <-- we are targeting a different branch here!
```

### 4. Provision your local OpenShift Cluster

**REMEMBER:**  All of the commands listed in the following sections must be run from the root **`openshift`** directory of your project's source code.

*You must have the OpenShift CLI installed on your system for the scripts to work*

Run;

```bash
oc-cluster-up.sh
```

, and wait for the cluster to start up...

```
Using Docker shared volumes for OpenShift volumes
Using <IP_ADDRESS> as the server IP
Starting OpenShift using openshift/origin:v4.5.0 ...
OpenShift server started.

The server is accessible via web console at:
    https://<IP_ADDRESS>:8443
```

This will start your local OpenShift cluster using persistence and Docker containers so your configuration is preserved across restarts.

By default, the OpenShift cluster will be setup with a routing suffix that ends in **`nip.io`**. This is to allow dynamic host names to be created for routes; e.g. http://your-app-dev.<IP_ADDRESS>.nip.io/

*To cleanly shutdown your local cluster use **`oc-cluster-down.sh`***

### 5. Login to your local OpenShift instance

**With the command-line (`oc`) tools:**

1. Copy the command line login string from https://<IP_ADDRESS>:8443/console/command-line

   It will should be like:

   ```bash
   oc login https://<IP_ADDRESS>:8443 --token=<hidden>
   ```

2. Paste the login string into a terminal session.

3. You are now authenticated against OpenShift and will be able to execute `oc <command>`.

**NOTE:**  If you are asked for credentials use `developer` as both the username and password.

**NOTE:**  `oc -h` provides a summary of available commands.

### 6. Generate local set of projects (dev, test, prod and tools)

*This command will only work on a LOCAL server context. It will fail if you are logged into a remote server.*

```bash
generateLocalProjects.sh
```

This will generate four OpenShift projects; **tools**, **dev**, **test** and **prod**. The "tools" project is used for builds and DevOps activities; while the "dev", "test", and "prod" projects will host your deployment environments.

##### 6.1 Resetting your local OpenShift cluster

To reset your local environments (i.e. start over) run;

```bash
# Caution - your OpenShift projects will be deleted!
generateLocalProjects.sh -D
```

**WARNING:**  This command will PERMANENTLY delete all your local OpenShift projects! Use with care.

### 7. Initialize your projects

Run;

```bash
initOSProjects.sh
```

This will initialize the projects with permissions that allow images from one project (tools) to be deployed into another project (dev, test, prod). For production environments will also ensure the persistent storage services exist.

**NOTE:**  When running on your local cluster, you will see some messages - *"No resources found"*. These can be safely ignored.

### 8. Generate settings files

Run;

```bash
# -f switch means "force" (i.e. overwrite any existing config files)
genParams.sh -f
```

**NOTE:**  Generated settings files (**`*.param`**) for the production instance of OpenShift should be committed to Git

### 9. Generate extra settings files - for your local cluster

When you are working with a local cluster you must generate a set of local "param" files.

Run;

```bash
# -f switch means "force" (i.e. overwrite any existing config files)
# -l switch means "local" params
genParams.sh -f -l
```

This will generate local settings files for all your build configurations, deployment configurations, and Jenkins pipelines. The local settings will ensure that the CPU and Memory resources (limits and requests) specified in your OpenShift templates are adjusted accordingly to avoid builds and deployments from hanging due to lack of sufficient resources in your local workstation.

**NOTE:**  These settings will be specific to your local OpenShift cluster and will override the production-ready values when running `genBuilds.sh` and `genDepls.sh` scripts with the `-l` switch (more on that below).

**NOTE:**  Generated local param files (**`*.local.param`**) are ignored by Git, so you don't need to worry about accidentally committing them to the repository.

### 10. Review generated param files

Before progressing through this guide it is a good idea that you review the generated **`*.param`** files and make any edits as needed.

**IMPORTANT:**  Before you continue, you MUST provide a value for NAME in the "*.pipeline.param" files.

- Set NAME=news-dashboard in *[Working-Copy]/Jenkinsfile.pipeline.param*
- Set NAME=news-dashboard in *[Working-Copy]/openshift/Jenkinsfile.pipeline.local.param*

### 11. Generate the Build Configurations for your app

This script will generate the build configurations into the `tools` project. Additionally, if your project contains any Jenkins pipelines (i.e. a Jenkinsfile), then a new Jenkins instance will be created in the `tools` project automatically. OpenShift will automatically wire the Jenkins pipelines to Jenkins projects within Jenkins.

Run;

```bash
# -l switch means "local"
genBuilds.sh -l
```

:warning: **IMPORTANT!**  The script will stop mid-way through.

Ensure all builds are complete in the **`tools`** project before proceeding:

1. Login to your local cluster.
2. Go to "Tools" project > **Builds** > **Builds**.
3. Wait for all the build to complete (i.e. status must be ":white_check_mark: Complete").
4. Go back to the command line, press any key to proceed.

### 12. Generate the Deployment Configurations for your app

This script will generate the deployment configurations for the selected environment; `dev`, `test`, and `prod`.

Run;

```bash
# genDepls.sh -l -e <EnvironmentName, one of [dev|test|prod]>
genDepls.sh -l -e dev
genDepls.sh -l -e test
genDepls.sh -l -e prod
```

, and follow the instructions.

:warning: **IMPORTANT!**  Verify that the deployments were executed successfully

1. Login to your local cluster.
2. Switch to your "DEV" project (from the projects drop-down).
3. Click **Applications** > **Deployments**.
4. Wait for all deployments to complete (i.e. status must be ACTIVE).
5. Go back to the command line, press any key to proceed.

![apps](./gcpe-frontend-and-server-apps.png)

### 13. Fix the routes (server URLs) - for local instances only

##### Why do I need to do this?

The current version of the automated OpenShift scripts ([openshift-project-tools](https://github.com/BCDevOps/openshift-project-tools)) use a hardcoded URL when creating the routes to your application deployment environments.

All routes created by these scripts are explicitly defined for the Pathfinder (BC Government) instance of OpenShift; i.e. your app URL (in dev) is defined as https://news-dashboard-05e933-dev.pathfinder.gov.bc.ca/ instead of pointing to your local instance.

Run;

```bash
# updateRoutes.sh -e <EnvironmentName, one of [dev|test|prod]>
updateRoutes.sh -e dev
updateRoutes.sh -e test
updateRoutes.sh -e prod
```

This will fix the routes in your local deployment environments (dev, test, prod). The script will re-point your routes (URLs) to your local OpenShift cluster.

Before:

https://news-dashboard-05e933-dev.pathfinder.gov.bc.ca/

After:

https://news-dashboard-05e933-dev.<IP_ADDRESS>.nip.io/

------

:tada: *Congratulations! Now you should have a fully functioning app running on your local OpenShift instance.* :tada:

## Scenario #2 - Running on the BC Government Pathfinder OpenShift instance

This section includes information on how to get your application up and running in the BC Government Pathfinder OpenShift instance:

### Getting Started

1. Install OpenShift [command line tools](https://github.com/openshift/origin/releases/) (CLI)
2. Change into the top level **`openshift`** folder
3. Create **`settings.sh`** file
4. Login to Pathfinder cluster with the command-line **`oc`** tools
5. Run `initOSProjects.sh` to initialize your projects (e.g. dev, test, prod and tools)
6. Run `genParams.sh` to generate settings files
7. Review generated settings files, make edits as needed
8. Run `genBuilds.sh` to generate the *build configurations*, or **`BuildConfig`** for your app
9. Run `genDepls.sh -e dev` to generate the *deployment configurations*, or **`DeploymentConfig`** for your DEV environment
   * Run `genDepls.sh -e test` for your TEST environment
   * Run `genDepls.sh -e prod` for your PROD environment

**NOTE:**  If you are looking for information on how to run your application in a local OpenShift Cluster, go to the next section (Scenario 2). It contains additional steps required for local OpenShift installations.

### 1. Install OpenShift command line tools (CLI)

1. Download OpenShift [command line tools](https://github.com/openshift/origin/releases/).
2. Unzip the downloaded file.
3. Add `oc` to your PATH.

The CLI is now available using the `oc` command:

```bash
oc <command>
```

**WINDOWS USERS:**  Ensure that you do not have a linux "oc" binary on your path if using Git Bash on a Windows PC to run the scripts.  A windows "oc.exe" binary will work fine.

### 2. Change into the top level OpenShift folder

```bash
cd /[Path-To-Working-Copy]/openshift
```

### 3. Settings.sh

You will need to include a `settings.sh` file in your top level **`./openshift`** directory. This file will contain your project-specific settings.

At a minimum this file should contain definitions for your `PROJECT_NAMESPACE`, `GIT_URI`, and `GIT_REF` all of which should be setup to be overridable.

**For Example:**

```bash
export PROJECT_NAMESPACE=${PROJECT_NAMESPACE:-05e933}
export GIT_URI=${GIT_URI:-"https://github.com/bcgov/gcpe-news-dashboard.git"}
export GIT_REF=${GIT_REF:-"develop"}
```

### 4. Login to Pathfinder

**REMEMBER:**  All of the commands listed in the following sections must be run from the root **`openshift`** directory of your project's source code.

*You must have the OpenShift CLI installed on your system for the scripts to work*

**With the command-line (`oc`) tools:**

1. Copy the command line login string from <https://console.pathfinder.gov.bc.ca:8443/console/command-line>

   It will should be like:

   ```bash
   oc login https://console.pathfinder.gov.bc.ca:8443 --token=<hidden>
   ```

2. Paste the login string into a terminal session.

3. You are now authenticated against OpenShift and will be able to execute `oc <command>`.

**NOTE:**  `oc -h` provides a summary of available commands.

### 5. Initialize your projects

Run;

```bash
initOSProjects.sh
```

This will initialize the projects with permissions that allow images from one project (tools) to be deployed into another project (dev, test, prod). For production environments will also ensure that persistent storage services exist.

**REMEMBER!**  These instructions are for the production cluster (Pathfinder). To run OpenShift locally refer to [Scenario #1](#scenario-#1---running-on-a-local-openshift-cluster).

### 6. Generate settings files

Run;

```bash
# -f switch means "force" (i.e. overwrite any existing config files)
genParams.sh -f
```

**NOTE:**  Generated settings files (**`*.param`**) for the production instance of OpenShift should be committed to Git

### 7. Review generated param files

Before progressing through this guide it is a good idea that you review the generated **`*.param`** files and make any edits as needed.

**IMPORTANT:**  Before you continue, you MUST provide a value for NAME in the "*.pipeline.param" files.

- Set NAME=news-dashboard in *[Working-Copy]/Jenkinsfile.pipeline.param*
- Set NAME=news-dashboard in *[Working-Copy]/openshift/Jenkinsfile.pipeline.local.param*

### 8. Generate the Build Configurations for your app

Run;

```bash
# genBuilds.sh -h to get advanced usage information...
genBuilds.sh
```

**IMPORTANT!**  The script will stop mid-way through. Ensure all builds are complete in the **`tools`** project before proceeding.

**REMEMBER!**  These instructions are for the production cluster (Pathfinder). To run OpenShift locally refer to [Scenario #1](#scenario-#1---running-on-a-local-openshift-cluster).

This script will generate the build configurations into the `tools` project. Additionally, if your project contains any Jenkins pipelines (i.e. a Jenkinsfile), then a new Jenkins instance will be created in the `tools` project automatically. OpenShift will automatically wire the Jenkins pipelines to Jenkins projects within Jenkins.

### 9. Generate the Deployment Configurations for your app

Run;

```bash
# genDepls.sh -e <EnvironmentName, one of [dev|test|prod]>
# genDepls.sh -h to get advanced usage information.
genDepls.sh -e dev
genDepls.sh -e test
genDepls.sh -e prod
```

**REMEMBER!**  These instructions are for the production cluster (Pathfinder). To run OpenShift locally refer to [Scenario #1](#scenario-#1---running-on-a-local-openshift-cluster).

This script will generate the deployment configurations for the selected environment; `dev`, `test`, and `prod`.

-----

:tada: *Congratulations! Now you should have a fully functioning app running on OpenShift.* :tada:

## Advanced Stuff

### Add Build Pipeline Webhook(s) to GitHub

Once you have a working OpenShift cluster, you might want to connect your build pipeline to GitHub (via webhooks) so that when there's a new commit (or pull request) pushed to your repo, it triggers a new build in OpenShift:

1. Log into the web console and switch to the project: "Your App (tools)"
2. Select Builds => BuildConfig => [name-of-your-build-pipeline] => Configuration
3. Under the Triggers section, copy the GitHub Webhook URL

[TODO: screenshot]

4. Go to your repository settings on GitHub, and add the webhook URL under "Webhooks"

   * Payload URL = The URL you copied from OpenShift

   * Content type = application/json

   * Secret = Leave Blank

   * Just push the event

   * Active

repository: bcgov/gcpe-news-dashboard

branch_name: refs/heads/develop

gha_language: TypeScript

repo_name: bcgov/gcpe-news-dashboard


text:
# pirunner

Tiny Project to control the raspberry pi task set from your browser.
Integrates with your web directory listings (separately) to allow you
to run multiple applications. Personal project, not meant to be used
anywhere as of now. Alpha quality.

## Goals
- Run audio, video, games from the browser
- Control current process by sending keystrokes from the browser
- Run a complete server of its own, perhaps?
    + As of now integrates with Apache web listings

## Known Issues

- Video playback fails if subtitles fail to download
- subliminal doesn't do hash based matches any more
- Killing vlc, cvlc, or omxplayer seems to be having issues
    + fceux dies easily with .terminate() though

## Over-Engineering

There is a lot of opportunity for over-engineering this.
I am inclined towards using a message queue to start/end
tasks, and maybe a separate taskrunner process as well.

Also need to convert it to a systemd service so it starts
at boot.

## License

Licensed uner [MIT License](http://nemo.mit-license.org).


text:
Apache Cordova for Windows Phone 8
===

Apache Cordova WP8 is a .net application library that lets you create Apache Cordova applications targeting Windows Phone 8 devices.
Apache Cordova based applications are, at the core, an application written with web technology: HTML, CSS and JavaScript.

Requires
---

- Windows Phone 8 SDK

Getting Started
---
- coming soon

BUGS?
-----
File them at Apache Incubator
https://issues.apache.org/jira/browse/CB

Further Reading
---

- [http://docs.phonegap.com](http://docs.phonegap.com)
- [http://wiki.phonegap.com](http://wiki.phonegap.com)


text:
---
layout: post
title: Live Fact-Checking in the Era of Fake News
excerpt: Fake news, political deception, and rumor mills are not new phenomena, but in recent years the internet has fueled an explosion of deliberate disinformation.
---

Fake news, political deception, and rumor mills are not new phenomena, but in recent years the internet has fueled an explosion of deliberate disinformation. The spread of deceptive content is often rapid and uncontrollable. A recent study by MIT found that falsehood diffuses significantly farther, faster, deeper, and more broadly than the truth, in all categories of information. Today, any individual group can spread untrue statements and manipulate the public without being held accountable.

Simultaneously, recent advances in machine learning models, namely transformer networks such as BERT,  have pushed computer’s ability to understand natural language ever closer to human performance. Our algorithm for live fact checking lies at the nexus of this technology and recent developments in politics.

Recent concern has stimulated research efforts to automate fact-checking. Machine learning efforts to tackle fact-checking are fueled by invaluable datasets such as the Fact Extraction and VERification (FEVER) dataset, Fake News Challenge (FNC), General Language Understanding Evaluation (GLUE), MultiGenre Natural Language Inference (MultiNLI), and Semantic Evaluation (SemEval).

In order to tackle this challenge we first sought to prove the effectiveness of our methods by achieving state of the art accuracy on the largest of these datasets,  FEVER. While such datasets are notoriously biased and often fail to generalize to real-world problems, they are a useful tool to at least know your technology is in the ballpark of effective. Once achieving this ballpark effectiveness we planned to see if such a pipelines could be deployed for real-world, low-latency fact checking, potentially by supplementing wikipedia with other ground truth data sources.

## Our System

![alt_text](https://raw.githubusercontent.com/koursaros-ai/koursaros-ai.github.io/master/images/Screen%20Shot%202019-09-25%20at%204.00.58%20PM.png "image_tooltip")

### Training Elasticsearch

Rather than relying on hand built matching and filtering heuristics, such as the “entity linking” described by Athene (the top team by information retrieval (IR) for Fever) we were interested in building a system that could be _trained_ for optimal recall on an IR task such as that proposed by FEVER. Additionally such systems could be trained in production by incorporating user feedback.

One of our primary concerns in designing such a system was performance and scalability. This is in keeping with our overall system design for Koursaros, which relies on pub-sub architecture and a robust broker.

We divide our search efforts into those powered primarily by machine learning, and those powered primarily by traditional text search. However, this distinction is blurred by our use of Bayesian optimization for tuning hyperparameters for text search. Our future plans include pursuing search exclusively powered by machine learning as we plan to explore a system of directly training a neural search system for document retrieval. However, such a solution will require more research and development. Notably an efficient method for KNN search in high dimensions using approximate nearest neighbors is needed to boost document recall. Such a system should be sharded and also implement multi-layer clustering, so that the entire index doesn’t need to stay in memory.

### Ranking Potential Evidence Sentences for Evaluation

We used RoBERTA, from Facebook AI, as our pretrained transformer network, since it recently set state of the art on many text understanding tasks. We used it to train regression on pairs of claims and evidence from the search results, labeling the correct claim evidence pair from the FEVER set with a 1.0 and all others with a 0.0. Notably we concatenated the title of the wiki article to the beginning of every line from the article, providing context sometimes lost by pronouns. This system resulted in 94% line recall when the candidate evidence was ranked in descending order by score and the top 5 were taken, **compared with 87% from the Athene** team. We performed this evaluation on the test set in cases where the correct document had been. Our boost in this score can be attributed to using a larger, newer LSTM model, and the concatenation of titles to the candidate evidence prior to scoring.

### Training an Inference Model

We decided to use pre trained RoBERTA again, this time fine-tuning it on the top 1 result from our evidence retrieval and ranking pipeline and the ground truth labels from FEVER train set. This achieved **74%** label accuracy, #2 on the continuous evaluation leaderboard. Due to the discrepancy of this score and our FEVER, score which was discounted for correctly labeled examples which lacked ground truth evidence in the top 5, I believe the inference is not a bottleneck on our system, and we could get an even higher score by boosting article recall.

## Results

     Model

     Label Accuracy

     Evidence F1

     FEVER Score

    Koursaros w/ Roberta

    73.64

   52

   63

   UNC-NLP

   68.21

   52.96

   64.21

   UCL ML

   67.62

   34.97

   62.52

   Athene UKP

   65.46

   36.97

   61.58

   MIT FAKTA

   59.35

   Columbia-NLP

   57.45

   35.33

   49.06

There are 2 primary outcomes we sought, which we mostly met, and a third development which was an unexpected and interesting discovery:

1. **Pursue academic benchmarks**
    1. **Goal:** Reaching SoTA on the FEVER benchmark.
    2. **Outcome:** 0.74 label accuracy (#2 overall), 0.637 FEVER score (#11 overall), on the [perpetual evaluation scoreboard ](https://competitions.codalab.org/competitions/18814#results)
    3. While we were very happy with our pipeline’s label accuracy rank, our trained ElasticSearch evidence retriever only achieved 85% document recall on the test set, whereas state of the art set by Athene (University of Darmstadt) was 93%. Since the FEVER score is calculated by discounting examples where some evidence is missing in the top 5 from overall accuracy, we believe this to me the primary factor lowering our overall rank in this category. However, our document retriever relies on **no entity extraction or other ML**, making it more practical and faster for production. Additionally it doesn’t rely on an external API like wikimedia, which Athene pipeline does.
2. **Production-ready ML**
    1. **Goal:** Be the first team to deploy their fact-checking pipeline in a highly available low-latency production environment
    2. **Outcome:** We realized that there was no elastic microservice framework for NLP that would allow us to easily deploy our pipeline, so we built our own, [Koursaros](https://github.com/koursaros-ai/koursaros).  [GNES](https://hanxiao.github.io/2019/07/29/Generic-Neural-Elastic-Search-From-bert-as-service-and-Go-Way-Beyond/) is notably building a similar platform, but are still in the process of development, and lack a stable release. Additionally their platform specifically for neural search, and not inference. We have used Koursaros to deploy our pipeline with a frontend to Kubernetes.
3. **Using Hyperparameter Tuning with a Bayesian Optimizer to Boost Elasticsearch**
    1. This was not part of our initial plan, but after establishing a baseline system for document retrieval on elastic search, we were shocked by how dismal the results were (65% document recall compared with 93% SoTA). Elasticsearch offers the sharding scalability which we sought so we didn’t want to switch to an entirely different system
    2. We trained the BM25 scorer function on the fever.ai set using Facebook’s Ax Bayesian Optimizer, and boosted our document recall from ~**65%** to ~**85%.**
    3. Even though this system is still not state of the art, **we view this as one of the most novel results of our paper, not only because such a result has not yet been published to our knowledge, but because ElasticSearch is so widely adopted such a method has phenomenal real-world implications for production system.**

## Conclusion and Next Steps

Overall we are thrilled with these initial results, but will continue to iterate, especially on the article retrieval model. We believe that we have reached the limit of our ability to train Elasticsearch, and moving forward plan to train a vector based neural KNN search, using custom pytorch code and vector space indexing. Such methodology is notably only occasionally talked about in academic literature, but holds incredible promise. We are closely monitoring the development of [GNES](https://hanxiao.github.io/2019/07/29/Generic-Neural-Elastic-Search-From-bert-as-service-and-Go-Way-Beyond/), a project which has a similar aim to ours.

## Notes

[^1]:
     [http://news.mit.edu/2018/study-twitter-false-news-travels-faster-true-stories-0308](http://news.mit.edu/2018/study-twitter-false-news-travels-faster-true-stories-0308)

[^2]:
     [https://arxiv.org/abs/1803.05355](https://arxiv.org/abs/1803.05355)

[^3]:
    [ http://aclweb.org/anthology/W18-5516](http://aclweb.org/anthology/W18-5516) (University of Darmstadt)

url: https://raw.githubusercontent.com/koursaros-ai/koursaros-ai.github.io/114fcbf3318b14fac72cf86826cabfba761c97ca/_posts/2019-9-25-Live Fact-Checking Algorithms in the Era of Fake News.md


text:
# Hooks

## About hooks

Hooks are used to tie into various parts of the application lifecycle.

## Available hooks

- `HOOK_APP_START` - while the app is starting, only called once
  - `HOOK_REQUEST_START` - while a request is starting, called for each request
    - `HOOK_RESPONSE_START` - before a route handler runs, called for each request
    - `HOOK_RESPONSE_END` - after a route handler completes, called for each request
    - `HOOK_HEADERS_START` - before headers are formatted to be sent, called for each request
    - `HOOK_HEADERS_END` - after headers have been sent, called for each request
  - `HOOK_REQUEST_END` - after a request completes, called for each request
- `HOOK_APP_END` - before the app exits, only called once

## Hook routines

* [`get_hook_name`](#get_hook_name)
* [`insert_hook`](#insert_hook)
* [`new_hook_type`](#new_hook_type)
* [`run_hooks`](#run_hooks)

### new_hook_type

`include mvc/hooks.e`
`public function new_hook_type( sequence name )`

Add new hook type.

**Parameters**

* **`name`** - the name of the hook. This should be the default routine name.

**Returns**

A new hook ID, an `integer` that should be used with `insert_hook`.

**Remarks**

You shouldn't really need to be registering new hooks. This is mostly used internally by the server and application routines.

### get_hook_name

`include mvc/hooks.e`
`public function get_hook_name( integer hook_type )`

Return a hook name.

**Parameters**

* **`hook_type`** - the hook ID returned from `new_hook_type`

**Returns**

A `sequence`, the name of the hook.

### insert_hook

`include mvc/hooks.e`
`public procedure insert_hook( integer hook_type, sequence func_name = get_hook_name(hook_type), integer func_id = routine_id(func_name) )`

Insert a new hook.

**Parameters**

* **`hook_type`** - the hook ID returned from `new_hook_type`.
* **`func_name`** - the name of the routine to be called.
* **`func_id`** - the ID of the routine to be called.

### run_hooks

`include mvc/hooks.e`
`public function run_hooks( integer hook_type )`

Run a list of hooks.

**Parameters**

* **`hook_type`** - the ID of the hooks to be run.

repository: OpenEuphoria/euphoria-mvc

gha_language: E

repo_name: OpenEuphoria/euphoria-mvc


text:
    Mews.Fiscalizations.Germany is a .NET library that was built to help reporting of e-invoices to the German authorities (BSI - Bundesamt für Sicherheit in der Informationstechnik) using Fiskaly KassenSichV API V1.

## 📃 Description

The library uses Fiskaly API to report the invoices, for more information, please check their [Documentation](https://developer.fiskaly.com/api/kassensichv/v1/).

## ⚙ Installation

The library can be installed through NuGet packages or the command line as mentioned below:
```bash
Install-Package Mews.Fiscalizations.Germany
```

## 🎯 Features

-   Functional approach via [FuncSharp](https://github.com/siroky/FuncSharp).
-   No German abbreviations.
-   Early data validation.
-   Asynchronous I/O.
-   All endpoints are covered with tests.
-   Intuitive immutable DTOs.
-   Pipelines that run on both Windows and Linux operating systems.
-   Cross platform (uses .NET Standard).

## 📦 NuGet

We have published the library as [Mews.Fiscalizations.Germany](https://www.nuget.org/packages/Mews.Fiscalizations.Germany/).

## 👀 Code Examples

Listed below are some of the common examples. If you want to see more code examples, please check the [Tests](https://github.com/MewsSystems/fiscalizations/tree/master/src/Germany/Mews.Fiscalizations.Germany.Tests).

Fiskaly Client can be created using the **ApiKey** and **ApiSecret** which can be created through Fiskaly dashboard.

```csharp
var client = new FiskalyClient(ApiKey, ApiSecret);
```

All endpoints require providing a valid **accessToken**

```csharp
var accessToken = await client.GetAccessTokenAsync();
```

In order to report an invoice to the German authorities, we would have to start a transaction and then finish it (change the state to **FINISHED** and provide the invoice to be reported.).

**Creation of a new invoice**

There are 3 required properties for creating an invoice:
1. **Invoice type** (invoice or receipt).
2. **Payments** which is a list of the amounts paid, type of payment, and the currency.
3. **Items** which is a list of the item amounts and the VAT rate ("NORMAL" "REDUCED_1" "SPECIAL_RATE_1" "SPECIAL_RATE_2" "NULL") -> ("19" "7" "10.7" "5.5" "0").

```csharp
var bill = new Bill(
    type: BillType.Receipt,
    payments: new List<Payment>() { new Payment(25, PaymentType.Cash, "EUR") },
    items: new List<Item>() { new Item(25, VatRateType.Normal) }
);
```

1. To start a transaction, we would need to provide valid **ClientId** and **TssId** which can be created through fiskaly dashboard or by calling **CreateClientAsync** for creating the client and **CreateTssAsync** for creating the TSS which will be described below, and a unique **id** for the transaction.
2. To finish a transaction, we would need to provide the **ClientId**, **TssId**, and the invoice to be reported and the transaction id that we specified in the step above.
(lastRevision is used for the preservation of order of subsequent calls).

Example:
```csharp
var transactionId = Guid.NewGuid();
var startedTransaction = await client.StartTransactionAsync(accessToken, clientId, tssId, transactionId);
var endedTransaction = await client.FinishTransactionAsync(accessToken, clientId, tssId, InvoiceToReport, transactionId, lastRevision: "1");
```

**Creation of a new client id**
```csharp
var client = await client.CreateClientAsync(accessToken, TssId);
var clientId = client.SuccessResult.Id;
```

**Creation of a new Tss id**
```csharp
var tss = await client.CreateTssAsync(accessToken, TssState.Initialized, description: "Creating a test TSS.");
var tssId = tss.SuccessResult.Id;
```

repository: abdallahbeshi/fiscalizations

repo_name: abdallahbeshi/fiscalizations


text:
---
title: Sharetribe Flex resources
slug: flex-operator-resources
updated: 2020-11-20
category: operator-guides
ingress:
  Index of resources to help you get familiar with Sharetribe Flex
published: true
---

If Flex is new to you, these index of articles will help you get
familiar with the most important aspects to consider and content to read
in the process of building your marketplace. This index contains many
links to information you will need: from resources with Flex information
and explanation of how different aspects of the Flex environment work,
to resources about building a marketplace business in general from our
[Marketplace Academy](https://www.sharetribe.com/academy).

Feel free to dive deep into all the Flex documentation as well as the
Marketplace Academy if you need to. Remember that the Sharetribe team is
here to help in case you have any question.

## Flex general information

These articles will help you get an overview of what is Flex and its
components and what you need to customize your Flex marketplace.

- Flex Overview:
  https://www.sharetribe.com/docs/background/introducing-flex/
- How to build a marketplace with Flex:
  https://www.sharetribe.com/docs/background/how-to-build-and-launch-with-flex/
- What development skills are needed to customize Flex:
  https://www.sharetribe.com/docs/background/development-skills/
- Flex Templates for Web (FTW):
  https://www.sharetribe.com/docs/background/concepts/#flex-template-for-web-ftw

## Flex Template for Web

These two articles will get started with the front end template that we
have made available for you. Though, bear in mind that you don't need to
use it, if you have different front end plans.

- Getting started with FTW:
  https://www.sharetribe.com/docs/tutorials/getting-started-with-ftw/
- Customization checklist:
  https://www.sharetribe.com/docs/guides/ftw-customization-checklist/

## Transaction Process

These articles contain a primer on how to understand and customize your
transaction process.

- Transaction Process information:
  https://www.sharetribe.com/docs/background/transaction-process/
- Flex CLI:
  https://www.sharetribe.com/docs/tutorials/getting-started-with-flex-cli/
- Custom Pricing:
  https://www.sharetribe.com/docs/guides/how-to-customize-pricing/
- Time-based bookings:
  https://www.sharetribe.com/docs/guides/how-to-take-time-based-bookings-into-use/

## Extended data

The following articles explain how to add extended data (extra fields)
to your marketplace users or listings and how to leverage this data to
create filters in your search page.

- Extended data information:
  https://www.sharetribe.com/docs/references/extended-data/
- How to extend listing data in FTW:
  https://www.sharetribe.com/docs/guides/how-to-extend-listing-data-in-ftw/
- How to setup search filters in FTW:
  https://www.sharetribe.com/docs/guides/how-to-change-search-filters-in-ftw/

## Stripe

Flex uses Stripe Connect with Custom accounts for its payment gateway.
Integrating other payment gateways is not possible at the moment. The
following articles clarify the way Stripe Connect works and how to set
it up with Sharetribe Flex.

- Using Stripe Connect with Custom accounts:
  https://stripe.com/docs/connect/custom-accounts
- Stripe Connect with Custom accounts works only when the marketplace
  operator and providers have accounts located in the following
  countries: https://stripe.com/docs/connect#availability
- How to setup and use Stripe in Flex:
  https://www.sharetribe.com/docs/guides/how-to-set-up-and-use-stripe/

## Launch

Ready to launch? Consider these articles.

- Going live process:
  https://www.sharetribe.com/docs/background/how-to-build-and-launch-with-flex/#4-going-live
- How to deploy FTW to production:
  https://www.sharetribe.com/docs/guides/how-to-deploy-ftw-to-production/

## Developer Resources

If you are new to Flex and have some technical knowledge and want to
move forward with your project, check out this content.

- Flex Documentation: https://www.sharetribe.com/docs/
- Flex API Reference: https://www.sharetribe.com/api-reference/
- FTW-daily Repo: https://github.com/sharetribe/flex-template-web
- FTW-hourly Repo: https://github.com/sharetribe/ftw-hourly
- Flex Developer Slack Channel: https://www.sharetribe.com/flex-slack
- Flex Support Email<EMAIL_ADDRESS>
## Design Resources

You need a push in the right direction for designing your marketplace?
Check out the following design articles.

- Designing your marketplace in Flex:
  https://www.sharetribe.com/docs/background/how-to-build-and-launch-with-flex/#2-designing-your-marketplace
- FTW-daily Sketch file:
  https://drive.google.com/drive/folders/171T-lYUGJURrAF5qCtTZ0298WPhhG0SG
- Customer Journey Map Toolkit:
  https://drive.google.com/drive/folders/1kI8-PDF6gi926AqlnXaMH66bJhmJbmvI?usp=sharing
- Partner Toolkit:
  https://drive.google.com/drive/folders/1Gcr54bvvajqSxZG-4ktLApcn12mg_PCD?usp=sharing

## Marketplace Resources

General information to build a marketplace business.

- A practical guide for building an online marketplace business:
  https://www.sharetribe.com/academy/guide/
- How to build a Minimum Viable Platform:
  https://www.sharetribe.com/academy/how-to-build-a-minimum-viable-platform/
- How to build the supply of your marketplace:
  https://www.sharetribe.com/academy/how-to-build-supply-marketplace/
- How to launch your marketplace:
  https://www.sharetribe.com/academy/how-to-launch-your-marketplace/

repository: TalAter/flex-docs

gha_license_id: NOASSERTION

repo_name: TalAter/flex-docs


text:
# dojo

Dojo is a web app for D&D (5E) dungeon masters.

You can find it at [https://andyaiken.github.io/dojo/](https://andyaiken.github.io/dojo/).

## Features

### Monster Designer

You can build your own monsters with the built-in monster designer, which lets you check your creations against other similar monsters. Or you can let the app do it for you - just select a few monsters and let it splice them together into a new hybrid monster.

![Monster](./public/screenshots/monster.png)

The app comes with all the standard monsters from the official D&D system reference document, and you can also quickly import a monster from D&D Beyond.

![Monsters](./public/screenshots/monsters.png)

### Encounter Builder

The encounter builder allows you to build combat encounters, and even split an encounter into multiple waves. You can check your encounter's difficulty for a group of PCs, and the calculations are all done for you. You can even ask it to build you a totally random encounter.

![Encounter difficulty](./public/screenshots/diff.png)

### Tactical Maps

You can create your own tactical maps by placing and dragging map tiles around a board, or by importing image files. Your map can include standard features like doors and stairs, and you can add notes to significant locations on the map.

![Map](./public/screenshots/map.png)

With the click of a button you can add a random room to the map, or generate an entirely random three-room dungeon delve or a larger ten-room dungeon.

Maps you create can then be used in the...

### Combat Manager

The app can help you to run combat encounters, taking care of the initiative order, monster hit points, and conditions. You can see at a glance which combatants are concentrating, which are prone or unconscious, which are affected by spells like *bless* and *bane*. If your encounter contains a monster with a rechargable action, the app will prompt you to roll to recharge it. The app will also remind you about legendary actions and lair actions.

If you're using a tactical map for your encounter, you can move tokens around the map, or add overlays to represent significant regions (such as spell effects or monster auras).

![Combat](./public/screenshots/combat.png)

If you have a second display, the app can show a separate window including the initiative list (which includes relevant condition information) and a copy of the map, if you're using one.

### DM Tools

Who needs a DM screen, when you have all this at your fingertips?

- a **die roller** if you want to go all-digital
- a **name generator** for NPCs
- **references** for skills, conditions, and combat actions
- a **text generator** that can quickly give you whole paragraphs of Elvish, Dwarvish, Orcish, Draconic, and so on

![DM tools](./public/screenshots/dmtools.png)

---
---

## Contributing

Dojo is written in TypeScript / JavaScript, using React and SCSS. If you would like to contribute to this project, you are welcome to do so.

### Initial set up

You will need to have `Git` and `Node.js` installed.

* Open a terminal in the root folder
* Run `npm install`
* Check that you're using the latest dependencies by running `npm update`

### Compiling and running the app

* Open a terminal in the root folder
* Run `npm start`

Your default browser should open; if it does not, open it and navigate to [http://localhost:3000](http://localhost:3000).

The page should automatically reload if you make edits.

If there are any build errors, you will see them in the terminal and the browser debug console.

### Making a change to the app

Check that your changes don't break the project's style rules:

* Open a terminal in the root folder
* Run `npm run lint`

Remember to update the app version number in `package.json` before pushing any change to the repository.

### Publishing a new version of the app

* Open a terminal in the root folder
* Run `npm run deploy`

This will build the app in the `build` folder and attempt to deploy it.

repository: revgizmo-forks/dojo

repo_name: revgizmo-forks/dojo


text:
# Hack Kosice Marathon: Calculator

*A template for projects submitted to HK Marathon 2021. You can [fork this repository](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) and use it as a starting point.*

## Team

*JustUs*

### Team members

- Mikuláš Zelenák, Spojená škola svätej Uršule
- Viera Michaela Blažíčková, Spojená škola svätého Františka z Assisi

## Description

*After covid there will be lots of and companies who will have hybrid workplaces. Employees will work both from home and physically. Companies will have many partially used or unused offices. Our calculator will help you calculate the most optimal solution so you won't have unnecessary unused or half empty offices.*

## Protoype

*It can du some basic calculations and give you useful information. It works properly and doesn't crush. The backend provides proofing so you can enter only valid information.*

## How to try

*Please watch video about our app here: https://youtu.be/-9Px-zBwtCc
Or if you have python, django and know how to run it localy you can download our ap and try it on your local maschine*

## Presentation

*We present our project vith this video: https://youtu.be/-9Px-zBwtCc*
*Feel free to pause it any time you want and take a better look*

## Challenges and accomplishments

*We learnd there are many challenges when working with backend. we had to write so many conditions for our project to work properly and without any bugs*

*We are proud of our algorithms and their use in our app. We are also proud of all of conditions we made so it looks good and says the right things and makes sense.*

## Next steps

*We are going to work on the looks of our App. We also need to fix small bug that coases that it maight in some cases calculate that you need more offices (1-3 (we think)) this bug occur only in Advanced Office Calculator and Unused Offices Calculator. we also plan to add more useful calculators and more advanced calculators*

## License

*This repository includes an [unlicense](http://unlicense.org/) statement though you may want [to choose a different license](https://choosealicense.com/).*

license: Unlicense

repository: Mi-Zel/calculator

branch_name: refs/heads/main

repo_name: Mi-Zel/calculator


text:
# php client

[![Latest Stable Version](https://poser.pugx.org/upsub/client/version)](https://packagist.org/packages/upsub/client)
[![Build Status](https://travis-ci.org/upsub/client-php.svg?branch=master)](https://travis-ci.org/upsub/client-php)

This is the php client for UpSub, its communicating to the [Dispatcher](https://github.com/upsub/dispatcher) via the http
protocol. This client is write only and can therefore not listen for message from the Dispatcher.
> Only clients with subscription support can listen for message, see the [JavaScript client](https://github.com/upsub/client-js).

## Install
The client is published to packagist and can be installed with [`composer`](https://getcomposer.org/).
```sh
composer require upsub/client
```

## Usage
```php
<?php
use UpSub\Client;

$client = new Client('http://localhost:4400', [
  // options
]);
```

#### Options
- `name: string`: Name the connection, useful for debugging.
- `appID: string`: App identifier for the dispatcher authentication.
- `secret: string`: Secret key for authentication.
- `timeout: int`: If the http request exceeds the timeout then terminate the request, default is `5` seconds.

#### Create a channel
The best way to structure eventstreams is by scoping it in different channels.
```php
<?php
// Single channel
$channel = $client->channel('channel');

// Multiple channels
$multiChannel = $client->channel('channel-1', 'channel-2');
```

#### Send message
Send message to the UpSub [Dispatcher](https://github.com/upsub/dispatcher).
```php
<?php
// Send message from the channel
$channel->send('event', [ 'key' => 'value' ]);

// Send message directly from client
$client->send('event', 'my message...');
```

## License
Released under the [MIT License](https://github.com/upsub/client-php/blob/master/LICENSE)

repository: upsub/client-php

gha_language: PHP

repo_name: upsub/client-php


text:
# Google Drive backend

## Parameters
Possible parameters are:
- `google_client_id`: The Google Client ID
- `google_client_secret`: The Google Client Secret, it shall never be shared
- `token_file`: The path of the token file that will be created
- `base_path`: The base path of the Google Drive folder

_Note:_ The token file will be updated regularly (every day). It's important that the server can write the token file
after its initial creation.

## How to use it
### Create an app
You can follow
[these instructions](https://medium.com/swlh/google-drive-api-with-python-part-i-set-up-credentials-1f729cb0372b).

### Use the created client credentials
You can either define the `google_client_id` and `google_client_secret` access params or specify the `GOOGLE_CLIENT_ID`
and `GOOGLE_CLIENT_SECRET` environment variables.

You should have a config file looking like this one:
```json
{
  "accesses": [
   {
      "user": "gdrive",
      "pass": "gdrive",
      "fs": "gdrive",
      "params": {
        "google_client_id": "*****.apps.googleusercontent.com",
        "google_client_secret": "*****",
        "basePath": "/ftp"
      }
    }
  ]
}
```

### Connect for the first time
You should run the ftpserver in interactive mode.
The first time you will login with the "gdrive" user, the server will ask you to open a link, wich
will authorize the app you just created and return a code. This code will allow the server to create
a token file (named `gdrive_token_$username.json` by default).

repository: fclairamb/ftpserver

gha_language: Go

repo_name: fclairamb/ftpserver


text:
# WebPDemo

### [https://support.cloudinary.com/hc/en-us/articles/202521522-How-can-I-make-my-images-load-faster-](https://support.cloudinary.com/hc/en-us/articles/202521522-How-can-I-make-my-images-load-faster-)

# How can I make my images load faster?
 Avatar  Amit Sharon ,4 months ago Updated
>When your images load faster, your website's / mobile app's user experience is enhanced and metrics such as time on site and conversion rate improve as a result.  When you use Cloudinary to deliver your images, they are served using market-leading Akamai CDN, so the caching and delivery part is solved. As for reducing image size, the following list includes the most effective and easy-to-implement tips for optimizing your images.

### 1. Scale images to display size
In your website or application you usually need to display images in specific dimensions, defined by the website's / application's graphic design. Use Cloudinary to smartly resize images to their actual display size, instead of having the client download large images and scale them on the client side. On Web and mobile Web you can automate resizing by taking advantage of Cloudinary's support for responsive design.

Use one of Cloudinary's multiple crop modes to achieve the exact visual result you are looking for.

### 2. Adjust image quality
Cloudinary allows you to control the image quality - the higher the quality is, the heavier the resulting image is, and vice versa. Quality is configured in a 0-100 scale, or using Cloudinary's automatic quality setting. The default quality used by Cloudinary when a quality setting is not provided can be configured in the Cloudinary UI under Settings->Upload.

Note that quality adjustment doesn't impact PNGs, because it is a lossless format (see below about auto-converting PNG to JPG).

Expected images size / bandwidth save - between 10%-50% with auto quality (q_auto).

### 3. Auto-select file format based on client detection
While the JPG format is most widely supported, some clients support more advanced and efficient file formats. The Chrome browser and Android devices (and even iOS devices when using Google's libwebp) support the Google WebP format, while the Internet Explorer browser supports Microsoft's JPEG XR format.

On website, including mobile web, simply set 'fetch format' to 'auto', and let Cloudinary auto-select the optimal file format for you (note: requires using Cloudinary's built-in Akamai CDN). For further reading see our WebP and JPEG-XR blog posts.

On native mobile app, set file format explicitly based on client-side logic by setting the 'format' attribute (or simply changing the file extension, e.g. http://res.cloudinary.com/demo/image/upload/sample.webp). Note that WebP is supported natively on Android (version 4 and up for lossy, and version 4.2.1 for lossless and transparency). On iOS it can be supported with libwebp, however, as WebP is not a native format on iOS decoding is not as efficient and there might be a performance toll, especially on older devices.

Note that setting fetch format to 'auto' ('f_auto' on the URL) cannot be part of a named transformation, as it should explicitly exist on the URL. It can be used together with a named transformation though, for example 't_my_transformation,f_auto'.

Expected images size / bandwidth save - about 30%.

### 4. Convert PNG to JPG
The PNG format supports transparency while JPG doesn't. But PNG files are also much larger, and in many cases they are used by mistake in use cases where transparency not really needed. In these case it makes sense to convert them JPG.

Luckily, Cloudinary can auto-detect if PNG has transparency (alpha channel) and convert it to JPG in case it doesn't. To take advantage of that use Cloudinary's 'lossy' flag. On Web use the 'lossy' flag combined with the 'auto' fetch format (on URL this would be 'fl_lossy,f_auto') so that Cloudinary will also automatically convert to more efficient formats, such as WebP, when possible depending on the user browser.

In addition to auto-detection using the 'lossy' flag, it is also possible to force conversion to JPG by setting the 'format' parameter to 'jpg' when using Cloudinary's client library, or by simply changing the file extension on URL.

Expected images size / bandwidth save - up to 85%.

### 5. Convert Animated GIF to WebM/MP4
If your website or application use short animated GIF-based video sequences, you can substantially reduce the size of these short video sequences by converting them to WebM/MP4.

In case you are looking to implement an autoplay experience, note that videos cannot be auto-played in iOS 9 and earlier. These restrictions have been lifted as of iOS 10 under certain conditions.

Expected images size / bandwidth save - up to 95%.

More optimization - Cloudinary reports and actionable optimization tips
Cloudinary offers deep reporting and actionable optimization tips based on your specific usage patterns. Visit the Reports page in your Cloudinary web console to get insights and optimization suggestions.

## Quick tips
Optimize:
On Web use ‘f_auto,fl_lossy,q_auto’
On native mobile apps use ‘f_webp,q_auto’, and on iOS make sure to include Google’s libwebp.
Scale: Make sure to scale the images to the right size. Use Cloudinary's automatic responsive support on Web.
Social networks: Use optimized image URL in the 'og:image' tag used for social sharing.

### Gif Demo
https://note.youdao.com/share/?id=a364a366b3ee7e9502c64c9e47835f03&type=note#/
source:https://www.jianshu.com/p/d8976cee3a82
Android源码阅读——GIF解码（如何提取各帧图片）

### 使用UIImage读取GIF图片的不足
UIImage类在UIKit框架中，是我们最常使用的存储图片类。该类提供了可以使用图片路径或是图片数据来实例化的类方法。UIImage类底层采用ImageIO框架来读取图片数据，下图分别为＋imageWithContentsOfFile:和＋imageWithData:调用的堆栈。

![image io](https://upload-images.jianshu.io/upload_images/1495816-f35f8bb6e14eb42c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)

从堆栈中我们可以看到图片读取的大致流程如下：

根据文件路径或是数据生成CGImageSource；
然后调用CGImageSourceCreateImageAtIndex方法获取一帧的图片，类型为CGImage;
让UIImage对象持有该CGImage。
在流程的第一步生成的CGImageSource，仍然保留着GIF的全部信息。而在流程的第二步中出了问题。动态的Gif图与静态格式图片不同，它包含有多张的静态图片。CGImageSourceCreateImageAtIndex只能返回索引值的图片，丢失了其他的图片信息。因此，我们只获取到了其中的一帧图片。出于好奇，我选择了一张只有四帧完全不同的Gif图，通过测试观察，UIImage获取的是第一帧的图片。既然我们不能用UIImage或CGImage来处理Gif图，我们是否可以降级，采用ImageIO框架来处理呢。答案是肯定的。
参考：https://www.jianshu.com/p/5c870860c187

### Loading images in iOS apps faster with progressive JPEGs
[Loading images in iOS apps faster with progressive JPEGs](https://www.airpair.com/ios/posts/loading-images-ios-faster-with-progressive-jpegs)

### First take: progressive download
One solution to this problem is progressive downloading – a technique which enables displaying parts of an image while it is being fetched. This can be quickly implemented with Apple's ImageIO framework and a little effort.

While progressive downloading certainly improves the experience a bit, it still isn't miracles.

### A better way: progressive JPEG
Progressive JPEG is a format which stores multiple passes of an image of progressively higher detail. When such image is being loaded, the reader would first see a low-quality pixelated version which would gradually improve in detail, until the image is fully downloaded. The idea is to display the visuals as early as possible to entertain the visitor and make the layout look as designed.

See how progressively downloading a regular JPEG (left) is different from displaying progressive JPEG (right): THE GIF

Most likely you've already seen this approach – it's been very common on the web for quite some time. However, there is no out-of-the-box library for displaying progressive JPEGs in iOS apps. Photos in the Facebook iOS app have been loading in this manner for some several months already, but their solution is not publicly available.

### Concorde helps
When there is no wheel at hand, it's a perfect opportunity to invent one. I have built Concorde – an open-source library for decoding progressive JPEGs on iOS and OS X. Download, plug in your projects, and make the user experience better.

#### Install and use
Install Concorde via CocoaPods (version 0.36 or higher, as the code is partially written in Swift):

pod 'Concorde'
Then use CCBufferedImageView which progressively downloads and displays an image:

let imageView = CCBufferedImageView(frame: ...)
if let url = NSURL(string: "http://example.com/yolo.jpg") {
    imageView.load(url)
}
If you use Contentful, install the subspec:

pod 'Concorde/Contentful'
Then replace your calls to UIImageView with CCBufferedImageView to automatically use progressive JPEGs, in case you have been using the UIImageView category before. This will work regardless whether the original images were converted to progressive JPEGs or not – Contentful delivery API takes care of converting the assets.

Of course, you can also manually integrate the framework as a subproject or download it as a binary build.

#### Implementation
Facebook based their solution on libjpeg-turbo, a variant of the commonly used libjpeg, accelerated by using SIMD instructions. This seemed like the right approach, so Concorde is also built on that.

Since Apple's WebKit already supports progressive JPEGs, the solution is based on the existing code. The basic flow of decoding buffered images, which is their jargon for progressive JPEGs is as follows:

jpeg_create_decompress()
set data source
jpeg_read_header()
set overall decompression parameters
cinfo.buffered_image = TRUE;    /* select buffered-image mode */
jpeg_start_decompress()
for (each output pass) {
    adjust output decompression parameters if required
   jpeg_start_output()         /* start a new output pass */
   for (all scanlines in image) {
       jpeg_read_scanlines()
     display scanlines
   }
   jpeg_finish_output()        /* terminate output pass */
}
jpeg_finish_decompress()
jpeg_destroy_decompress()
The part which deals directly with libjpeg-turbo is written in Objective-C, so that the framework does not have to expose all of libjpeg.h to the outside world. It also deals with a little oddity of error handling.

Fatal errors are handled by doing a longjmp which is a direct jump to a memory address, to some error-handling code. This was a bit painful to deal with, because a part of the libjpeg calls are made in the initializer of CCBufferedImageDecoder. But course we cannot jump back there once the instance has been initialized! The solution was to have a first jump target for errors during the initialization, and a second one for errors happening later in the process.

Hopefully you would be happy to know that since I’ve dealt with all this already, you can simply enjoy displaying progressive JPEGs in the apps you build.

### Do I have to convert all my images?
Media content producers might wonder if they have to convert all their standard JPEGs into progressive ones, how to do it, and how do they check if a JPEG is progressive.

If you use Contentful for content delivery, please stop reading this paragraph. The Contentful API takes care of it all: regardless of the original format, the Contentful delivery API processes all the media assets to make them mobile-friendly.

Generally, to make an image loadable in this modern fashion – yes, you have to prepare the files so they are in the appropriate progressive format. You can do that with different tools: for example, Photoshop, ImageMagick, or command-line-friendly jpegtran.

To check whether a JPEG is progressive or not, use this online tool or use command line interface of ImageMagick.


text:
---
title: Visualizing some polynomial roots with Datashader
layout: post
comments: true
author: François Pacull
tags:
- Python
- Roots
- Polynomial
- Datashader
- Cython
- Pandas
- NumPy
---

Last week-end I found this interesting [tweet](https://twitter.com/souplovr23/status/1591228278454767616?s=20&t=w8A4XrwQGsax_zbbkY9GIg) by [sara](https://twitter.com/souplovr23):

The above figure shows all the complex roots from the various polynomials of degree 10 with coefficients in the set $\left\\{ -1, 1 \right\\}$. It made me think of [Bohemian matrix](https://en.wikipedia.org/wiki/Bohemian_matrices) eigenvalues, and I guess it is related (through the polynomial's *companion matrix*).

If we think of the general polynomial:

$$P(x) = \sum_{i=0}^m  a_i \; x^{m-i}$$

we have in the above tweet, $m=10$ and $a_i \in \left\\{-1 , 1 \right\\}, \;  \forall i \geq 0$. We are going to keep this set of possible values for the polynomial coefficients, but increase the polynomial degree $m$ a little bit.

The roots of $P(x)$ are going to be computed with [NumPy](https://numpy.org/) and [Cython](https://cython.org/) (we could have done it with [Numba](https://numba.pydata.org/) as well). Then we are going to visualize the point density in the complex plane with [datashader](https://datashader.org/), which is the appropriate tool in Python for such a visualization I think.

## Imports

```python
import colorcet
import datashader as ds
import numpy as np
import pandas as pd
from datashader import tf

%load_ext cython
```

Package versions:

    Python version       : 3.10.6
    colorcet             : 3.0.1
    cython               : 0.29.32
    datashader           : 0.14.2
    numpy                : 1.23.4
    pandas               : 1.5.1
    OS                   : Linux

## Cartesian product of all coefficient values

We first evaluate the number of distinct polynomials with coefficients in the given set. This corresponds to a Cartesian product of the provided set $\left\\{-1 , 1 \right\\}$ with itself $m+1$ times:

```python
coef_values = [-1, +1]
coef_values_np = np.array(coef_values, dtype=np.int8)

m = 23  # degree of the polynomial
n = np.power(len(coef_values), m + 1)
print(f"we have {n} distinct polynomials of degree {m}")
```

    we have 16777216 distinct polynomials of degree 23

With `np.roots`, the polynomials $P(x) = a_0 \; x^m + a_1 \; x^{m-1} + ... + a_{m-1} \; x + a_m$ are only defined by the coefficients, in this order:

$$\left[a_0 \; a_1 \; ... \; a_{m-1} \; a_m\right]$$

Let's generate the coefficient values:

```python
poly_coefs_all = np.stack(np.meshgrid(*((m+1) * [coef_values_np])), -1).reshape(-1, m+1)
```

```python
for poly_coefs in poly_coefs_all[:5]:
    print(poly_coefs)
```

    [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
    [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1]
    [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1 -1]
    [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1  1]
    [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1  1 -1 -1]

```python
poly_coefs_all.shape
```

    (16777216, 24)

## Polynomial roots

Now we compute the roots of each of the 16777216 polynomials:

```cython
%%cython --compile-args=-Ofast
# cython: language_level=3, boundscheck=False, wraparound=False, embedsignature=False, initializedcheck=False

import numpy as np

cimport numpy as cnp

cdef void loop_over_polys_cython(cnp.complex128_t[:,:] roots_all, cnp.int8_t[:,:] poly_coefs_all, ssize_t n, ssize_t m):

    cdef:
        ssize_t i, j

    roots = np.empty(m-1, dtype=np.complex128)
    for i in range(n):
        roots = np.roots(np.array(poly_coefs_all[i, :], dtype=np.float64))
        for j in range(m-1):
            roots_all[i, j] = <cnp.complex64_t>roots[j]

cpdef loop_over_polys(poly_coefs_all):
    cdef:
        ssize_t n = <ssize_t>poly_coefs_all.shape[0]
        ssize_t m = <ssize_t>poly_coefs_all.shape[1]

    roots_all = np.empty((n, m-1), dtype=np.complex128)

    cdef cnp.complex128_t[:,:] roots_all_view = roots_all
    loop_over_polys_cython(roots_all_view, poly_coefs_all, n, m)
    return roots_all
```

This computation could be done in parallel:  we could assign some chunks of polynomials to each job. However, this is sequential in the present short post. Since the roots are computed with NumPy on the Python level, we cannot release the GIL and use a `prange` loop from Cython. The computation takes around 43 minutes on my laptop.

```python
%%time
roots_all = loop_over_polys(poly_coefs_all)
```

    CPU times: user 43min 50s, sys: 6.1 s, total: 43min 56s
    Wall time: 43min 48s

```python
roots_all.shape
```

    (16777216, 23)

We transform the 2D array into a 1D array:

```python
roots_all = roots_all.flatten()
```

```python
roots_all.shape
```

    (385875968,)

```python
roots_all[:5]
```

    array([0.96592581+0.25881904j, 0.96592581-0.25881904j,
           0.86602539+0.5j       , 0.86602539-0.5j       ,
           0.70710677+0.70710677j])

## Plot with datashader

Finally, we separate the real and imaginary part of the roots, load them into a Pandas dataframe and plot them with datashader.

```python
df = pd.DataFrame(data={"x": roots_all.real, "y": roots_all.imag})
```

```python
plot_width = 1600
plot_height = int(
    np.round((df.y.max() - df.y.min()) * plot_width / (df.x.max() - df.x.min()))
)
cvs = ds.Canvas(plot_width=plot_width, plot_height=plot_height)
agg = cvs.points(df, "x", "y")
img = ds.tf.shade(agg, cmap=colorcet.dimgray, how="eq_hist")
img = tf.set_background(img, "black")
img
```

{% if page.comments %}

Please enable JavaScript to view the comments powered by Disqus.
{% endif %}

gha_language: SCSS


text:
# Beautiful Order Documents [![Docker Pulls](https://img.shields.io/docker/pulls/oozz/beautiful-order-documents.png)](https://hub.docker.com/r/oozz/beautiful-order-documents/)

This app shows a list of orders for a configured shop.
Each order has a link, that triggers rendering the order invoice as a PDF.

## Screenshot

![Screenshot of the app](screenshot.png)

Explanation:

* **left**: list of orders
* **right**: PDF that is generated when an order from the list is clicked
* **top**: using ePages Now&Beyond REST API
* **bottom**: using ePages Base/Now REST API

## Running it

The Makefile does most of the heavy lifting for you:

```
# 0. Build the image
make docker_build

# 1. Create docker environments from the templates
make docker_init_env

# 2. Edit env.list or/and env-beyond.list to match your app's credentials
#    using an editor of your choice

# 3a. To run the ePages Base/Now version:
make docker_run

# 3b. To run the ePages Now&Beyond version:
make docker_run_beyond
```

repository: ooz/epages-rest-python-examples

repo_name: ooz/epages-rest-python-examples