text:
# Jar

- [1. Create Jar File](#1-create-jar-file)
- [2. Testing the JAR file](#2-testing-the-jar-file)
- [3. Creating JAR manifests](#3-creating-jar-manifests)
- [4. Adding extra metadata to the JAR](#4-adding-extra-metadata-to-the-jar)
- [5. JAR file best practices](#5-jar-file-best-practices)
- [6. Signing JAR files](#6-signing-jar-files)
  - [6.1. Generating a signing key](#61-generating-a-signing-key)
  - [6.2. Signing the file](#62-signing-the-file)
- [7. Testing With Jar Files](#7-testing-with-jar-files)

我的总结：

- （1） 创建Jar文件
  - 使用`<jar>` Task
  - 添加meta data，例如`manifest.mf`
- （2） 对Jar文件进行签名
- （3） 对Jar文件进行JUnit测试

The **JAR** file is the central redistributable of Java. It has derivatives, the most common of which are the **WAR** and **EAR** files for web applications and Enterprise applications, respectively. Underneath, they’re all **Zip archives**. Zip files/archives can store lots of files inside by using a choice of compression algorithms, including “uncompressed.”

The **JAR**, **WAR**, and **EAR** archives are all variations of the basic Zip file, with a text manifest to describe the file and potentially add signing information. The **WAR** and **EAR** files add standardized subdirectories to the JAR file to store libraries, classes, and XML configuration files. This can make the **WAR** and **EAR** files self-contained redistributables.

Building and manipulating JAR files is a common activity; anyone who uses Ant to build a project will soon become familiar with the `<zip>` and `<jar>` tasks.

A **JAR** file stores **classes** in a simple tree resembling a package hierarchy, with any **metadata** added to the `META-INF` directory注：Jar文件中包含了两类文件，class文件和meta data文件。. This directory contains a manifest file `MANIFEST.MF`, which describes the JAR file to the classloader.

## 1. Create Jar File

The `<jar>` task creates a manifest file unless you explicitly provide one.

```xml
<target name="jar" depends="compile">
    <jar destfile="${dist.dir}/d1-core.jar"
         duplicate="preserve"
         compress="false">
        <fileset dir="${build.classes.dir}"/>
    </jar>
</target>
```

The `compress` attribute controls whether the archive is compressed. By default `compress="true"`, but an uncompressed archive may be faster to load. Compressed files do download faster, however.注：这里讲compress属性

One thing that is important is that all the `<jar>` targets in this book have `duplicate="preserve"` set. The `duplicate` attribute tells Ant what to do when multiple filesets want to copy a file to the same path in the archive. It takes three values

- `add`: silently add the duplicate file. This is the default.
- `preserve`: ignore the duplicate file; preserve what is in the archive.
- `fail`: halt the build with an error message.

The default option, `add`, is dangerous because it silently corrupts JAR files. Ant itself will ignore the duplicate entry, and so will the JDK `jar` program. Other tools, such as the `javac` compiler, aren’t so forgiving, and will throw an `IndexOutOfBoundsException` or some other obscure stack trace if they encounter duplicate entries. If you don’t want to have users of your application or library making support calls, or want to waste mornings trying to track down these problems in other people’s libraries, change the default value! The most rigorous(谨慎的) option is `fail`, which warns of a duplication; `preserve` is good for producing good files without making a fuss.

The current preferred practice for libraries注：这里讲的是命名规则 is to create an archive filename from a **project name** along with a **version number** in the format `d1-core-0.1.jar`. This lets users see at a glance what version a library is. We can support this practice with some property definitions ahead of the `jar` target:

```xml
<property name="project.name" value="${ant.project.name}" />
<property name="project.version" value="0.1alpha" />
<property name="target.name" value="${project.name}-${project.version}.jar" />
<property name="target.jar" location="${dist.dir}/${target.name}" />

<target name="jar" depends="compile">
    <jar destfile="${target.jar}"
         duplicate="preserve"
         compress="false">
        <fileset dir="${build.classes.dir}"/>
    </jar>
</target>
```

This target will now create the JAR file `dist/diary-core-0.1alpha.jar`. The `<jar>` task is **dependency-aware**; if any source file is newer than the JAR file, the JAR is rebuilt. Deleting source files doesn’t constitute a change that merits a rebuild; a clean build is needed to purge those from the JAR file.

There is an `update` attribute that looks at dependencies between **source files** and **files stored inside the archive**. It can be used for incremental JAR file updates, in which only changed files are updated. Normally, we don’t bother with things like this; we just rebuild the entire JAR when a source file changes. JAR creation time only becomes an issue with big projects, such as in EAR files or WAR files.

Once created, we need to check that the JAR file contains everything it needs.

## 2. Testing the JAR file

Just as there’s a `<jar>` task, there’s an `<unjar>` task to expand a JAR, a task which is really an alias of `<unzip>`. The task expands the Zip/JAR file into a directory tree, where you can verify that files and directories are in place either manually or by using the `<available>` and `<filesmatch>` conditions. Graphical tools may be easier to use, but they have a habit of changing the case of directories for usability, which can cause confusion. WinZip is notorious for doing this, making any all-upper-case directory lower-case and leading to regular bug reports in Ant, bug reports that are always filed as “INVALID”.

Expanding a file is easy:

```xml
<target name="unjar" depends="dist" >
    <unjar src="${target.jar}" dest="${build.dir}/unjar"/>
</target>
```

The `<unjar>` task takes a source file, specified by `src`, and a destination directory, `dest`, and unzips the file into the directory, preserving the hierarchy. It’s dependency-aware; newer files are not overwritten, and the timestamp of the files in the archive is propagated to the unzipped files.

You can selectively unzip parts of the archive, which may save time when the file is large. To use the task to **validate the build process after the archive has been unzipped**, you should **check for the existence of needed files** or, perhaps, even their values:

```xml
<target name="test-jar" depends="jar" >
    <property name="unjar.dir" location="${build.dir}/unjar"/>
    <unjar src="${target.jar}" dest="${unjar.dir}">
        <patternset>
            <include name="d1/**/*"/>
        </patternset>
    </unjar>

    <condition property="jar.uptodate">
        <filesmatch file1="${build.classes.dir}/d1/core/Event.class" file2="${unjar.dir}/d1/core/Event.class"/>
    </condition>

    <fail unless="jar.uptodate" message="file mismatch in JAR"/>
</target>
```

Here we expand classes in the archive and then verify that a file in the expanded directory tree matches that in the tree of compiled classes. Binary file comparison is a highly rigorous form of validation, but it can be slow for large files.

**To be honest, we rarely bother with these verification stages**. Instead, we include the JAR file on the classpath when we run our unit tests. This is the best verification of them all. If we left something out of the JAR , the unit tests will let us know.

## 3. Creating JAR manifests

The `<jar>` task creates a JAR manifest if needed. It will contain **the manifest version** and **the version of Ant** used to build the file:

```txt
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.10.6
Created-By: 1.8.0_181-b13 (Oracle Corporation)
```

Adding a manifest to the JAR file is trivial; point the manifest attribute of the task at a predefined manifest file:

```xml
<target name="dist-with-manifest" depends="compile" description="make the distribution">
    <jar destfile="${target.jar}"
         duplicate="preserve"
         index="true"
         manifest="src/META-INF/MANIFEST.MF">
        <fileset dir="${build.classes.dir}"/>
    </jar>
</target>
```

This target needs a manifest file here in `src/META-INF/MANIFEST.MF`

```xml
Manifest-Version: 1.0
Created-By: Antbook Development Team
Sealed: true
Main-Class: d1.core.Diagnostics
```

When Ant runs the `<jar>` task, it will parse and potentially correct the manifest before inserting it into the JAR file. If the manifest is invalid, you’ll find out now, rather than when you ship.

This process has one weakness: someone has to create the manifest first. Why not create it during the build process, enabling us to use Ant properties inside the manifest? This is where the `<manifest>` task comes in.

```xml
<target name="jar-dynamic-manifest" depends="compile">
    <property name="manifest.mf" location="${build.dir}/manifest.mf"/>

    <manifest file="${manifest.mf}">
        <attribute name="Built-By" value="${user.name}"/>
        <attribute name="Sealed" value="true"/>
        <attribute name="Built-On" value="${timestamp.isoformat}"/>
        <attribute name="Main-Class" value="${main.class}"/>
    </manifest>

    <jar destfile="${target.jar}" duplicate="preserve" manifest="${manifest.mf}">
        <fileset dir="${build.classes.dir}"/>
    </jar>
</target>
```

## 4. Adding extra metadata to the JAR

There’s a nested fileset element, `<metainf>`, which lets you specify the metadata files to add to the JAR .

```xml
<jar destfile="${target.jar}"
     duplicate="preserve"
     manifest="src/META-INF/MANIFEST.MF">
    <fileset dir="${build.classes.dir}"/>
    <metainf dir="src/META-INF/"/>
</jar>
```

## 5. JAR file best practices

There are four things to consider for better `<jar>` tasks:

- Copy all the files you want to include in the JAR into one place before building. This makes it easier to see what will be included.
- Create your own manifest, either in a file or in Ant, and explicitly ask for it with the manifest attribute. If you leave it to the `<jar>` task, you get a minimal manifest.
- Always set `duplicate="preserve"`. It keeps duplicate entries out of a file and avoids possible problems later on.
- Finally, and arguably most importantly, give your libraries a **version number** at the end.

## 6. Signing JAR files

Signed JAR files are loaded slightly differently, with the classloader preventing other JAR files from declaring classes in the same packages.

To sign JAR files, we need **a public/private key pair** in a **password-protected keystore**, and Ant will need that **password**. One thing you don’t want to do is put that in the build file itself—anyone with access to the source repository will see it. This isn’t what you want in your build file:

```xml
<property name="keystore.password" value="secret"/>
```

Instead, you need the `<input>` task to prompt the user.

```xml
<target name="get-password" >
    <input addproperty="keystore.password" >password for keystore:</input>
    <echo level="verbose">password = ${keystore.password}</echo>
</target>
```

This task pauses the build with a prompt; the user then has to enter a string. In a `-verbose` run, we echo this back:

```txt
get-password:
    [input] password for keystore:
more-secret
    [echo] password = more-secret
```

Here we use `${user.home}/.secret`, a location which is restricted to the user on a Windows NTFS file system. For Unix, we want to make it readable only by us. For that, we declare a `<chmod>` operation to lock it down. This task runs the `chmod` program to set file or directory
permissions, but only on platforms that support it. On Windows, it’s a harmless no-op. We look for a `keystore.properties` file in this directory and save the keystore there to keep it private:

```xml
<target name="init-security">
    <property name="keystore.dir" location="${user.home}/.secret"/>
    <mkdir dir="${keystore.dir}"/>
    <chmod file="${keystore.dir}" perm="700"/>
    <property name="keystore" location="${keystore.dir}/local.keystore"/>
    <property file="${keystore.dir}/keystore.properties"/>
    <property name="keystore.alias" value="code.signer"/>
</target>
```

After changing the `get-password` target to depend upon this new `init-security` target, the file `keystore.properties` will be read before the `<input>` operation. If we put the relevant declaration in there (`keystore.password=hidden.secret`)

```xml
<target name="get-password" depends="init-security">
    <input addproperty="keystore.password">password for keystore:</input>
    <echo level="verbose">password = ${keystore.password}</echo>
</target>
```

this is what we see at input time:

```txt
init-security:
    [mkdir] Skipping /home/liusen/.secret because it already exists.
    [chmod] Skipping fileset for directory /home/liusen. It is empty.
 [property] Loading /home/liusen/.secret/keystore.properties

get-password:
    [input] skipping input as property keystore.password has already been set.
     [echo] password = hidden.secret
```

With the password in a property, we’re nearly ready to sign the JAR . We just need **a certificate** and the `<signjar>` task. First, **the certificate**.

### 6.1. Generating a signing key

To authenticate JARs in a Java runtime, you have to buy a certificate from one of the approved vendors. For testing purposes or for private use, you can generate a self-signed certificate using Sun’s `keytool` tool, which Ant wraps up into the `<genkey>` task. This task adds **a key** into **a keystore**, creating **the store** if needed:

```xml
    <target name="create-signing-key" depends="get-password">
        <genkey
                alias="${keystore.alias}"
                keystore="${keystore}"
                storepass="${keystore.password}"
                validity="366">
            <dname>
                <param name="CN" value="autosigner"/>
                <param name="OU" value="Steve and Erik"/>
                <param name="O" value="Apache Software Foundation"/>
                <param name="C" value="EU"/>
            </dname>
        </genkey>
    </target>
```

This task creates **a new alias** in the **keystore**, with a certificate that’s valid for 366 days. Although these keys are cryptographically sound, tools such as the Java Web Start don’t trust them. If you’re verifying JAR files in your own application, you’re free to use self-generated keys, and within an organization or community you may be able to convince end users to add your certificate (or private certification authority) to the trusted list.

### 6.2. Signing the file

The `<signjar>` task **signs JAR files**. It checksums all the entries in the file, signs these checksums, and adds them to the manifest. It also adds signature information to the `META-INF` directory in the JAR file. The task needs **the location and the password of the keystore file**, and **the alias** and **any optional extra password for the signature itself**. It will then modify the JAR file in place by invoking the `jarsigner` tool in the JDK :

```xml
<target name="sign-jar" depends="jar,get-password">
    <signjar jar="${target.jar}"
             alias="${keystore.alias}"
             keystore="${keystore}"
             storepass="${keystore.password}"/>
</target>
```

Our manifest now contains digest signatures of the classes inside the JAR, and there are new files in the `META-INF` directory, including **the public certificate of the generated pair**.

The `<signjar>` task can bulk(批量) sign a set of JAR files, using a nested `fileset` element. It also performs basic dependency checking, by not attempting to sign any files that are already signed by the user. It doesn’t check to see if the file has changed since the last signing. This means that you should not mix JAR signing with incremental JAR creation: the `update` flag in the `<jar>` task must remain at `false`.

Java behaves differently with signed JARs, and some applications can break. To be sure that this has not happened, we must take the signed JAR file of the diary classes and run our existing tests against it.

## 7. Testing With Jar Files

Running JUnit against a signed JAR file, rather than the raw classes, lets us test more things. It lets us test (1)that the classes were added to the JAR file注：第一，class文件没有缺失, (2)that we’ve remembered to add any resources the application needs注：第二，资源文件没有缺失, and (3)that the signing process has not broken anything注：第三，签名没有破坏Jar文件. It also lets us state that the tests were run against the redistributables, which is something to be proud of.

It is very easy to test against the JAR file. Recall that we set up our classpath for compiling and running tests like this:

```xml
<path id="test.compile.classpath">
    <path refid="compile.classpath"/>
    <pathelement location="${build.classes.dir}"/>
</path>
```

We need to change one line to run against the generated JAR file:

```xml
<path id="test.compile.classpath">
    <path refid="compile.classpath"/>
    <pathelement location="${target.jar}"/>
</path>
```

To verify everything works, run `ant clean test`. As `clean` builds are usually fast, don’t be afraid to run them regularly.

```xml
<path id="test.jar.classpath">
    <path refid="compile.classpath"/>
    <pathelement location="${target.jar}"/>
    <pathelement location="${test.classes.dir}"/>
</path>

<target name="test-jar" depends="test-compile,sign-jar">
    <junit printsummary="false" haltonfailure="false">
        <classpath refid="test.jar.classpath"/>
        <formatter type="brief" usefile="false"/>
        <batchtest todir="${test.data.dir}">
            <fileset dir="${test.classes.dir}"
                     includes="**/test/*Test.class"/>
        </batchtest>
    </junit>
</target>
```

repository: lsieun/learn-Ant

repo_name: lsieun/learn-Ant


text:
smooth.foundations
==================

Smooth.Foundations is an MIT licensed code package that provides basic classes for boosting programmer productivity and writing clean, maintainable, allocation-free code in Unity.  The code is written in C# and very little is Unity specific; It can also be used on other .Net platforms.

Smooth.Foundations includes:

- Smooth.Compare, a replacement for the System.Collections.Generic comparers that helps reduce runtime allocations and prevent JIT exceptions on AOT platforms.
- Smooth.Slinq, a faster, allocation-free replacement for LINQ with increased functionality and a more robust API.
- Algebraic structs like Option<T>, Either<L, R>, Union <T1, T2, T3>, and Tuple<T1, ..., Tn>.
- Pattern matching module based on David Arno's SuccincT
- Generic pools with a delegate-based API.
- Generic event helpers for creating and maintaining robust, type safe events backed by multicast delegates.
- A disposal API for performing cleanup operations in a background thread during the rendering phase.
- Methods for determining basic information about the runtime platform.
- Other miscellaneous utilities.

license: MIT

branch_name: refs/heads/master

extension: md

gha_language: C#

license_type: permissive


text:
------

### 127. Word Ladder
Given two words (`beginWord` and `endWord`), and a `wordList`, find the length of shortest transformation sequence from `beginWord` to `endWord`, such that:
- Only one letter can be changed for each transformation.
- Each transformed word must exist in the `wordList`.

Insights:
- `beginWord` and `endWord` are symmetric. We should optimize it with two-end BFS, where we have a beginSet and an endSet, and choose one to expand based on size.
- The correct way to traverse:
  - For each word, try all possible transformations. `O(26L)`
  - For each word, traverse all existing words and check if reachable or not. `O(NL)`
  - If we preprocess the `wordList` and store it as adjacent list, which take `Time O(N^2 L) Space O(N^2)`. Then for each word, we can get all its neighbors in `O(1)`. This will be optimal if we were to perform this task multiple times.

### 126. Word Ladder II
In order to return all valid paths, dfs is a must. It then becomes critical to prune unnecessary branches for better time performance.

#### Two choices:

Either
1. Use BFS to find the shortest distance between `beginWord` and `endWord`, meanwhile store distances of visited nodes to `beginWord`, (optinal) and store node's neighbors in a HashMap for later use;
2. Use DFS to output paths with the same distance as the shortest distance from distance HashMap: compare if the distance of the next level node equals the distance of the current node + 1.

Or

1. Use BFS to find the shortest distance between `beginWord` and `endWord`, meanwhile construct a **graph** as adjacency list, that have **all the connections traversed while BFS**.
> **CRITICAL**: nodes at the same level should be allowed to be visited multiple times; Be careful when checking if a node has been visited; One solution is to use a `Set<String> curLevel` to store all nodes at current level and after finishing current level, add all these nodes to `Set<String> visited`, also add these nodes to `Queue<String> queue`
2. Use DFS to traverse the constructed graph, by doing so we avoid visiting any unnecessary connections.

#### One lesson:
**Not** particularly useful to map word to index for space usage. Afterall, we are only parsing String's references around.

### 785. Is Graph Bipartite?
The graph can consist of several independent sub-graphs. Start from all vertices to ensure traversing the whole graph.


text:
# Simple-Calculator

## Algorithm

* Parse expression to seperate numbers and operators
* Convert Infix format to Postfix format by using [Shunting-yard algorithm](https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail)
* Then using [Postfix evaluation algorithm](https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_evaluation_algorithm)

## Special Case

### Multiple Plus or Minus Sign or spaces

Note: Follow order to filter the expression before converting

1. ------ -> use replace all with regex exact two negative signs and replace with '+'
2. +++ -> use replace all with regex more than two plus signs and replace with '+'
3. +- or -+ -> use replace all with regex +-|-+ and replace with '-'
4. '4 + 3 - 4' -> use replace all with regex ' ' and replace with ''

### Negative Number

* **-**(x + y) -> check negative at index 0. Then add **0** before it => **0** - (x+y)
* 3*-2 or (-2+3) -> if **'*'**, **'/'**, **'^'**, **'('** before negative, then push **'-'** to stack. When the next char is number, the new number is stack.pop + number.
* Note: For the '+' sign, just ignore it.

### Multiply between parentheses

* (2)(3) or 3(2) -> if (index > 0) and cur = '(' and ( prev = ')' or prev is number ) => add *
* (2)3 -> if (index < size -1) and cur = ')' and next is number => add *

### Absolute

* Use square bracker '[]' instead of pipe '|' because it's easier to detect the ending of absolute function
* To use binary operation, add '1' and '|' to the postfix when coverting

## Test

* Use JUnit 5 to run CalculatorTest.java
* It's best if you run in Intellij

## Output

Note: Windows does not support ANSI. It means no color in console.

![output](https://github.com/quyentruong/Simple-Calculator/blob/master/images/calculator_output.JPG?raw=true)

repository: quyentruong/Simple-Calculator

repo_name: quyentruong/Simple-Calculator


text:
[![Gem Version](https://badge.fury.io/rb/kitchen-softlayer.svg)](http://badge.fury.io/rb/kitchen-softlayer)
[![Gem Downloads](http://ruby-gem-downloads-badge.herokuapp.com/kitchen-softlayer?type=total&color=brightgreen)](https://rubygems.org/gems/kitchen-softlayer)
[![Build Status](https://travis-ci.org/neillturner/kitchen-softlayer.png)](https://travis-ci.org/neillturner/kitchen-softlayer)

# Kitchen::Softlayer

A Test Kitchen Driver for Softlayer

## Installation

Add this line to your application's Gemfile:

    gem 'kitchen-softlayer'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install kitchen-softlayer

## Usage

By default set the following environment variables to your softlayer credentials:

```
      softlayer_username
      softlayer_api_key
      softlayer_default_datacenter    (optional)
      softlayer_default_domain        (optional)
```

So you don't need to code these in the .kitchen.yml file which is much better from a security point
of view as the kitchen.yml file can be checked in to source control without containing key data.

An example of the driver options in your `.kitchen.yml` file:

```yaml
    driver:
      name: softlayer
        key_name: 'myuploadedsshkeylabel'
        ssh_key: C:/mykeys/my_private_sshkey.pem
        username: root
        server_name: 'myserver-test'
        domain: softlayer.com
        flavor_id: m1.tiny
     #  image_id: '3b235124-a190-40b5-9720-c020e61b99e1'
        os_code: 'CENTOS_7_64'
        private_network_only: true
        cpu: 1,
        ram: 1024,
        datacenter: lon02
```

### os_code and image_id
you need to either specify softlayer's operating System Reference Code via parameter os_code
or an image_id.

### private_network_only
By default this parameter is set to false so no public network with be created.
For test-kitchen to access the server via ssh it needs to be on the softlayer private VPN. See:

[Using SSL VPN](http://knowledgelayer.softlayer.com/procedure/using-ssl-vpn)

### ssh_key
 Currently the driver only supports using SSH keys to access servers. This requires that you upload an SSH Key in Softlayer see:

[SSH Keys](http://knowledgelayer.softlayer.com/procedure/ssh-keys-0)

 in the kitchen.yml file specify the label of the ssh key as the parameter key_name
 and specify the private key for the uploaded public key as parameter ssh_key.

The `image_ref` and `flavor_ref` options can be specified as an exact id,
an exact name, or as a regular expression matching the name of the image or flavor.

### server_name

the driver checks for a server with the server_name and will use that server instead of creating another one.

### disable_ssl_validation

the driver uses the fog-softlayer ruby client to communicate with softlayer.
If you get SSL certificate validation errors then the workaround is to set disable SSL cert validation to true
however it is better to set the environment variable 'SSL_CERT_FILE' to a valid certificate file.

# Softlayer Driver Options

key | default value | Notes
----|---------------|--------
softlayer_username | ENV['softlayer_username']
softlayer_api_key | ENV['softlayer_api_key']
softlayer_default_datacenter | ENV['softlayer_default_datacenter']
softlayer_default_domain | ENV['softlayer_default_domain']
server_name | nil | Server Name
server_name_prefix | nil | If you want to have a static prefix for a random server name.
key_name | nil | the label of the uploaded key
ssh_key| nil | file location of private key
disable_ssl_validation | false | ssl validation for fog softlayer api
username | 'root' | server's administration user
password | nil | server's administration password
port | '22' | ssh port of servef
domain | ENV['softlayer_default_domain'] | domain nane of server
fqdn | nil | fully qualified domain name
cpu | nil | no of cpus
ram | nil | memory size
disk | nil | disk size
flavor_id | nil | type of server i.e. m1.tiny
bare_metal | false | server to be created on bare metal (takes longer)
os_code | nil | softlayer's operating System Reference Code
image_id | nil | image name or internal id
ephemeral_storage | nil | storage
network_components | nil | network
ssh_timeout | 300 | timeout to ssh when server starting
ssh_via_hostname | false | use server_name for ssh instead of IP
alternate_ip | nil | alternate ip address for ssh access
destroy_wait | true | wait for destroy to complete
destroy_timeout | 300 | timeout to wait until server destroyed
account_id | nil | softlayer account id
datacenter | ENV['softlayer_default_datacenter'] | datacenter code
single_tenant | false | don't share server
global_identifier | nil | softlayer global id
hourly_billing_flag | true
tags | [] | tags for the server
private_network_only | false | if only a private network
use_private_ip_with_public_network | false | otherwise uses public ip
user_data | nil |string of user data for server
uid | nil | softlayer global id
vlan | nil | numeric id of vlan for server
private_vlan | nil | numeric id of private_vlan for server
provision_script | nil | url of provision script to run

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Run style checks and RSpec tests (`bundle exec rake`)
4.  Push to the branch (`git push origin my-new-feature`)
6. Create new Pull Request

repository: neillturner/kitchen-softlayer

gha_language: Ruby

repo_name: neillturner/kitchen-softlayer


text:
# Version-1.14.9

Release Date : 6/21/19

### Updates
- Option to save heat maps from Scanning Diffraction as .svg formatted files
- Added options to use arrows or ellipses for the Scanning Diffraction orientation display in folder mode
- Added scaling options to rescale the orientation indicators in Scanning Diffraction
- Fixed bugs with 1D scans including not being able to show more details about an image after clicking on a heatmap tile
- Changed the eq fitting tab layout to allow for a larger peaks plot
- Added new recorded test Pickle files that are compatible with Python 2 and 3
- Added Cython, opencv-python, and pyFAI to the setup.py requirements

repository: biocatiit/musclex

gha_language: Python

gha_license_id: NOASSERTION

repo_name: biocatiit/musclex


text:
## ex6.01
> What is the difference between a parameter and an argument?

Parameters are local variables declared inside the function parameter lis.
Parameters are initialized by the arguments provided in each function call.

Arguments are values supplied in a function call that are used to initialize
the function's parameters.

## ex6.02
> Indicate which of the following functions are in error and why. Suggest
> how you might correct the problems.
```cpp
(a) int f() {
      string s;
      //...
      return s;
    }

(b) f2(int i){/* ... */}

(c) int calc(int v1, int v1) /* ... */ }

(d) double square(double x) return x * x;
```

```cpp
(a) string f() {
      string s;
      //...
      return s;
    }

(b) void f2(int i){/* ... */}

(c) int calc(int v1, int v2){ /* ... */ }

(d) double square(double x){ return x * x;}
```

## ex6.03
> Write and test your own version of fact.

[code](ex6_03.cpp)

## ex6.04
> Write a function that interacts with the user, asking for a number and ]
> generating the factorial of that number. Call this function from main.

Refer [ex6.03](ex6_03.cpp)

## ex6.05
> Write a function to return the absolute value of its argument.

[code](ex6_05.cpp)

## ex6.06
> Explain the differences between a parameter, a local variable, and a local
> static variable. Give an example of a function in which each might be useful.

Parameter: local variable declared inside the function parameter list;

local variable: variable defined inside a block;

local static variable: local variable whose value persists across calls to the
function. Local static variable that is created and initialized before control
reaches their use and is destroyed when the program ends.

```cpp
int func(int a){ // a is parameter
  static int n = 1; // n is local static variable

  for(int i = a; a > 0; --i){ // i is local variable
    n *= i;
  }
  return n;
} // func
```

## ex6.07
> Write a function that returns 0 when it is first called and then generates
> numbers in sequence each time it is called again.

[code](ex6_07.cpp)

## ex6.08
> Write a header file named Chapter6.h that contains declarations for the
> functions you wrote for the exercises in § 6.1 (p. 205).

[code](ex6_08.h)

## ex6.09
> Write your own versions of the fact.cc and factMain.cc files. These files
> should include your Chapter6.h from the exercises in the previous section.
> Use these files to understand how your compiler supports separate compilation.

[fact.cpp](fact.cpp)

[factMain.cpp](factMain.cpp)

## ex6.10
> Using pointers, write a function to swap the values of two ints. Test the
> function by calling it and printing the swapped values.

[code](ex6_10.cpp)

## ex6.11
> Write and test your own version of reset that takes a reference.

[code](ex6_11.cpp)

## ex6.12
> Rewrite the program from exercise 6.10 in § 6.2.1 (p. 210) to use references
> instead of pointers to swap the value of two ints. Which version do you think
> would be easier to use and why?

[code](ex6_12.cpp)

I think the reference version is much easier to use, because it is much
easier to understand.

## ex6.13
> Assuming T is the name of a type, explain the difference between a function
> declared as void f(T) and void f(T&).

void f(T) will copy the object of type T, while void f(T&) avoids to copy the
object.

## ex6.14
> Give an example of when a parameter should be a reference type. Give an
> example of when a parameter should not be a reference.
```cpp
int reset(int &a){ // the parameter should be a reference type
  a = 0;
}

// pezy's answer, the parameter should not be a reference type
void print(std::vector<int>::iterator begin, std::vector<int>::iterator end){
  for(std::vector<int>::iterator iter = begin; iter != end; ++iter)
    std::cout << *iter << std::endl;
}
```

## ex6.15
> Explain the rationale for the type of each of find_char’s parameters In
> particular, why is s a reference to const but occurs is a plain reference? Why
> are these parameters references, but the char parameter c is not? What would
> happen if we made s a plain reference? What if we made occurs a reference to
> const?

Because we don't want to change the value of s, therefore, s is a reference to
const, occurs is a plain reference because it can be changed;

Actually, we can set c as reference;

If we made s a plain reference and made occurs a reference to const, s would be
changable, and occurs unchangable, therefore, occurs = 0.

## ex6.16
> The following function, although legal, is less useful than it might be.
> Identify and correct the limitation on this function:
```cpp
bool is_empty(string& s) { return s.empty(); }
```

```cpp
bool is_empty(const string& s) { return s.empty(); }
```

This function doesn't change s, therefore, we should use const

## ex6.17
> Write a function to determine whether a string contains any capital letters.
> Write a function to change a string to all lowercase. Do the parameters you
> used in these functions have the same type? If so, why? If not, why not?

no, the first function doesn't change the string, hence, the parameters should
be const, the second function should be plain string.

[code](ex6_17.cpp)

## ex6.18
> Write declarations for each of the following functions. When you write these
> declarations, use the name of the function to indicate what the function does.
>
> (a) A function named compare that returns a bool and has two parameters that
>     are references to a class named matrix.
>
> (b) A function named change_val that returns a vector<int> iterator and takes
>     two parameters: One is an int and the other is an iterator for a
>     vector<int>.

```cpp
bool compare(const matrix&, const matrix&);

vector<int>::iterator change_val(int, vector<int>::iterator);
```

## ex6.19
> Given the following declarations, determine which calls are legal and which
> are illegal. For those that are illegal, explain why.
```cpp
double calc(double);
int count(const string &, char);
int sum(vector<int>::iterator, vector<int>::iterator, int);
vector<int> vec(10);
(a) calc(23.4, 55.1);
(b) count("abcda", 'a');
(c) calc(66);
(d) sum(vec.begin(), vec.end(), 3.8);
```

(a) illegal, only one parameter;

(b) legal;

(c) legal;

(d) legal;

## ex6.20
> When should reference parameters be references to const? What happens if we
> make a parameter a plain reference when it could be a reference to const?

When we want to read the parameter, but don't want to write the parameter, use
reference to const.

## ex6.21
> Write a function that takes an int and a pointer to an int and returns the
> larger of the int value or the value to which the pointer points. What type
> should you use for the pointer?

[code](ex6_21.cpp)

## ex6.22
> Write a function to swap two int pointers.

[code](ex6_22.cpp)

## ex6.23
> Write your own versions of each of the print functions presented in this
> section. Call each of these functions to print i and j defined as follows:
> int i = 0, j[2] = {0, 1};

[code](ex6_23.cpp)

## ex6.24
> Explain the behavior of the following function. If there are problems in the
> code, explain what they are and how you might fix them.
```cpp
void print(const int ia[10]){
  for (size_t i = 0; i != 10; ++i)
   cout << ia[i] << endl;
}
```
This function wants to print all the elements of an array.

because we cannot copy an array, we cannot pass an array by value. In C++,
a parameter declared as int ia[10] or as int ia[1024] is actually declared
as int *ia.

```cpp
void print(const int (&ia)[10]){
  for(size_t i = 0; i != 10; ++i)
    cout << ia[10] << endl;
}
```

## ex6.25
> Write a main function that takes two arguments. Concatenate the supplied
> arguments and print the resulting string.

[code](ex6_25.cpp)

## ex6.26
> Write a program that accepts the options presented in this section. Print the
> values of the arguments passed to main.

[code](ex6_25.cpp)

## ex6.27
> Write a function that takes an initializer_list<int> and produces the sum of
> the elements in the list.

[code](ex6_27.cpp)

## ex6.28
> In the second version of error_msg that has an ErrCode parameter, what is the
> type of elem in the for loop?

const reference bound to string.

## ex6.29
> When you use an initializer_list in a range for would you ever use a reference
> as the loop control variable? If so, why? If not, why not?

[*Pezy's answer:*](https://github.com/pezy/CppPrimer/tree/master/ch06)
Depends on the type of elements of initializer_list. When the type is PODType,
reference is unnecessary. Because POD is cheap to copy(such as int). Otherwise,
Using reference(const) is the better choice.

## ex6.30
> Compile the version of str_subrange as presented on page 223 to see what your
> compiler does with the indicated errors.

error: non-void function 'str_subrange' should return a value [-Wreturn-type]

return;

1 error generated.

## ex6.31
> When is it valid to return a reference? A reference to const?

When you can find the preexist object that the reference bound;

When you can find the preexist const object that the reference bound.

## ex6.32
> Indicate whether the following function is legal. If so, explain
> what it does; if not, correct any errors and then explain it.

```cpp
int &get(int *arry, int index){ return arry[index];}
int main() {
  int ia[10];
  for (int i = 0; i != 10; ++i)
    get(ia, i) = i;
}
```

legal, it assigns the index value to the array.

## ex6.33
> Write a recursive function to print the contents of a vector.

[code](ex6_33.cpp)

## ex6.34
> What would happen if the stopping condition in factorial were
> if(val != 0)

~~The output will not change.~~

Two situations can happen: case1, if the argument is positive, recursion
stops at 0. case2, if the argument is negative, recursion would never
stop. As a result, a stack overflow would occur.

## ex6.35
> In the call to fact, why did we pass val - 1 rather than val--?

Because val-- will return val, therefore, var will always be the parameter
of this function, as a result, the function will never stop.

## ex6.36
> Write the declaration for a function that returns a reference to an array of
> ten strings, without using either a trailing return, decltype, or a type
> alias.
```cpp
string (&func(string (&arrStr)[10]))[10];
```

## ex6.37
> Write three additional declarations for the function in the previous exercise.
> One should use a type alias, one should use a trailing return, and the third
> should use decltype. Which form do you prefer and why?

```cpp
using strT = string[10];
strT& func(strT& arrStr); // use type alias

auto func(strT& arrStr) -> string&[10]; // use trailing return

decltype(arrStr) &func(strT& arrStr); // use decltype
```

## ex6.38
> Revise the arrPtr function on to return a reference to the array.
```cpp
decltype(odd) &arrPtr(int i){
  return(i % 2) ? odd : even;
}
```

## ex6.39
> Explain the effect of the second declaration in each one of the following sets
> of declarations. Indicate which, if any, are illegal.
```cpp
(a) int calc(int, int);
    int calc(const int, const int);
(b) int get();
    double get();
(c) int *reset(int *);
    double *reset(double *);
```

(a) ~~illegal;~~ legal, repeated declarations(without definition) are legal in
C++;

(b) ~~legal;~~ illegal, only the return type is different;

(c) legal, the parameter type is different and return type is changed.

repository: yunongzhou/cppprimer

repo_name: yunongzhou/cppprimer


text:
---
layout: post
title: Crack the code
time: "02:36"
extended: ":EXTENDED:"
---

Just came cross this interesting problelm on ZJU Online Judge.

Basic solution:
1) determine the key length, and then,
2) determine the key.

Method one:

1) 'English' means the text is printable(spaces included). Assuming the key length is N (1 to 30), xor each possible key character in [a-z0-9] against every other N character of the shifted (from 0 to N-1) cipher. The resulted value shoule be printable. If N is the right key length, there must exist at least one key character that meets this 'printable' condition for each displacement. Since each key character is uniqe in the key and we are given enough long cipher, the smallest N is the key length.

2) With the right key length N, we calculate those right key characters as above. If we are lucky enough, there's only one character for each displacement. Thus we get the right key. If we are not so lucky, remember each key character should be exclusive with each other. Thus we _could_ get the right key.

Again, code explains better than mere words. Here's the code representing this method.

You can generate a cipher and then test the code. And you may find that there're some times that it cant determine the key.

Why? You may ask. Cause we havent used the 'English' condition as that much. As what much? You may then ask.

'English' means it's English... Duh!  It's not only printable but should be composed of English words and have human-readable meanings.

Indeed. When you cant determine the key with the code above, there are only several keys possible (-DVERBOSE). You can xor these keys with the cipher text, read the ouputs and see which is English and which is not. This way you can find the right key.

Any better ways? You finally ask.
Yes.
Method Two:

1) Compare the cipher with itself shifted N bytes. If N is the right key length, there should be at round 6% equal bytes. If not, the rate is less than 0.4%. The smallest N is the right answer. [1]

2) With this right key length N, we try all possible key characters and calculate the English character frequencies in the 'plain' text. If the key character is right, then the frequencies should be like this.

A working code here.

Since the given cipher is long enough, i have used a rather simplified method in the code: test if coincidence rate > 5.5% and only calculate the letter 'e' frequency and see if it's > 9%. (These 2 number are selected after a few tests.) In fact, to be more precise, you can calculate each coincidence probability to find which one is closest to 6% (using fabs() libroutine) and calculate all the 26 English characters' frequencies to get the right answer that's closest to real life.

Interestingly, we can see method 2 ues the 'English' condition so heavily and extensively that if you try a plain text that's composed of random characters or a c source code, you are not supposed to find the key.

For random characters, maybe we can combine these 2 methods. [2]

[1] Bruce Schneier, in his Applied Cryptography Section 1.4, introduces a method using index of coincidence to determine key length.

[2] If the text is random, and the different letters are chosen with equal probability, the probability of a coincidence is much smaller (around 3.8 percent).

extension: markdown


text:
* Commit history: https://github.com/pegjs/pegjs/commits/master
* Previous changelogs: https://github.com/pegjs/pegjs/tree/master/docs/changelogs
* Contributors this release: https://github.com/pegjs/pegjs/graphs/contributors?from=2016-08-20

> This is a work in progress changelog for the next release _(currently v0.11)_.

### Major Changes

* [Implemented value plucking](https://github.com/pegjs/pegjs/commit/460f0cc5bc9e7b12e7830a13a9afa5026a5f20f4): e.g. When `grammar = "-" @$[a-z]i* "-"` is given `-PEGjs-`, it returns `PEGjs`
* Upgraded JavaScript support:
  - Parser's are generated in ES5
  - Source code for PEG.js and scripts in the repository are written in ES2015, for Node 8+
  - The browser release is in ES5, generated using [Rollup](https://rollupjs.org/) and [Babel](https://babeljs.io/)
  - Dropped support for Node versions _0.x_, _4_, _6_ and _non-LTS_ versions (e.g. `7`, `9`, etc)
  - Dropped support for IE versions _8_, _9_ and _10_
* Updated documentation:
  - extracted to separate markdown files in the [docs folder](https://github.com/pegjs/pegjs/tree/master/docs)
  - better explanation about error messages
  - added documentation for case-insensitivity in grammar
  - added documentation for backtracking in grammar
  - clarify details for the execution environment for actions ([#531](https://github.com/pegjs/pegjs/pull/531))
  - added a clear explanation of balanced braces ([#533](https://github.com/pegjs/pegjs/pull/533))
  - updated documentation for the JavaScript API
  - added a guide for plugins
  - added documentation for tracer usage
  - added a guide for the CLI
* Rewrote command line tool:
  - added 2 aliases for `--extra-options-file`: `-c` and `--config`
  - options can accept their values via the assignment operator (e.g. `pegjs -c=config.js`)
  - all arguments after `--` are passed to `options["--"]`
  - added aliases for some CLI options; Check them out using `pegjs -h`
  - added "bare" to accepted module formats
* Updated the helpers providable to the generated parsers:
  - reintroduced `offset()` which was removed in a previous release ([#528](https://github.com/pegjs/pegjs/pull/528))
  - added `range()`; returns `[starting offset, current offset]`
  - `location()` also returns a `filename` property if one was passed to the generated parser as an option ([#421](https://github.com/pegjs/pegjs/issues/421))
  - helpers can be disabled via the new `features` option (e.g. `{ text: false }` will remove the `text()` helper)
* Parser returns an instance of the new Grammar class instead of a plain JavaScript object
* Added the ASTVisitor class ([#451](https://github.com/pegjs/pegjs/issues/451))
* Moved all code generation from the `generateBytecode` pass to the `generateJs` pass ([#459](https://github.com/pegjs/pegjs/pull/459))
* Use `.js` files with the `--extra-options-file` (aliased by `-c` and `--config`) option on CLI
* Added the Session API (`peg.compiler.Session`); this should simplify extending PEG.js using plugins
* Implemented warning and error emitters: `session.warn`, `session.error` and `session.fatal` ([#327](https://github.com/pegjs/pegjs/issues/327), [#430](https://github.com/pegjs/pegjs/issues/430), [#431](https://github.com/pegjs/pegjs/issues/431))

### Minor Changes

* Omit PEG.js version from the browser release's filename
* Added support for generating the parser as a ES module using `"format": "es"`
* Added [bundled](https://www.npmjs.com/package/pegjs) TypeScript declaration files for
  - the PEG.js API: `pegjs/typings/api.d.ts`
  - the PEG.js modules: `pegjs/typings/modules.d.ts`
  - generated parsers: `pegjs/typings/generated-parser.d.ts`
* Updated bytecode generator; Generated parsers look slightly better
  - optimize silent fails ([#399](https://github.com/pegjs/pegjs/issues/399))
  - optimize redundant fail checks ([#400](https://github.com/pegjs/pegjs/issues/400))
  - remove unnecessary opcode ([#509](https://github.com/pegjs/pegjs/pull/509))
* Added `ASTVisitor.on.{property,children}`; these are helper's to create visitor's for use with the new ASTVisitor class
* Merged ast utility functions into the new Grammar class; faster and simpler to use now.
* Pass `options.parser` from `peg.generate` to the PEG.js parser (`peg.parser`, or a custom parser)
* Added a pass for the compiler to warn when unused rules are found ([#200](https://github.com/pegjs/pegjs/issues/200))
* Added a `header` option to the compiler; Adds custom comments to the header of the generated parser
* CLI restores original output file (if it already exists) when parser generation fails
* Added the option `extractComments` to the PEG.js parser which if _true_ will extract comments from the grammar ([#511](https://github.com/pegjs/pegjs/pull/511))
* Made the default tracer optional (disabled like so `peg.generate(grammar, { features: { DefaultTracer: false } })`)
* Pass variables to generated parsers through the `context` option when `output: "parser"` ([#517](https://github.com/pegjs/pegjs/issues/517))
* On the CLI added the use of `input` and `output` from the _config file_ instead of passing them as arguments
* Updated examples
* Upgraded support for Unicode (from _v8_ to _v11_)
* Forward location to `SyntaxError.buildMessage` ([#608](https://github.com/pegjs/pegjs/pull/608))

### Bugfixes

* Report consistent errors on look ahead + cached results (fix's [#452](https://github.com/pegjs/pegjs/issues/452) via [#555](https://github.com/pegjs/pegjs/issues/555))
* Improve error messages ([#194](https://github.com/pegjs/pegjs/issues/194), [#475](https://github.com/pegjs/pegjs/pull/475), [#534](https://github.com/pegjs/pegjs/pull/534), [#547](https://github.com/pegjs/pegjs/pull/547), [#552](https://github.com/pegjs/pegjs/pull/552))
* Do not indent backtick quoted strings in code blocks ([#492](https://github.com/pegjs/pegjs/pull/492))
* Fix shadowing issue for UMD generated parsers ([#499](https://github.com/pegjs/pegjs/issues/499))
* Check rules from `options.allowedStartRules` exist within the grammar ([#524](https://github.com/pegjs/pegjs/issues/524))

### Internal

* Use ESLint to enforce code style
* Switch from Jasmine to Mocha & Chai ([#409](https://github.com/pegjs/pegjs/issues/409))
* Removed Makefile (Had switched to Gulp, but removed that as well); Using the _scripts_ field of `package.json` instead
* Rewrote `tools/impact`; previously a bash script that required external programs, it's now a cross-platform Node script
* Added coverage via [Istanbul](https://www.npmjs.com/package/nyc) ([#546](https://github.com/pegjs/pegjs/pull/546))
* Test coverage reports are now submitted to [https://codecov.io/gh/pegjs/pegjs](https://codecov.io/gh/pegjs/pegjs)
* Updated existing spec tests
* Switched to Yarn for workspace based development (_NOTE:_ Yarn is not be required for production use)
* Updated keywords for the [NPM package](https://www.npmjs.com/package/pegjs)
* Archived the website's repository; it is now built from the docs and deployed every time the main repository is updated
* Added the [spec](https://pegjs.org/development/test) and [benchmark](https://pegjs.org/development/benchmark) tests to the website
* Switch from [Browserify](https://github.com/browserify/browserify) to [Webpack](https://webpack.js.org/)
* Export's PEG.js version from `require("pegjs/package.json").version`
* Added https://pegjs.org/development/try; an editor that uses the latest source files for PEG.js
* Replaced [Travis CI support](https://travis-ci.org/pegjs/pegjs/builds) with GitHub Actions

repository: manbaum/pegjs

gha_language: JavaScript

gha_license_id: MIT

repo_name: manbaum/pegjs


text:
#Chipmunk
![chipmunk logo](app/images/icon-128.png)

Chipmunk is a bookmarking Google Chrome extension to stash data into your Google Spreadsheet.
It works with a companion [Chipmunk Rest Api](https://github.com/GlassyMedia/chipmunk-restapi) that handles the data.

##Usage

###Getting started:
You'll need [bower](http://bower.io/) and [node/npm](http://nodejs.org/) to install dependecies.

```sh
  npm install && bower install
```

###To Run:
* go to `chrome://extensions` in chrome and check the "Developer Mode" box
* click "Load unpacked extensions" and navigate to the `app` directory and load that up
* set your configuration by using the options menu of the plugin

###To Build:
```sh
  grunt build
```

###Configuration:
Configuration happens in the options menu of the plugin, within Chrome. Right click on the plugin icon to see the option menu.

###Documentation:
```sh
  npm install docco
  grunt docs
```

## License

The MIT License (MIT)

Copyright (c) 2014 Glassy Media Inc.

repository: Spokepoint/chipmunk-chrome-extension

repo_name: Spokepoint/chipmunk-chrome-extension


text:
# Detect JPEG quality from bytes or io.ReadSeeker (like os.File)

Input a JPEG file to detect the quality of the image along with the Quanization Table and DQTs.

[![Build Status](https://travis-ci.org/liut/jpegquality.svg?branch=master)](https://travis-ci.org/liut/jpegquality)

Inpiration from [Estimating Quality](http://fotoforensics.com/tutorial-estq.php).

Fixed bug base on HuangYeWuDeng [ttys3/jpegquality](https://github.com/ttys3/jpegquality/commit/6176ce2bb32baad02c5b3dcd977dbc2eab406312).

## Languages/Dependencies:

Golang

## How to Install/Run:

In order to install and run this program, please follow the steps below:

### 1. Clone the repository to your local device

```bash
git clone https://github.com/liut/jpegquality.git
```

### 2. Install Golang:

```bash
Follow this [link](https://go.dev/doc/install) for help.
```

### 3. Build Executable:

```bash
cd jpegq && go build
 ```

### 4. Run executable and specify input jpeg file.
```bash
jpegq [FILENAME]

Example: jpegq myphoto.jpg
```

## How to Contribute:

### 1. Fork the [main repository](https://github.com/liut/jpegquality)

### 2. Clone the repo to your local device

```bash
git clone https://github.com/liut/jpegquality.git
```

### 3. Install Golang:

```bash
Follow this [link](https://go.dev/doc/install) for help.
```

### 5. Create a new branch for your changes.

```bash
git checkout -b <name-of-branch>
```

### 6. Submit a Pull Request to the main repository

## Code usage:

````go

	file, err := os.Open("file.jpg")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	j, err := jpegquality.New(file) // or NewWithBytes([]byte)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("jpeg quality %d", j.Quality())

````

## Testing

This program's output accurracy was tested thoroughly in jpegquality_tests.go. Feel free to add anymore tests for edge cases!

## Bugs
Please report any bugs below to ensure contributors can keep this code functional and easy to use

## Command line tool

```sh
go get github.com/liut/jpegquality/cmd/jpegq

jpegq myphoto.jpg

```

### Output example
```
2019/10/03 00:09:08 jpegquality.go:135: Quantization table length 130
2019/10/03 00:09:08 jpegquality.go:144: read bytes 130
2019/10/03 00:09:08 jpegquality.go:161: DQT: table index 0 (luminance), precision: 8
2019/10/03 00:09:08 jpegquality.go:208: tbl 0: 23.90413 572.61780 88.04793
2019/10/03 00:09:08 jpegquality.go:212: aver_quality 88
88
```

## Custom logger for debug
```go

jpegquality.SetLogger(log.New(os.Stderr, "jpegq", log.LstdFlags|log.Lshortfile))

```

repository: scaszoo/jpegquality

repo_name: scaszoo/jpegquality


text:
---
title: About
date: 2013-07-02T08:23:30+00:00
author: Janik von Rotz
disable_comments: true
---

[![Untitled](/images/me-casual.jpg)](/images/me-casual.jpg)

Hi, my name is Janik von Rotz. I’m a Software Engineer / IT Consultant from Switzerland.

This is my blog where I share my personal and professional experiences. It is mostly about IT-related stuff. I always and still admire the Open Source Software (OSS) community, where everybody shares their insight and solution for the benefit of the whole. This blog is a contribution to this community.

Here are a few things about me:

* I did some [traveling](https://gist.github.com/janikvonrotz/37dc61480790b07ab91d88d624caef2b) in the past. Not so much anymore as flying has a huge impact on the environment.
* There is not enough time to [read books](/tags/book).
* As with books I'm not taking enough [photos](/categories/photography/).

I describe my personality in 3 words:

* Curious
* Dedicated
* Open-Minded

At work I value:

* Collaboration and autonomy
* Openess and honesty
* Leaness and speed

Let me know if you:

* Come to Switzerland
* Are working on a cool project and need help
* Want to discuss anything related to my work

I believe in:

* [User Data Manifesto](https://userdatamanifesto.org/)
* [GNU Manifest](https://www.gnu.org/gnu/manifesto.html)
* [Open Source Software](https://opensourcesoftware.ch)

Currently I am working on various opportunities and projects:

* Get the latest startup [Mint System GmbH](https://www.mint-system.ch/) up and running.
* Developing web applications as [Apland GmbH](https://apland.ch).
* Helping companies to improve their business with software.
* Searching for challenges to improve my soft and tech skills.


text:
---
title: HTML5 Collisions
module: 11
jotted: true
---

# HTML5 Collisions

With any game, you need to be able to handle collisions. We are going to use a simple box collider.  It checks the corners of the boxes to see if they are overlapping.  If they are, then it returns true, else it returns false.  Keep in mind, a collision can be more precise, but it takes more processing because of all the algorithm checks all the points of the shape.  Also, every move checks collision.

Here is our collision code:

```javascript
function hasCollided(object1, object2) {
    return !(
        ((object1.y + object1.height) < (object2.y)) ||
        (object1.y > (object2.y + object2.height)) ||
        ((object1.x + object1.width) < object2.x) ||
        (object1.x > (object2.x + object2.width))
    );
}
```

Now, wait a minute. You might have thought that objects were going away. But what if I told you that you could create an object out of each of your squares (assuming you have at least two).  Then, you can send your objects into this function, and it will check to see if you have collided or not.

## Try it out!

Do you remember how to create a class? Can you create a class called Square with the properties x, y, height, width, and color?  Then, create your constructor and getters and setters.

Check to see if everything is in your objects by writing to the console.  Did it work? Yes? Great job!

## Try it yourself!

Can you create two squares and add them to the screen? Make them different colors and different sizes. (I know you can!  The power is in you!).

## Try it yourself!

Now, can you make the one square move with the KeyEvents using WASD?  Yes, yes, you can!

Look how far you have come!  I am so proud of you!

## Try it yourself!

Now, here comes the new stuff, check for collision.  You can use the code above and check the collision between your two squares each time the first square moves.  Just make sure that the first square can no longer move or have the first square move back a bit from the second square (like a bounce)if they collide or move. It's up to you!

You did it!  I am proud of you! I knew you could do it!  Is there more?  Of course, there is, but we are going to wait until next week to do more.  Good job this week!

gha_language: CSS


text:
# Troll Hub API

---
*Published URL = https://troll-hub.herokuapp.com/*

---
Schemas

     User Schema:
     {
     firstName: string
     lastName: string
     email: string
     country: string
     password: string
     }

    Comments Schema:
    {
     name: string
    comment:string
    score:string
    }

__Base URL = https://troll-hub.herokuapp.com/api__

1. Creation/Login Flow ~~ RestAPI ~~ See Charts for Endpoints

|      Endpoints       | Method|            Other                |
| :------------------: | :----:| :-----------------------------: |
|   /auth/register     |  POST |  Registers a User with Token    |
|   /auth/login        |  POST |  Logins a User with Token       |

2. User Routes ~~ RestAPI ~~ See Chart for Endpoints

|      Endpoints       | Method|            Other                |
| :------------------: | :----:| :-----------------------------: |
|      /newUser        | GET   |     Gets a List of Users        |
|      /newUser/:id    | GET   |      Gets a User By Id          |
|      newUser/:id/favorites  | GET   |      Gets a Users Favorite Comment |
|      /newUser/:id    | PUT   |        Edits a User             |
|      /newUser/:id    |DELETE |        Deletes a User           |

3. Comment Routes ~~ RestAPI ~~ See Chart for Endpoints

|      Endpoints       | Method|            Other                |
| :------------------: | :----:| :-----------------------------: |
|    /comments         |  GET  | Gets all Users for DS API    |
| /comments/user_comments/:name|GET| Gets comments for a user |

4. Favorites Comment Routes ~~RestAPI ~~ See Chart for Endpoints

|      Endpoints       | Method|            Other                |
| :------------------: | :----:| :-----------------------------: |
|   /favorites:id        |  GET  |   Gets a Comment By ID          |
|    /favorites        | POST  |   Saves A Comment to User Favs   |
|    /favorites/:favorites.id    | DELETE |  Deletes a Comment             |

repository: squashgray/back-end

repo_name: squashgray/back-end


text:
# Day 1
Today I submitted my final proposal at https://github.com/freesers/AppStudioProject/blob/master/README.md
I'm planning to make a WieBetaaldWat-like app for cleaning schedules in student houses. After consulting with a TA i found out the server component can be done using FireBase.

# Day 2
Today I submitted my (first) design document and I met with my group (H)
![](doc/UISketches.png)
The user first logs in or registers, the is presented with a tab bar controller between three main screens. Then there will be a couple loose viewcontrollers either presented modally or with a show - detail style.

![](doc/UtilityModels.png)
The first ideas on how the data should be modeled. The main structures are Users (detailing user information) and Chores.

# Day 3
Today I mainly foccused reading the Human Interface guidelines and working on my prototype. Spent the day reading up on FireBase, articles from John Sundell (https://www.swiftbysundell.com) about GCD and the basics of UserNotifications

# Day 4
The day started off with our first team meeting with Emma, we discussed our projects and prototypes. Fried (teammember) mentioned that he had had a TA telling him FireBase might be too big for the scope of this project. And to use a local server instead. I'm personally not sure yet whether I want to use it or not, as a local server would kind of defeat the purpose of this app. I finished the day with completing my prototype and reading more about FireBase Realtime Storage
Storyboard:
![](doc/Prototype10:01.png)
Detail of first version custom table cell:
![](doc/ChoreTableCellV1.png)

# Day 5
Spent all day trying to get FireBase storage to work, unfortunately too large a hassle to integrate into the project (Should have listened to earlier advice). Decided I will only be using FireBase for Authentication, then using the specific UID in own local server. Will modify the resto server to work with my app.

# Day 6
Today I began modelling the datastructure of the users and houses. I decided I'd create datamodelcontrollers which can be used troughout the app. Still have to figure out how to make it work with the new resto server, Martijn still has to do some modifcations to the server for it to work with the app (filtering in querries).
Then had a team meeting for the basic style guide (https://github.com/freesers/AppStudioProject/blob/master/STYLE.md) and updates. Fried is also waiting on the server to work.
Almost finished with work for user registration. Uses FireBase Auth, for registration and login. Handles most cases (wrong password, same email etc. Decided that if you chose to create a new house, you become the administrator. App warns you about that.
Basic registration screen:
![](doc/RegistrationScreen14jan.png)

# Day 7
I completed the registration procces, users can now register, select or create house, login, logout and stay logged in. One problem when you restart the app but are logged in: loggout unwind segue doesn't work because the loginViewController is not loaded. Couldn't figure it out and no TA available.
Will try to sync users and houses with the server tommorow

# Day 8
Problem from yesterday solved, always boot with loginVC and immediately segue to next screen if already logged in. Further polished registration/login process. After that I started to work with the server. Used a playground to test network functions. Figured out al the code to work with the reste server. I can store multiple key-value pairs in the same array index.
I will use /list & /menu as users and houses. Also encoded image to ascii to store on the server, retrieving and decoding work as well.

# Day 9
The network code to store users on the server works, also loading users to have their information ready throughout the app. Unfortunately, I later realised that the resto server had been updated with new filtering options. Which made previous work unnecessary, I also strugled a very long time with a very simple bug that i only spotted at the end of the day. Hopefully tommorow I can add in the rest of the house info to the server.

# Day 10
Finally figured all the network stuff out, completion blocks in completion blocks... Wrote extensions to UIViewcontroller and UIColor to have keyboarddismissal and custom app color easily available troughout the app. Users can now add basic chore to the table view.

![](doc/addChore.png)
![](doc/launchScreen.png)

# Day 11
Houses and residents can be added, new users can choose existing houses. Users can see the other residents in the house.
Server code had to be adjusted to work with arrays. Networkcode now shows networkactivity indicator. Some buttons have animations

# Day 12
Chores can be updates to the server, including the encoded jpeg image. PNG is too large. Wrote all of the Date & Calender code to keep track of the cleaning day. Chores can be downloaded, only the image doesn't decode yet

# Day 13
Image decoding problem solved. Residents can now upload and delete chores (if they are administrator). And all users download the chores for their house. Residents can now complete a chore by tapping "cleaned", they will have to take a picture as verification. Updated chore is uploaded to server.
To make tableview quicker; all chores are stored in the documents directory, quickly showing the last known chores (and corresponding images), then replacing with the new ones. Will choose not to implement the chore -> detail viewcontroller as it won't present new information. Instead tapping the picture of the chore will show a viewcontroller dedicated for the picture, with zooming capabilities.
### Tasks left:
* image viewcontroller
* automatic schedule
* leave house option
* prettier "residents" tap
* overal prettier design

# Day 14
Finished the imageviewcontroller. Users can now tap an image and pan/zoom the image. The automatic schedule is done. Created quite a few problems because the tableview is dynamic and the number of residents/chores needn't be the same. Made a workaround the loop the residents over the chores. Made an ScheduleController which creates the correct schedule upon opening app.
#### Stretch goal
* local notification to alert user of chore

# Day 15
Schedule didn't change properly when a new week started. To tackle this, the array is shifted at launch of the app from a reference date. Created local notifications with UserNotifications. Users are presented a notification saterday afternoon if they are due for a chore that week. Created an animation to fade in the chores upon launch too look more fluid

###### Saterday
Made sure everything is nicely commented and looks acording to the style guide. And added a little easter egg to the Schedule tab

# Day 16
Made a coherent app design. Settled on a type of blue that is used troughout the app. Choose Futura as font type for most stuff. Fiddled a lot with the chore cell, but finally chose a small blue border around the image and the blue background that shows trough the navigation controller. Tried to add a feature that shows how many chores each resident completed, but too much a hassle so I didn't finish it. Might do it if I have time left tommorow and wednessday.
The resident tab contains a small tableview with the residents. Users can now also leave the house and delete their account.
### TODO:
* app icon
* error messages to the user
* new message delete alert
* loading chores faster
* perform segue before save
* testing
* (stretch) finish chore count

### New Screens:
![](doc/signIn.PNG)
![](doc/register.PNG)
![](doc/chores.PNG)
![](doc/addChore.PNG)
![](doc/schedule.PNG)
![](doc/residentScreen.PNG)
![](doc/delete.PNG)

# Day 17
Made app icon, updated the warning if user wants to leave house. New error messages if something goes wrong with server. Decided not to finish chore count. Not enough time, and want to further polish the existing app. Added functionality that the administrator can only go in editing mode of the chores view if the network request is done. Display a little alert if tapped before network request

# Day 18
Loading chores bug fixed, and now sorts chores on alphabet. Lasts code tweaks. Discussed and tested each others app in the team meeting, talked about features that we decided to skip.

repository: freesers/AppStudioProject

gha_language: Swift

repo_name: freesers/AppStudioProject


text:
# leaflet-html2canvas
A Leaflet plugin to take screenshot using html2canvas

[demo](https://iklotho.github.io/leaflet-html2canvas/examples/index.html).

## Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| hidden | Boolean | false | Show icon or hide. |
| screenName | String | 'screen' | Title of the image downloaded. |
| position | String | 'topleft' | Button position. |
| elementQuery | String | '#container' | The element query to screenshot. |
| iconUrl | String | a camera icon | Icon of the button. |

Inspired by [leaflet-simple-map-screenshoter](https://github.com/grinat/leaflet-simple-map-screenshoter)

branch_name: refs/heads/main


text:
**PHP 7 is required (Windows executables are bundled).**

Supports:

* GF
* AdvExt GF/GE
* HF - thanks to Eressea
* GD - thanks to [@ChaosPaladin](https://github.com/ChaosPaladin)

To run copy `ai.obj` to current folder & run:

```bash
$ php core/main.php
...
```

Or just run `./run.bat` on Windows.

See decompiled code in `ai` directory.

## Command Line Arguments

```
--input         AI file to decompile. Default: 'ai.obj'
--chronicle     AI chronicle. Provide a directory name from the data directory. Default: 'gf'
--language      Resulting language. Provide a file name from the core/generators directory (without .php extension). Default: 'nasc'
--tree          Split result in tree structure. Provide the tree depth (0 - don't split, 1 - flat, more than 3 can cause problems on Windows). Default: 3
--join          Join split classes into one file. Provide a directory which contains the classes.txt file. Default: NULL
--utf16le       Encode output in UTF-16LE instead of UTF-8. NASC Compiler supports only UTF-16LE. Default: false
--test          Run regression tests. Provide a test file name from the tests directory (without .bin extension). Default: NULL
--generate      Generate regression tests. Provide a new test file name (without extension). Default: NULL
```

Example (don't split & convert to UTF16-LE for NASC Compiler):

```
./run.bat --input=gf_off.obj --tree=0 --utf16le=1
```

Join classes & convert to UTF16-LE for NASC Compiler:

```
./run.bat --join=gf_off --utf16le=1
```

## Example

VM code:

```
class 0 hello : (null)

handler 3 23	//  TALKED
	variable_begin
		"i0"
		"talker"
		"myself"
		"_choiceN"
		"_code"
		"_from_choice"
	variable_end

	push_event	//  i0
	push_const 280			//i0
	add
	fetch_i
	branch_false L1
L0
	push_event	//  myself
	push_const 784			//Say
	add
	fetch_i			//Say
S0.	"Hello "
	push_string S0
	push_event	//  talker
	push_const 40			//talker
	add
	fetch_i			//name
	push_const 164			//name
	add
	add_string 1028
	func_call 234946622	//  func[Say]
	shift_sp -1
	shift_sp -1
L1
handler_end

class_end
```

Decompiled code:

```c++
set_compiler_opt base_event_type(@NTYPE_NPC_EVENT)

class hello {
handler:
	EventHandler TALKED(i0, talker) {
		if (i0) {
			Say("Hello " + talker.name);
		}
	}
}
```

repository: master-toma/nasc-decompiler

repo_name: master-toma/nasc-decompiler


text:
---
hrs_structure:
  division: '1'
  volume: '2'
  title: '9'
  chapter: '104'
  section: 104-32
type: hrs_section
tags:
  - Government
menu:
  hrs:
    identifier: HRS_0104-0032
    parent: HRS0104
    name: 104-32 Suspension during emergency
weight: 68095
title: Suspension during emergency
full_title: 104-32 Suspension during emergency
---
**§104-32 Suspension during emergency.** During a national emergency declared by the President or the Congress of the United States, or a state of emergency declared by the governor, subject to the provisions of section 127-10 or 128-7, the governor, by executive order in writing, may suspend this chapter; provided that the governor may not suspend this chapter except in the event such an emergency occurs and is so proclaimed. [L 1995, c 181, pt of §2; am L 2008, c 61, §1]

repository: SamMade/BlueAndKrabby

repo_name: SamMade/BlueAndKrabby


text:
# unittests  for pdbslicer
cd into the unittests directory and then run each unittest file.
## Example

```
[user@csm_server unit_tests]$ ./test.Cut-ByAmino.pl
 ------------------------------------
 new PDBslicer object to create peptide
 ------------------------------------
ok 1 - The object isa OpSym::PDBslicer
parsing file progress: 100.00%
ok 2 - parse_file: single_peptide.pdb
ok 3 - single_peptide.pdb has one model in it
ok 4 - no gaps in pdb struct
 ------------------------------------
 new Cut::ByAmino object to create peptide
 ------------------------------------
ok 5 - The object isa OpSym::Cut::ByAmino
ok 6 - we have 1 aminos in the list
-----
6
#
C        3.674    -0.160    -0.222
C        4.711     0.684     0.027
O        4.510     1.838     0.434
H        2.354     1.437     0.384
H        3.809    -1.046     0.397
H        3.738    -0.441    -1.272
 ------------------------------------
 new Cut::ByAmino object to create peptide  but this time filtered using Filter::Aminos
 ------------------------------------
ok 7 - The object isa OpSym::Cut::ByAmino
ok 8 - we have 0 aminos in the list
 ------------------------------------
 new Cut::ByAmino object to create peptide  but this time filtered using Filter::Aminos
 ------------------------------------
ok 9 - The object isa OpSym::Cut::ByAmino
ok 10 - we have 1 aminos in the list
-----
6
#
C        3.674    -0.160    -0.222
C        4.711     0.684     0.027
O        4.510     1.838     0.434
H        2.354     1.437     0.384
H        3.809    -1.046     0.397
H        3.738    -0.441    -1.272
 ------------------------------------
 new Cut::ByAmino object to create peptide  but this time filtered using Filter::Resseqs
 ------------------------------------
ok 11 - The object isa OpSym::Cut::ByAmino
ok 12 - we have 1 reseqs_list in the list
 ------------------------------------
 new Cut::ByAmino object to create peptide  but this time filtered using Filter::Resseqs
 and create full pdb file from results
 ------------------------------------
ok 13 - The object isa OpSym::PDBslicer
parsing file progress: 100.00%
ok 14 - parse_file: two_peptides_no_model.pdb
ok 15 - {pdb}->[0],'MODEL_No_ZERO_NOT_EXISTS'
ok 16 - {pdb}->[1] is an array( first model)
ok 17 - modle->[0] 'ZERO_PEPTIDE_NOT_EXISTS'
ok 18 - model->[1] is an array( first peptide )
ok 19 - model->[2] is an array( second peptide)
ok 20 - two_peptides.pdb has one model in it
ok 21 - two_peptides.pdb has two peptide in it

1..21

```

repository: continuous-symmetry-measure/pdbslicer

repo_name: continuous-symmetry-measure/pdbslicer


text:
<!-- README.md is generated from README.Rmd. Please edit that file -->

# campout: Converting DataCamp material to another, free format

<!-- badges: start -->

[![Lifecycle:
experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental)
[![Travis build
status](https://travis-ci.org/lwjohnst86/campout.svg?branch=master)](https://travis-ci.org/lwjohnst86/campout)
[![Codecov test
coverage](https://codecov.io/gh/lwjohnst86/campout/branch/master/graph/badge.svg)](https://codecov.io/gh/lwjohnst86/campout?branch=master)
<!-- badges: end -->

The goal of campout is for instructors of a DataCamp course to easily
begin converting their course into an alternative format that allows
others to take their course without having to get a DataCamp
subscription. Use this if you, for instance, want to [distance yourself
from DataCamp](https://noamross.github.io/datacamp-sexual-assault/), had
your course cancelled and still want the material to be available to
others, or you disagree with other aspects of how DataCamp conducts
themselves.

## Installation

You can install the development version from
[GitHub](https://github.com/) with:

``` r
# install.packages("remotes")
remotes::install_github("lwjohnst86/campout")
```

# Usage

So far there is only one conversion to the [learnr
tutorials](https://rstudio.github.io/learnr), with this function:

``` r
datacamp_to_learnr_pkg("path/to/data-camp-course",
                       # Folder the new material will be converted and saved to.
                       "path/to/new-learnr-package",
                       "Your name here")
```

  - **Note**: This roughly converts your DataCamp material to the learnr
    tutorial format… it is *not* perfect\!\! So please make sure to look
    through all your material before publicizing\!
  - Also *note*, so far the slides are only converted to a text
    document, they are not slides. If you have the original videos of
    the slides, you can insert the video link into the chapter
    documents, which will then include the video files for you in the
    tutorial.


text:
# Creating my own to-go restaurant list

## Brief overview

This is ossc final project of Group 11.

The name of our project is **"Creating my own to-go restaurant list"**.

By crawling data of one hundred data for each of the 25 boroughs in Seoul from _MangoPlate_(망고플레이트), Korea's trusted restaurant review site.

The crawled four items are as follows:

    - the borough which the restaurant belongs
    - restaurant name
    - rating by reviewers
    - restaurant type (Korean, Chinese, Western...)

Crawled data are stored in **Excel(.xlsx)** file.

(We excluded restaurants that don't have a rating.)

To start, when a user clicks on '파일 선택' button and select the downloaded xlsx file, a table appears in which restaurants throughout Seoul have high ratings.

Simply click on the section of the map above that you want to visit to see the results categorized by borough.

Enter one of the following in the text box: "한식, 양식, 일식, 중식, 디저트" to see the results categorized by restaurant type.

Finally, you can add the restaurant that you want to go to the list and manage your own list.

**Whenever you are wondering which restaurant to go to, visit this website and check your list! :)**

## Link of resources

1. crawling

-   https://m.blog.naver.com/owl6615/221518357627
-   https://galid1.tistory.com/478
-   https://hello-bryan.tistory.com/194

2. reading xlsx file in javascript

-   https://eblo.tistory.com/83
-   https://code.tutsplus.com/ko/tutorials/parsing-a-csv-file-with-javascript--cms-25626

3. mapping by region

-   https://woodstar.tistory.com/124

4. making my own list

-   https://github.com/e-/skku-todo-2.git

## Screenshots of the web page

## Short demo video link

>Making my own list by taking a look at restaurants in all of Seoul

   https://www.youtube.com/watch?v=-5eOaU17v1Y

>Making my own list by taking a look at restaurants within the selected borough

   https://www.youtube.com/watch?v=f5eYgoCO5Ws

## Installation

**CRAWL**

You can download the excel file from this git repo and use it, but if you want to do crawling on your own:

    1. Download CRAWL.py, seoul.txt, chromedriver.exe
    2. Edit seoul_file_path in CRWAL.py to your file path
    3. Edit chrome_driver_path in CRWAL.py to your file path
    4. Do 'pip install selenium' on command line
    5. Run CRAWL.py
    6. As the homepage of mangoplate comes up, you need to click the popup manually to crawl normally
    7. Check the excel file!

## Code of Conduct

- If you want to see the list of restaurants in all of Seoul . . .
```
1. Click on '파일 선택' button.
2. Enter one of the following in the text box: "한식, 양식, 일식, 중식, 디저트".
 ```
- If you want to see the list of restaurants within the selected borough by restaurant type . . .
```
1. Click on '파일 선택' button.
2. Click on the image section that corresponds to the borough.
3. Enter one of the following in the text box: "한식, 양식, 일식, 중식, 디저트".
```

## Examples (of screenshots above)

Person A wants to visit '일식'(Japanese) restaurant in '은평구'!

Then, A should follow the directions below:
```
1. Click '파일 선택' button and select 'Mat-zip-list.xlsx' file
2. Click on '은평구' of the map above
3. Enter '일식'(Japanese) in the text box
4. Add the restaurant that you want to go to your own list!
```

## API reference

We directly parsed HTML page and crawled data without utilizing API...

## Releases (versions)

v1.0.1 (Latest release)

## How to contribute

    1. Fork our repo to your account
    2. Modify your own repo
    3. Write pull request
    4.

## License

    MIT license


text:
# How-To

So you've followed some of our TrueNAS guides, setup your domain name, certificates and use Cloudflare for your DNS management, however you don't have a static IP, then this guide is for you. This quick guide will help you go through the steps to use Cloudflareddns to update your dynamic IP along with your entire deployment so that even if you change IP your domain will point to the right address.

## Requirements

Domain name (can be purchased through Cloudflare or any other domain registrar)

Cloudflare DNS management

- Sign up for Cloudflare free
- Point your nameservers to the ones Cloudflare assigns to you

  ![cloudflare-ns](img/cloudflare-ns.png)

Cloudflareddns chart

## Prerequisites

This guide assumes you've followed our [clusterissuer guide](https://truecharts.org/charts/enterprise/clusterissuer/how-to) with your domain on TrueNAS and done the configuration for your DNS on Cloudflare

The recommended way is to setup CNAMEs for your subdomains (charts) and keep your A record pointed to your base domain, such as below

![cloudflare-dns](img/cloudflare-dns.png)

> Create an API Token, with the following permissions:
> Click `Create Token` and `Use Template` on the Edit zone DNS.
>
> - Zone - DNS - Edit
> - Zone - Zone - Read
>
> And the following Zone resources
>
> - Include - Specific zone - yourdomain.com
>
>   ![cloudflare-token](img/cloudflare-token.png)

## Cloudflareddns Chart Setup

![cloudflare-config](img/cloudflare-config.png)

Use API Token previously created for the `CF API Token` field.

Click Add for Hosts, Zones and Record Types.

- Change `Domain` to your DNS Zone A record (yourdomain.com)
- Change `Zone` to DNS Zone ID found on the Cloudflare Overview Page for your domain.
- Change `Record Type` to A if you're only changing your main domain

If you're using or changing specific A records or CNAMEs you may want to refer to the upstream documentation for more examples [here](https://hotio.dev/containers/cloudflareddns/))

repository: mcowger/charts

repo_name: mcowger/charts