Chaste File Formats
General
- .cable
-
File defining 1D elements that can be used in a MixedDimensionMesh. It has almost the same format as a .ele file.
The difference is that the attribute field (rightmost column) of the .cab file is a floating point number (rather than a
non-negative integer). This attribute represents the radius of the cable element.
- .dat
-
This extension is used as a flexible format for several purposes.
- Simulation statistics. The structure of each file varies depending on the data they contain. The structure should be described by comments in the methods which write these data.
An example is the CellAgesWriter class:
- The output is a single value [current simulation time], followed by a tab, followed by a sequence of space-separated values.
- This sequence has the form '...[location index] [x-pos] [y-pos] [z-pos] [cell age] ...' where [y-pos] and [z-pos] are included for 2 and 3 dimensional simulations, respectively.
- Also used for the fixed-width space-separated column data file format, written by the ColumnDataWriter class, and compatible with Gnuplot.
- First line is a header, of the form Name1(units1) Name2(units2) ... NameN(unitsN).
- Subsequent lines give the data. Columns are padded with spaces to a fixed width, determined by the precision argument to the writer constructor.
They are all, however, data files with a similar structure suitable for plotting with Gnuplot.
- .edge
-
Edge file for Triangle or Tetgen format meshes.
- First line: <number of edges> <number of boundary markers (0 or 1)>
- Optional marker BIN at the end of the first line indicates
that all following data are presented as raw binary data with no
whitespace (this is a Chaste modification of the Triangle format)
- Following lines: <edge number> <endpoint node> <endpoint node> [boundary marker]
- Lines starting with a hash (#) are comments
- .ele
-
Element file for Triangle or Tetgen format meshes.
- First line: <number of elements> <nodes per element> <numer of attributes>
- Optional marker BIN at the end of the first line indicates
that all following data are presented as raw binary data with no
whitespace (this is a Chaste modification of the Triangle format)
- Remaining lines: <element number> <node> <node> <node> ... [attributes]
- Lines starting with a hash (#) are comments
- .exnode
-
CMGUI node format, see the Cmgui guide.
- .exelem
-
CMGUI element format, see the Cmgui guide.
- .face
-
Faces file for Tetgen format meshes.
- First line: <number of faces> <boundary marker (0 or 1)>
- Optional marker BIN at the end of the first line indicates
that all following data are presented as raw binary data with no
whitespace (this is a Chaste modification of the Triangle format)
- Remaining lines: <face number> <node> <node> <node> [boundary marker]
- Lines starting with a hash (#) are comments
- .h5
-
HDF5 format used for cardiac simulation results. HDF5 represents data in a hierarchical way. Each file contains different datasets, with each dataset containing dataspaces and attributes. Every HDF5 file generated by Chaste defines two main datasets:
- Data, containing:
- A 3D array with the simulation results. First dimension being timestep number, second node number, and third variable index.
- Variable Details: attribute with the variable names and units.
- IsDataComplete: attribute to say whether the file contains information for all the nodes in the mesh or only for a subset.
- Chaste Provenance: attribute giving provenance information (Chaste release, time, OS and machine built on).
- Time, containing:
- A 1D array with the time at the end of each timestep.
- Unit: attribute with the unit of time.
The program h5dump (if installed) can be used to view the contents of small HDF5 files. Larger datasets can be converted to Meshalyzer, CMGUI or VTK readable files using the classes Hdf5ToMeshalyzerConverter, Hdf5ToCmguiConverter or Hdf5ToVtkConverter. One of these is generally called at the end of a cardiac simulation that writes HDF5 data.
- .info
-
There are 3 different sorts of .info file:
- archive.info is read and written by the cardiac archiving code, and is not for user consumption.
- The ColumnDataWriter also creates a .info file, to tell it how many variables of different types there are.
- The final kind, named "something_times.info", is created by the cardiac post-processing code, to give a human readable summary of the timesteps used.
- .log
-
Used for test output.
- .ncl
-
Node connectivity file for Triangle or Tetgen format meshes. For each mesh node, records which elements contain the node. Note that this file format is not part of the standard Triangle or Tetgen format, but can be created by Chaste and then used to make the mesh load faster in parallel.
- First line: <number of nodes> <maximum number of containing elements>
- Marker BIN at the end of the first line indicates
that all following data are presented as raw binary data with no
whitespace (this is a Chaste modification of the Triangle format).
All .ncl files are binary.
- Remaining lines: <node number> <element> <element> <element> ... [padding to ensure all lines are equal length]
- .node
-
Nodes file for Triangle or Tetgen format meshes.
- First line: <number of nodes> <space dimension> <number of attributes> <number of boundary markers (0 or 1)>
- Optional marker BIN at the end of the first line indicates
that all following data are presented as raw binary data with no
whitespace (this is a Chaste modification of the Triangle format)
- Remaining lines: <node number> <x> [<y>] [<z>] [attributes] [boundary marker]
- Lines starting with a hash (#) are comments
- .vtu
-
An XML file format used to visualize simulation results in a VTK visualizer. The file format represents a Chaste mesh as a vtkUnstructuredGrid, with each variable represented as point data. The file consists of:
- XML headers that define the data structure (vtkUnstructuredGrid), the number of nodes (called points in VTK) and elements (called cells in VTK) in the grid and the point data defined on it.
- Data as a sequence of ASCII characters.
Cardiac
- .axi
-
Defines the fibre direction for each element (used for setting up axisymmetric (transversely isotropic) conductivity tensors).
- First line: <number of elements>
- Following lines give the primary (longitudinal) fibre direction vector for each element
For the binary version
- First line: <number of elements> BIN
- The following line gives the primary (longitudinal) fibre direction vector for each element as raw binary
- .epi
-
Used to specify a list of node numbers (one column) of the nodes belonging to the epicardial surface.
- .endo
-
Used to specify a list of node numbers (one column) of the nodes belonging to the endocardial surface.
- .mid
-
Used to specify a list of node numbers (one column) of the nodes belonging to the midmyocardial surface.
- .ortho
-
Defines the fibre, sheet and normal directions for each element (used for setting up orthotropic (anisotropic) conductivity tensors).
- First line: <number of elements>
- Following lines give the fibre direction vectors for each element,
primary/longitudinal direction, then transverse/laminar direction, then normal, i.e. fibre1 fibre2 fibre3 sheet1 sheet2 sheet3 normal1 normal2 normal3
For the binary version
- First line: <number of elements> BIN
- The following line gives the primary/longitudinal fibre direction, then transverse/laminar direction, then normal vector for each element as raw binary
- .pts
-
Meshalyzer (used for visualisation) nodes format. First line is <number of nodes>. Following lines are the nodal coordinates.
- .tri
-
Meshalyzer (used for visualisation) triangles format. Represents elements in 2D, and boundary elements in 3D.
- .tetra
-
Meshalyzer (used for visualisation) elements format.
Cell-based
- *.arch
-
File format for a saved (archived) simulation.
- build.info
-
Details of computer setup for a particular cell_based chaste simulation. This contains information on versions of libraries used and the revision of the Chaste code.
- results.parameters
-
Details of all the classes and parameters used in a cell_based chaste simulation.
- *.dat
-
General format of results files written by cell writer classes, which include a range of different properties of cells at each printing timestep. These take different
formats but, as a representative example, the file cellages.dat (which is written using the class CellAgesWriter) consists of space-separated lines of the form
[time] [location index] [cell 0 x-pos] [cell 0 y-pos] [cell 0 z-pos] [cell 0 age] [cell 1 x-pos] [cell 1 y-pos] [cell 1 z-pos] [cell 1 age].... Note that if
VTK output is switched on, then cell writer objects also output VTK data for the cell population at each printing timestep.
- .viz*
-
General format of results files written by cell_based chaste for the Visualize2dCentreCells.java and Visualize2dVertexCells.java programs.
- .vizancestors
-
The ancestor index of each cell at each timestep in a CellBasedSimulation. Each line has the form time ancestor_1 ancestor_2 ... ancestor_n.
- .vizbetacatenin
-
The levels of membrane-bound, cytoplasmic and nuclear beta-catenin in each cell at each timestep in a CryptSimulation2d.
Each line has the form time location_index_1 x_1 y_1 b_cat_membrane_1 b_cat_cytoplasm_1 b_cat_nuclear_1 ...
location_index_n x_n y_n b_cat_membrane_n b_cat_cytoplasm_n b_cat_nuclear_n.
- .vizboundarynodes
-
Whether each node at each timestep in a CellBasedSimulation is a boundary node. Each line has the form time bool_1 bool_2 ... bool_n.
- .vizcelltypes
-
The cell type of each cell at each timestep in a CellBasedSimulation. Each line has the form time c_1 c_2 ... c_n.
- .vizcellphases
-
The cell cycle phase that each cell is in at each timestep in a CellBasedSimulation. Each line has the form time p_1 p_2 ... p_n.
- .vizcoarsepdesolution
-
The solution to a PDE, associated with a CellBasedSimulation, which is solved on a 'coarse' mesh for efficiency. In 2D, each line has the form time coarse_mesh_node_index_1 coarse_mesh_node_x_1 coarse_mesh_node_y_1 solution_at_coarse_mesh_node_1 ... coarse_mesh_node_index_n coarse_mesh_node_x_n coarse_mesh_node_y_n solution_at_coarse_mesh_node_n.
- .vizelements
-
The nodes associated with each element at each timestep in
a CellBasedSimulation.
For a mesh-based simulation
(visualised with Visualize2dCentreCells) where elements have
exactly 3 nodes, each line has the form time element1_node1 element1_node2 element1_node3 ... elementn_node1 elementn_node2 elementn_node3.
For a vertex or Potts simulation
(visualised with Visualize2dVertexCells) where elements have varying
numbers of node, each line has the form time element1_size
element1_node1 element1_node2 element1_node3 element1_node4 ... elementn_size elementn_node1 elementn_node2 elementn_node3.
- .vizlocationindices
-
The location of each cell each timestep in a CaBasedCellPopulation, which allows for multiple occupancy of lattice sites. Each line has the form time location_index_1 ... location_index_n
Also used in MeshBasedCellPopulationWithGhostNodes to indicate which nodes have cells attached.
- .viznodes
-
The position of each node at each timestep in a CellBasedSimulation. Each line has the form time x_1 ... x_n in 1D, time x_1 y_1 ... x_n y_n in 2D and time x_1 y_1 z_1... x_n y_n z_n in 3D.
- .vizpdesolution
-
The solution to a PDE, associated with a CellBasedSimulation, which is solved on a 'coarse' mesh for efficiency. In 2D, each line has the form time location_index_1 x_1 y_1 solution_1 ... location_index_n x_n y_n solution_n.
- .vizsetup
-
The cell_based visualiser setup file. This contains such things as mesh_width for periodic simulations.
- .vizstress
-
The stress distribution in a MeshBasedCellPopulation, measured by the extremal normal forces on each cell. Each line has the form time location_index_1 x_1 y_1 minimum_normal_force_1 maximum_normal_force_1 ... location_index_n x_n y_n minimum_normal_force_n maximum_normal_force_n.


404
It seems this page doesn't exist.
If you're looking for what to do next, you could take a look at our community garden.
{{ define "main"}}
It seems this page doesn't exist. If you're looking for what to do next, you could take a look at our community
garden.
404


JGR: Java GUI for R
Java GUI for R - cross-platform, universal and unified Graphical User Interface for R. For full functionality on Windows and Mac OS X JGR requires a start application which depends on your OS.
| Version: |
1.8-6 |
| Depends: |
R (≥ 3.0.0), rJava (≥ 0.9-5), JavaGD (≥ 0.6) |
| Suggests: |
XLConnect |
| Published: |
2018-07-12 |
| Author: |
Markus Helbig, Simon Urbanek, Ian Fellows |
| Maintainer: |
Markus Helbig <info at markushelbig.de> |
| License: |
GPL-2 |
| URL: |
http://rforge.net/JGR/ |
| NeedsCompilation: |
no |
| SystemRequirements: |
Java JDK 1.4 or higher |
| Materials: |
NEWS |
| CRAN checks: |
JGR results |
Downloads:
Reverse dependencies:
Linking:
Please use the canonical form
https://CRAN.R-project.org/package=JGR
to link to this page.


A family is like a forest, when you are outside it is dense, when you are inside you see that each tree has its place.
~ Afrikan Proverb


Description
    -
Design
    -
Specifications
    -
Finish
Description
Name
summery
Full Description
Math behind the game
Credits(Ex..Programmer</br>-Bob)
Design
image(resources/images/...)
Color(should be similar to image background)
Specifications
ID in Boxes.js(last number in brackets + 1)
Link(projects/.../index.html)
beta
date(YYYY-MM-DD)
Specifications
1. Add to Boxes.js
2. Create HTML file in "[Link]/" named "game.html"
3. Create HTML file in "[Link]/" named "index.html"


Ben Healy Added To Munster Squad While Leinster Make Five Changes
by Michael CorryMunster have added 20-year-old out-half Ben Healy in place of Alex Wootton to their Champions Cup squad ahead of Saturday’s Pool 4 opener against the Ospreys.
With first-choice ten Joey Carbery out injured and back-up J.J Hanrahan a doubt for this weekend, Munster are light of options with Tyler Bleyendaal the side’s only available out-half.
Despite Johann van Graan suggesting that both Rory Scannell and Conor Murray could provide emergency cover at out-half, it is expected that youngster Healy will be involved in the matchday 23 squad off the back of his inclusion.
Meanwhile, Leinster have added five players to their squad with Scott Penny, Ryan Baird, Ciarán Frawley, Cian Kelleher and Bryan Byrne replacing Dan Leavy, Jack Conan, Barry Daly, Fergus McFadden and Vakh Abdaladze.
Ulster have not made any changes to their squad ahead of their meeting with Bath on Saturday.
Connacht have added two players to their squad ahead of Saturday’s meeting with Montpellier. 20-year-old lock Niall Murray and prop Peter McCabe come into the squad in place of the injured duo Sean O’Brien and Paddy McAllister.
Montpellier, meanwhile, have registered former All Blacks out-half Aaron Cruden in place of Springboks World Cup winner Handré Pollard.
Each of the nominations may be reversed before the knockout stages.


The following security groups could not be found in the selected account/region/VPC and were removed:
The following server groups in the same cluster have different security groups:
Security groups last refreshed {{ getSecurityGroupRefreshTime() | timestamp }} refreshing...
If you're not finding a security group that was recently added, click here to refresh the list.


I'm a self taught web developer, freelancer from Tunisia. I'm currently working as a remote freelancer and building my own apps. My passion is to use technology based solutions, to help solve real world challenges.


The following documentation is written to be packaged with Zenject as it appears in the Asset store (which you can find here)
Zenject is a lightweight dependency injection framework built specifically to target Unity 3D. It can be used to turn your Unity 3D application into a collection of loosely-coupled parts with highly segmented responsibilities. Zenject can then glue the parts together in many different configurations to allow you to easily write, re-use, refactor and test your code in a scalable and extremely flexible way.
Tested in Unity 3D on the following platforms: PC/Mac/Linux, iOS, Android, WP8, and Webplayer
This project is open source. You can find the official repository here.
For general troubleshooting / support, please use the google group which you can find here. If you have found a bug, you are also welcome to create an issue on the github page, or a pull request if you have a fix / extension. You can also follow @Zenject on twitter for updates. Finally, you can also email me directly at<EMAIL_ADDRESS>Quick Start: If you are already familiar with dependency injection and are more interested in the syntax than anything else, you might want to start by looking over the cheatsheet at the bottom of this page, which shows a bunch of typical example cases of usage.
Unity is a fantastic game engine, however the approach that new developers are encouraged to take does not lend itself well to writing large, flexible, or scalable code bases. In particular, the default way that Unity manages dependencies between different game components can often be awkward and error prone.
Having worked on non-unity projects that use dependency management frameworks (such as Ninject, which Zenject takes a lot of inspiration from), the problem irked me enough that I decided a custom framework was in order. Upon googling for solutions, I found a series of great articles by Sebastiano Mandalà outlining the problem, which I strongly recommend that everyone read before firing up Zenject:
Sebastiano even wrote a proof of concept and open sourced it, which became the basis for this library.
What follows in the next section is a general overview of Dependency Injection from my perspective. I highly recommend seeking other resources for more information on the subject, as there are many (often more intelligent) people that have written on the subject. In particular, I highly recommend anything written by Mark Seeman on the subject - in particular his book 'Dependency Injection in .NET'.
Finally, I will just say that if you don't have experience with DI frameworks, and are writing object oriented code, then trust me, you will thank me later! Once you learn how to write properly loosely coupled code using DI, there is simply no going back.
When writing an individual class to achieve some functionality, it will likely need to interact with other classes in the system to achieve its goals. One way to do this is to have the class itself create its dependencies, by calling concrete constructors:
public class Foo
{
ISomeService _service;
public Foo()
{
_service = new SomeService();
}
public void DoSomething()
{
_service.PerformTask();
...
}
}
This works fine for small projects, but as your project grows it starts to get unwieldy. The class Foo is tightly coupled to class 'SomeService'. If we decide later that we want to use a different concrete implementation then we have to go back into the Foo class to change it.
After thinking about this, often you come to the realization that ultimately, Foo shouldn't bother itself with the details of choosing the specific implementation of the service. All Foo should care about is fulfilling its own specific responsibilities. As long as the service fulfills the abstract interface required by Foo, Foo is happy. Our class then becomes:
public class Foo
{
ISomeService _service;
public Foo(ISomeService service)
{
_service = service;
}
public void DoSomething()
{
_service.PerformTask();
...
}
}
This is better, but now whatever class is creating Foo (let's call it Bar) has the problem of filling in Foo's extra dependencies:
public class Bar
{
public void DoSomething()
{
var foo = new Foo(new SomeService());
foo.DoSomething();
...
}
}
And class Bar probably also doesn't really care about what specific implementation of SomeService Foo uses. Therefore we push the dependency up again:
public class Bar
{
ISomeService _service;
public Bar(ISomeService service)
{
_service = service;
}
public void DoSomething()
{
var foo = new Foo(_service);
foo.DoSomething();
...
}
}
So we find that it is useful to push the responsibility of deciding which specific implementations of which classes to use further and further up in the 'object graph' of the application. Taking this to an extreme, we arrive at the entry point of the application, at which point all dependencies must be satisfied before things start. The dependency injection lingo for this part of the application is called the 'composition root'.
There are many misconceptions about DI, due to the fact that it can be tricky to fully wrap your head around at first. It will take time and experience before it fully 'clicks'.
As shown in the above example, DI can be used to easily swap different implementations of a given interface (in the example this was ISomeService). However, this is only one of many benefits that DI offers.
More important than that is the fact that using a dependency injection framework like Zenject allows you to more easily follow the 'Single Responsibility Principle'. By letting Zenject worry about wiring up the classes, the classes themselves can just focus on fulfilling their specific responsibilities.
Another common mistake that people new to DI make is that they extract interfaces from every class, and use those interfaces everywhere instead of using the class directly. The goal is to make code more loosely coupled, so it's reasonable to think that being bound to an interface is better than being bound to a concrete class. However, in most cases the various responsibilities of an application have single, specific classes implementing them, so using an interfaces in these cases just adds unnecessary maintenance overhead. Also, concrete classes already have an interface defined by their public members. A good rule of thumb instead is to only create interfaces when the class has more than one implementation. This is known, by the way, as the Reused Abstraction Principle)
Other benefits include:
What follows is a general overview of how DI patterns are applied using Zenject. For further documentation I highly recommend the sample project itself (a kind of asteroids clone, which you can find by opening "Extras/SampleGame/Asteroids.unity"). I would recommend using that for reference after reading over these concepts.
You may also find the cheatsheet at the bottom of this page helpful in understanding some typical usage scenarios.
The unit tests may also be helpful to show usage for each specific feature (which you can find by extracting Extras/ZenjectUnitTests.zip)
using Zenject;
using UnityEngine;
using System.Collections;
public class TestInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind<ITickable>().ToSingle<TestRunner>();
Container.Bind<IInitializable>().ToSingle<TestRunner>();
}
}
public class TestRunner : ITickable, IInitializable
{
public void Initialize()
{
Debug.Log("Hello World");
}
public void Tick()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Exiting!");
Application.Quit();
}
}
}
You can run this example by doing the following:
The CompositionRoot MonoBehaviour is the entry point of the application, where Zenject sets up all the various dependencies before kicking off your scene. To add content to your Zenject scene, you need to write what is referred to in Zenject as an 'Installer', which declares all the dependencies used in your scene and their relationships with each other. If the above doesn't make sense to you yet, keep reading!
Every dependency injection framework is ultimately just a framework to bind types to instances.
In Zenject, dependency mapping is done by adding bindings to something called a container. The container should then 'know' how to create all the object instances in our application, by recursively resolving all dependencies for a given object.
When the container is asked to construct an instance of a given type, it uses C# reflection to find the list of constructor arguments, and all fields/properties that are marked with an [Inject] attribute. It then attempts to resolve each of these required dependencies, which it uses to call the constructor and create the new instance.
Each Zenject application therefore must tell the container how to resolve each of these dependencies, which is done via Bind commands. The format for the bind command can be any of the following:
Note that you can find more examples in the cheatsheet section below.
Container.Bind<Foo>().ToSingle();
When a type is bound using ToSingle this will construct one and only one instance of Foo and use that everywhere that has Foo as a dependency
You may also bind the singleton instance to one or more interfaces:
Container.Bind<IFoo>().ToSingle<Foo>();
Container.Bind<IBar>().ToSingle<Foo>();
This will cause any dependencies of type IFoo or IBar to use the same instance of Foo. Of course, Foo must implement both IFoo and IBar for this to compile. However, with only the above two lines the Foo singleton will not be accessible directly. You can achieve this by using another line to uses ToSingle directly:
Container.Bind<Foo>().ToSingle();
Container.Bind<IFoo>().ToSingle<Foo>();
Container.Bind<IBar>().ToSingle<Foo>();
Note again that the same instance will be used for all dependencies that take Foo, IFoo, or IBar.
Container.Bind<Foo>().ToInstance(new Foo());
Container.Bind<string>().ToInstance("foo");
// Or with shortcut:
Container.BindInstance(new Bar());
In this case the given instance will be used for every dependency with the given type
Container.Bind<Foo>().ToTransient();
In this case a new instance of Foo will be generated each time it is injected. Similar to ToSingle, you can bind via an interface as well:
Container.Bind<IFoo>().ToTransient<Foo>();
Container.Bind<FooMonoBehaviour>().ToSinglePrefab(PrefabGameObject);
This will instantiate a new instance of the given prefab, and then search the newly created game object for the given component (in this case FooMonoBehaviour).
Also, because it is ToSingle it will only instantiate the prefab once, and otherwise use the same instance of FooMonoBehaviour.
You can also bind multiple singletons to the same prefab. For example:
Container.Bind<FooMonoBehaviour>().ToSinglePrefab(PrefabGameObject);
Container.Bind<BarMonoBehaviour>().ToSinglePrefab(PrefabGameObject);
This will result in the prefab `PrefabGameObject` being instantiated once, and then searched for monobehaviour's `FooMonoBehaviour` and `BarMonoBehaviour`
Container.Bind<FooMonoBehaviour>().ToTransientPrefab<FooMonoBehaviour>(PrefabGameObject);
This works similar to ToSinglePrefab except it will instantiate a new instance of the given prefab every time the dependency is injected.
Container.Bind<FooMonoBehaviour>().ToSingleGameObject();
This binding will create a new game object and attach the given FooMonoBehaviour. Also note that since it is ToSingle that it will use the same instance everywhere that has FooMonoBehaviour as a dependency
ToMethod - Inject using a custom method
This binding allows you to customize creation logic yourself by defining a method:
Container.Bind<IFoo>().ToMethod(SomeMethod);
public IFoo SomeMethod(InjectContext context)
{
...
return new Foo();
}
This method can be useful if you want to bind to a property of another object.
Container.Bind<IFoo>().ToSingle<Foo>()
Container.Bind<Bar>().ToGetter<IFoo>(x => x.GetBar())
Container.Bind<IFoo>().ToLookup<IBar>()
Container.Bind<IBar>().ToLookup<Foo>()
In some cases it is useful to be able to bind an interface to another interface. However, you cannot use ToSingle or ToTransient because they both require concrete types.
In the example code above we assume that Foo inherits from IBar, which inherits from IFoo. The result here will be that all dependencies for IFoo will be bound to whatever IBar is bound to (in this case, Foo).
You can also supply an identifier to the ToLookup() method. See here section for details on identifiers.
Container.BindValue<float>().To(1.5f);
Container.BindValue<int>().To(42);
Primitive types such as int, float, struct, etc. are treated specially in Zenject. Note that when binding to primitives you will almost certaintly want to specify the type that the binding is for using WhenInjectedInto
(described below). I'll also add that while it can be useful to inject primitives for configuration settings it is often better to inject a "settings" object instead. There are other advantages to this approach as well as described here.
Container.Rebind<IFoo>().To<Foo>();
The Rebind function can be used to override any existing bindings that were added previously. It will first clear all previous bindings and then add the new binding. This method is especially useful for tests, where you often want to use almost all the same bindings used in production, except override a few specific bindings.
Container.Bind(typeof(IFoo)).ToSingle(typeof(Foo));
In some cases it is not possible to use the generic versions of the Bind<> functions. In these cases a non-generic version is provided, which works by taking in a Type value as a parameter.
public class Foo : ITickable, IInitializable
{
...
}
...
Container.Bind<Foo>().ToSingle();
Container.BindAllInterfacesToSingle<Foo>();
The above is equivalent to the following:
Container.Bind<Foo>().ToSingle();
Container.Bind<ITickable>().ToSingle<Foo>();
Container.Bind<IInitializable>().ToSingle<Foo>();
When Zenject finds multiple bindings for the same type, it interprets that to be a list. So, in the example code below, Bar would get a list containing a new instance of Foo1, Foo2, and Foo3:
// In an installer somewhere
Container.Bind<IFoo>().ToSingle<Foo1>();
Container.Bind<IFoo>().ToSingle<Foo2>();
Container.Bind<IFoo>().ToSingle<Foo3>();
...
public class Bar
{
public Bar(List<IFoo> foos)
{
}
}
Also worth noting is that if you try and declare a single dependency of IFoo (like Bar below) and there are multiple bindings for it, then Zenject will throw an exception, since Zenject doesn't know which instance of IFoo to use. Also, if the empty list is valid, then you should mark your List constructor parameter (or [Inject] field) as optional (see here for details).
public class Bar
{
public Bar(IFoo foo)
{
}
}
You can declare some dependencies as optional as follows:
public class Bar
{
public Bar(
[InjectOptional]
IFoo foo)
{
...
}
}
In this case, if IFoo is not bound in any installers, then it will be passed as null.
Note that when declaring dependencies with primitive types as optional, they will be given their default value (eg. 0 for ints). However, if you need to distinguish between being given a default value and the primitive dependency not being specified, you can do this as well by declaring it as nullable:
public class Bar
{
int _foo;
public Bar(
[InjectOptional]
int? foo)
{
if (foo == null)
{
// Use 5 if unspecified
_foo = 5;
}
else
{
_foo = foo.Value;
}
}
}
...
// Can leave this commented or not and it will still work
// Container.BindValue<int>().To(1);
You can also give a name to your binding by supplying it as a parameter to the Bind() method. For example:
Container.Bind<IFoo>("foo").ToSingle<Foo1>();
Container.Bind<IFoo>().ToSingle<Foo2>();
...
public class Bar1
{
[Inject("foo")]
IFoo _foo;
}
public class Bar2
{
IFoo _foo;
}
In this example, the Bar1 class will be given an instance of Foo1, and the Bar2 class will use the default version of IFoo which is bound to Foo2.
Note also that you can add a name constructor arguments as well, for example:
public class Bar
{
Foo _foo;
public Bar(
[Inject("foo")] Foo foo)
{
}
}
You can also do the same with [PostInject] parameters:
public class Bar
{
Foo _foo;
public Bar()
{
}
[PostInject]
public Init(
[Inject("foo")] Foo foo)
{
}
}
It is also possible to supply an identifier to the ToSingle methods as well. This allows you to force Zenject to create multiple singletons instead of just one. Normally, the singleton is uniquely identified based on the type given as generic argument to the ToSingle<> method. So for example:
Container.Bind<IFoo>().ToSingle<Foo>();
Container.Bind<IBar>().ToSingle<Foo>();
Container.Bind<IQux>().ToSingle<Qux>();
In the above code, both uses of ToSingle<Foo>()
will be bound to the same instance. Only one instance of Foo will be created.
Container.Bind<IFoo>().ToSingle<Foo>("foo1");
Container.Bind<IBar>().ToSingle<Foo>("foo2");
In this case, two instances will be created.
Something else worth noting is that the behaviour of ToSinglePrefab works slightly differently from the above. Given the following:
Container.Bind<IFoo>().ToSingleFromPrefab<Foo>(MyPrefab);
Container.Bind<IBar>().ToSingleFromPrefab<Bar>(MyPrefab);
It will only instantiate the prefab MyPrefab once. The generic parameter given to ToSingleFromPrefab can be interpreted as "Search the instantiated prefab for this component". If instead, you want Zenject to instantiate a new instance of the prefab for each ToSingleFromPrefab binding, then you can do that as well by supplying an identifier to the ToSingleFromPrefab function like so:
Container.Bind<IFoo>().ToSingleFromPrefab<Foo>("foo", MyPrefab);
Container.Bind<IBar>().ToSingleFromPrefab<Bar>("bar", MyPrefab);
Now two instances of the prefab will be created.
In many cases you will want to restrict where a given dependency is injected. You can do this using the following syntax:
Container.Bind<IFoo>().ToSingle<Foo1>().WhenInjectedInto<Bar1>();
Container.Bind<IFoo>().ToSingle<Foo2>().WhenInjectedInto<Bar2>();
Note that WhenInjectedInto
is simple shorthand for the following. You can use the more general When()
method for more complex conditionals. For example, this is equivalent to WhenInjectedInto:
Container.Bind<IFoo>().ToSingle<Foo>().When(context => context.ParentType == typeof(Bar));
The InjectContext class (which is passed as the context
parameter above) contains the following information that you can use in your conditional:
Type ParentType
- The type of the newly instantiated object, which we are injecting dependencies into.object ParentInstance
- The newly instantiated instance that is having its dependencies filled. Note that this is only available when injecting fields or into [PostInject] and null for constructor parametersstring Identifier
- This will be null in most cases and set to whatever is given as a parameter to the [Inject] attribute. For example, [Inject("foo")] _foo
will result in Identifier
being equal to the string "foo".string MemberName
- The name of the field or parameter that we are injecting into. This can be used, for example, in the case where you have multiple constructor parameters that are strings. However, using the parameter or field name can be error prone since other programmers may refactor it to use a different name. In many cases it's better to use an explicit identifierType MemberType
- The type of the field or parameter that we are injecting into.List<Type> ParentTypes
- This contains the entire object graph that precedes the current class being created. For example, dependency A might be created, which requires an instance of B, which requires an instance of C. In this case, the InjectContext given for any fields when creating C will contains the list {typeof(A), typeof(B)}
.bool Optional
- True if the [InjectOptional] parameter is declared on the field being injectedI prefer to avoid the extra weight of MonoBehaviours when possible in favour of just normal C# classes. Zenject allows you to do this much more easily by providing interfaces that mirror functionality that you would normally need to use a MonoBehaviour for.
For example, if you have code that needs to run per frame, then you can implement the ITickable interface:
public class Ship : ITickable
{
public void Tick()
{
// Perform per frame tasks
}
}
Then it's just a matter of including the following in one of your installers:
Container.Bind<ITickable>().ToSingle<Ship>();
Note that the order that Tick() is called on all ITickables is also configurable, as outlined here.
If you have some initialization that needs to occur on a given object, you can include this code in the constructor. However, this means that the initialization logic would occur in the middle of the object graph being constructed, so it may not be ideal.
One alternative is to implement IInitializable, and then perform initialization logic in an Initialize() method. This method would be called immediately after the entire object graph is constructed. This is also nice because the initialization order is customizable in a similar way to ITickable, as explained here.
IInitializable works well for start-up initialization, but what about for objects that are created dynamically via factories? (see this section for what I'm referring to here).
In these cases you can mark any methods that you want to be called after injection occurs with a [PostInject] attribute:
public class Foo
{
[Inject]
IBar _bar;
[PostInject]
public void Initialize()
{
...
_bar.DoStuff();
...
}
}
This still has the drawback that it is called in the middle of object graph construction, but can be useful in many cases. In particular, if you are using property injection (which isn't generally recommended but necessary in some cases) then you will not have your dependencies in the constructor, and therefore you will need to define a [PostInject] method in this case.
You will also want to use [PostInject] for MonoBehaviours, since MonoBehaviours cannot have constructors. You may also include injected parameters in any [PostInject] method in the same way you would for constructors. For example:
public class Foo : MonoBehaviour
{
IBar _bar;
[PostInject]
public void Init(IBar bar)
{
_bar = bar;
...
_bar.DoStuff();
...
}
}
Using [PostInject] to inject dependencies is the recommended approach for MonoBehaviours.
In the case where there are multiple [PostInject] methods on a given object, they are called in the order of Base class to Derived class.
If you have external resources that you want to clean up when the app closes, the scene changes, or for whatever reason the composition root object is destroyed, you can do the following:
public class Logger : IInitializable, IDisposable
{
FileStream _outStream;
public void Initialize()
{
_outStream = File.Open("log.txt", FileMode.Open);
}
public void Log(string msg)
{
_outStream.WriteLine(msg);
}
public void Dispose()
{
_outStream.Close();
}
}
Then in your installer you can include:
Container.Bind<Logger>().ToSingle();
Container.Bind<IInitializable>().ToSingle<Logger>();
Container.Bind<IDisposable>().ToSingle<Logger>();
Or you can use the following shortcut:
Container.Bind<Logger>().ToSingle();
Container.BindAllInterfacesToSingle<Logger>();
This works because when the scene changes or your unity application is closed, the unity event OnDestroy() is called on all MonoBehaviours, including the CompositionRoot class, which then triggers all objects that are bound to IDisposable
Note that this example may or may not be a good idea (for example, the file will be left open if your app crashes), but illustrates the point :)
Often, there is some collection of related bindings for each sub-system and so it makes sense to group those bindings into a re-usable object. In Zenject this re-usable object is called an Installer. You can define a new installer as follows:
public class FooInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Bind<ITickable>().ToSingle<Foo>();
Container.Bind<IInitializable>().ToSingle<Foo>();
}
}
You add bindings by overriding the InstallBindings method, which is called by the CompositionRoot when your scene starts up. MonoInstaller is a MonoBehaviour so you can add FooInstaller by attaching it to a GameObject. Since it is a GameObject you can also add public members to it to configure your installer from the Unity inspector. However, note that in order for your installer to be used it must be attached to the Installers property of the CompositionRoot object.
In many cases you want to have your installer derive from MonoInstaller. There is also another base class called Installer which you can use in cases where you do not need it to be a MonoBehaviour.
It can also be nice to use Installer since this allows you to "include" it from another installer. For example:
public class BarInstaller : Installer
{
public override void InstallBindings()
{
...
}
}
public class FooInstaller : MonoInstaller
{
public override void InstallBindings()
{
Container.Install<BarInstaller>();
}
}
This way you don't need to have an instance of BarInstaller in your scene in order to use it. Any calls to Container.Install will immediately instantiate the given installer type and then call InstallBindings on it. This will repeat for any installers that this installer installs. Note also that it will only install the same installer once so you can make repeated calls to Container.Install
One of the main reasons we use installers as opposed to just having all our bindings declared all at once for each scene, is to make them re-usable. So how then do we use the same installer in multiple scenes?
The recommended way of doing this is to use unity prefabs. After attaching your MonoInstaller to a gameobject in your scene, you can then create a prefab out of it. This is nice because it allows you to share any configuration that you've done in the inspector on the MonoInstaller across scenes (and also have per-scene overrides if you want)
Installers that simply implement Installer instead of MonoInstaller can be simply bound as described above, to re-use in different scenes.
A Zenject driven application is executed by the following steps:
Do not use GameObject.Instantiate if you want your objects to have their dependencies injected
Do not use IInitializable, ITickable and IDisposable for dynamically created objects
Using multiple constructors
Injecting into MonoBehaviours
Injecting For Root Game Objects
Using Zenject outside of Unity
Please feel free to submit any other sources of confusion to<EMAIL_ADDRESS>and I will add it here.
In many cases, especially for small projects, the order that classes update or initialize in does not matter. However, in larger projects update or initialization order can become an issue. This can especially be an issue in Unity, since it is often difficult to predict in what order the Start(), Awake(), or Update() methods will be called in. Unfortunately, Unity does not have an easy way to control this (besides in Edit -> Project Settings -> Script Execution Order, though that is pretty awkward to use)
In Zenject, by default, ITickables and IInitializables are updated in the order that they are added, however for cases where the update or initialization order matters, there is a much better way: By specifying their priorities explicitly in the installer. For example, in the sample project you can find this code in the scene installer:
public class AsteroidsInstaller : MonoInstaller
{
...
void InitPriorities()
{
Container.Bind<List<Type>>().To(InitializablesOrder)
.WhenInjectedInto<InitializablePrioritiesInstaller>();
Container.Install<InitializablePrioritiesInstaller>();
Container.Bind<List<Type>>().To(Tickables)
.WhenInjectedInto<TickablePrioritiesInstaller>();
Container.Install<TickablePrioritiesInstaller>();
}
static List<Type> InitializablesOrder = new List<Type>()
{
// Re-arrange this list to control init order
typeof(GameController),
};
static List<Type> TickablesOrder = new List<Type>()
{
// Re-arrange this list to control update order
typeof(AsteroidManager),
typeof(GameController),
};
}
This way, you won't hit a wall at the end of the project due to some unforeseen order-dependency.
You can also assign priorities one class at a time using the following helper method:
InitializablePrioritiesInstaller.BindPriority(Container, typeof(Foo), -100);
Container.Bind<IInitializable>().ToSingle<Bar>();
Note that any ITickables, IInitializables, or IDisposable's that are not assigned a priority are automatically given the priority of zero. This allows you to have classes with explicit priorities executed either before or after the unspecified classes. For example, the above code would result in 'Foo.Initialize' being called before 'Bar.Initialize'. If you instead gave it 100 instead of -100, it would be executed afterwards.
The usual workflow when setting up bindings using a DI framework is something like this:
This works ok for small projects, but as the complexity of your project grows it is often a tedious process. The problem gets worse if the startup time of your application is particularly bad, or when the resolve errors only occur from factories at various points at runtime. What would be great is some tool to analyze your object graph and tell you exactly where all the missing bindings are, without requiring the cost of firing up your whole app.
You can do this in Zenject out-of-the-box by executing the menu item Edit -> Zenject -> Validate Current Scene
or simply hitting CTRL+SHIFT+V with the scene open that you want to validate. This will execute all installers for the current scene and construct a fully bound container. It will then iterate through the object graphs and verify that all bindings can be found (without actually instantiating any of them).
Also, if you happen to be a fan of automated testing (as I am) then you can include calls to this menu item as part of your testing suite.
One of the things that often confuses people new to dependency injection is the question of how to create new objects dynamically, after the app/game has fully started up and all the IInitializable objects have had their Initialize() method called. For example, if you are writing a game in which you are spawning new enemies throughout the game, then you will want to construct a new object graph for the 'enemy' class. How to do this? The answer: Factories.
Remember that an important part of dependency injection is to reserve use of the container to strictly the "Composition Root Layer". The container class (DiContainer) is included as a dependency in itself automatically so there is nothing stopping you from ignoring this rule and injecting the container into any classes that you want. For example, the following code will work:
public class Enemy
{
DiContainer Container;
public Enemy(DiContainer container)
{
Container = container;
}
public void Update()
{
...
var player = Container.Resolve<Player>();
WalkTowards(player.Position);
...
etc.
}
}
HOWEVER, the above code is an example of an anti-pattern. This will work, and you can use the container to get access to all other classes in your app, however if you do this you will not really be taking advantage of the power of dependency injection. This is known, by the way, as Service Locator Pattern.
Of course, the dependency injection way of doing this would be the following:
public class Enemy
{
Player _player;
public Enemy(Player player)
{
_player = player;
}
public void Update()
{
...
WalkTowards(_player.Position);
...
}
}
The only exception to this rule is within factories and installers. Again, factories and installers make up what we refer to as the "composition root layer".
For example, if you have a class responsible for spawning new enemies, before DI you might do something like this:
public class EnemySpawner
{
List<Enemy> _enemies = new List<Enemy>();
public void Update()
{
if (ShouldSpawnNewEnemy())
{
var enemy = new Enemy();
_enemies.Add(enemy);
}
}
}
This will not work however, since in our case the Enemy class requires a reference to the Player class in its constructor. We could add a dependency to the Player class to the EnemySpawner class, but then we have the problem described above. The EnemySpawner class doesn't care about filling in the dependencies for the Enemy class. All the EnemySpawner class cares about is getting a new Enemy instance.
The recommended way to do this in Zenject is the following:
public class Enemy
{
Player _player;
public Enemy(Player player)
{
_player = player;
}
...
public class Factory : Factory<Enemy>
{
}
}
public class EnemySpawner
{
Enemy.Factory _enemyFactory;
List<Enemy> _enemies = new List<Enemy>();
public EnemySpawner(Enemy.Factory enemyFactory)
{
_enemyFactory = enemyFactory;
}
public void Update()
{
if (ShouldSpawnNewEnemy())
{
var enemy = _enemyFactory.Create();
_enemies.Add(enemy);
}
}
}
Then in your installer, you would include:
Container.Bind<Enemy.Factory>().ToSingle();
By using Enemy.Factory above, all the dependencies for the Enemy class (such as the Player) will be automatically filled in.
There is no requirement that the Enemy.Factory class be a subclass of Enemy, however we have found this to be a very useful convention. Enemy.Factory is empty and simply derives from the built-in Zenject Factory<> class, which handles the work of using the DiContainer to construct a new instance of Enemy.
Also note that by using the built-in Zenject Factory<> class, the Enemy class will be automatically validated as well. So if the constructor of the Enemy class includes a type that is missing a binding, this error can be caught before running your app, by simply running validation. Validation can be especially useful for dynamically created objects, because otherwise you may not catch the error until the factory is invoked at some point during runtime. See this section for more details on Validation.
However, in more complex examples, the EnemySpawner class may wish to pass in custom constructor arguments as well. For example, let's say we want to randomize the speed of each Enemy to add some interesting variation to our game. Our enemy class becomes:
public class Enemy
{
Player _player;
float _runSpeed;
public Enemy(Player player, float runSpeed)
{
_player = player;
_runSpeed = runSpeed;
}
public class Factory : Factory<float, Enemy>
{
}
}
public class EnemySpawner
{
Enemy.Factory _enemyFactory;
List<Enemy> _enemies = new List<Enemy>();
public EnemySpawner(Enemy.Factory enemyFactory)
{
_enemyFactory = enemyFactory;
}
public void Update()
{
if (ShouldSpawnNewEnemy())
{
var newSpeed = Random.Range(MIN_ENEMY_SPEED, MAX_ENEMY_SPEED);
var enemy = _enemyFactory.Create(newSpeed);
_enemies.Add(enemy);
}
}
}
The dynamic parameters that are provided to the Enemy constructor are declared by using generic arguments to the Factory<> base class of Enemy.Factory. This will add a method to Enemy.Factory that takes the parameters with the given types.
You can also use the same approach as described above to create factories that construct game objects. For example:
public class FooMonoBehaviour : MonoBehaviour
{
...
public class Factory : GameObjectFactory<FooMonoBehaviour>
{
}
}
The only difference here is that this factory requires a prefab to be installed on it. There is a convenience method that you can use to handle both installing the prefab and also declaring FooMonoBehaviour.Factory as a singleton:
public override void InstallBindings()
{
...
Container.BindGameObjectFactory<FooMonoBehaviour.Factory>(_prefab);
...
}
Now classes can simply declare a constructor parameter of type FooMonoBehaviour.Factory and by calling the Create() method, construct new instances of a given prefab.
You may also use your own custom factory. This is often necessary when you want to construct an instance of an interface at runtime. In this case you do not want to refer to a concrete factory class (eg. Enemy.Factory) as described above.
public enum Difficulties
{
Easy,
Hard,
}
public interface IEnemy
{
...
}
public class Demon : IEnemy
{
...
}
public class Dog : IEnemy
{
...
}
public class EnemyFactory
{
DiContainer _container;
Difficulties _difficulty;
public EnemyFactory(DiContainer container, Difficulties difficulty)
{
_container = container;
_difficulty = difficulty;
}
public IEnemy Create(float speed)
{
if (_difficulty == Difficulties.Hard)
{
return _container.Instantiate<Demon>(speed);
}
return _container.Instantiate<Dog>(speed);
}
}
And then in our installer we would include:
Container.Bind<EnemyFactory>().ToSingle();
Container.BindValue<Difficulties>().To(Difficulties.Easy);
This way we can change the type of enemy we spawn by simply changing the difficulty bound in the installer.
One issue with the above implementation is that it will not be validated properly. Any constructor parameters added to the Dog or Demon classes that cannot be resolved will not be detected until runtime. If you wish to address this you can implement it the following way:
public class EnemyFactory : IValidatable
{
DiContainer _container;
Difficulties _difficulty;
public EnemyFactory(DiContainer container, Difficulties difficulty)
{
_container = container;
_difficulty = difficulty;
}
public IEnemy Create(float speed)
{
if (_difficulty == Difficulties.Hard)
{
return _container.Instantiate<Demon>(speed);
}
return _container.Instantiate<Dog>(speed);
}
public IEnumerable<ZenjectResolveException> Validate()
{
return _container.ValidateObjectGraph<Dog>(typeof(float))
.Concat(_container.ValidateObjectGraph<Demon>(typeof(float)));
}
}
This is optional but can be nice if you are fan of validation. The parameters provided to the ValidateObjectGraph method indicate the dependencies that can be skipped for validation. This should include any runtime parameters.
Note that we are injecting the DiContainer directly into the EnemyFactory class, which is generally a bad thing to do but ok in this case because it is a factory (and therefore part of the "composition root layer")
In the real world there can sometimes be complex construction that needs to occur in your custom factory classes. In some of these cases it can be useful to use a feature called BindScope.
For example, suppose one day we decide to add further runtime constructor arguments to the Enemy class:
public class Enemy
{
public Enemy(EnemyWeapon weapon)
{
...
}
}
public class EnemyWeapon
{
public EnemyWeapon(float damage)
{
...
}
}
And let's say we want the damage of the EnemyWeapon class to be specified by the EnemySpawner class. How do we pass that argument down to EnemyWeapon? In this case it might be easiest to create the EnemyWeapon class first and then pass it to the factory. However, for the sake of this example let's pretend we want to create the EnemyClass in one call to Instantiate
public class EnemyFactory
{
DiContainer _container;
public EnemyFactory(DiContainer container)
{
_container = container;
}
public Enemy Create(float weaponDamage)
{
using (BindScope scope = Container.CreateScope())
{
scope.Bind<float>().ToSingle(weaponDamage).WhenInjectedInto<EnemyWeapon>();
return _container.Instantiate<Enemy>();
}
}
}
BindScope can be used in factories to temporarily configure the container in a similar way that's done in installers. This can be useful when creating complex object graphs at runtime. After the function returns, whatever bindings you added in the using{} block are automatically removed. BindScope can also be used to specify injection identifiers as well.
In some cases it's useful to pass arguments from one scene to another. The way Unity allows us to do this by default is fairly awkward. Your options are to create a persistent GameObject and call DontDestroyOnLoad() to keep it alive when changing scenes, or use global static classes to temporarily store the data.
Let's pretend you want to specify a 'level' string to the next scene. You have the following class that requires the input:
public class LevelHandler : IInitializable
{
readonly string _startLevel;
public LevelHandler(
[InjectOptional("StartLevelName")]
string startLevel)
{
if (startLevel == null)
{
_startLevel = "default_level";
}
else
{
_startLevel = startLevel;
}
}
public void Initialize()
{
...
[Load level]
...
}
}
You can load the scene containing LessonStandaloneStart
and specify a particular level by using the following syntax:
ZenUtil.LoadScene("NameOfSceneToLoad",
delegate (DiContainer container)
{
container.Bind<string>("StartLevelName").To("custom_level").WhenInjectedInto<LevelHandler>();
});
Note that you can still run the scene directly, in which case it will default to using "level01". This is possible because we are using the InjectOptional flag.
An alternative and arguably cleaner way to do this would be to customize the installer itself rather than the LevelHandler class. In this case we can write our LevelHandler class like this (without the [InjectOptional] flag)
public class LevelHandler : IInitializable
{
readonly string _startLevel;
public LevelHandler(string startLevel)
{
_startLevel = startLevel;
}
public void Initialize()
{
...
[Load level]
...
}
}
Then, in the installer for our scene we can include the following:
public class GameInstaller : Installer
{
[InjectOptional]
public string LevelName = "default_level";
...
public override void InstallBindings()
{
...
Container.Bind<string>().To(LevelName).WhenInjectedInto<LevelHandler>();
...
}
}
Then, instead of injecting directly into the LevelHandler we can inject into the installer instead.
ZenUtil.LoadScene("NameOfSceneToLoad",
delegate (DiContainer container)
{
container.Bind<string>().To("level02").WhenInjectedInto<GameInstaller>();
});
Note that in this case I didn't need to use the "LevelName" identifier since there is only one string injected into the GameInstaller class.
Some people have also found it useful to separate out content into different scenes and then load each scene additively using the Unity method Application.LoadLevelAdditive
. In some cases it's useful to have the dependencies in the new scene resolved using the container of the original scene. To achieve this, you can call ZenUtil.LoadSceneAdditiveWithContainer
and pass in your scene's container. Note however that it is assumed in this case that the new scene does not have its own container + Composition Root.
One implication of writing most of your code as normal C# classes instead of MonoBehaviour's is that you lose the ability to configure data on them using the inspector. You can however still take advantage of this in Zenject by using the following pattern, as seen in the sample project:
public class AsteroidsInstaller : MonoInstaller
{
public Settings SceneSettings;
public override void InstallBindings()
{
...
Container.Bind<ShipStateMoving.Settings>().ToSingle(SceneSettings.StateMoving);
...
}
[Serializable]
public class Settings
{
...
public ShipStateMoving.Settings StateMoving;
...
}
}
Note that if you follow this method, you will have to make sure to always include the [Serializable] attribute on your settings wrappers, otherwise they won't show up in the Unity inspector.
To see this in action, start the asteroids scene and try adjusting Ship -> State Moving -> Move Speed
setting and watch live as your ship changes speed.
This all works great for each individual scene, but what if have dependencies that you wish to persist permanently across all scenes? In Zenject you can do this by adding installers to the global container.
This works by first add a global composition root and then adding installers to it. You can create an empty global composition root by selecting Edit -> Zenject -> Create Global Composition Root. After selecting this menu item you should see a new asset in the root level Resources folder called 'ZenjectGlobalCompositionRoot'.
If you click on this it will display a property for the list of Installers in the same way that it does for the composition root object that is placed in each scene. The only difference in this case is that the installers you add here must exist in the project as prefabs and cannot exist in any specific scene. You can then directly reference those prefabs by dragging them into the Installers property of the global composition root.
Then, when you start any scene, the CompositionRoot for the scene will call the global composition root to install the global bindings, before installing any scene specific bindings. If you load another scene from the first scene, the global composition root will not be called again and the bindings that it added previously will persist into the new scene. You can declare ITickable / IInitializable / IDisposable objects in your global installers in the same way you do for your scene installers with the result being IInitializable.Initialize is called only once across each play session and IDisposable.Dispose is only called once the application is fully stopped.
Scene Decorators can be used to add behaviour to another scene without actually changing the installers in that scene. The usual way to achieve this is to use flags on MonoInstallers to conditionally add different bindings within the scene itself. However the scene decorator approach can be cleaner sometimes because it doesn't involve changing the main scene.
For example, let's say we want to add some special keyboard shortcuts to our main production scene for testing purposes. In order to do this using decorators, you can do the following:
public class ExampleDecoratorInstaller : DecoratorInstaller
{
public override void PostInstallBindings()
{
// Add bindings here that you want added AFTER installing the main scene
Container.Bind<ITickable>().ToSingle<TestHotKeysAdder>();
}
public override void PreInstallBindings()
{
// Add bindings here that you want added BEFORE installing the main scene
}
}
public class TestHotKeysAdder : ITickable
{
public void Tick()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Hotkey triggered!");
}
}
}
If you run your scene it should now behave exactly like the scene you entered in 'Scene Name' except with the added functionality in your decorator installer.
The PostInstallBindings method is useful when you want to override a binding in the main scene using 'Rebind'. And PreInstallBindings is necessary if you want to inject data into the installers in the main scene. For a better example see the asteroids project that comes with Zenject (open 'AsteroidsDecoratorExample' scene).
Note also that Zenject validate (using CTRL+SHIFT+V or the menu item via Edit->Zenject->Validate Current Scene) also works with decorator scenes.
One of the really cool features of DI is the fact that it makes testing code much, much easier. This is because you can easily substitute one dependency for another by using a different Composition Root. For example, if you only want to test a particular class (let's call it Foo) and don't care about testing its dependencies, you might write 'mocks' for them so that you can isolate Foo specifically.
public class Foo
{
IWebServer _webServer;
public Foo(IWebServer webServer)
{
_webServer = webServer;
}
public void Initialize()
{
...
var x = _webServer.GetSomething();
...
}
}
In this example, we have a class Foo that interacts with a web server to retrieve content. This would normally be very difficult to test for the following reasons:
However, if we create a mock class for IWebServer then we can address all these problems:
public class MockWebServer : IWebServer
{
...
}
Then hook it up in our installer:
Container.Bind<IWebServer>().ToSingle<MockWebServer>();
Then you can implement the fields of the IWebServer interface and configure them based on what you want to test on Foo. Hopefully You can see how this can make life when writing tests much easier.
Zenject also allows you to even avoid having to write the MockWebServer class in favour of using a library called "Moq" which does all the work for you.
Note that by default, Auto-mocking is not enabled in Zenject. If you wish to use the auto-mocking feature then you need to go to your Zenject install directory and extract the contents of "Extras/ZenjectAutoMocking.zip". Note also that AutoMocking is incompatible with webplayer builds, and you will also need to change your "Api Compatibility Level" from ".NET 2.0 Subset" to ".NET 2.0" (you can find this in PC build settings)
After extracting the auto mocking package it is just a matter of using the following syntax to mock out various parts of your project:
Container.Bind<IFoo>().ToMock();
However, this approach will not allow you to take advantage of the advanced features of Moq. For more advanced usages, see the documentation for Moq
Every DiContainer exposes a FallbackProvider property, which by default is null. In cases where the container is unable to resolve a dependency, the container will first try using the FallbackProvider before throwing a ZenjectResolveException.
This allows for the ability to define nested sub-containers by executing the following:
Container.FallbackProvider = new DiContainerProvider(_nestedContainer);
Nested sub-containers can be useful in some rare cases. For example, if you are creating a word processor it may be useful to have a sub-container for each tab that represents a separate document. Nested sub-containers is also the way that the Global Composition Root works under the hood. In the future we plan to add more support for this kind of thing.
There are other uses for FallbackProvider as well.
For example, if you are writing test code and want to automatically auto-mock missing dependencies, you can do the following:
Container.FallbackProvider = new TransientMockProvider(Container);
Or, perhaps you wish to write custom logic to handle cases of missing dependencies. You can do that as well, by writing a custom "Provider" class and setting it to be used as the FallbackProvider
Zenject allows users to generate UML-style images of the object graphs for their applications. You can do this simply by running your Zenject-driven app, then selecting from the menu Assets -> Zenject -> Output Object Graph For Current Scene
. You will be prompted for a location to save the generated image file.
Note that you will need to have graphviz installed for this to work (which you can find here). You will be prompted to choose the location the first time.
The result is two files (Foo.dot and Foo.png). The dot file is included in case you want to add custom graphviz commands. As an example, this is the graph that is generated when run on the sample project:
However, admittedly, I personally haven't gotten a lot of mileage out of this feature. When I have found it useful it's when I first encounter a lot of unfamiliar code. Reading a visual diagram can be easier than reading the code in some cases.
DI can affect start-up time when it builds the initial object graph. However it can also affect performance any time you instantiate new objects at run time.
Zenject uses C# reflection which is typically slow, but in Zenject this work is cached so any performance hits only occur once for each class type. In other words, Zenject avoids costly reflection operations by making a trade-off between performance and memory to ensure good performance.

///////////// ToTransient
// Create a new instance of Foo for every class that asks for it
Container.Bind<Foo>().ToTransient();
// Create a new instance of Foo for every class that asks for an IFoo
Container.Bind<IFoo>().ToTransient<Foo>();
// Non generic versions
Container.Bind(typeof(IFoo)).ToTransient();
Container.Bind(typeof(IFoo)).ToTransient(typeof(Foo));
///////////// ToSingle
// Create one definitive instance of Foo and re-use that for every class that asks for it
Container.Bind<Foo>().ToSingle();
// Create one definitive instance of Foo and re-use that for every class that asks for IFoo
Container.Bind<IFoo>().ToSingle<Foo>();
// In this example, the same instance of Foo will be used for all three cases
Container.Bind<Foo>().ToSingle();
Container.Bind<IFoo>().ToSingle<Foo>();
Container.Bind<IBar>().ToSingle<Foo>();
// Non generic versions
Container.Bind(typeof(Foo)).ToSingle();
Container.Bind(typeof(IFoo)).ToSingle(typeof(Foo));
///////////// BindAllInterfacesToSingle
// Bind all interfaces that Foo implements to a new singleton of type Foo
Container.BindAllInterfacesToSingle<Foo>();
// So for example if Foo implements ITickable and IInitializable then the above
// line is equivalent to this:
Container.Bind<ITickable>().ToSingle<Foo>();
Container.Bind<IInitializable>().ToSingle<Foo>();
///////////// ToInstance
// Use the given instance everywhere that Foo is used
Container.Bind<Foo>().ToInstance(new Foo());
// This is simply a shortcut for the above binding
// This can be a bit nicer since the type argument can be deduced from the parameter
Container.BindInstance(new Foo());
// Note that ToInstance is different from ToSingle because it does allow multiple bindings
// and you can't re-use the same instance in multiple bindings like you can with ToSingle
// For example, the following is allowed and will match any constructor parameters of type List<Foo>
// (and throw an exception for parameters that ask for a single Foo)
Container.Bind<Foo>().ToInstance(new Foo());
Container.Bind<Foo>().ToInstance(new Foo());
///////////// ToSingleInstance
// Use the given instance everywhere Foo is requested and ensure that it is the only Foo that is created
Container.Bind<Foo>().ToSingleInstance(new Foo());
// We assume here that Foo implements both IFoo and IBar
// This will result in the given instance of Foo used for all three cases
Container.Bind<IFoo>().ToSingleInstance(new Foo());
Container.Bind<IBar>().ToSingle<Foo>();
Container.Bind<Foo>().ToSingle();
///////////// BindValue
// Use the number 10 every time an int is requested
// You'd never really want to do this, you should almost always use a When condition for primitive values (see conditions section below)
Container.BindValue<int>().To(10);
Container.BindValue<bool>().To(false);
// These are the same as above
// This can be a bit nicer though since the type argument can be deduced from the parameter
// Again though, be careful to use conditions to limit the scope of usage for values
// or consider using a Settings object as described above
Container.BindValueInstance(10);
Container.BindValueInstance(false);
///////////// ToMethod
// Create instance of Foo when requested, using the given method
// Note that for more complex construction scenarios, you might consider using a factory
// instead
Container.Bind<Foo>().ToMethod(GetFoo);
Foo GetFoo(InjectContext ctx)
{
return new Foo();
}
// Randomly return one of several different implementations of IFoo
// We use Instantiate here instead of just new so that Foo1 gets its members injected
Container.Bind<IFoo>().ToMethod(GetFoo);
IFoo GetFoo(InjectContext ctx)
{
switch (Random.Range(0, 3))
{
case 0:
return ctx.Container.Instantiate<Foo1>();
case 1:
return ctx.Container.Instantiate<Foo2>();
}
return ctx.Container.Instantiate<Foo3>();
}
// Using lambda syntax
Container.Bind<Foo>().ToMethod((ctx) => new Foo());
// This is equivalent to ToTransient
Container.Bind<Foo>().ToMethod((ctx) => ctx.Container.Instantiate<Foo>());
///////////// ToGetter
// Bind to a property on another dependency
// This can be helpful to reduce coupling between classes
Container.Bind<Foo>().ToSingle();
Container.Bind<Bar>().ToGetter<Foo>(foo => foo.GetBar());
// Another example using values
Container.BindValue<string>().ToGetter<Foo>(foo => foo.GetTitle());
///////////// ToSingleGameObject
// Create a new game object at the root of the scene, add the Foo MonoBehaviour to it, and name it "Foo"
Container.Bind<Foo>().ToSingleGameObject("Foo");
// Bind to an interface instead
Container.Bind<IFoo>().ToSingleGameObject<Foo>("Foo");
///////////// ToSinglePrefab
// Create a new game object at the root of the scene using the given prefab
// It is assumed that the Foo is a MonoBehaviour here and that Foo has been
// previously added to the prefab
// After zenject creates a new GameObject from the given prefab, it will
// search the prefab for a component of type 'Foo' and return that
GameObject fooPrefab;
Container.Bind<Foo>().ToSinglePrefab(fooPrefab);
// Bind to interface instead
Container.Bind<IFoo>().ToSinglePrefab<Foo>(fooPrefab);
// Note that in this case only one prefab will be instantiated and re-used
// for all three bindings
// (Prefab singletons are uniquely identified by their prefab)
Container.Bind<Foo>().ToSinglePrefab(fooPrefab);
Container.Bind<IInitializable>().ToSinglePrefab<Foo>(fooPrefab);
Container.Bind<ITickable>().ToSinglePrefab<Foo>(fooPrefab);
///////////// ToTransientPrefab
// Instantiate a new copy of 'fooPrefab' every time an instance of Foo is
// requested by a constructor parameter, injected field, etc.
GameObject fooPrefab;
Container.Bind<Foo>().ToTransientPrefab(fooPrefab);
// Bind to interface instead
Container.Bind<IFoo>().ToTransientPrefab<Foo>(fooPrefab);
///////////// Identifiers
// By default this will use 'Qux' for every place that requires an instance of IFoo
// But also allow for classes to use FooA or FooB by using identifiers
Container.Bind<IFoo>().ToSingle<Qux>();
Container.Bind<IFoo>("FooA").ToSingle<Bar>();
Container.Bind<IFoo>("FooB").ToSingle<Baz>();
public class Norf
{
// Uses Qux
[Inject]
IFoo _foo;
// Uses Bar
[Inject("FooA")]
IFoo _foo;
// Uses Baz if it exists, otherwise leaves it as null
[InjectOptional("FooB")]
IFoo _foo;
}
// Bind a globally accessible string with the name 'PlayerName'
// A better option might be to create a Settings object and bind that
// instead however
Container.BindValue<string>("PlayerName").To("name of the player");
///////////// Conditions
// This will only allow dependencies on Foo by the Bar class
Container.Bind<Foo>().ToSingle().WhenInjectedInto<Bar>();
// Use different implementations of IFoo dependending on which
// class is being injected
Container.Bind<IFoo>().ToSingle<Foo1>().WhenInjectedInto<Bar>();
Container.Bind<IFoo>().ToSingle<Foo2>().WhenInjectedInto<Qux>();
// Use "Foo1" as the default implementation except when injecting into
// class Qux, in which case use Foo2
Container.Bind<IFoo>().ToSingle<Foo1>();
Container.Bind<IFoo>().ToSingle<Foo2>().WhenInjectedInto<Qux>();
// Allow depending on Foo in only a few select classes
Container.Bind<Foo>().ToSingle().WhenInjectedInto(typeof(Bar), typeof(Qux), typeof(Baz));
// Supply "my game" for any strings that are injected into the Gui class with the identifier "Title"
Container.BindInstance("Title", "my game").WhenInjectedInto<Gui>();
// Supply 5 for all ints that are injected into the Gui class
Container.BindInstance(5).WhenInjectedInto<Gui>();
// Supply 5 for all ints that are injected into a parameter or field
// inside type Gui that is named 'width'
// This is usually not a good idea since the name of a field can change
// easily and break the binding but shown here as an example :)
Container.BindInstance(5.0f).When(ctx =>
ctx.ParentType == typeof(Gui) && ctx.MemberName == "width");
// Create a new 'Foo' for every class that is created as part of the
// construction of the 'Bar' class
// So if Bar has a constructor parameter of type Qux, and Qux has
// a constructor parameter of type IFoo, a new Foo will be created
// for that case
Container.Bind<IFoo>().ToTransient<Foo>().When(
ctx => ctx.ParentTypes.Contains(typeof(Bar)));
///////////// ToLookup
// This will result in IBar, IFoo, and Foo, all being bound to the same instance of
// Foo which is assume to exist somewhere on the given prefab
GameObject fooPrefab;
Container.Bind<Foo>().ToSinglePrefab(fooPrefab);
Container.Bind<IBar>().ToLookup<Foo>()
Container.Bind<IFoo>().ToLookup<IBar>()
// This is result in the same as the above
GameObject fooPrefab;
Container.Bind<Foo>().ToSinglePrefab(fooPrefab);
Container.Bind<IBar>().ToSinglePrefab<Foo>(fooPrefab);
Container.Bind<IFoo>().ToSinglePrefab<Foo>(fooPrefab);
///////////// Rebind
// Rebind can be used to override previous bindings
// This will result in IFoo being bound to only Bar
// The binding to Foo will have been removed
// Normally the order that the bindings occur in doesn't
// matter at all, but Rebind does create an order-dependency
// so use with caution
Container.Bind<IFoo>().ToSingle<Foo>();
Container.Rebind<IFoo>().ToSingle<Bar>();
///////////// Installing Other Installers
// Immediately call InstallBindings() on FooInstaller
Container.Install();
// Before calling FooInstaller, configure a property of it
Container.BindInstance("foo").WhenInjectedInto();
Container.Install();
// After calling FooInstaller, override one of its bindings
// We assume here that FooInstaller binds IFoo to something
Container.Install();
Container.Rebind().ToSingle();
///////////// Manual Use of Container
// This will fill in any parameters marked as [Inject] and also call the [PostInject]
// function
foo = new Foo();
Container.Inject(foo);
// Return an instance for IFoo, using the bindings that have been added previously
// Internally it is what is triggered when you fill in a constructor parameter of type IFoo
// Note: It will throw an exception if it cannot find a match
Container.Resolve<IFoo>();
// Same as the above except returns null when it can't find the given type
Container.TryResolve<IFoo>();
// Return a list of 2 instances of type Foo
Container.BindInstance(new Foo());
Container.BindInstance(new Foo());
var foos = Container.ResolveAll<IFoo>();
// Instantiate a new instance of Foo and inject on any of its members
Container.Instantiate<Foo>();
For general troubleshooting / support, please use the google group which you can find here. If you have found a bug, you are also welcome to create an issue on the github page, or a pull request if you have a fix / extension. Finally, you can also email me directly at<EMAIL_ADDRESS>2.2
2.1
2.0
Container.Bind<IFoo>().ToSingle<Foo1>()
and then override for specific classes with Container.Bind<IFoo>().ToSingle<Foo2>().WhenInjectedInto<Bar>()
, etc.1.19
1.18
1.17
1.16
1.15
1.14
1.13
1.12
1.11
1.10
1.09
1.08
1.07
1.06
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


This app was a first of a lot of things. First time building a fully functional android app. First time designing the entire UI. First time using Android's activity framework.
The application was written in Java. It consisted of 2 activities. One for displaying a grid of images and the other to enlarge and display that image on the entire screen.
The UI was designed mainly using the Android Studio's built-in UI GUI, with some small manual XML changes to specify the layout.

The application was written using C++ and XLibraries. This was my first attempt in dealing with User-Computer interaction. I had never before created GUIs or dealt with event loops in so direct a manner as I did when coding this.
My first experience writing a video game! I was a member of the 3 person team responsible for creating this clone of Rogue for the terminal.
The entire application was written in C++. I was also responsible for the initial software architecture before any actual code was written. Various design patterns were used in the OOP architecture to make the game easier to code while making it extensible.
PS. Our initial version was too hard to win so we also put in some secret cheat codes that only the developers know ;)
Aah ragdolls. Extremely fun to play with and program. Yes, I know the suit could've gone on better.
An application written when learning Java and creating GUIs using its Swing library. There some important concepts implemented behind the scenes including Scene graphs, widget layouts, event listeners (and adapters), etc.
This application is a working clone of typical Paint applications. It only implements a subset of the features but is still powerful.
The application logic was written in Java and the GUI was designed and created using its lightweight Swing library. This was the first time I had used the Swing library or Java to write a full application, or even create a GUI.
At heart, I am an engineer. I absolutely love to build things! I love to learn about the latest and greatest the tech world has to offer. My goal in life is to architect and engineer meaningful software that helps to solve the many problems we currently face.
I am an extremely driven, passionate and resilient individual. In Summer 2015, I was diagnosed with a rare subtype of Leaukemia. That was the single greatest battle I have ever fought in my life. It put my life on hold for 2 years but I braved it through and came back with more gratitude, passion and an undying hunger for knowledge!
I am currently pursuing a Bachelors of Computer Science(Software Engineering Option) from the University of Waterloo. I expect to graduate end of 2020.
Apart from writing code, I love to play guitar. I fell in love with the instrument in high school and have been practicing and improving ever since. (For the guitar people: I currently own a PRS SE Custom 24 :D)
I also really enjoy running and working out. I am training to run a half-marathon someday. I am also big into video games. I love the aspect of a 'playable' story. It is a great way to relax.


Written by
Keir Johnson
on
on
Here Goes...
Well, here it is. The first post. It’s in the wild- running like a unicorn with a sloth on its back.
You may be asking yourself “hold up, is this a corner of the internet I don’t want to be in? Should I back away slowly?” Don’t worry, this blog won’t bite. I am writing it to share information that I’ve found useful and to learn a few things myself. Take a look for yourself and see if anything catches your eye.
First, I’ll focus on things I’ve learned using Python for data analysis. More posts to come.
Let’s go…


Small-Medium Assets Insurance
Please inform the following forms.
Please chooses image of assets you want.


Before Change
image_id = tf.reshape(image_id, (1,1))
start_location = tf.zeros((1, self.spatial_rank))
end_location = tf.constant(self.window_size[:self.spatial_rank])
end_location = tf.reshape(end_location, (1, self.spatial_rank))
end_location = tf.to_float(end_location)
locations = tf.concat([image_id, start_location, end_location], axis=1)
return windows, locations
After Change
resampler = ResamplerLayer(
interpolation="linear", boundary="replicate")
windows = resampler(combined_volume, computed_grid)
out_shape = [self.batch_size] + \
list(self.window_size[:self.spatial_rank]) + \
[window_channels]
windows.set_shape(out_shape)


Old notes
These notes were written during the courses deep learning by Yoshua Bengio, and computer vision by Roland Memisevitch.
Notes for course ift6268 computer vision
- Notes for paper - Image Super-Resolution Using Deep Convolutional Networks (09 Mar 2016)
- Notes for paper - Predicting Depth, Surface Normals and Semantic Labels with a Common Multi-Scale Convolutional Architecture (08 Mar 2016)
Notes for course ift6266 deep learning
- Cats and dogs - Some experiments and full VGGNet (10 Apr 2016)
- Cats and dogs - Improving the validation accuracy (01 Apr 2016)
- Cats and dogs - Some better results (17 Mar 2016)
- Cats and dogs - Notes building a simple deep learning framework (16 Feb 2016)
- Cats and dogs - First convolutional network trained on Calcul Québec (09 Feb 2016)
- Cats and dogs - Minimum viable product (02 Feb 2016)
- Cats and dogs - Working plan (28 Jan 2016)


Minecraft is a sandbox video game developed by Mojang. The game was created by Markus "Notch" Persson in the Java programming language. Following several early test versions, it was released as a paid public alpha for personal computers in 2009 before releasing in November 2011, with Jens Bergensten taking over development. Minecraft has since been ported to several other platforms and is the best-selling video game of all time, with 200 million copies sold and 126 million monthly active users as of 2020.
In Minecraft, players explore a blocky, procedurally-generated 3D world with infinite terrain, and may discover and extract raw materials, craft tools and items, and build structures or earthworks. Depending on game mode, players can fight computer-controlled "mobs", as well as cooperate with or compete against other players in the same world. Game modes include a survival mode, in which players must acquire resources to build the world and maintain health, and a creative mode, where players have unlimited resources. Players can modify the game to create new gameplay mechanics, items, and assets.


https://python-pillow.org/
https://pillow.readthedocs.io/en/latest/
Warning. Pillow and PIL cannot co-exist in the same environment. Before installing Pillow, please uninstall PIL.
PIP (in a virtual environment) python3 -m pip install Pillow APT (for the entire computer) Debian packages (Pillow fork): python-pil, python-pil.imagetk, python3-pil, python3-pil.imagetk
PIL is the Python Imaging Library by Fredrik Lundh and Contributors. Pillow is the friendly PIL fork by Alex Clark and Contributors.
PIL adds image processing capabilities to your Python interpreter. The core image library is designed for fast access to data stored in a few basic pixel formats. It should provide a solid foundation for a general image processing tool.
Why a fork? PIL is not setuptools compatible. Also, PIL’s current release schedule is too infrequent to accommodate the large number and frequency of issues reported.
import PIL print(PIL.__version__) # 5.4.1 in Debian 10
https://pillow.readthedocs.io/en/latest/handbook/concepts.html
https://en.wikipedia.org/wiki/Raster_graphics
https://en.wikipedia.org/wiki/Vector_graphics
PIL handles 'raster images' (rectangles of pixel data). The opposite to 'raster graphics' is 'vector graphics'.
BANDS An image can consist of one or more bands of data. A PNG image might have ‘R’, ‘G’, ‘B’, and ‘A’ bands for the red, green, blue, and alpha transparency values. Many operations act on each band separately. It is often useful to think of each pixel as having one value per band. image.getbands() # the number and names of bands in an image (tuple)
MODES The 'mode' of an image is a string which defines the type and depth of a pixel in the image. Selected standard modes: '1' (1-bit pixels, black and white, stored with one pixel per byte) # a range of 0-1 'L' (8-bit pixels, black and white) # a range of 0-255 'P' (8-bit pixels, mapped to any other mode using a color palette) 'RGB' (3x8-bit pixels, true color) 'RGBA' (4x8-bit pixels, true color with transparency mask) 'CMYK' (4x8-bit pixels, color separation) image.mode # the image mode
SIZE image.size # the image size in pixels, 2-tuple, (width, height)
COORDINATE SYSTEM PIL uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles are represented as 4-tuples (left, upper, right, lower).
PALETTE The palette mode (P) uses a color palette to define the actual color for each pixel.
INFO You can attach auxiliary information to an image using the 'info' attribute. This is a dictionary object. image.info # get the info attribute
FILTERS For geometry operations that may map multiple input pixels to a single output pixel, PIL provides different resampling filters (NEAREST, BOX, BILINEAR, HAMMING, BICUBIC, LANCZOS).
https://pillow.readthedocs.io/en/latest/handbook/image-file-formats.html
The open() function identifies files from their contents, not their names, but the save() method looks at the name to determine which format to use, unless the format is given explicitly.
The 'format' attribute identifies the source of an image. If the image was not read from a file, it is set to 'None'.
from PIL import Image image1 = Image.open('fruits.png') image1.mode # 'RGB' image1.size # (512, 512) = (width, height) image1.width # 512 image1.height # 512 image1.format # 'PNG', the image is from the PNG file image1.info # {'dpi': (72, 72)} image1.show()
image2 = Image.open('boy.bmp') image2.mode # 'P' image2.size # (768, 512) image2.width # 768 image2.height # 512 image2.format # 'BMP', the image is from the BMP file image2.info # {'dpi': (0, 0), 'compression': 0} image2.show()


|
|
std::atomic< int > | m_signal |
| |
◆ EncoderCounter()
| EncoderCounter::EncoderCounter |
( |
int |
channelA, |
|
|
int |
channelB, |
|
|
int |
ticksPerRev |
|
) |
| |
Counts a two-channel encoder.
- Parameters
-
| channelA | WiringPi Pin for channel A. |
| channelB | WiringPi Pin for channel B. |
| ticksPerRev | Number of ticks per revolution on this encoder. |
◆ ~EncoderCounter()
| EncoderCounter::~EncoderCounter |
( |
| ) |
|
Destructs the encoder counter.
◆ getCount()
| long EncoderCounter::getCount |
( |
| ) |
|
Get the current count from the encoder.
- Returns
- a long, the encoder count (+/-)
◆ getSpeedRPM()
| double EncoderCounter::getSpeedRPM |
( |
| ) |
|
Get the encoder current speed in RPM.
- Returns
- A speed in RPM.
◆ read()
| std::list< Message * > * EncoderCounter::read |
( |
| ) |
|
|
virtual |
Read a list containing a message with the current encoder count for this encoder, and a message with the current speed.
- Returns
- A message list object containing the count/speed for this encoder.
Implements IHardwareInterface.
◆ resetCount()
| void EncoderCounter::resetCount |
( |
| ) |
|
Reset the encoder count to 0.
◆ run()
| void * EncoderCounter::run |
( |
| ) |
|
|
virtual |
Runs the encoder counter worker thread.
- Returns
- nothing
Implements Thread.
The documentation for this class was generated from the following files:


JavaScript is disabled on your browser.
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Letter
Next Letter
Frames
No Frames
All Classes
A
C
D
E
F
G
H
I
M
N
P
R
S
T
G
getCurrentBallsPlayed()
- Method in class com.simpl.cricketsimulation.model.
State
getCurrentNonStriker()
- Method in class com.simpl.cricketsimulation.model.
State
getCurrentPlayerPosition()
- Method in class com.simpl.cricketsimulation.model.
State
getCurrentRunCount()
- Method in class com.simpl.cricketsimulation.model.
State
getCurrentStriker()
- Method in class com.simpl.cricketsimulation.model.
State
getCurrentWicketLeft()
- Method in class com.simpl.cricketsimulation.model.
State
getExceptionMsg()
- Method in exception com.simpl.cricketsimulation.exceptions.
InvalidTeamException
getExceptionMsg()
- Method in exception com.simpl.cricketsimulation.exceptions.
NoPlayerOnStrikeException
getNextRuns(State, List<Player>)
- Method in class com.simpl.cricketsimulation.gamestrategy.
AbstractGameStrategy
getNextRuns will be used to calculate next runs It is based on probablity distribution given for each player
getNextRuns(State, List<Player>)
- Method in interface com.simpl.cricketsimulation.gamestrategy.
IGameStrategy
getOppositionTeam()
- Method in class com.simpl.cricketsimulation.model.
Team
getOvers()
- Method in class com.simpl.cricketsimulation.model.
Team
getPlayerName()
- Method in class com.simpl.cricketsimulation.model.
Player
getPlayerProbablity()
- Method in class com.simpl.cricketsimulation.model.
Player
getPlayingTeam()
- Method in class com.simpl.cricketsimulation.model.
Team
getRules()
- Method in class com.simpl.cricketsimulation.gamestrategy.
AbstractGameStrategy
getRules()
- Method in interface com.simpl.cricketsimulation.gamestrategy.
IGameStrategy
getRunsToWin()
- Method in class com.simpl.cricketsimulation.model.
State
getRunsToWin()
- Method in class com.simpl.cricketsimulation.model.
Team
getTeam()
- Method in class com.simpl.cricketsimulation.model.
Player
getTotalBallsPlayed()
- Method in class com.simpl.cricketsimulation.model.
Player
getTotalRuns()
- Method in class com.simpl.cricketsimulation.model.
Player
getWickets()
- Method in class com.simpl.cricketsimulation.model.
Team
A
C
D
E
F
G
H
I
M
N
P
R
S
T
Skip navigation links
Overview
Package
Class
Use
Tree
Deprecated
Index
Help
Prev Letter
Next Letter
Frames
No Frames
All Classes