text:
# 2 Modeling

## 2.1 Equation oriented models

A low pass filter block with input `u` and output `y`

```math
\begin{aligned}
T \cdot \frac{dx}{dt} + x &= u\\
     y &= x \\
x(t_0) &= 0
\end{aligned}
```
can be defined as:

```julia
using Modia

LowPassFilter = Model(
    T = 0.2,
    u = input,
    y = output | Var(:x),
    x = Var(init=0),
    equations = :[T * der(x) + x = u],
)
```

The symbols `input` and `output` refer to predefined variable constructors to define the input and output variables.
If an equation has just a unique variable in the left hand side, `y`, the right hand side can be given as a quoted expression in a Var-constructor `Var(:x)` after the `output` constructor combined with the merge operator, `|`, see below.

## 2.2 Merging models

It is possible to combine models by merging.
If we want to change the model to become a high-pass filter, an alternative output equation

```math
y = -x + u
```

is defined in an anonymous model `Model( y = :(-x + u) )`.
This anonymous model is merged with `LowPassFilter` using the merge operator `|`:

```julia
HighPassFilter = LowPassFilter | Model( y = Var(:(-x + u) ) )
```

The merging implies that the `output` property of `y` is kept, but the binding expression is changed from `:x` to `:(-x + u)`.

In general, recursive merging is desired and Modia provides a `mergeModels` function for that (see appendix [A.3 MergeModels algorithm](@ref)).
This function is invoked as a binary operator `|` (also used for merge in Python).
Note, that the order of the arguments/operands are important.

Generalizing the block to have two outputs for both low and high pass filtering would be done as follows:

```julia
LowAndHighPassFilter = LowPassFilter | Model(
        y = nothing,
        low = output | Var(:x),
        high = output | Var(:(-x + u)),
    )
```
The equation for `y` is removed by "assigning" `nothing` and two variables are defined and declared as outputs.

Model `LowAndHighPassFilter` represents the following equations:

```math
\begin{aligned}
T \cdot \frac{dx}{dt} + x &= u\\
     low &= x \\
    high &= -x + u \\
x(t_0) &= 0
\end{aligned}
```

By turning on logging of merging `setLogMerge(true)`, the translator gives the log:

```julia
Adding: value = :(x)
Adding: value = :(-x + u)
Deleting: y
Adding: low = Var(
      output = true,
      value = :(x),
    ),
Adding: high = Var(
      output = true,
      value = :(-x + u),
    ),
```

The resulting model is pretty printed by calling `@showModel LowAndHighPassFilter`:

```julia
LowAndHighPassFilter = Model(
  T = 0.2,
  u = Var(
    input = true,
  ),
  x = Var(
    init = 0.0 V,
  ),
  equations = :([T * der(x) + x = u]),
  low = Var(
    output = true,
    value = :(x),
  ),
  high = Var(
    output = true,
    value = :(-x + u),
  ),
),
```

## 2.3 Functions and tables

In order to test an input/output block as defined in the previous section, an input needs to be defined.
This can be made by adding an equation for `u`.
Assume we want `u` to be sinusoidal with an increasing frequency:

```julia
TestLowAndHighPassFilter = LowAndHighPassFilter | Model(
        u = :(sin( (time+1u"s")*u"1/s/s" * time)*u"V"),
        x = Var(init=0.2u"V")
    )
```

`time` is a reserved name for the independent variable.
It has unit `s` for seconds.
The Julia package [Unitful](https://painterqubits.github.io/Unitful.jl/stable/) provides a means for defining units and managing unit inference.
It need not be explicitly defined, because its symbols are exported by `using Modia`.
Definition of units is done with a string macro `u"..."`.
In this case, the input signal was given unit Volt.
The state `x` must then also have consistent unit, that is Volt.
If the model equations contain systems of simultaneous equations, then approximate guess values, optionally with units, must be given `start`: `i = Var(start=0.0u"A")`.

The input signal can also be defined by interpolation in a table:

```julia
using Interpolations

table = CubicSplineInterpolation(0:0.5:2.0, [0.0, 0.7, 2.0, 1.8, 1.2])
TestLowAndHighPassFilter2 = TestLowAndHighPassFilter | Map(u = :(table(time*u"1/s")*u"V"))
```

It is possible to call Julia functions that have more than one return argument:

```julia
function ref(time)
    y1 = sin(time)
    y2 = cos(time)
    return (y1,y2)
end

TestMultiReturningFunction1 = Model(
    equations = :[
        (y1,y2) = ref(time)
        y3 = y1+y2
    ]
)
```

The returned arguments are typically numbers or arrays (see below).
It is also possible to return an instance of a `struct` and, say,
pass this instance as input to another function call.

It is currently not supported that a function call modifies one of its arguments,
or that a function call returns no argument at all:

```
equations = :[
    fc!(u,y)                   # Error: Not known that fc! computes y
    println("This is a test")  # Error: One equation is introduced but no unknown
]
```

## 2.4 Hierarchical modeling

So far, the composition of models has resulted in dictionaries of key/value pairs with values being numeric values or quoted expressions.
Hierarchical models are obtained if the values themselves are `Models`, i.e. dictionaries.
A model with two filters can, for example, be defined as follows:

```julia
TwoFilters = Model(
    high = HighPassFilter,
    low = LowPassFilter,
)
```

Note, that the previous definitions of `HighPassFilter` and `LowPassFilter` was used instead of making the Model definitions inline.

A band pass filter is a series connection of a high pass filter and a low pass filter and can be described as:

```julia
BandPassFilter = Model(
    u = input,
    y = output,
    high = HighPassFilter | Map(T=0.5, x=Var(init=0.1u"V")),
    low = LowPassFilter | Map(x=Var(init=0.2u"V")),
    equations = :[
        high.u = u,
        low.u = high.y,
        y = low.y]
)
```

A new input, `u`, has been defined which is propagated to `high.u`.
The series connection itself is obtained by the equation `low.u = high.y`.
Note, that dot-notation is allowed in equations.

The input and output for the `BandPassFilter` when using the same input definition as for the `TestLowPassFilter`

```julia
TestBandPassFilter = BandPassFilter | Map(
        u = :(sin( (time+1u"s")*u"1/s/s" * time)*u"V")
    )
bandPassFilter = @instantiateModel(TestBandPassFilter)
simulate!(bandPassFilter, Tsit5(), stopTime = 50u"s")
plot(bandPassFilter, ["u", "y"], figure=2)
```

is shown below:

![Band Pass Filter Plot](../../resources/images/BandPassFilterPlot.png)

## 2.5 Physically oriented modeling

So far, only signal flow modeling has been used, i.e. input/output blocks coupled with equations between outputs and inputs.
For object oriented modeling more high level constructs are necessary.
Coupling is then acausal and involves potentials such as electric potential, positions, pressure, etc. and flows such as electric current, forces and torques and mass flow rate.

### 2.5.1 Connectors

Models which contain any `flow` variable, i.e. a variable having an attribute `flow=true`, are considered connectors.
Connectors must have equal number of flow and potential variables, i.e. variables having an attribute `potential=true`, and have matching array sizes.
Connectors may not have any equations.
An example of an electrical connector with potential (in Volt) and current (in Ampere) is shown below.

```julia
Pin = Model( v = potential, i = flow )
```

The value `potential` is a shortcut for `Var(potential=true)` and similarly for `flow`.

### 2.5.2 Components

Components are declared in a similar ways as blocks.
However, the interfaces between components are defined using connector instances.

An electrical resistor can be described as follows:

```julia
Resistor = Model(
    R = 1.0u"Ω",
    p = Pin,
    n = Pin,
    equations = :[
        0 = p.i + n.i
        v = p.v - n.v
        i = p.i
        R*i = v ]
    )
```

### 2.5.3 Inheritance

Various physical components sometimes share common properties.
One mechanism to handle this is to use inheritance.
In Modia, **merging** is used.

Electrical components such as resistors, capacitors and inductors are categorized as `OnePort`s which have two `Pin`s.
Common properties are: constraint on currents at the pins and definitions of voltage over the component and current through the component.

```julia
OnePort = Model(
    p = Pin,
    n = Pin,
    equations = :[
        0 = p.i + n.i
        v = p.v - n.v
        i = p.i ] )
```

Having such a `OnePort` definition makes it convenient to define electrical component models by merging `OnePort` with specific parameter definitions with default values and equations:

```julia
Resistor = OnePort | Model( R = 1.0u"Ω", equations = :[ R*i = v ], )

Capacitor = OnePort | Model( C = 1.0u"F", v=Map(init=0.0u"V"), equations = :[ C*der(v) = i ] )

Inductor = OnePort | Model( L = 1.0u"H", i=Map(init=0.0u"A"), equations = :[ L*der(i) = v ] )

ConstantVoltage = OnePort | Model( V = 1.0u"V", equations = :[ v = V ] )
```

The merged `Resistor` is shown below:

```julia
Resistor = Model(
  p = Model(
    v = Var(potential = true),
    i = Var(flow = true),
  ),
  n = Model(
    v = Var(potential = true),
    i = Var(flow = true),
  ),
  equations = :([v = p.v - n.v; 0 = p.i + n.i; i = p.i, R * i = v]),
  R = 1.0 Ω,
),
```

Note, there is a special merge-rule that the vectors of keys `equations` are appended.

### 2.5.4 Connections

Connections are described as an array of tuples listing the connectors that are connected:

```julia
    ( <connect reference 1>, <connect reference 2>, ... )
```

A connect reference has either the form 'connect instance name' or 'component instance name'.'connect instance name' with 'connect instance name' being either a connector instance, input or output variable.

Examples
```julia
    connect = :[
      (V.p, R1.p)
      (R1.n, p)
      (C1.n, V.n, R2.p)
      ...
    ]
```

For connectors, all the potentials of the connectors in the same connect tuple are set equal and the sum of all incoming flows to the model are set equal to the sum of the flows into sub-components.
A Modelica inspired form of connections, i.e. connect-equations, are also supported:

```julia
    equations = :[
      connect(V.p, R1.p)
      connect(R1.n, p)
      connect(C1.n, V.n, R2.p)
      ...
    ]
```

### 2.5.5 Connected models

Having the above electrical component models, enables defining a filter

![Filter Circuit](../../resources/images/Filter.png)

by instantiating components, setting parameters and defining connections.

```julia
Filter = Model(
    R = Resistor | Map(R=0.5u"Ω"),
    C = Capacitor | Map(C=2.0u"F"),
    V = ConstantVoltage | Map(V=10.0u"V"),
    connect = :[
      (V.p, R.p)
      (R.n, C.p)
      (C.n, V.n)
    ]
)
```

The connect tuples are translated to:

```julia
  V.p.v = R.p.v
  0 = V.p.i + R.p.i
  R.n.v = C.p.v
  0 = R.n.i + C.p.i
  C.n.v = V.n.v
  0 = C.n.i + V.n.i
```

### 2.5.6 Parameter propagation

Hierarchical modification of parameters is powerful but sometimes a bit inconvenient.
It is also possible to propagate parameters introduced on a high level down in the hierarchy.
The following Filter model defines three parameters, `r`, `c` and `v`.
The `r` parameter is used to set the resistance of the resistor R: `Map(R=:r)`.

```julia
Filter2 = Model(
    r = 2.0u"Ω",
    c = 1.0u"F",
    v = 10u"V",
    R = Resistor | Map(R=:r),
    C = Capacitor | Map(C=:c),
    V = ConstantVoltage | Map(V=:v),
    connect = :[
      (V.p, R.p)
      (R.n, C.p)
      (C.n, V.n)
    ]
)
```

Two separate filters can then be defined with:

```julia
TwoFilters = Model( f1 = Filter | Map( r = 10.0, c = 2.0), f2 = Filter )
```

### 2.5.7 Re-declarations

It is possible to reuse a particular model topology by re-declaring the models of particular components.
For example, changing the filter `f1` to a voltage divider by changing `C` from a Capacitor to a Resistor.
A predefined definition `redeclare` is used for this purpose.

```julia
VoltageDividerAndFilter = TwoFilters | Map(f1 = Map(C = redeclare | Resistor | Map(R = 20.0)))
```

By using `redeclare`, a new model based on a Resistor is used for `C` and the usual merge semantics with the previously defined model of `C` is not used.

The above examples are available in file `FilterCircuit.jl`.

### 2.5.8 Drive train example

A larger example that utilizes most of the previously described features of Modia is available as `$(Modia.path)/examples/ServoSystem.jl`.
This is a textual (Modia) representation of a Modelica model

![ServoSystem](../../resources/images/ServoSystem.png)

and demonstrates how to build up a hierarchical, multi-domain model consisting of a servo-system with a load, where the servo-system consists of an electric motor with a current and speed controller, as well with a more detailed model of a gearbox.

## 2.6 Arrays

Model parameters and variables can be arrays.
For example a linear state space system

```math
\begin{aligned}
\frac{d\boldsymbol{x}}{dt} &= \boldsymbol{A} \cdot \boldsymbol{x} + \boldsymbol{B} \cdot \boldsymbol{u}\\
            \boldsymbol{y} &= \boldsymbol{C} \cdot \boldsymbol{x} + \boldsymbol{D} \cdot \boldsymbol{u}
\end{aligned}
```

can be defined as:

```julia
StateSpace = Model(
    A = fill(0.0, 0, 0),
    B = fill(0.0, 0, 0),
    C = fill(0.0, 0, 0),
    D = fill(0.0, 0, 0),
    u = input,
    y = output,
    x = Var(init = zeros(0)),
    equations = :[
        der(x) = A*x + B*u
             y = C*x + D*u
    ]
)
```

and used as:

```julia
SecondOrder = Model(
    w = 20.0,
    D =  0.1,
    k =  2.0,
    sys = StateSpace | Map(A = :([  0        1;
                                 -w^2  -2*D*w]),
                           B = :([0; w^2;;]),    # Julia 1.7: Trailing ";;" defines a column matrix
                           C = :([k 0]),
                           D = :(zeros(1,1)),
                           x = Var(init = zeros(2)) ),
    equations = :[sys.u = [1.0]]
)
```

Variables `sys.u` and `sys.y` are vectors with one element each.

Note, `[0; w^2]` is a vector in Julia and not a column matrix.
In order that `B` is defined as column matrix, the Julia 1.7 feature is used to append two semicolons, that is,
`[0; w^2;;]`

Array equations remain array equations during symbolic transformation and in the generated code,
so the code is both compact and efficient.
In order that this is reasonably possible, the definition of an array cannot be split in different statements:

```julia
equations = :[             # error, vector v is not defined as one symbol
    m1*der(v[1]) = 2.0
    m2*der(v[2]) = 3.0
]
```

If scalar equations are needed in which arrays are used, then the arrays have to be first defined and then elements can be used.

```julia
v = Var(init=zeros(2)),
equations = :[
    a = der(v)
    a1 = a[1]
    a2 = a[2]
    m1*a1 = 2.0
    m2*a2 = 3.0
]
```

When the `init` or `start` value of an array variable is defined as a [StaticArrays.jl `StaticArray`](https://github.com/JuliaArrays/StaticArrays.jl),
then the type of this array variable will be `StaticArray` in the generated code.
The benefit is that array operations are more efficient:

```julia
using StaticArrays
TestArray1 = Model
    v = Var(init=SVector{3,Float64}(1.0, 2.0, 3.0)),
    equations = :[der(v) = -v]
)
testArray1 =  @instantiateModel(TestArray1, logCode=true)
```

Note, the generated code is shown in the REPL if `logCode=true` is defined:

```julia
function getDerivatives(_x, _m::Modia.InstantiatedModel{_FloatType,_TimeType} ...
    ...
    v::ModiaBase.SVector{3,_FloatType} = ModiaBase.SVector{3,_FloatType}(_x[1:3])
    var"der(v)" = -v
    ...
```

The sizes of StaticArrays variables cannot be changed, after `@instantiatedModel` was called.
However, the sizes of standard array variables can be changed with keyword argument `merge` in `simulate!`
(so no re-generation and re-compilation of the code is needed):

```julia
TestArray2 = Model(
    v = Var(init=[1.0, 2.0, 3.0]),   # length(v) = 3
    equations = :[der(v) = -v]
)
testArray2 = @instantiateModel(TestArray2)
simulate!(testArray2, stopTime=2.0, merge=Map(v = [4.0, 3.0, 2.0, 1.0]))   # length(v) = 4
plot(testArray2, "v", figure=5)
```

## 2.7 Model libraries

Modia provides a small set of predefined model components in directory `Modia.modelsPath`:

- `AllModels.jl` - Include all model libraries
- `Blocks.jl` - Input/output control blocks
- `Electric.jl` - Electric component models
- `HeatTransfer.jl` - 1D heat transfer component models
- `Rotational.jl` - 1D rotational, mechanical component models
- `Translational.jl` - 1D translational, mechanical component models
- [PathPlanning](@ref) - Defining reference trajectories and access them.

The desired libraries must be explicitly included with the help of utility
path variable `Modia.modelsPath`. For example, the circuit of section [2.5.5 Connected models](@ref)
is constructed with these libraries in the following way:

```julia
using Modia
include("$(Modia.modelsPath)/Electric.jl")

FilterCircuit = Model(
    R = Modia.Resistor  | Map(R=0.5u"Ω"),
    C = Modia.Capacitor | Map(C=2.0u"F", v=Var(init=0.1u"V")),
    V = Modia.ConstantVoltage | Map(V=10.0u"V"),
    ground = Modia.Ground,
    connect = :[
      (V.p, R.p)
      (R.n, C.p)
      (C.n, V.n, ground.p)
    ]
)

filterCircuit = @instantiateModel(FilterCircuit)
simulate!(filterCircuit, Tsit5(), stopTime=10.0)
@usingModiaPlot
plot(filterCircuit, ["C.v", "C.i"], figure=3)
```

It is planned to support a much larger set of predefined model components in the future.

gha_language: Julia


text:
# Oracle Content and Experience Toolkit

Templates and resources for development platforms.

| Folder  | Description |
| ------------- | ------------- |
|  [Root](/../../) | Link to root folder.|
|  [Sites](Sites/) | Work with tools to create, test, and package your own site templates, themes, and components.|

repository: BobLies/doc

branch_name: refs/heads/master

extension: md

license_type: permissive

repo_name: BobLies/doc


text:
# agnoster.zsh-theme

A ZSH theme optimized for people who use:

- Solarized
- Git
- Unicode-compatible fonts and terminals (I use iTerm2 + Menlo)

For Mac users, I highly recommend iTerm 2 + Solarized Dark

# Compatibility

**NOTE:** In all likelihood, you will need to install a [Powerline-patched font](https://github.com/Lokaltog/powerline-fonts) for this theme to render correctly.

To test if your terminal and font support it, check that all the necessary characters are supported by copying the following command to your terminal: `echo "\ue0b0 \u00b1 \ue0a0 \u27a6 \u2718 \u26a1 \u2699"`. The result should look like this:

![Character Example](https://gist.githubusercontent.com/agnoster/3712874/raw/characters.png)

## What does it show?

- If the previous command failed (✘)
- User @ Hostname (if user is not DEFAULT_USER, which can then be set in your profile)
- Git status
  - Branch () or detached head (➦)
  - Current branch / SHA1 in detached head state
  - Dirty working directory (±, color change)
- Working directory
- Elevated (root) privileges (⚡)

![Screenshot](https://gist.githubusercontent.com/agnoster/3712874/raw/screenshot.png)

## Customize your prompt view

By default prompt has these segments: `prompt_status`, `prompt_context`, `prompt_virtualenv`, `prompt_dir`, `prompt_git`, `prompt_end` in that particular order.

If you want to add, change the order or remove some segments of the prompt, you can use array environment variable named `AGNOSTER_PROMPT_SEGMENTS`.

Examples:
- Show all segments of the prompt with indices:
```
echo "${(F)AGNOSTER_PROMPT_SEGMENTS[@]}" | cat -n
```
- Add the new segment of the prompt to the beginning:
```
AGNOSTER_PROMPT_SEGMENTS=("prompt_git" "${AGNOSTER_PROMPT_SEGMENTS[@]}")
```
- Add the new segment of the prompt to the end:
```
AGNOSTER_PROMPT_SEGMENTS+="prompt_end"
```
- Insert the new segment of the prompt = `PROMPT_SEGMENT_NAME` on the particular position = `PROMPT_SEGMENT_POSITION`:
```
PROMPT_SEGMENT_POSITION=5 PROMPT_SEGMENT_NAME="prompt_end";\
AGNOSTER_PROMPT_SEGMENTS=("${AGNOSTER_PROMPT_SEGMENTS[@]:0:$PROMPT_SEGMENT_POSITION-1}" "$PROMPT_SEGMENT_NAME" "${AGNOSTER_PROMPT_SEGMENTS[@]:$PROMPT_SEGMENT_POSITION-1}");\
unset PROMPT_SEGMENT_POSITION PROMPT_SEGMENT_NAME
```
- Swap segments 4th and 5th:
```
SWAP_SEGMENTS=(4 5);\
TMP_VAR="$AGNOSTER_PROMPT_SEGMENTS[$SWAP_SEGMENTS[1]]"; AGNOSTER_PROMPT_SEGMENTS[$SWAP_SEGMENTS[1]]="$AGNOSTER_PROMPT_SEGMENTS[$SWAP_SEGMENTS[2]]"; AGNOSTER_PROMPT_SEGMENTS[$SWAP_SEGMENTS[2]]="$TMP_VAR"
unset SWAP_SEGMENTS TMP_VAR
```
- Remove the 5th segment:
```
AGNOSTER_PROMPT_SEGMENTS[5]=
```

A small demo of the dummy custom prompt segment, which has been created with help of the built-in `prompt_segment()` function from Agnoster theme:
```
# prompt_segment() - Takes two arguments, background and foreground.
# Both can be omitted, rendering default background/foreground.

customize_agnoster() {
  prompt_segment 'red' '' ' ⚙ ⚡⚡⚡ ⚙  '
}
```
![Customization demo](https://github.com/apodkutin/agnoster-zsh-theme/raw/customize-prompt/agnoster_customization.gif)

## Future Work

I don't want to clutter it up too much, but I am toying with the idea of adding RVM (ruby version) and n (node.js version) display.

 I guess it's not overly so for comparable themes, but it bugs me, and I'd love to hear ideas about how to improve the performance.

Would be nice for the code to be a bit more sane and re-usable. Something to easily append a section with a given FG/BG, and add the correct opening and closing.

Also the dependency on a powerline-patched font is regrettable, but there's really no way to get that effect without it. Ideally there would be a way to check for compatibility, or maybe even fall back to one of the similar unicode glyphs.

license: MIT

repository: hfcorreia/dotfiles

branch_name: refs/heads/main

gha_language: Shell

gha_license_id: MIT

repo_name: hfcorreia/dotfiles


text:
# How to report the bug？

### Report the bug detail
> - **Important：** You need have a [Github](https://github.com) account.
> - Provide your problem information：
  - Kaku version
  - OS platform and version
  - Open DevTools and switch to ** Console Panel ** and copy the **Error Message**：
    - Mac：cmd + option + i
    - Linux：ctrl + alt + i
    - Windows：ctrl + alt + i
  - Maybe you can snap image give our more information.
> - Which platform you are using to listen to music. _（Youtube、Vimeo、SoundCloud）_
> - Which song caused the problem or you can even use `settings -> backup to local` feature to export your playlist contain that song and share it for debugging use.
> - Any error you found on the UI part.
> - Finally, open a new [issue](https://github.com/EragonJ/Kaku/issues) report bug.

## How to open DevTools？

### Mac
Click cmd + option + i open it：

![console panel](http://imgur.com/f6pAgSP.png)

### Linux & Windows
Click ctrl + alt + i open it：

![console panel](http://imgur.com/GTlm7rY.png)

then you can copy error message from **Console** panel.

## Open a new issue
Click [here](https://github.com/EragonJ/Kaku/issues) you can open a new issue.

1. Click **New Issue**.

![Open a new issue](http://imgur.com/97okREc.png)

2. You can write your error message or snap image pass here use [Markdown](https://zh.wikipedia.org/wiki/Markdown) format,
then you can preview your content, finally submit a new issue.

![issue content](http://imgur.com/uoGEXOB.png)

repository: EragonJ/Kaku-website

branch_name: refs/heads/gh-pages

gha_language: HTML

repo_name: EragonJ/Kaku-website


text:
##### Scala notes continued from Structuring information : https://www.scala-exercises.org/scala_tutorial/structuring_information
* case class to group the related data
* seal trait to define set of values for variable, compiler warning in case of not handling all the cases.
* equal to operator can perform the comparison between objects.

##### https://www.scala-exercises.org/scala_tutorial/higher_order_functions
* anonymous function
  * why do we need to have x=>x ???
* Higher order function : function taking function as argument or returing function as value

##### https://www.scala-exercises.org/scala_tutorial/standard_library
* right association
```
println(1 :: (5 to 10) ::xs) ==> List(1, Range(5, 6, 7, 8, 9, 10), 2, 3, 4)

println(xs .:: (5 to 10) .:: (1)) ==> List(1, Range(5, 6, 7, 8, 9, 10), 2, 3, 4)

println(1 :: xs .:: (2)) ==> List(1, 2, 2, 3, 4)
```
* optional value : may have None or Some()

 ```
 def abc : Option[String] = if (true) None else Some("1")
abc
 ```

* Either, Left, Right
  * in "Some" case we have either type of the variable or None case
  * In Either case we can have type of the variable or any specified type.
  * Right keyword explicitly mentions it is 2nd type in Either case
  * Similarly, Left indicates the first type mentioned in the Either declaration.
  * fetching left or right value
  ```
  val aa = Left(2)
  println( aa.left.get == 2) ==> true
  println(aa.right.get == 2) ==>
  java.util.NoSuchElementException: Either.right.value on Left
  ```

* val type does not allow re assignment but allows appending
 ``` val builder1 = new StringBuilder; builder1 += 'A';builder1 += 'C'; println(builder1)```: ```AC```

* lazy evaluation:
  * it is pretty intuitive but the coding can go tricky
  ```
  val builder = new StringBuilder

  val x = { builder += 'x'; 1 }
  lazy val y = { builder += 'y'; 2 }
  def z = { builder += 'z'; 3 }

  z + y + x + z + y + x

  builder.result() shouldBe
  "xzyz"

  ```
  * Let us see in details how it works and results in "xzyz":
    * Note that x and y are val; though y is lazy it is a val. Therefore, both will have the value only once.
    * z is definition/function without parameter and hence will execute the fixed operation each time called.
    * Now, since x is defined first, value 'x' goes into to builder for the first and last time and also x gets a value 1
    * size y is defined lazy 'y' does not goes into builder at the time of definition and also would not get value 2
    * z is not lazy but it is a function and hence it would not put value 'z' into builder until called.

    * Now let us look at the execution order:
      * 'z' value is appended to builder and 3 is in memory ==> Output: xz and sum = 3
      * 'y' value si appended to builder and 2 gets added to 3 ==> Output: xzy and sum = 5
      * 1 gets added to 5 ==> Output: xzy and sum = 6
      * 'z' value is appended to builder and 3 gets added to 6 ==> output xzyz and sum = 9
      * 2 gets added to 9 ==> Output: xzyz and sum = 12
      * 1 gets added to 12 ==> Output: builder = xzyz and sum = 13

* tuples:

```
val a  = (1,2)
val (b,c) = a
println(b,c)

Here b = 1 and c is 2
```

* OOPs
  * default variables inside class is public, need to specify private to make it private
  ```
  class abc(x:Int){
  val xx = x
  }

  println(new abc(10).xx)
  ```
  * Not only defines a class but also constructor
  * auxillary constructor - this constructor
  * abstract class = cannot have object instantiation, may or may not define function, class extending can override the method and parameter
  * def + (x : class_name) = operator overriding

* difference between foreach and map : https://stackoverflow.com/questions/17080186/difference-between-map-and-foreach-method-in-scala
 * foreach does not have any return of values and works on the same principle as that of map
 * map works on each of the items on which it is applied (usually list) and return the set of transformed items.

* Imperative programming : https://www.scala-exercises.org/scala_tutorial/imperative_programming
 * to see the python like value assignment we need to have the variable declared as var x : Any. This would allow x to have value of an integer or a string too or for that matter "Any"thing.

* ```(1 until 3).foreach(i=> "abcd".foreach(j => println(s"$i $j")))```
  * for each of 1,2 values associate each of "abcd". How? println inthis just a simple association. It could be anything. Note that foreach takes a function that operates on one instance of the var to which it is associated. This function can be anonymous. Anymous function do not have name but like other function operates on variable and hence starts witha variable and right hand side of "=>" this determines the body of it.

 * ```(1 until 3).foreach(x => println(x)) : Note that ``` : Note that here we did not mention the data type of x. Even if you mentioned data type it would fail with syntax error. The reason being the foreach function takes the array or object on which it is being used as reference and provide the same to println. Therefore no data type is required.

 * ```val aa = {i:Any => println(i)} ; aa("abcd","abcd")```: ```(abcd,abcd)``` = Here we need to define the type of the variable i because it is being passed to it and hence it has to be explicit about what is being passed and nothing to infer about the data type. Note that here it can take any number of argumets :)

 * ```val states = Map("AL" -> List(1,2,3,4), "AK" -> "Alaska"); states("AL")``` : equivalent to python dictionary
    * states += ("KA"-> "Karnataka") would fail here because states is "val" but works fine if it was "var"

* Type Classes:
  * to define a generic class which can cater to different class type.

* partial function vs curried function:
```
def isInRange(left: Int, right: Int, n: Int): Boolean = {
    if (left < n && n < right) true else false
}

val a = (isInRange _).curried

val b = a(10)

val c=  b(30)

val abc = isInRange(20, 30,_ :Int)

println(abc(0))

println(c(0))
```
* Let us read the above code:
 * isInRange will take 3 parameter; 3rd parameter is check for existing between first 2 parameters.
 * now curried function let us create a function with respect each of those parameters in isInRange function.
   * note that here it lets you create a function with respect one parameter only
 * however, partial functions lets u change multiple parameter at a go.
 * That does not say partial is better over curried.
   * curried not only simplifies the code
   * and also confirms that we have addressed all the parameters

path: /Scala Notes.md

filename: Scala Notes.md


text:
---
layout: post
title: 30 Years of Programming & My First Programs
tags: [programming]
image: /images/ms-dos/qbasic-screenshot.png
---

The other day I was thinking about how much experience I have programming. After all, that's a common question that comes up in job interviews.

Which led me to wonder how long ago I wrote my first program. That was a very long time ago - after all, I've been using computers since I was in the single digits. I'm sure I also wrote my first program when I was in the single digits.

I know I didn't program on the first computer I ever used - a Tandy (probably a [Tandy 1000](https://en.wikipedia.org/wiki/Tandy_1000)) that I remember my grandpa getting. It didn't have a hard drive - and what program we ran depended on what floppy disk (and I'm talking about 5'¼' floppies that were actually *floppy*) we put in it. The only things we did on that thing were play games like Hangman and T-Road, or print out birthday cards on its dot matrix printer.

{% include image.html src="/images/tandy-hangman.png" alt="Hangman on the Tandy" caption="Hangman on the Tandy. Source <http://toastytech.com/guis/deskmate3.html>" %}

It wasn't until my mom brought home a computer from her work that things began to get interesting. It was a PC in the 86 series - either a 286, 386, or 486 or even all of the above since they upgraded her over the years - loaded with MS-DOS. Eventually, it even had [Windows 3.1](https://en.wikipedia.org/wiki/Windows_3.1x).

In addition to playing games and visiting [BBSs](https://en.wikipedia.org/wiki/Bulletin_board_system), I liked to poke around the file system. I noticed there were three types of files that ran: .exe files, .com files, and .bat files. I also knew I could edit text files with the EDIT command.

So I opened up an EXE file with the EDIT command, only to be greeted with a bunch of gobbledygook:

{% include image.html src="/images/ms-dos/move.exe-in-edit.exe-screenshot.png" alt="An EXE file open in the MS-DOS EDIT program." caption="An EXE file open in the MS-DOS EDIT program. Screenshot taken from <https://www.pcjs.org/software/pcx86/sys/dos/microsoft/6.22/>" %}

This didn't deter me - instead, I made my own EXE file with a bunch of gobbledygook.

When I ran the program, the computer reset. I thought *I just wrote a program that resets the computer!*

So is this the first program I wrote? Was it even a program?

I don't know the answer to that, but I do know I also took a peek at the BAT files.

BAT files - or more accurately MS-DOS Batch files - are simply a list of command prompt commands. BAT files still exist today - you can script standard command prompt commands - or even PowerShell commands. But what made this like "programming" is that certain commands such as IF that were useless if you were typing yourself, but valuable when scripting.

I remember making a few text-based games where you can go to only a few places. And one of those places was grandma's house.

Finally, I stumbled across QBasic. An actual honest-to-goodness programming language.

{% include image.html src="/images/ms-dos/qbasic-screenshot.png" alt="QBasic's splash screen." caption="QBasic's splash screen. Screenshot taken from <https://www.pcjs.org/software/pcx86/sys/dos/microsoft/6.22/>" %}

After going through a Basic programming book over a couple of nights (its title was something like *Basic Programming for Ages 1 through 100*) I was simply fascinated by the things I could do.

One game I made was a simple number guessing game. The computer chose a number between one and a hundred, and you had to guess what it was in a certain number of guesses. Each guess and the computer would tell you if the number was higher or lower. (Binary search, anyone?)

My most ambitious project involved an animation of Mario walking across the screen. And I say ambitious because I never got it to work quite right - QBasic could only output text, so I drew each frame only to clear the screen and draw the next frame. Frames per second? More like frames per minute.

Onto the original question - how long ago was this? It was sometime after my mom remarried (so after July 1992) but before [Windows 95](https://en.wikipedia.org/wiki/Windows_95) (so before August 1995, although we probably didn't get it right away). This means I was somewhere between 8 and 11.

As of today, that could mean I have upwards of 30 years of programming experience.


text:
# pyopendnp3

This project is a minor fork of the great
[pydnp3](https://github.com/ChargePoint/pydnp3) library, which provides Python
bindings for OpenDNP3.

Why fork? Because pydnp3 only provides pip-friendly wheels for Python 2
and Python 2.7 has reached end of life. This fork aims to provide pip-friendly
wheels for Python 3 available on PyPI.

While the name of the project is pyopendnp3, module names are unchanged and
thus code that worked with pydnp3 should work with no changes.

This project currently produces wheels for the following platforms:

* Windows
  * Python 3.5 x86-64
  * Python 3.6 x86-64
  * Python 3.7 x86-64
  * Python 3.8 x86-64

The remainder of this README is reproduced verbatim from pydnp3.

Python bindings for the [opendnp3](https://github.com/automatak/dnp3) library,  an open source
implementation of the [DNP3](http://ww.dnp.org) protocol stack written in C++14.

Note:  This is a work in progress.  See [Issues](http://github.com/Kisensum/pydnp3/issues) for things we know about and feel free to add your own.

**Supported Platforms:** Linux, MacOS

## Dependencies
To build the library from source, you must have:

* A toolchain with a C++14 compiler
* CMake >= 2.8.12 (https://cmake.org/download/)

This repository includes two repositories as submodules (under `deps/`):

* dnp3 (https://github.com/automatak/dnp3)
* pybind11 (https://github.com/Kisensum/pybind11) - This is a fork containing a minor patch
required to compile some of the pydnp3 wrapper code. It will be replaced with pybind11 proper
when the issue is resolved.

## Build & Install
At the moment, this library must be built from source:
```
    $ clone --recursive http://github.com/Kisensum/pydnp3
    $ cd pydnp3
    $ python setup.py install
```

## Documentation

pydnp3 is a thin wrapper around most all of the opendnp3 classes.  Documentation for the opendnp3
classes is available at [automatak](https://www.automatak.com/opendnp3/#documentation).

Use python's help to discover the available wrapper classes and functions.  For example,

```
> import pydnp3
> help (pydnp3.opendnp3)
Help on module pydnp3.opendnp3 in pydnp3:

NAME
    pydnp3.opendnp3 - Bindings for opendnp3 namespace

FILE
    (built-in)

CLASSES
    pybind11_builtins.pybind11_object(__builtin__.object)
        AnalogCommandEvent
        AnalogInfo
            AnalogSpec
...
```

gha_language: Python


text:
---
layout: post
title: "SPEECH-COCO: 600k Visually Grounded Spoken Captions Aligned to MSCOCO Data Set"
date: 2019-02-26 16:32:37
categories: arXiv_CV
tags: arXiv_CV Caption
author: William Havard, Laurent Besacier, Olivier Rosec
mathjax: true
---

* content
{:toc}

##### Abstract
This paper presents an augmentation of MSCOCO dataset where speech is added to image and text. Speech captions are generated using text-to-speech (TTS) synthesis resulting in 616,767 spoken captions (more than 600h) paired with images. Disfluencies and speed perturbation are added to the signal in order to sound more natural. Each speech signal (WAV) is paired with a JSON file containing exact timecode for each word/syllable/phoneme in the spoken caption. Such a corpus could be used for Language and Vision (LaVi) tasks including speech input or output instead of text. Investigating multimodal learning schemes for unsupervised speech pattern discovery is also possible with this corpus, as demonstrated by a preliminary study conducted on a subset of the corpus (10h, 10k spoken captions).

##### Abstract (translated by Google)

##### URL
[https://arxiv.org/abs/1707.08435](https://arxiv.org/abs/1707.08435)

##### PDF
[https://arxiv.org/pdf/1707.08435](https://arxiv.org/pdf/1707.08435)


text:
# Voice activity detection using subband noncircularity
Code for paper [1] presented at ICASSP 2015. Please cite this paper if you find this code useful! There are two main scripts ready to be run out of the box:

main_demo.m Reproduces figures 3 and 4 from [1]

main_test_circ_vad.m Computes the single-channel summed degree of impropriety (SDOI) metric from [1] on the included example audio, which comes from the QUT-NOISE corpus [2].

[1] S. Wisdom, G. Okopal, L. Atlas, and J. Pitton, “Voice Activity Detection Using Subband Noncircularity,” in Proceedings of IEEE International Conference on Acoustics, Speech, and Signal Processing (ICASSP), Brisbane, Austrailia, 2015.

[2] D. B. Dean, S. Sridharan, R. J. Vogt, and M. W. Mason, “The QUT-NOISE-TIMIT corpus for the evaluation of voice activity detection algorithms,” in Proc. Interspeech, Makuhari, Japan, 2010.


text:
# Spring Doge - Such Boot!

```
cf push -p target/demo-0.0.1-SNAPSHOT.jar  -b  https://github.com/cloudfoundry/java-buildpack.git  doge

http://www.java-allandsundry.com/2014/08/deploying-spring-boot-application-to.html
```

Interesting introduction [to deploying Spring Boot applications using Spring Cloud](http://www.java-allandsundry.com/2014/08/deploying-spring-boot-application-to.html)
https://gist.github.com/relaxdiego/7539911

https://github.com/pivotal-cf/java-8-buildpack/blob/master/docs/example-java_main.md

## Building and running the application using docker and docker-compose

The maven build for this project integrates with Docker using the [Spotify Maven plugin](https://github.com/spotify/docker-maven-plugin). You need to have Docker installed and configured. See [Installing Docker](https://docs.docker.com/installation/).

In order to build a docker image:
```
mvn package
```

You can customize the Docker Hub user for your image (by default it will create chanezon/spring-doge) in spring-doge/pom.xml.

Then to run the app:
```
docker-compose -f spring-doge/target/docker-compose.yml up
```

## Old Building and running with Docker

You can use STS or a locally installation of maven to build spring-doge. However, if you need to build that on a new machine where you don't have all your development environment setup, you can build it with the maven Docker container.

```
docker run -v ~/.m2:/root/.m2 -v "$PWD":/usr/src -w /usr/src maven:3-jdk-8 mvn install
```

This will create the spring-doge jar file in target.
Then, you can build a container for the app and run the app and a Mongodb database in containers with the following commands:

```
docker build -t foo/spring-doge .
docker-compose up
```

Change chanezon to your docker hub username (change it also in the docker-compose.yml file) if you want to push a modification to this image to your repository in Docker hub.

repository: trecloux/spring-doge

repo_name: trecloux/spring-doge


text:
# Front End Engineer Challenge – IPL

A data visualization challenge to build a web app with IPL (Indian Premier League) data provided in CSV files. Goal was to present stats and interesting information about IPL to someone who knows about cricket but has not seen IPL.

  - Great UI/UX
  - Responsive Design
  - Mobile friendly

![Screetshot of Project](https://i.ibb.co/d0HycDW/Capture2.png)

## Built With
  - [React](https://reactjs.org/) - the web framework used
  - [Chart.js](https://www.chartjs.org/) - used to create charts
  - [node.js](http://nodejs.org) - for the backend
  - [jQuery](http://jquery.com) - javaScript library
  - [Papaparse](https://www.papaparse.com/) - for parsing CSV files to JSON

## Dataset
  - [Click Here](https://www.kaggle.com/harsha547/indian-premier-league-csv-dataset)

## Link to Hosted Website
  - [Click Here](https://socialcops.netlify.com)
  *(Hosted on Netlify)*

## Bonus Points Explanation
  - I used React instead of Vue solely because I'm more familiar with React, although I'm very keen on learning Vue as well.
  - Used a fast library, papaparser, for parsing all CSV data. I've used CSS whereever possible for best performance and used best practices for writing Javascript code.
  - The website is fully mobile responsive, I've made sure that every little detail looks good on mobile! I focused on making an easy-to-use User Interface (UI) for great constrast and visual appeal. Added a fullscreen mode toggle to enhance User Experience (UX). Moreover, I've written all CSS code by myself without any library.
  - It is a progressive webapp as verified on [Lighthouse](https://developers.google.com/web/tools/lighthouse/). It is fast and reliable, installable, PWA optimized.
  - It is also usable offline.

## Thought Process
  - Idea was to use the SocialCops yellow and dark grey color scheme as yellow also happens to be one of my favorite colors.
  - I searched through all the given datasets to look for attributes that would intrigue a person who knows cricket but has never watched IPL.
  - I wanted the Navigation bar to initially be in 'full' state while browsing on desktop and in 'minimal' state while on mobile to give mobile users more space yet have menu items easily accessible in one click.
  - I was duelling over whether to choose Chart.js or D3.js for my charting library. I went with Chart.js as it provided many predefined graphs, just what I needed for my time constraint.
  - When looking for a CSV file parsing solution, papaparser was the best one I could find.
  - Making a mobile responsive website is a must in 2019. With mobile in-mind, I carefully planned my layout design. I used grid layout and flex box for most of my layout design process.
  - The top bar seemed empty, so I added a search bar that would fit in with the design scheme.
  - Used Poppins and Lato as fonts for this challenge, both being popular and modern choices. For the icons I used Font Awesome Pro.
  - I decided to add a fullscreen toggle button in the header bar because an admin panel is best viewed in fullscreen. Less clutter, the better. :)

## Potential New Features/Improvements
  - Storing parsed JSON data in database for faster reading.
  - Can add a loading animation while the data and graphs are loading.
  - Display more data related to players such as who won the most purple caps?
  - Make a trivia using this data to make the web app more fun and interactive.
  - Light/Dark Theme

repository: PawanKolhe/IPL-Data-Challenge

gha_language: JavaScript

repo_name: PawanKolhe/IPL-Data-Challenge


text:
Movie Booking System

Requirements:

* Able to select a city where our system has affiliated cinema are present
* Each cinema has multiple halls and each hall can run a movie one at a time
* Each movie will have multiple show
* We can search a movie by name, language, rating, release date
* Each movie has multiple shows running at a time
* Movies you may like
* Trailer of the movie
* Each show has a cinema hall assigned and has seating arrangement
* There are multiple types of seat available: recliner, silver, gold
* System should be able show distinction between booked and available seats
* Select show, seat and Book the ticket based on number of user
* No two user can book the same seat
* User can cancel the booked ticket
* Notification for booked, canceled and new movie release
* Can apply coupons while making a transaction

repository: kamalnis/systemdesign

repo_name: kamalnis/systemdesign


text:
## Docker команды

[Шпаргалка по docker](https://habr.com/ru/company/flant/blog/336654/)
[DO guide-1](https://www.digitalocean.com/community/tutorials/how-to-build-a-node-js-application-with-docker)
[DO - How To Secure a Containerized Node.js Application with Nginx, Let's Encrypt, and Docker Compose](https://www.digitalocean.com/community/tutorials/how-to-secure-a-containerized-node-js-application-with-nginx-let-s-encrypt-and-docker-compose)
[Как установить Nginx в Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/nginx-ubuntu-18-04-ru)

### Команды для Windows
```sh
docker-machine start default
docker-compose up --build
```
### Команды для использования

`docker ps -a`  ---  посмотреть запущеные контейнеры
`docker run -it <container_name>`  ---  запуск контейнера по идентефикатору
`docker inspect app_nginx_1 | grep IPAddress | cut -d '"' -f 4`  ---  узнать ip nginx
`docker exec -it <id of container> bash`  ---  зайти в контейнер и запустить bash

## Структура

- api -- сервис
- bin --- находятся скрипты для запуска docker
- database -- база данных
- logs -- логи доступа и ошибки nginx
- nginx -- конфигурация прокси-сервера
- static -- статичные файлы (стили, шрифты, скрипты, картинки ...)
- web -- приложение

[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors)
[![license](https://img.shields.io/github/license/mashape/apistatus.svg?style=flat-square)](LICENSE)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)

[![Watch on GitHub](https://img.shields.io/github/watchers/paralect/docker-compose-starter.svg?style=social&label=Watch)](https://github.com/paralect/docker-compose-starter/watchers)
[![Star on GitHub](https://img.shields.io/github/stars/auxilincom/docker-compose-starter.svg?style=social&label=Stars)](https://github.com/auxilincom/docker-compose-starter/stargazers)
[![Follow](https://img.shields.io/twitter/follow/auxilincom.svg?style=social&label=Follow)](https://twitter.com/auxilin)
[![Tweet](https://img.shields.io/twitter/url/https/github.com/auxilincom/docker-compose-starter.svg?style=social)](https://twitter.com/intent/tweet?text=I%20run%20my%20development%20environment%20with%20a%20simple%20command%20using%20docker-compose%20%F0%9F%9A%80.%20Check%20it%20out:%20https://github.com/auxilincom/docker-compose-starter)

Run your development environment with a single command using docker-compose 🚀.
This repository was boarn with aim to share how simple development environment could be with [docker-compose](https://docs.docker.com/compose/). If you ever had to perform 100 steps to run a new project you will like this a lot. You could read more on the problem in [this blog post](https://blog.maqpie.com/2017/02/22/fully-automated-development-environment-with-docker-compose/).

## Features

* 🔥 **Simple project start** run your development evnrionment with a single command
* 🙀 **Environment agnostic** with [docker-compose](https://docs.docker.com/compose/) you can run your project on Mac, Windows or Linux environments without any issues.
* ⚡ **Multi-language projects** choose whatever language you need to solve the problem, but keep development environment easy for developers.

## Getting Started

`./bin/start.sh` — starts entire application
`./bin/run-tests.sh` — runs tests using docker-compose

The repository consists 4 demo-purpose independent services:
1. Landing - a landing site
2. Web - a simple frontend that serves client side assets for React application and do some server side rendering.
3. Api - a restful api.
4. Admin - an admin site

For learning purpose just pay attention to the following files:
1. [Dockerfile](./api/Dockerfile)
2. [Dockerfile.dev](./api/Dockerfile.dev)
3. [package.json](./api/package.json)
4. [docker-compose.yml](./docker-compose.yml)
5. [docker-compose.local-tests.yml](./docker-compose.local-tests.yml)
6. [.env](./.env)

### Separate Dockerfile for development

Dockerfile.dev used to run every project on local environment. There are two reasons for using separate dockerfile for local environments:

1. To run application using Nodemon, which automatically restart application on code change. (same can be achieved by overriding `command` in docker-compose.yml)
2. Production Docker files has `npm run build && npm prune --production`. That needed to keep your Docker images smaller, by removing devDependencies after `build` step has been completed. In this step you would typically use Webpack, Gulp or any other bundlers / task runners.

If image size is not an issue - I would recommend to keep same Dockerfile for both development and production environments. You might also want to look into [this](https://github.com/paralect/docker-compose-starter/issues/3) discussion

## Прототип
[Github](https://github.com/paralect/docker-compose-starter/)

repository: Titiaiev/docker-compose-starter

repo_name: Titiaiev/docker-compose-starter


text:
# Brackets Elixir

Provides primitive highlighting for [Elixir](http://elixir-lang.org). It's at least a step up from telling Brackets you're using Ruby.

This extension is nothing more than glue between [halohalospecial](https://github.com/halohalospecial)'s [codemirror-elixir-mode](https://github.com/halohalospecial/codemirror-elixir-mode) and [BigBlueHat](https://github.com/BigBlueHat)'s [brackets-langman](https://github.com/BigBlueHat/brackets-langman).

## Contributing

Want Brackets-Elixir improved? Me too! Feel free to open an issue or PR here on github.

## License

[MIT](http://opensource.org/licenses/mit)

Glued together by Matt Enlow ([@novaugust](http://github.com/novaugust) on most parts of the internet)

repository: novaugust/brackets-elixir

repo_name: novaugust/brackets-elixir